diff --git a/main.js b/main.js index 6f1bc6e..fb4eae9 100644 --- a/main.js +++ b/main.js @@ -1,103 +1,103 @@ -"use strict";var ho=Object.create;var Ai=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var po=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty;var se=(h,A)=>()=>(h&&(A=h(h=0)),A);var fo=(h,A)=>()=>(A||h((A={exports:{}}).exports,A),A.exports),ci=(h,A)=>{for(var t in A)Ai(h,t,{get:A[t],enumerable:!0})},Ys=(h,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of po(A))!uo.call(h,i)&&i!==t&&Ai(h,i,{get:()=>A[i],enumerable:!(e=go(A,i))||e.enumerable});return h};var Co=(h,A,t)=>(t=h!=null?ho(Io(h)):{},Ys(A||!h||!h.__esModule?Ai(t,"default",{value:h,enumerable:!0}):t,h)),Bo=h=>Ys(Ai({},"__esModule",{value:!0}),h);function os(h){return Array.isArray(h)?h.filter(A=>typeof A=="string"):typeof h=="string"?h.split(/[,\s]+/).filter(Boolean):[]}function Ie(h,A){let t=A.replace(/^#/,"");return os(h?.tags).some(e=>e.replace(/^#/,"")===t)}function as(h,A){let t=A.replace(/^#/,""),e=os(h.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),h.tags=e}function rs(h,A){let t=A.replace(/^#/,""),e=os(h.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?h.tags=e:delete h.tags}function ue(h){return h.split("/").some(A=>Ge.has(A))}function zs(h){return h.split("/").some(A=>A==="_archive"||A===".archive")}function Gt(h){let A=(h??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function ae(h){let A=(h??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function Vs(h){let A=h.match(/\.([^./]+)$/);return!!A&&mo.has(A[1].toLowerCase())}function Ws(h,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(h))return!0}catch{}else if(h===e||h.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function li(h,A){let t=h.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function Xt(h){if(typeof h!="string")return null;let A=h.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function Re(h){let A=h?.assignedTo,t=Array.isArray(A)?A:A!=null?[A]:[],e=[];for(let i of t){let s=Xt(i);s&&e.push(s)}return e}var dt,Vt,ne,oe,U,Wt,Ge,mo,wt=se(()=>{"use strict";dt="stashpad-view",Vt="stashpad-panels",ne="stashpad-folder-panel",oe="stashpad-detail",U="__root__";Wt=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],Ge=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);mo=new Set(["edtz"])});function Qo(h,A){return h>12?h>=24?0:h:A==="am"?h===12?0:h:h===12?12:h+12}function hi(h,A){h.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=h.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let a=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});a.type="button";let r=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};r(),o.addEventListener("mousedown",E=>E.preventDefault()),a.addEventListener("mousedown",E=>E.preventDefault()),o.addEventListener("click",E=>{E.preventDefault(),t="am",r()}),a.addEventListener("click",E=>{E.preventDefault(),t="pm",r()});let c=i;i.addEventListener("focus",()=>{c=i,i.select()}),s.addEventListener("focus",()=>{c=s,s.select()});let l=()=>{let w=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",w),a.toggleClass("is-disabled",w),o.disabled=w,a.disabled=w},g=E=>{let w=E.value.replace(/\D/g,"").slice(0,2);if(w===""){E.value="",E===i&&l();return}let y=parseInt(w,10);E===i?y>24&&(y=24):y>59&&(y=59),E.value=String(y),E===i&&l()};for(let E of[i,s])E.addEventListener("input",()=>g(E));l();let p=()=>{let E=parseInt(i.value||"12",10)||12,w=parseInt(s.value||"0",10)||0,y=E>12;A.onFinalize({hours24:Qo(E,t),minutes:w,raw:{hh:E,mm:w,period:t,is24:y}}),A.close()};A.setOnEnter?.(p);let d=[i,s,o,a],I=(E,w)=>{let y=d.indexOf(E);if(y===-1)return;let F=(y+w+d.length)%d.length;d[F].focus()},u=E=>{E.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),p()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),A.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),I(E,w.shiftKey?-1:1))})},f=h.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let E of C){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",E==="backspace"?(0,_s.setIcon)(w,"delete"):E==="insert"?(w.setText("OK"),m=w):w.setText(E),E==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{if(y.preventDefault(),E==="insert"){p();return}if(E==="backspace"){c.value=c.value.slice(0,-1),g(c),c.focus();return}let F=c.selectionStart===0&&c.selectionEnd===c.value.length&&c.value.length>0,D=2,L=F||c.value.length>=D?E:c.value+E;c.value=L,g(c),c.focus(),c.setSelectionRange(c.value.length,c.value.length),c===i&&c.value.length>=D&&(s.focus(),s.select())})}m&&d.push(m);for(let E of d)u(E);i.focus(),i.select()}function js(h){let{hh:A,mm:t,period:e,is24:i}=h.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var _s,As=se(()=>{"use strict";_s=require("obsidian")});function en(h){let A=Math.floor(4294967296/h)*h,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%h}function sn(h=5){let A=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),Eo.has(h.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function yo(h){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Pe(h){let A="stashpad-",t=yo(h),e=64-A.length-1-t.length,i=h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var tn,Eo,gi=se(()=>{"use strict";tn="able acid acorn actor adept agile alarm album alert algae amber amble anchor angle ankle apple april arbor arc arctic arena armor arrow ascot aspen atlas atom attic auburn audio autumn award axis bacon badge bagel baker balmy bamboo banjo barge basil basin batch beach beam bean bear beaver begin belt bench berry birch bison black blade blaze bliss bloom blue board boat bold bolt bonus boost booth borax bother bottle boulder bounce bovine bowl brave bread breeze brick bridge brisk broad bronze brook broom brown brush bubble bucket bug bulb bundle burst cabin cable cacao cactus camel cameo candle canoe canvas canyon cargo carol carrot castle catch cedar cello chalk charm chart cheese cherry chess chime chirp cider cinder circle citrus clamp clay clever cliff cloak clock cloud clover coast cobra cocoa comet coral cosmos cotton couch cougar crane crater cream crest cricket crisp crown crumb crystal cube cumin curio dagger daisy dapper dawn deck deer delta denim depot desert dial diamond dingo ditch dock dodge dolphin domino donut draft dragon drift drum dune dusk eagle early earth easel ebony echo eclipse edge eel eagle elbow elder ember emboss emerald ember emu engine ermine ether ever fable falcon fancy farm fawn feather felt fennel fern ferry fiber fiddle field fig finch flame flask flax fleet flint float flock flora flute focus foam forest fossil fox frame frost fudge garden gecko ginger glacier glade glass glide globe glory glove gnat goat golden gopher gourd grape grass gravel grove guava gull hammer hamlet harbor hatch hazel heron hickory hippo honey hornet hostel ivory ivy jade jaguar jasmine jelly jetty jewel jolly jungle juniper kayak kelp kettle kiwi koala ladle lagoon lamp lantern larch lark lasso lava ledge lemon lentil leopard lever lilac lime linen lizard llama lobby locket lodge lotus lunar lupine lynx maple marble marsh meadow medal melon mellow mentor mesa metro mimic mint mirror mocha morsel moss mottle mural muslin nacho nectar nest noble nomad noodle nougat nutmeg oasis oat ocean ochre olive onyx opal orbit orca otter oval owl oxide oyster pace paddle palm panda pantry papaya parka parsley pasta pearl pebble pelican pepper pewter phantom piano picnic pigeon pilot pine pixel plank plaza plum pocket pollen pond poplar poppy portal potato pottery prairie prism puffin pumice quail quartz quill quilt quince rabbit radish raft rapid raven reed reef relish ribbon ridge rind ripple river robin rocket rope rover ruby rudder rust saffron sage salmon sandal sash satin sauce scout sedge sequin shadow shale shark shell shore shrub silk silo silver siren sketch slate sleet slope sloth smoke snail sonar sorrel spark sparrow spice spire sprig spruce squid stable stamp starling steam stem stilt stone stork storm stove straw stream stucco summit sundae sunset swan sweater syrup tabby talon tango tapir tassel tawny teal tempo thicket thimble thistle thorn thunder tidal tiger timber toffee token topaz torch totem trail tulip tundra turtle tusk twig umber unicorn valley vanilla velvet vermil violet viper vista vivid vortex waffle walnut warbler wasp water weasel wharf wheat whisk willow window winter wisp wombat wonder woven yam yarn yeast yew yodel yonder zebra zenith zephyr zigzag zinc zircon".split(/\s+/).filter(Boolean);Eo=new Set(["password","passw0rd","password1","123456","12345678","123456789","qwerty","abc123","letmein","welcome","admin","iloveyou","monkey","dragon","sunshine","princess","football","baseball","trustno1","000000","111111","secret"])});var pi={};ci(pi,{newId:()=>yt});function yt(h=6){let A="",t=new Uint8Array(h);crypto.getRandomValues(t);for(let e=0;e{"use strict";on="abcdefghijkmnpqrstuvwxyz23456789"});var We={};ci(We,{AssignModal:()=>Ke,ColorPickerModal:()=>le,ConfirmDeleteModal:()=>Ce,ConfirmModal:()=>vt,CustomColorModal:()=>Ii,DueDatePickerModal:()=>Ye,ExportStashModal:()=>qe,ImportDupChoiceModal:()=>Ve,ImportLogModal:()=>cs,LogModal:()=>fe,NotificationHistoryModal:()=>ze,SplitNoteModal:()=>Je,StashPasswordModal:()=>Oe,buildAssigneePicker:()=>ls});function ls(h,A){let t=[...A.initial],e=A.knownAuthors,i=h.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=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 r=()=>A.onChange([...t]),c=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let p of t){let d=s.createSpan({cls:"stashpad-assign-chip"});d.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let I=d.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});I.title=`Remove ${p.name}`,I.onclick=()=>{t=t.filter(u=>u.id!==p.id),r(),c()}}},l=p=>{p.name.trim()&&(t.some(d=>d.id===p.id)||t.push(p),o.value="",a.style.display="none",r(),c(),o.focus())},g=()=>{let p=o.value.trim();a.empty();let d=new Set(t.map(f=>f.id)),u=e.filter(f=>!d.has(f.id)&&li(p,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>l(f)}));if(p&&!e.some(f=>f.name.toLowerCase()===p.toLowerCase())&&u.push({label:`Create \u201C${p}\u201D`,onPick:()=>l({id:yt(6),name:p})}),u.length===0){a.style.display="none";return}a.style.display="";for(let f of u){let C=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});C.onmousedown=m=>{m.preventDefault(),f.onPick()}}};o.addEventListener("input",g),o.addEventListener("focus",g),o.addEventListener("keydown",p=>{if(p.key==="Enter"){p.preventDefault();let d=a.querySelector(".stashpad-assign-suggest-item");d&&d.dispatchEvent(new MouseEvent("mousedown"))}else p.key==="Escape"&&a.style.display!=="none"&&(p.stopPropagation(),a.style.display="none")}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.style.display="none"},120)}),c()}var ct,Ae,fe,Ce,Je,qe,Oe,Ii,Le,le,vt,Ke,Ye,ce,ze,cs,Ve,Mt=se(()=>{"use strict";ct=require("obsidian");As();wt();gi();Rt();Ae=class Ae extends ct.Modal{constructor(t,e,i){super(t);this.text=e;this.jsonlPath=i;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 r of this.text.trim().split(/\r?\n/))if(r)try{this.events.push(JSON.parse(r))}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 i=t.createEl("button",{text:"Open in default app"});i.onclick=()=>this.shellAct("open");let s=t.createEl("button",{text:"Copy raw JSONL"}),n=null;s.onclick=async()=>{await navigator.clipboard.writeText(this.text),s.setText("Copied"),n!=null&&window.clearTimeout(n),n=window.setTimeout(()=>{s.setText("Copy raw JSONL"),n=null},1500)};let o=t.createEl("button",{text:"Export copy"});o.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(Ae.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 i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All types (${this.events.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});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 i=this.shownCount;i{this.appendMore(Ae.PAGE),this.renderFooter()},t>Ae.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.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:i}=window.require("electron");t==="reveal"?i.showItemInFolder(e):i.openPath(e)}catch(e){new ct.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,ct.moment)().format("YYYY-MM-DD_HHmmss"),e=this.jsonlPath.replace(/\/[^/]+$/,"")||"",i=e?`${e}/${t}-log.jsonl`:`${t}-log.jsonl`;return await this.app.vault.adapter.write(i,this.text),new ct.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new ct.Notice(`Export failed: ${t.message}`),null}}clearLog(){new vt(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(i){new ct.Notice(`Clear failed: ${i.message}`);return}this.text="",this.events=[],this.typeFilter=null,this.shownCount=0,this.refreshTypeFilter(),this.refreshList(),this.footerEl&&this.footerEl.empty(),new ct.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,ct.moment)(t.ts).isValid()?(0,ct.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,s=document.createElement("span");s.className="stashpad-log-ts",s.textContent=i,e.appendChild(s);let n=document.createElement("span");n.className="stashpad-log-type",n.textContent=t.type,e.appendChild(n);let o=document.createElement("span");o.className="stashpad-log-author",o.textContent=t.author?t.author:"\u2014",t.author||o.classList.add("is-empty"),e.appendChild(o);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 i=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,s=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${s}${i?` \u2014 also removed ${i} attachment${i===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let i=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${i}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let i=e.count??1,s=e.dir??"?",n=e.parent??t.id??"?";return`Reordered ${i} note${i===1?"":"s"} (${s}) under ${n}`}case"complete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${i} note${i===1?"":"s"} complete${s}`}case"uncomplete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${i} note${i===1?"":"s"}${s}`}case"stash_export":{let i=e.noteCount??"?";return`Exported ${i} note${i===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let i=e.noteCount??"?",s=[];e.attachmentsWritten&&s.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&s.push(`${e.collisionsRenamed} renamed`);let n=s.length?` (${s.join(", ")})`:"";return`Imported ${i} note${i===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()}};Ae.PAGE=100;fe=Ae,Ce=class extends ct.Modal{constructor(t,e,i,s,n,o){super(t);this.noteTitle=e;this.descendantCount=i;this.attachmentCount=s;this.offerAttachmentDelete=n;this.onChoose=o}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 o=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=o.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},o.createSpan({text:" Also delete attachments"})}let i=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.close();let n=i.createEl("button",{cls:"mod-warning",text:"Delete"});n.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},Je=class extends ct.Modal{constructor(t,e,i,s){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` +"use strict";var ho=Object.create;var Ai=Object.defineProperty;var go=Object.getOwnPropertyDescriptor;var po=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,uo=Object.prototype.hasOwnProperty;var se=(h,A)=>()=>(h&&(A=h(h=0)),A);var fo=(h,A)=>()=>(A||h((A={exports:{}}).exports,A),A.exports),li=(h,A)=>{for(var t in A)Ai(h,t,{get:A[t],enumerable:!0})},Ys=(h,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of po(A))!uo.call(h,i)&&i!==t&&Ai(h,i,{get:()=>A[i],enumerable:!(e=go(A,i))||e.enumerable});return h};var Co=(h,A,t)=>(t=h!=null?ho(Io(h)):{},Ys(A||!h||!h.__esModule?Ai(t,"default",{value:h,enumerable:!0}):t,h)),Bo=h=>Ys(Ai({},"__esModule",{value:!0}),h);function os(h){return Array.isArray(h)?h.filter(A=>typeof A=="string"):typeof h=="string"?h.split(/[,\s]+/).filter(Boolean):[]}function Ie(h,A){let t=A.replace(/^#/,"");return os(h?.tags).some(e=>e.replace(/^#/,"")===t)}function as(h,A){let t=A.replace(/^#/,""),e=os(h.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),h.tags=e}function rs(h,A){let t=A.replace(/^#/,""),e=os(h.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?h.tags=e:delete h.tags}function ue(h){return h.split("/").some(A=>Ge.has(A))}function zs(h){return h.split("/").some(A=>A==="_archive"||A===".archive")}function Gt(h){let A=(h??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function ae(h){let A=(h??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function Vs(h){let A=h.match(/\.([^./]+)$/);return!!A&&mo.has(A[1].toLowerCase())}function Ws(h,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(h))return!0}catch{}else if(h===e||h.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function ci(h,A){let t=h.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function Xt(h){if(typeof h!="string")return null;let A=h.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function Re(h){let A=h?.assignedTo,t=Array.isArray(A)?A:A!=null?[A]:[],e=[];for(let i of t){let s=Xt(i);s&&e.push(s)}return e}var dt,Vt,ne,oe,U,Wt,Ge,mo,wt=se(()=>{"use strict";dt="stashpad-view",Vt="stashpad-panels",ne="stashpad-folder-panel",oe="stashpad-detail",U="__root__";Wt=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],Ge=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);mo=new Set(["edtz"])});function Qo(h,A){return h>12?h>=24?0:h:A==="am"?h===12?0:h:h===12?12:h+12}function hi(h,A){h.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=h.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let a=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});a.type="button";let r=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};r(),o.addEventListener("mousedown",E=>E.preventDefault()),a.addEventListener("mousedown",E=>E.preventDefault()),o.addEventListener("click",E=>{E.preventDefault(),t="am",r()}),a.addEventListener("click",E=>{E.preventDefault(),t="pm",r()});let l=i;i.addEventListener("focus",()=>{l=i,i.select()}),s.addEventListener("focus",()=>{l=s,s.select()});let c=()=>{let w=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",w),a.toggleClass("is-disabled",w),o.disabled=w,a.disabled=w},g=E=>{let w=E.value.replace(/\D/g,"").slice(0,2);if(w===""){E.value="",E===i&&c();return}let y=parseInt(w,10);E===i?y>24&&(y=24):y>59&&(y=59),E.value=String(y),E===i&&c()};for(let E of[i,s])E.addEventListener("input",()=>g(E));c();let p=()=>{let E=parseInt(i.value||"12",10)||12,w=parseInt(s.value||"0",10)||0,y=E>12;A.onFinalize({hours24:Qo(E,t),minutes:w,raw:{hh:E,mm:w,period:t,is24:y}}),A.close()};A.setOnEnter?.(p);let d=[i,s,o,a],I=(E,w)=>{let y=d.indexOf(E);if(y===-1)return;let F=(y+w+d.length)%d.length;d[F].focus()},u=E=>{E.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),p()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),A.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),I(E,w.shiftKey?-1:1))})},f=h.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let E of C){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",E==="backspace"?(0,_s.setIcon)(w,"delete"):E==="insert"?(w.setText("OK"),m=w):w.setText(E),E==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{if(y.preventDefault(),E==="insert"){p();return}if(E==="backspace"){l.value=l.value.slice(0,-1),g(l),l.focus();return}let F=l.selectionStart===0&&l.selectionEnd===l.value.length&&l.value.length>0,D=2,L=F||l.value.length>=D?E:l.value+E;l.value=L,g(l),l.focus(),l.setSelectionRange(l.value.length,l.value.length),l===i&&l.value.length>=D&&(s.focus(),s.select())})}m&&d.push(m);for(let E of d)u(E);i.focus(),i.select()}function js(h){let{hh:A,mm:t,period:e,is24:i}=h.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var _s,As=se(()=>{"use strict";_s=require("obsidian")});function en(h){let A=Math.floor(4294967296/h)*h,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%h}function sn(h=5){let A=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),Eo.has(h.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function yo(h){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Pe(h){let A="stashpad-",t=yo(h),e=64-A.length-1-t.length,i=h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var tn,Eo,gi=se(()=>{"use strict";tn="able acid acorn actor adept agile alarm album alert algae amber amble anchor angle ankle apple april arbor arc arctic arena armor arrow ascot aspen atlas atom attic auburn audio autumn award axis bacon badge bagel baker balmy bamboo banjo barge basil basin batch beach beam bean bear beaver begin belt bench berry birch bison black blade blaze bliss bloom blue board boat bold bolt bonus boost booth borax bother bottle boulder bounce bovine bowl brave bread breeze brick bridge brisk broad bronze brook broom brown brush bubble bucket bug bulb bundle burst cabin cable cacao cactus camel cameo candle canoe canvas canyon cargo carol carrot castle catch cedar cello chalk charm chart cheese cherry chess chime chirp cider cinder circle citrus clamp clay clever cliff cloak clock cloud clover coast cobra cocoa comet coral cosmos cotton couch cougar crane crater cream crest cricket crisp crown crumb crystal cube cumin curio dagger daisy dapper dawn deck deer delta denim depot desert dial diamond dingo ditch dock dodge dolphin domino donut draft dragon drift drum dune dusk eagle early earth easel ebony echo eclipse edge eel eagle elbow elder ember emboss emerald ember emu engine ermine ether ever fable falcon fancy farm fawn feather felt fennel fern ferry fiber fiddle field fig finch flame flask flax fleet flint float flock flora flute focus foam forest fossil fox frame frost fudge garden gecko ginger glacier glade glass glide globe glory glove gnat goat golden gopher gourd grape grass gravel grove guava gull hammer hamlet harbor hatch hazel heron hickory hippo honey hornet hostel ivory ivy jade jaguar jasmine jelly jetty jewel jolly jungle juniper kayak kelp kettle kiwi koala ladle lagoon lamp lantern larch lark lasso lava ledge lemon lentil leopard lever lilac lime linen lizard llama lobby locket lodge lotus lunar lupine lynx maple marble marsh meadow medal melon mellow mentor mesa metro mimic mint mirror mocha morsel moss mottle mural muslin nacho nectar nest noble nomad noodle nougat nutmeg oasis oat ocean ochre olive onyx opal orbit orca otter oval owl oxide oyster pace paddle palm panda pantry papaya parka parsley pasta pearl pebble pelican pepper pewter phantom piano picnic pigeon pilot pine pixel plank plaza plum pocket pollen pond poplar poppy portal potato pottery prairie prism puffin pumice quail quartz quill quilt quince rabbit radish raft rapid raven reed reef relish ribbon ridge rind ripple river robin rocket rope rover ruby rudder rust saffron sage salmon sandal sash satin sauce scout sedge sequin shadow shale shark shell shore shrub silk silo silver siren sketch slate sleet slope sloth smoke snail sonar sorrel spark sparrow spice spire sprig spruce squid stable stamp starling steam stem stilt stone stork storm stove straw stream stucco summit sundae sunset swan sweater syrup tabby talon tango tapir tassel tawny teal tempo thicket thimble thistle thorn thunder tidal tiger timber toffee token topaz torch totem trail tulip tundra turtle tusk twig umber unicorn valley vanilla velvet vermil violet viper vista vivid vortex waffle walnut warbler wasp water weasel wharf wheat whisk willow window winter wisp wombat wonder woven yam yarn yeast yew yodel yonder zebra zenith zephyr zigzag zinc zircon".split(/\s+/).filter(Boolean);Eo=new Set(["password","passw0rd","password1","123456","12345678","123456789","qwerty","abc123","letmein","welcome","admin","iloveyou","monkey","dragon","sunshine","princess","football","baseball","trustno1","000000","111111","secret"])});var pi={};li(pi,{newId:()=>yt});function yt(h=6){let A="",t=new Uint8Array(h);crypto.getRandomValues(t);for(let e=0;e{"use strict";on="abcdefghijkmnpqrstuvwxyz23456789"});var We={};li(We,{AssignModal:()=>Ke,ColorPickerModal:()=>ce,ConfirmDeleteModal:()=>Ce,ConfirmModal:()=>vt,CustomColorModal:()=>Ii,DueDatePickerModal:()=>Ye,ExportStashModal:()=>qe,ImportDupChoiceModal:()=>Ve,ImportLogModal:()=>ls,LogModal:()=>fe,NotificationHistoryModal:()=>ze,SplitNoteModal:()=>Je,StashPasswordModal:()=>Oe,buildAssigneePicker:()=>cs});function cs(h,A){let t=[...A.initial],e=A.knownAuthors,i=h.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=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 r=()=>A.onChange([...t]),l=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let p of t){let d=s.createSpan({cls:"stashpad-assign-chip"});d.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let I=d.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});I.title=`Remove ${p.name}`,I.onclick=()=>{t=t.filter(u=>u.id!==p.id),r(),l()}}},c=p=>{p.name.trim()&&(t.some(d=>d.id===p.id)||t.push(p),o.value="",a.style.display="none",r(),l(),o.focus())},g=()=>{let p=o.value.trim();a.empty();let d=new Set(t.map(f=>f.id)),u=e.filter(f=>!d.has(f.id)&&ci(p,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>c(f)}));if(p&&!e.some(f=>f.name.toLowerCase()===p.toLowerCase())&&u.push({label:`Create \u201C${p}\u201D`,onPick:()=>c({id:yt(6),name:p})}),u.length===0){a.style.display="none";return}a.style.display="";for(let f of u){let C=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});C.onmousedown=m=>{m.preventDefault(),f.onPick()}}};o.addEventListener("input",g),o.addEventListener("focus",g),o.addEventListener("keydown",p=>{if(p.key==="Enter"){p.preventDefault();let d=a.querySelector(".stashpad-assign-suggest-item");d&&d.dispatchEvent(new MouseEvent("mousedown"))}else p.key==="Escape"&&a.style.display!=="none"&&(p.stopPropagation(),a.style.display="none")}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.style.display="none"},120)}),l()}var lt,Ae,fe,Ce,Je,qe,Oe,Ii,Le,ce,vt,Ke,Ye,le,ze,ls,Ve,Mt=se(()=>{"use strict";lt=require("obsidian");As();wt();gi();Rt();Ae=class Ae extends lt.Modal{constructor(t,e,i){super(t);this.text=e;this.jsonlPath=i;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 r of this.text.trim().split(/\r?\n/))if(r)try{this.events.push(JSON.parse(r))}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 i=t.createEl("button",{text:"Open in default app"});i.onclick=()=>this.shellAct("open");let s=t.createEl("button",{text:"Copy raw JSONL"}),n=null;s.onclick=async()=>{await navigator.clipboard.writeText(this.text),s.setText("Copied"),n!=null&&window.clearTimeout(n),n=window.setTimeout(()=>{s.setText("Copy raw JSONL"),n=null},1500)};let o=t.createEl("button",{text:"Export copy"});o.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(Ae.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 i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All types (${this.events.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});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 i=this.shownCount;i{this.appendMore(Ae.PAGE),this.renderFooter()},t>Ae.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.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:i}=window.require("electron");t==="reveal"?i.showItemInFolder(e):i.openPath(e)}catch(e){new lt.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,lt.moment)().format("YYYY-MM-DD_HHmmss"),e=this.jsonlPath.replace(/\/[^/]+$/,"")||"",i=e?`${e}/${t}-log.jsonl`:`${t}-log.jsonl`;return await this.app.vault.adapter.write(i,this.text),new lt.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new lt.Notice(`Export failed: ${t.message}`),null}}clearLog(){new vt(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(i){new lt.Notice(`Clear failed: ${i.message}`);return}this.text="",this.events=[],this.typeFilter=null,this.shownCount=0,this.refreshTypeFilter(),this.refreshList(),this.footerEl&&this.footerEl.empty(),new lt.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,lt.moment)(t.ts).isValid()?(0,lt.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,s=document.createElement("span");s.className="stashpad-log-ts",s.textContent=i,e.appendChild(s);let n=document.createElement("span");n.className="stashpad-log-type",n.textContent=t.type,e.appendChild(n);let o=document.createElement("span");o.className="stashpad-log-author",o.textContent=t.author?t.author:"\u2014",t.author||o.classList.add("is-empty"),e.appendChild(o);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 i=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,s=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${s}${i?` \u2014 also removed ${i} attachment${i===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let i=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${i}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let i=e.count??1,s=e.dir??"?",n=e.parent??t.id??"?";return`Reordered ${i} note${i===1?"":"s"} (${s}) under ${n}`}case"complete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${i} note${i===1?"":"s"} complete${s}`}case"uncomplete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${i} note${i===1?"":"s"}${s}`}case"stash_export":{let i=e.noteCount??"?";return`Exported ${i} note${i===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let i=e.noteCount??"?",s=[];e.attachmentsWritten&&s.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&s.push(`${e.collisionsRenamed} renamed`);let n=s.length?` (${s.join(", ")})`:"";return`Imported ${i} note${i===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()}};Ae.PAGE=100;fe=Ae,Ce=class extends lt.Modal{constructor(t,e,i,s,n,o){super(t);this.noteTitle=e;this.descendantCount=i;this.attachmentCount=s;this.offerAttachmentDelete=n;this.onChoose=o}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 o=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=o.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},o.createSpan({text:" Also delete attachments"})}let i=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.close();let n=i.createEl("button",{cls:"mod-warning",text:"Delete"});n.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},Je=class extends lt.Modal{constructor(t,e,i,s){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;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 ct.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 i=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});i.onmousedown=n=>n.preventDefault(),i.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let s=this.contentEl.createDiv({cls:"stashpad-split-help"});ct.Platform.isMobile?s.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):s.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 s=Math.max(1,Math.min(this.lines.length-1,e));s!==this.lineCursorIdx&&(this.lineCursorIdx=s,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 i=parseFloat(getComputedStyle(e).lineHeight)||22,s=ct.Platform.isMobile?3:12,n=2,o=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,i*s+16);e.style.height=`${Math.max(a,i*n+16)}px`};requestAnimationFrame(()=>{o();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",o)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},qe=class extends ct.Modal{constructor(t,e,i,s,n){super(t);this.defaultBaseName=e;this.noteCount=i;this.onConfirm=s;this.kdfProbe=n;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Export to .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`${this.noteCount} note${this.noteCount===1?"":"s"} will be bundled into a single .stash file.`});let t=this.contentEl.createDiv({cls:"stashpad-export-field"});t.createEl("label",{cls:"stashpad-export-label",text:"File name"});let e=t.createEl("input",{type:"text"});e.addClass("stashpad-export-name"),e.value=this.defaultBaseName;let i=this.contentEl.createEl("div",{cls:"stashpad-export-preview"}),s=this.contentEl.createDiv({cls:"stashpad-export-encrypt"}),n=s.createDiv({cls:"stashpad-export-toggle"}),o=n.createEl("input",{type:"checkbox"});o.id="stashpad-export-encrypt-cb";let a=n.createEl("label",{text:"Encrypt with a password"});a.htmlFor=o.id;let r=s.createDiv({cls:"stashpad-export-pw-area"});r.style.display="none";let c=[],l=K=>{let z=r.createDiv({cls:"stashpad-export-pw-row"}),ot=z.createEl("input",{type:"password"});ot.addClass("stashpad-export-name"),ot.placeholder=K;let pt=z.createEl("button",{cls:"stashpad-export-copy"}),st=()=>{let at=ot.value.length===0;pt.setText(at?"Paste":"Copy"),pt.toggleClass("is-paste",at),pt.setAttr("aria-label",`${at?"Paste into":"Copy"} ${K.toLowerCase()}`)};return pt.onclick=async at=>{if(at.preventDefault(),ot.value.length===0)try{let At=(await navigator.clipboard?.readText())?.trim();if(!At){new ct.Notice("Clipboard is empty.");return}ot.value=At,ot.dispatchEvent(new Event("input")),new ct.Notice("Pasted from clipboard.")}catch{new ct.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(ot.value).then(()=>new ct.Notice("Passphrase copied to clipboard."),()=>new ct.Notice("Couldn't access the clipboard."))},st(),c.push(st),ot},g=l("Password"),p=l("Confirm password"),d=r.createDiv({cls:"stashpad-export-strength"}),I=d.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),f=d.createEl("span",{cls:"stashpad-strength-label"}),C=r.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),E=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=r.createEl("div",{cls:"stashpad-export-pw-hint"}),y=r.createEl("div",{cls:"stashpad-export-pw-suite"});y.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(K=>{y.toggleClass("is-weak",!K),y.setText(K?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run on this device, so this export will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>{y.setText("Encryption: AES-256-GCM with a password-derived key.")}):y.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let F=this.app.secretStorage,D=r.createDiv({cls:"stashpad-export-remember"}),L=D.createEl("input",{type:"checkbox"});L.id="stashpad-export-remember-cb";let S=D.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});S.htmlFor=L.id;let b=r.createDiv({cls:"stashpad-export-remember-note"});b.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),b.style.display="none",L.onchange=()=>{b.style.display=L.checked?"":"none"},F||(D.style.display="none");let Q=()=>{let K=e.value.trim()||this.defaultBaseName;return o.checked?`${K}-encrypted`:K},H=()=>i.setText(`Saves as: ${Q()}-.stash`);e.oninput=H;let $=this.contentEl.createDiv({cls:"stashpad-export-footer"}),M=$.createEl("button",{text:"Cancel"});M.onclick=()=>this.close();let T=$.createEl("button",{cls:"mod-cta",text:"Export"}),J=()=>{let K=nn(g.value);d.style.visibility=g.value?"visible":"hidden",u.forEach((z,ot)=>z.toggleClass("is-on",g.value!==""&&ot<=K.level)),I.dataset.level=String(K.level),f.setText(K.label)},Z=()=>{let K=o.checked;r.style.display=K?"":"none";let z=!0;K&&(g.value?g.value!==p.value?(w.setText("Passwords don't match."),w.addClass("is-error"),z=!1):(w.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),w.removeClass("is-error")):(w.setText("Enter a password to encrypt this export."),w.removeClass("is-error"),z=!1)),J(),c.forEach(ot=>ot()),T.disabled=!z,T.toggleClass("is-disabled",!z),H()},G=!1,N=K=>{G=K,g.type=p.type=K?"text":"password",E.setText(K?"Hide":"Show")};E.onclick=K=>{K.preventDefault(),N(!G)},m.onclick=K=>{K.preventDefault(),g.value=p.value=sn(),N(!1),new ct.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),Z()},o.onchange=Z,g.oninput=Z,p.oninput=Z,Z();let _=()=>this.commit(Q(),o.checked?g.value:null,o.checked&&L.checked);T.onclick=_,this.scope.register([],"Enter",K=>{K.preventDefault(),T.disabled||_()}),requestAnimationFrame(()=>{e.focus(),e.select()})}commit(t,e,i){let s=t.trim()||this.defaultBaseName,n=e&&e.length?e:null;this.delivered=!0,this.close(),this.onConfirm(s,n,!!n&&i)}onClose(){this.contentEl.empty()}},Oe=class extends ct.Modal{constructor(t,e,i,s){super(t);this.errorMsg=e;this.allowLater=i;this.onResult=s;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Encrypted .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This export is password-protected. Enter its password to import it."}),this.errorMsg&&this.contentEl.createEl("div",{cls:"stashpad-export-error",text:this.errorMsg});let t=this.contentEl.createEl("input",{type:"password"});t.addClass("stashpad-export-name"),t.placeholder="Password";let e=this.contentEl.createDiv({cls:"stashpad-export-footer"});if(e.createEl("button",{text:"Cancel"}).onclick=()=>this.close(),this.allowLater){let s=e.createEl("button",{text:"Remind me later"});s.title="Don't import now \u2014 surface the reminder again later.",s.onclick=()=>this.finish({kind:"later"})}let i=e.createEl("button",{cls:"mod-cta",text:"Decrypt & import"});i.onclick=()=>this.submit(t.value),this.scope.register([],"Enter",s=>{s.preventDefault(),this.submit(t.value)}),requestAnimationFrame(()=>t.focus())}submit(t){t&&this.finish({kind:"password",value:t})}finish(t){this.delivered=!0,this.close(),this.onResult(t)}onClose(){this.delivered||(this.delivered=!0,this.onResult({kind:"cancel"})),this.contentEl.empty()}},Ii=class extends ct.Modal{constructor(t,e,i){super(t);this.onResult=i;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 i=t.createEl("input",{type:"color"});i.value=this.value,i.addClass("stashpad-custom-color-wheel"),e.onclick=()=>i.click();let s=t.createEl("input",{type:"text"});s.addClass("stashpad-custom-color-hex"),s.placeholder="#RRGGBB",s.value=this.value,s.maxLength=7;let n=l=>{let g=l.startsWith("#")?l:"#"+l;/^#[0-9a-f]{6}$/i.test(g)&&(this.value=g,e.style.background=g,i.value=g,s.value!==g&&(s.value=g))};i.oninput=()=>n(i.value),s.oninput=()=>n(s.value);let o=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=o.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let r=o.createEl("button",{cls:"mod-cta",text:"Save"});r.title="Apply this color to the selection (without adding to your palette).",r.onclick=()=>this.commit({addToPalette:!1});let c=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});c.title="Apply and save this color so it appears as a tile next time.",c.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",l=>{l.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",l=>{l.preventDefault(),this.commit({addToPalette:!0})}),requestAnimationFrame(()=>s.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()}},Le=class Le extends ct.Modal{constructor(t,e,i,s,n){super(t);this.currentColor=e;this.customPalette=i;this.onPick=s;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 i=[...Le.DEFAULT_PALETTE,...this.customPalette];for(let a of i){let r=t.createDiv({cls:"stashpad-color-tile"});r.style.background=a,r.title=a;let c=!Le.DEFAULT_PALETTE.some(g=>g.toLowerCase()===a.toLowerCase()),l=this.items.length;if(r.onclick=()=>this.activate(l),c&&this.onDeleteCustom){let g=r.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});g.title="Remove from palette",g.onclick=p=>{p.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:c?"custom":"preset",color:a,el:r})}let s=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});s.title="Custom color\u2026";let n=this.items.length;s.onclick=()=>this.activate(n),this.items.push({kind:"add",color:null,el:s});let o=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=o>=0?o: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 Ii(this.app,this.currentColor,(i,s)=>{this.onPick(i,s)}).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(),i=this.items[0].el.getBoundingClientRect();if(i.width<=0)return 1;let s=i.top,n=0;for(let o of this.items){let a=o.el.getBoundingClientRect();if(Math.abs(a.top-s)<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(i=>i.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 s=e.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};Ke=class extends ct.Modal{constructor(t,e,i){super(t);this.opts=e;this.onPick=i;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"});ls(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Cancel"});i.onclick=()=>{this.didChoose=!0,this.close()};let s=e.createEl("button",{cls:"mod-cta",text:"Save"});s.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},Ye=class extends ct.Modal{constructor(t,e,i,s={}){super(t);this.current=e;this.onPick=i;this.opts=s;this.didChoose=!1;this.assignees=[];this.tinyClosePopover=null;this.assignees=[...s.currentAssignees??[]]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Set due date");let t=null;if(this.current){let f=Date.parse(this.current);Number.isNaN(f)||(t=new Date(f))}let e=this.contentEl.createDiv({cls:"stashpad-due-picker"}),i=e.createDiv({cls:"stashpad-due-fields"}),s=i.createDiv({cls:"stashpad-due-field"}),n=s.createSpan({cls:"stashpad-due-field-icon"});(0,ct.setIcon)(n,"calendar");let o=s.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=i.createDiv({cls:"stashpad-due-field"}),r=a.createSpan({cls:"stashpad-due-field-icon"});(0,ct.setIcon)(r,"clock");let c=a.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{o.showPicker?.()}catch{}},r.onclick=()=>this.openTimeNumpad(r,c),t&&(o.value=this.toDateValue(t),c.value=this.toTimeValue(t)),this.renderAssignSection(e);let l=e.createDiv({cls:"stashpad-due-grid"}),g=(f,C)=>{let m=l.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});m.onclick=()=>{let E=C();o.value=this.toDateValue(E),c.value||(c.value=this.toTimeValue(E))}},p=f=>(f.setHours(9,0,0,0),f);g("Today",()=>p(this.startOfTodayLocal())),g("Tomorrow",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+1),p(f)}),g("Next week",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+7),p(f)});let d=l.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});d.onclick=()=>{o.value="",c.value="",o.focus()};let I=l.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});I.onclick=()=>{this.didChoose=!0,this.close()};let u=l.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});u.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[f,C,m]=o.value.split("-").map(F=>parseInt(F,10)),E=9,w=0;if(c.value){let[F,D]=c.value.split(":").map(L=>parseInt(L,10));E=F,w=D}let y=new Date(f,C-1,m,E,w,0,0);this.didChoose=!0,this.close(),this.onPick({iso:y.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){ls(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let i=9,s=0;if(e.value){let[d,I]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(d)&&(i=d),Number.isFinite(I)&&(s=I)}else{let d=new Date;i=d.getHours(),s=d.getMinutes()}let n=i>=12?"pm":"am",o=i===0?12:i>12?i-12:i,a=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});a.style.position="fixed",a.style.zIndex="9999";let r=null,c=()=>{a.remove(),document.removeEventListener("mousedown",l,!0),document.removeEventListener("keydown",g,!0),this.tinyClosePopover===c&&(this.tinyClosePopover=null)},l=d=>{!a.contains(d.target)&&d.target!==t&&!t.contains(d.target)&&c()},g=d=>{d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),c()):d.key==="Enter"&&r&&(d.preventDefault(),d.stopPropagation(),r())};this.tinyClosePopover=c,hi(a,{seedH:o,seedM:s,seedPeriod:n,close:c,setOnEnter:d=>{r=d},onFinalize:d=>{e.value=`${String(d.hours24).padStart(2,"0")}:${String(d.minutes).padStart(2,"0")}`}});let p=t.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(p.left,window.innerWidth-220))}px`,a.style.top=`${p.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",l,!0),document.addEventListener("keydown",g,!0)},0)}startOfTodayLocal(){let t=new Date;return t.setHours(0,0,0,0),t}toDateValue(t){let e=t.getFullYear(),i=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0");return`${e}-${i}-${s}`}toTimeValue(t){let e=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${e}:${i}`}},ce=class ce extends ct.Modal{constructor(t,e,i,s=null,n){super(t);this.service=e;this.openLog=i;this.currentAuthorId=s;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 i=t.createEl("button",{text:"Open log"});i.title="Open the per-folder Stashpad log for the most recent notification's folder.",i.onclick=()=>{let s=this.records.find(n=>!!n.folder);this.openLog?.(s?.folder)}}let e=t.createEl("button",{cls:"mod-warning",text:"Clear history"});e.onclick=()=>{new vt(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",i=>{i&&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 s of this.records)s.authorId&&s.authorId!==this.currentAuthorId&&e.add(s.authorId);if(e.size>0){let s=t.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});s.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 i of t.affectedAuthorIds??[])if(i&&i!==e)return!0;if(!this.getNoteAuthorIds)return!1;for(let i of t.affectedIds){let s=this.getNoteAuthorIds(i);for(let n of s)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 i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All categories (${this.records.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});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(ce.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let c=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let l of e.actionLabels){let g=c.createSpan({cls:"stashpad-notif-action-chip"});g.setText(l),g.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(ce.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(ce.PAGE),this.renderFooter()},t>ce.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};ce.PAGE=100;ze=ce,cs=class extends ct.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 i=t.createDiv({cls:"stashpad-import-log-row"}),s=(0,ct.moment)(e.ts).format("YYYY-MM-DD HH:mm");i.createSpan({cls:"stashpad-import-log-when",text:s});let n=e.kind==="folder"?"folder":e.kind==="md"?"note":"file";i.createSpan({cls:`stashpad-import-log-kind is-${e.kind}`,text:n}),i.createSpan({cls:"stashpad-import-log-name",text:e.originalName});let o=[e.folder.split("/").pop()||e.folder];e.notePaths.length>1&&o.push(`${e.notePaths.length} notes`),i.createSpan({cls:"stashpad-import-log-meta",text:o.join(" \xB7 ")})}}onClose(){this.contentEl.empty()}},Ve=class extends ct.Modal{constructor(t,e,i){super(t);this.message=e;this.onChoose=i;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 o of this.message.split(` -`))t.createDiv({cls:"stashpad-confirm-line",text:o});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Skip duplicates"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let s=e.createEl("button",{text:"Replace existing"});s.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 Dt(h,A=Pt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(h.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function bt(h,A){return`${h}-${A}.md`}function Be(h){let A=h.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var Pt,me=se(()=>{"use strict";Pt=["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 mi={};ci(mi,{JdBuildConfirmModal:()=>Ze,buildJdIndexNotes:()=>hs,buildJdIndexPreview:()=>Ci,buildJdPreviewNotice:()=>Bi,scanForJdNotes:()=>Qe});function ds(h,A){if(/^\d+-\d+$/.test(h))return null;if(h.includes(".")){let e=h.split(".").slice(0,-1).join(".");return A.has(e)?e:ds(e,A)}if(/^\d+$/.test(h)){let t=parseInt(h,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function Qe(h,A,t){let e=h.vault.getMarkdownFiles(),i=Fo(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=d=>s?!1:Array.from(n).some(I=>d===I||d.startsWith(I+"/")),a=[],r=[],c=[];for(let d of i){let I=d.parent?.path?.replace(/\/+$/,"")??"";if(o(I)){c.push(d);continue}let u=d.basename.match(an);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:d,folder:null}):r.push(d)}let l=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=d=>{let I=d.path.replace(/\/+$/,"");if(!(l&&I&&I!==l&&!I.startsWith(l+"/"))){if(I&&!o(I)){let u=d.name.match(an);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:d})}}for(let u of d.children)u instanceof Ft.TFolder&&g(u)};g(h.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((d,I)=>vo(d,I,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:c}}async function Ci(h,A,t){let e=gs(t.jdIndexStashpadFolder??"");if(!e)return{...Qe(h,A,t),previewPath:null,error:"no-dest"};let i=Qe(h,A,t),s=wo(h,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=ko(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await h.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await h.vault.modify(s,r),{...i,previewPath:s.path}}function wo(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof Ft.TFolder))return null;for(let e of t.children){if(!(e instanceof Ft.TFile)||e.extension!=="md")continue;if((h.metadataCache.getFileCache(e)?.frontmatter??{}).id===U)return e}return null}async function hs(h,A,t){let e=gs(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(A.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let s=Qe(h,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let C=1;C{r.push(f);for(let C of a.get(f)??[])c(C)};for(let f of o)c(f);let l=new Map,g=h.vault.getAbstractFileByPath(e);if(g instanceof Ft.TFolder)for(let f of g.children){if(!(f instanceof Ft.TFile)||f.extension!=="md")continue;let C=h.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&l.set(C.jdPrefix,f)}let p=new Map,d=0,I=0,u=0;for(let f of r){let C=n.get(f)??null,m=ds(f,new Set(n.keys())),E=m?p.get(m)??U:U,w=C?`${f} ${C.title}`:f,y=C?.file?`[[${C.file.basename}]]`:"",F=y?`${y} +`),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 lt.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 i=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});i.onmousedown=n=>n.preventDefault(),i.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let s=this.contentEl.createDiv({cls:"stashpad-split-help"});lt.Platform.isMobile?s.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):s.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 s=Math.max(1,Math.min(this.lines.length-1,e));s!==this.lineCursorIdx&&(this.lineCursorIdx=s,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 i=parseFloat(getComputedStyle(e).lineHeight)||22,s=lt.Platform.isMobile?3:12,n=2,o=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,i*s+16);e.style.height=`${Math.max(a,i*n+16)}px`};requestAnimationFrame(()=>{o();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",o)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},qe=class extends lt.Modal{constructor(t,e,i,s,n){super(t);this.defaultBaseName=e;this.noteCount=i;this.onConfirm=s;this.kdfProbe=n;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Export to .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`${this.noteCount} note${this.noteCount===1?"":"s"} will be bundled into a single .stash file.`});let t=this.contentEl.createDiv({cls:"stashpad-export-field"});t.createEl("label",{cls:"stashpad-export-label",text:"File name"});let e=t.createEl("input",{type:"text"});e.addClass("stashpad-export-name"),e.value=this.defaultBaseName;let i=this.contentEl.createEl("div",{cls:"stashpad-export-preview"}),s=this.contentEl.createDiv({cls:"stashpad-export-encrypt"}),n=s.createDiv({cls:"stashpad-export-toggle"}),o=n.createEl("input",{type:"checkbox"});o.id="stashpad-export-encrypt-cb";let a=n.createEl("label",{text:"Encrypt with a password"});a.htmlFor=o.id;let r=s.createDiv({cls:"stashpad-export-pw-area"});r.style.display="none";let l=[],c=K=>{let z=r.createDiv({cls:"stashpad-export-pw-row"}),ot=z.createEl("input",{type:"password"});ot.addClass("stashpad-export-name"),ot.placeholder=K;let pt=z.createEl("button",{cls:"stashpad-export-copy"}),st=()=>{let at=ot.value.length===0;pt.setText(at?"Paste":"Copy"),pt.toggleClass("is-paste",at),pt.setAttr("aria-label",`${at?"Paste into":"Copy"} ${K.toLowerCase()}`)};return pt.onclick=async at=>{if(at.preventDefault(),ot.value.length===0)try{let At=(await navigator.clipboard?.readText())?.trim();if(!At){new lt.Notice("Clipboard is empty.");return}ot.value=At,ot.dispatchEvent(new Event("input")),new lt.Notice("Pasted from clipboard.")}catch{new lt.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(ot.value).then(()=>new lt.Notice("Passphrase copied to clipboard."),()=>new lt.Notice("Couldn't access the clipboard."))},st(),l.push(st),ot},g=c("Password"),p=c("Confirm password"),d=r.createDiv({cls:"stashpad-export-strength"}),I=d.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),f=d.createEl("span",{cls:"stashpad-strength-label"}),C=r.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),E=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=r.createEl("div",{cls:"stashpad-export-pw-hint"}),y=r.createEl("div",{cls:"stashpad-export-pw-suite"});y.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(K=>{y.toggleClass("is-weak",!K),y.setText(K?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run on this device, so this export will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>{y.setText("Encryption: AES-256-GCM with a password-derived key.")}):y.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let F=this.app.secretStorage,D=r.createDiv({cls:"stashpad-export-remember"}),L=D.createEl("input",{type:"checkbox"});L.id="stashpad-export-remember-cb";let S=D.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});S.htmlFor=L.id;let b=r.createDiv({cls:"stashpad-export-remember-note"});b.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),b.style.display="none",L.onchange=()=>{b.style.display=L.checked?"":"none"},F||(D.style.display="none");let Q=()=>{let K=e.value.trim()||this.defaultBaseName;return o.checked?`${K}-encrypted`:K},H=()=>i.setText(`Saves as: ${Q()}-.stash`);e.oninput=H;let $=this.contentEl.createDiv({cls:"stashpad-export-footer"}),M=$.createEl("button",{text:"Cancel"});M.onclick=()=>this.close();let T=$.createEl("button",{cls:"mod-cta",text:"Export"}),J=()=>{let K=nn(g.value);d.style.visibility=g.value?"visible":"hidden",u.forEach((z,ot)=>z.toggleClass("is-on",g.value!==""&&ot<=K.level)),I.dataset.level=String(K.level),f.setText(K.label)},Z=()=>{let K=o.checked;r.style.display=K?"":"none";let z=!0;K&&(g.value?g.value!==p.value?(w.setText("Passwords don't match."),w.addClass("is-error"),z=!1):(w.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),w.removeClass("is-error")):(w.setText("Enter a password to encrypt this export."),w.removeClass("is-error"),z=!1)),J(),l.forEach(ot=>ot()),T.disabled=!z,T.toggleClass("is-disabled",!z),H()},G=!1,N=K=>{G=K,g.type=p.type=K?"text":"password",E.setText(K?"Hide":"Show")};E.onclick=K=>{K.preventDefault(),N(!G)},m.onclick=K=>{K.preventDefault(),g.value=p.value=sn(),N(!1),new lt.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),Z()},o.onchange=Z,g.oninput=Z,p.oninput=Z,Z();let _=()=>this.commit(Q(),o.checked?g.value:null,o.checked&&L.checked);T.onclick=_,this.scope.register([],"Enter",K=>{K.preventDefault(),T.disabled||_()}),requestAnimationFrame(()=>{e.focus(),e.select()})}commit(t,e,i){let s=t.trim()||this.defaultBaseName,n=e&&e.length?e:null;this.delivered=!0,this.close(),this.onConfirm(s,n,!!n&&i)}onClose(){this.contentEl.empty()}},Oe=class extends lt.Modal{constructor(t,e,i,s){super(t);this.errorMsg=e;this.allowLater=i;this.onResult=s;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Encrypted .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This export is password-protected. Enter its password to import it."}),this.errorMsg&&this.contentEl.createEl("div",{cls:"stashpad-export-error",text:this.errorMsg});let t=this.contentEl.createEl("input",{type:"password"});t.addClass("stashpad-export-name"),t.placeholder="Password";let e=this.contentEl.createDiv({cls:"stashpad-export-footer"});if(e.createEl("button",{text:"Cancel"}).onclick=()=>this.close(),this.allowLater){let s=e.createEl("button",{text:"Remind me later"});s.title="Don't import now \u2014 surface the reminder again later.",s.onclick=()=>this.finish({kind:"later"})}let i=e.createEl("button",{cls:"mod-cta",text:"Decrypt & import"});i.onclick=()=>this.submit(t.value),this.scope.register([],"Enter",s=>{s.preventDefault(),this.submit(t.value)}),requestAnimationFrame(()=>t.focus())}submit(t){t&&this.finish({kind:"password",value:t})}finish(t){this.delivered=!0,this.close(),this.onResult(t)}onClose(){this.delivered||(this.delivered=!0,this.onResult({kind:"cancel"})),this.contentEl.empty()}},Ii=class extends lt.Modal{constructor(t,e,i){super(t);this.onResult=i;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 i=t.createEl("input",{type:"color"});i.value=this.value,i.addClass("stashpad-custom-color-wheel"),e.onclick=()=>i.click();let s=t.createEl("input",{type:"text"});s.addClass("stashpad-custom-color-hex"),s.placeholder="#RRGGBB",s.value=this.value,s.maxLength=7;let n=c=>{let g=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(g)&&(this.value=g,e.style.background=g,i.value=g,s.value!==g&&(s.value=g))};i.oninput=()=>n(i.value),s.oninput=()=>n(s.value);let o=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=o.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let r=o.createEl("button",{cls:"mod-cta",text:"Save"});r.title="Apply this color to the selection (without adding to your palette).",r.onclick=()=>this.commit({addToPalette:!1});let l=o.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(()=>s.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()}},Le=class Le extends lt.Modal{constructor(t,e,i,s,n){super(t);this.currentColor=e;this.customPalette=i;this.onPick=s;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 i=[...Le.DEFAULT_PALETTE,...this.customPalette];for(let a of i){let r=t.createDiv({cls:"stashpad-color-tile"});r.style.background=a,r.title=a;let l=!Le.DEFAULT_PALETTE.some(g=>g.toLowerCase()===a.toLowerCase()),c=this.items.length;if(r.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let g=r.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});g.title="Remove from palette",g.onclick=p=>{p.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:l?"custom":"preset",color:a,el:r})}let s=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});s.title="Custom color\u2026";let n=this.items.length;s.onclick=()=>this.activate(n),this.items.push({kind:"add",color:null,el:s});let o=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=o>=0?o: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 Ii(this.app,this.currentColor,(i,s)=>{this.onPick(i,s)}).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(),i=this.items[0].el.getBoundingClientRect();if(i.width<=0)return 1;let s=i.top,n=0;for(let o of this.items){let a=o.el.getBoundingClientRect();if(Math.abs(a.top-s)<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(i=>i.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 s=e.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};Ke=class extends lt.Modal{constructor(t,e,i){super(t);this.opts=e;this.onPick=i;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"});cs(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Cancel"});i.onclick=()=>{this.didChoose=!0,this.close()};let s=e.createEl("button",{cls:"mod-cta",text:"Save"});s.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},Ye=class extends lt.Modal{constructor(t,e,i,s={}){super(t);this.current=e;this.onPick=i;this.opts=s;this.didChoose=!1;this.assignees=[];this.tinyClosePopover=null;this.assignees=[...s.currentAssignees??[]]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Set due date");let t=null;if(this.current){let f=Date.parse(this.current);Number.isNaN(f)||(t=new Date(f))}let e=this.contentEl.createDiv({cls:"stashpad-due-picker"}),i=e.createDiv({cls:"stashpad-due-fields"}),s=i.createDiv({cls:"stashpad-due-field"}),n=s.createSpan({cls:"stashpad-due-field-icon"});(0,lt.setIcon)(n,"calendar");let o=s.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=i.createDiv({cls:"stashpad-due-field"}),r=a.createSpan({cls:"stashpad-due-field-icon"});(0,lt.setIcon)(r,"clock");let l=a.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{o.showPicker?.()}catch{}},r.onclick=()=>this.openTimeNumpad(r,l),t&&(o.value=this.toDateValue(t),l.value=this.toTimeValue(t)),this.renderAssignSection(e);let c=e.createDiv({cls:"stashpad-due-grid"}),g=(f,C)=>{let m=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});m.onclick=()=>{let E=C();o.value=this.toDateValue(E),l.value||(l.value=this.toTimeValue(E))}},p=f=>(f.setHours(9,0,0,0),f);g("Today",()=>p(this.startOfTodayLocal())),g("Tomorrow",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+1),p(f)}),g("Next week",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+7),p(f)});let d=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});d.onclick=()=>{o.value="",l.value="",o.focus()};let I=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});I.onclick=()=>{this.didChoose=!0,this.close()};let u=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});u.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[f,C,m]=o.value.split("-").map(F=>parseInt(F,10)),E=9,w=0;if(l.value){let[F,D]=l.value.split(":").map(L=>parseInt(L,10));E=F,w=D}let y=new Date(f,C-1,m,E,w,0,0);this.didChoose=!0,this.close(),this.onPick({iso:y.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){cs(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let i=9,s=0;if(e.value){let[d,I]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(d)&&(i=d),Number.isFinite(I)&&(s=I)}else{let d=new Date;i=d.getHours(),s=d.getMinutes()}let n=i>=12?"pm":"am",o=i===0?12:i>12?i-12:i,a=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});a.style.position="fixed",a.style.zIndex="9999";let r=null,l=()=>{a.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",g,!0),this.tinyClosePopover===l&&(this.tinyClosePopover=null)},c=d=>{!a.contains(d.target)&&d.target!==t&&!t.contains(d.target)&&l()},g=d=>{d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),l()):d.key==="Enter"&&r&&(d.preventDefault(),d.stopPropagation(),r())};this.tinyClosePopover=l,hi(a,{seedH:o,seedM:s,seedPeriod:n,close:l,setOnEnter:d=>{r=d},onFinalize:d=>{e.value=`${String(d.hours24).padStart(2,"0")}:${String(d.minutes).padStart(2,"0")}`}});let p=t.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(p.left,window.innerWidth-220))}px`,a.style.top=`${p.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",c,!0),document.addEventListener("keydown",g,!0)},0)}startOfTodayLocal(){let t=new Date;return t.setHours(0,0,0,0),t}toDateValue(t){let e=t.getFullYear(),i=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0");return`${e}-${i}-${s}`}toTimeValue(t){let e=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${e}:${i}`}},le=class le extends lt.Modal{constructor(t,e,i,s=null,n){super(t);this.service=e;this.openLog=i;this.currentAuthorId=s;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 i=t.createEl("button",{text:"Open log"});i.title="Open the per-folder Stashpad log for the most recent notification's folder.",i.onclick=()=>{let s=this.records.find(n=>!!n.folder);this.openLog?.(s?.folder)}}let e=t.createEl("button",{cls:"mod-warning",text:"Clear history"});e.onclick=()=>{new vt(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",i=>{i&&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 s of this.records)s.authorId&&s.authorId!==this.currentAuthorId&&e.add(s.authorId);if(e.size>0){let s=t.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});s.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 i of t.affectedAuthorIds??[])if(i&&i!==e)return!0;if(!this.getNoteAuthorIds)return!1;for(let i of t.affectedIds){let s=this.getNoteAuthorIds(i);for(let n of s)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 i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All categories (${this.records.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});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(le.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let l=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let c of e.actionLabels){let g=l.createSpan({cls:"stashpad-notif-action-chip"});g.setText(c),g.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(le.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(le.PAGE),this.renderFooter()},t>le.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};le.PAGE=100;ze=le,ls=class extends lt.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 i=t.createDiv({cls:"stashpad-import-log-row"}),s=(0,lt.moment)(e.ts).format("YYYY-MM-DD HH:mm");i.createSpan({cls:"stashpad-import-log-when",text:s});let n=e.kind==="folder"?"folder":e.kind==="md"?"note":"file";i.createSpan({cls:`stashpad-import-log-kind is-${e.kind}`,text:n}),i.createSpan({cls:"stashpad-import-log-name",text:e.originalName});let o=[e.folder.split("/").pop()||e.folder];e.notePaths.length>1&&o.push(`${e.notePaths.length} notes`),i.createSpan({cls:"stashpad-import-log-meta",text:o.join(" \xB7 ")})}}onClose(){this.contentEl.empty()}},Ve=class extends lt.Modal{constructor(t,e,i){super(t);this.message=e;this.onChoose=i;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 o of this.message.split(` +`))t.createDiv({cls:"stashpad-confirm-line",text:o});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Skip duplicates"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let s=e.createEl("button",{text:"Replace existing"});s.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 Dt(h,A=Pt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(h.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function bt(h,A){return`${h}-${A}.md`}function Be(h){let A=h.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var Pt,me=se(()=>{"use strict";Pt=["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 mi={};li(mi,{JdBuildConfirmModal:()=>Ze,buildJdIndexNotes:()=>hs,buildJdIndexPreview:()=>Ci,buildJdPreviewNotice:()=>Bi,scanForJdNotes:()=>Qe});function ds(h,A){if(/^\d+-\d+$/.test(h))return null;if(h.includes(".")){let e=h.split(".").slice(0,-1).join(".");return A.has(e)?e:ds(e,A)}if(/^\d+$/.test(h)){let t=parseInt(h,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function Qe(h,A,t){let e=h.vault.getMarkdownFiles(),i=Fo(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=d=>s?!1:Array.from(n).some(I=>d===I||d.startsWith(I+"/")),a=[],r=[],l=[];for(let d of i){let I=d.parent?.path?.replace(/\/+$/,"")??"";if(o(I)){l.push(d);continue}let u=d.basename.match(an);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:d,folder:null}):r.push(d)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=d=>{let I=d.path.replace(/\/+$/,"");if(!(c&&I&&I!==c&&!I.startsWith(c+"/"))){if(I&&!o(I)){let u=d.name.match(an);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:d})}}for(let u of d.children)u instanceof Ft.TFolder&&g(u)};g(h.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((d,I)=>vo(d,I,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:l}}async function Ci(h,A,t){let e=gs(t.jdIndexStashpadFolder??"");if(!e)return{...Qe(h,A,t),previewPath:null,error:"no-dest"};let i=Qe(h,A,t),s=wo(h,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=ko(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await h.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await h.vault.modify(s,r),{...i,previewPath:s.path}}function wo(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof Ft.TFolder))return null;for(let e of t.children){if(!(e instanceof Ft.TFile)||e.extension!=="md")continue;if((h.metadataCache.getFileCache(e)?.frontmatter??{}).id===U)return e}return null}async function hs(h,A,t){let e=gs(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(A.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let s=Qe(h,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let C=1;C{r.push(f);for(let C of a.get(f)??[])l(C)};for(let f of o)l(f);let c=new Map,g=h.vault.getAbstractFileByPath(e);if(g instanceof Ft.TFolder)for(let f of g.children){if(!(f instanceof Ft.TFile)||f.extension!=="md")continue;let C=h.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&c.set(C.jdPrefix,f)}let p=new Map,d=0,I=0,u=0;for(let f of r){let C=n.get(f)??null,m=ds(f,new Set(n.keys())),E=m?p.get(m)??U:U,w=C?`${f} ${C.title}`:f,y=C?.file?`[[${C.file.basename}]]`:"",F=y?`${y} `:`${w} -`,D=l.get(f);if(D){try{let L=null;await h.fileManager.processFrontMatter(D,H=>{H.jdPrefix=f,E&&(H.parent=E),(!H.id||typeof H.id!="string")&&(H.id=yt()),H.created||(H.created=new Date().toISOString()),H.attachments||(H.attachments=[]),L=H.id});let b=(await h.vault.read(D)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=b?`${b[0]}${F}`:F;await h.vault.modify(D,Q),L&&p.set(f,L),I++}catch(L){console.error("[stashpad] buildJdIndexNotes: update failed",L),u++}continue}try{let L=yt();p.set(f,L);let S=Dt(w,t.slugStopWords),b=bt(S,L),Q=`${e}/${b}`,H=["---",`id: ${L}`,`parent: ${E}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` -`);await h.vault.create(Q,H+F),d++}catch(L){console.error("[stashpad] buildJdIndexNotes: create failed for",f,L),u++}}return{created:d,updated:I,skipped:u,destFolder:e}}function gs(h){return(h||"").trim().replace(/^\/+|\/+$/g,"")}function Fo(h,A){if((A.jdIndexScope??"vault")==="vault")return h;let t=gs(A.jdIndexScopeFolder??"");return t?h.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):h}function vo(h,A,t){if(t==="created"){let e=h.file.stat?.ctime??0,i=A.file.stat?.ctime??0;if(e!==i)return e-i}return An(h.segments,A.segments)}function rn(h,A){let t=h.match(/^(\d+)-(\d+)$/),e=A.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:h.split("."),s=e?[e[1]]:A.split(".");return An(i,s)}function An(h,A){let t=Math.min(h.length,A.length);for(let e=0;e{s.set(o,a);for(let r of e.get(o)??[])n(r,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function ko(h,A,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),h.length===0){let s=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(s)}else{let s=new Map;for(let c of h)s.set(c.prefix,c);for(let c of h)if(c.prefix.includes("."))for(let l=1;l{let l=s.get(c),g=a.get(c)??0,p=" ".repeat(g),d=i(g),I=l?.folder?` ${l.title} _(folder)_`:(l?.file,"");l?.file?e.push(`${p}- ${d} [[${l.file.basename}|${l.prefix} ${l.title}]]`):l?.folder?e.push(`${p}- ${d} ${l.prefix}${I}`):e.push(`${p}- ${d} ${c}`);for(let u of o.get(c)??[])r(u)};for(let c of n)r(c)}if(A.length>0){e.push(""),e.push(`# Non-indexed (${A.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 s of A)e.push(`- # [[${s.basename}]] \xB7 \`${s.path}\``)}if(t.length>0){let s=new Map;for(let o of t){let a=o.parent?.path?.replace(/\/+$/,"")??"";s.set(a,(s.get(a)??0)+1)}let n=Array.from(s.entries()).sort((o,a)=>o[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[o,a]of n)e.push(`- # All ${a} file${a===1?"":"s"} in \`${o||"(vault root)"}\``)}return e.join(` +`,D=c.get(f);if(D){try{let L=null;await h.fileManager.processFrontMatter(D,H=>{H.jdPrefix=f,E&&(H.parent=E),(!H.id||typeof H.id!="string")&&(H.id=yt()),H.created||(H.created=new Date().toISOString()),H.attachments||(H.attachments=[]),L=H.id});let b=(await h.vault.read(D)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=b?`${b[0]}${F}`:F;await h.vault.modify(D,Q),L&&p.set(f,L),I++}catch(L){console.error("[stashpad] buildJdIndexNotes: update failed",L),u++}continue}try{let L=yt();p.set(f,L);let S=Dt(w,t.slugStopWords),b=bt(S,L),Q=`${e}/${b}`,H=["---",`id: ${L}`,`parent: ${E}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` +`);await h.vault.create(Q,H+F),d++}catch(L){console.error("[stashpad] buildJdIndexNotes: create failed for",f,L),u++}}return{created:d,updated:I,skipped:u,destFolder:e}}function gs(h){return(h||"").trim().replace(/^\/+|\/+$/g,"")}function Fo(h,A){if((A.jdIndexScope??"vault")==="vault")return h;let t=gs(A.jdIndexScopeFolder??"");return t?h.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):h}function vo(h,A,t){if(t==="created"){let e=h.file.stat?.ctime??0,i=A.file.stat?.ctime??0;if(e!==i)return e-i}return An(h.segments,A.segments)}function rn(h,A){let t=h.match(/^(\d+)-(\d+)$/),e=A.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:h.split("."),s=e?[e[1]]:A.split(".");return An(i,s)}function An(h,A){let t=Math.min(h.length,A.length);for(let e=0;e<t;e++){let i=h[e],s=A[e],n=/^\d+$/.test(i),o=/^\d+$/.test(s);if(n&&o){let a=parseInt(i,10)-parseInt(s,10);if(a!==0)return a}else{if(n&&!o)return-1;if(!n&&o)return 1;{let a=i.localeCompare(s,void 0,{numeric:!0,sensitivity:"base"});if(a!==0)return a}}}return h.length-A.length}function ln(h){let A=new Set(h.keys()),t=new Map,e=new Map;for(let o of A){let a=ds(o,A);if(t.set(o,a),a!==null){let r=e.get(a)??[];r.push(o),e.set(a,r)}}let i=[];for(let o of A)t.get(o)===null&&i.push(o);i.sort(rn);for(let o of e.values())o.sort(rn);let s=new Map,n=(o,a)=>{s.set(o,a);for(let r of e.get(o)??[])n(r,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function ko(h,A,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),h.length===0){let s=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(s)}else{let s=new Map;for(let l of h)s.set(l.prefix,l);for(let l of h)if(l.prefix.includes("."))for(let c=1;c<l.segments.length;c++){let g=l.segments.slice(0,c).join(".");s.has(g)||s.set(g,null)}let{roots:n,childrenOf:o,depthOf:a}=ln(s),r=l=>{let c=s.get(l),g=a.get(l)??0,p=" ".repeat(g),d=i(g),I=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${p}- ${d} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${p}- ${d} ${c.prefix}${I}`):e.push(`${p}- ${d} ${l}`);for(let u of o.get(l)??[])r(u)};for(let l of n)r(l)}if(A.length>0){e.push(""),e.push(`# Non-indexed (${A.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 s of A)e.push(`- # [[${s.basename}]] \xB7 \`${s.path}\``)}if(t.length>0){let s=new Map;for(let o of t){let a=o.parent?.path?.replace(/\/+$/,"")??"";s.set(a,(s.get(a)??0)+1)}let n=Array.from(s.entries()).sort((o,a)=>o[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[o,a]of n)e.push(`- # All ${a} file${a===1?"":"s"} in \`${o||"(vault root)"}\``)}return e.join(` `)+` -`}function Bi(h,A){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let i=t.createEl("ul");i.style.margin="0 0 8px 0",i.style.paddingLeft="18px",i.createEl("li",{text:`${A.indexed.length} indexed`}),i.createEl("li",{text:`${A.nonIndex.length+A.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.style.padding="2px 10px",s.style.fontSize="var(--font-ui-smaller)";let n;return s.onclick=async o=>{if(o.stopPropagation(),A.previewPath){let a=h.vault.getAbstractFileByPath(A.previewPath);a instanceof Ft.TFile&&await h.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new Ft.Notice(t,0),n}var Ft,an,Ze,$e=se(()=>{"use strict";Ft=require("obsidian");Rt();me();wt();an=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ze=class extends Ft.Modal{constructor(t,e,i,s,n){super(t);this.plugin=e;this.settings=i;this.indexedCount=s;this.onBuild=n;this.LARGE_BUILD=50;this.previewRan=!1;this.previewPath=null}onOpen(){let{contentEl:t,titleEl:e}=this,i=!this.settings.jdIndexHasBuilt,s=this.indexedCount>this.LARGE_BUILD;e.setText(i?"Build JD index \u2014 first time?":"Build JD index");let n=this.settings.jdIndexStashpadFolder,o=t.createEl("p"),a=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;i?(o.appendText(`Stashpad is about to create ${a} (plus synthetic parents as needed) inside "`),o.createEl("code",{text:n}),o.appendText('". Existing notes with the same '),o.createEl("code",{text:"jdPrefix"}),o.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.")):s?(o.appendText(`You're about to create ${this.indexedCount} notes in "`),o.createEl("code",{text:n}),o.appendText(`". That's a big batch \u2014 if anything looks off, Preview the single-file output first.`)):(o.appendText('Build the JD index into "'),o.createEl("code",{text:n}),o.appendText(`"? Stashpad will create / update ${a}. Existing notes with matching `),o.createEl("code",{text:"jdPrefix"}),o.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 r=new Ft.Setting(t);(i||s)&&r.addButton(c=>{c.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),c.setCta(),c.onClick(async()=>{try{let l=await Ci(this.app,this.plugin,this.settings);if(l.error==="no-dest"){new Ft.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(l.error==="no-home"){new Ft.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=l.previewPath,Bi(this.app,l),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(l){new Ft.Notice(`Preview failed: ${l?.message??l}`,8e3)}})}),r.addButton(c=>{c.setButtonText(i?"Build anyway":"Build"),!i&&!s&&c.setCta(),c.onClick(async()=>{this.close(),await this.onBuild()})}),r.addButton(c=>{c.setButtonText("Cancel"),c.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var Mn=fo((xn,vs)=>{(function(h){typeof xn=="object"&&typeof vs<"u"?vs.exports=h():typeof define=="function"&&define.amd?define([],h):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=h()})(function(){return function h(A,t,e){function i(o,a){if(!t[o]){if(!A[o]){var r=typeof require=="function"&&require;if(!a&&r)return r(o,!0);if(s)return s(o,!0);var c=new Error("Cannot find module '"+o+"'");throw c.code="MODULE_NOT_FOUND",c}var l=t[o]={exports:{}};A[o][0].call(l.exports,function(g){var p=A[o][1][g];return i(p||g)},l,l.exports,h,A,t,e)}return t[o].exports}for(var s=typeof require=="function"&&require,n=0;n<e.length;n++)i(e[n]);return i}({1:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,c,l,g,p,d=[],I=0,u=n.length,f=u,C=e.getTypeOf(n)!=="string";I<n.length;)f=u-I,r=C?(o=n[I++],a=I<u?n[I++]:0,I<u?n[I++]:0):(o=n.charCodeAt(I++),a=I<u?n.charCodeAt(I++):0,I<u?n.charCodeAt(I++):0),c=o>>2,l=(3&o)<<4|a>>4,g=1<f?(15&a)<<2|r>>6:64,p=2<f?63&r:64,d.push(s.charAt(c)+s.charAt(l)+s.charAt(g)+s.charAt(p));return d.join("")},t.decode=function(n){var o,a,r,c,l,g,p=0,d=0,I="data:";if(n.substr(0,I.length)===I)throw new Error("Invalid base64 input, it looks like a data url.");var u,f=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===s.charAt(64)&&f--,n.charAt(n.length-2)===s.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=i.uint8array?new Uint8Array(0|f):new Array(0|f);p<n.length;)o=s.indexOf(n.charAt(p++))<<2|(c=s.indexOf(n.charAt(p++)))>>4,a=(15&c)<<4|(l=s.indexOf(n.charAt(p++)))>>2,r=(3&l)<<6|(g=s.indexOf(n.charAt(p++))),u[d++]=o,l!==64&&(u[d++]=a),g!==64&&(u[d++]=r);return u}},{"./support":30,"./utils":32}],2:[function(h,A,t){"use strict";var e=h("./external"),i=h("./stream/DataWorker"),s=h("./stream/Crc32Probe"),n=h("./stream/DataLengthProbe");function o(a,r,c,l,g){this.compressedSize=a,this.uncompressedSize=r,this.crc32=c,this.compression=l,this.compressedContent=g}o.prototype={getContentWorker:function(){var a=new i(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),r=this;return a.on("end",function(){if(this.streamInfo.data_length!==r.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new i(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(a,r,c){return a.pipe(new s).pipe(new n("uncompressedSize")).pipe(r.compressWorker(c)).pipe(new n("compressedSize")).withStreamInfo("compression",r)},A.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(h,A,t){"use strict";var e=h("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=h("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(h,A,t){"use strict";var e=h("./utils"),i=function(){for(var s,n=[],o=0;o<256;o++){s=o;for(var a=0;a<8;a++)s=1&s?3988292384^s>>>1:s>>>1;n[o]=s}return n}();A.exports=function(s,n){return s!==void 0&&s.length?e.getTypeOf(s)!=="string"?function(o,a,r,c){var l=i,g=c+r;o^=-1;for(var p=c;p<g;p++)o=o>>>8^l[255&(o^a[p])];return-1^o}(0|n,s,s.length,0):function(o,a,r,c){var l=i,g=c+r;o^=-1;for(var p=c;p<g;p++)o=o>>>8^l[255&(o^a.charCodeAt(p))];return-1^o}(0|n,s,s.length,0):0}},{"./utils":32}],5:[function(h,A,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(h,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:h("lie"),A.exports={Promise:e}},{lie:37}],7:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=h("pako"),s=h("./utils"),n=h("./stream/GenericWorker"),o=e?"uint8array":"array";function a(r,c){n.call(this,"FlateWorker/"+r),this._pako=null,this._pakoAction=r,this._pakoOptions=c,this.meta={}}t.magic="\b\0",s.inherits(a,n),a.prototype.processChunk=function(r){this.meta=r.meta,this._pako===null&&this._createPako(),this._pako.push(s.transformTo(o,r.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 i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var r=this;this._pako.onData=function(c){r.push({data:c,meta:r.meta})}},t.compressWorker=function(r){return new a("Deflate",r)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(h,A,t){"use strict";function e(l,g){var p,d="";for(p=0;p<g;p++)d+=String.fromCharCode(255&l),l>>>=8;return d}function i(l,g,p,d,I,u){var f,C,m=l.file,E=l.compression,w=u!==o.utf8encode,y=s.transformTo("string",u(m.name)),F=s.transformTo("string",o.utf8encode(m.name)),D=m.comment,L=s.transformTo("string",u(D)),S=s.transformTo("string",o.utf8encode(D)),b=F.length!==m.name.length,Q=S.length!==D.length,H="",$="",M="",T=m.dir,J=m.date,Z={crc32:0,compressedSize:0,uncompressedSize:0};g&&!p||(Z.crc32=l.crc32,Z.compressedSize=l.compressedSize,Z.uncompressedSize=l.uncompressedSize);var G=0;g&&(G|=8),w||!b&&!Q||(G|=2048);var N=0,_=0;T&&(N|=16),I==="UNIX"?(_=798,N|=function(z,ot){var pt=z;return z||(pt=ot?16893:33204),(65535&pt)<<16}(m.unixPermissions,T)):(_=20,N|=function(z){return 63&(z||0)}(m.dosPermissions)),f=J.getUTCHours(),f<<=6,f|=J.getUTCMinutes(),f<<=5,f|=J.getUTCSeconds()/2,C=J.getUTCFullYear()-1980,C<<=4,C|=J.getUTCMonth()+1,C<<=5,C|=J.getUTCDate(),b&&($=e(1,1)+e(a(y),4)+F,H+="up"+e($.length,2)+$),Q&&(M=e(1,1)+e(a(L),4)+S,H+="uc"+e(M.length,2)+M);var K="";return K+=` -\0`,K+=e(G,2),K+=E.magic,K+=e(f,2),K+=e(C,2),K+=e(Z.crc32,4),K+=e(Z.compressedSize,4),K+=e(Z.uncompressedSize,4),K+=e(y.length,2),K+=e(H.length,2),{fileRecord:r.LOCAL_FILE_HEADER+K+y+H,dirRecord:r.CENTRAL_FILE_HEADER+e(_,2)+K+e(L.length,2)+"\0\0\0\0"+e(N,4)+e(d,4)+y+H+L}}var s=h("../utils"),n=h("../stream/GenericWorker"),o=h("../utf8"),a=h("../crc32"),r=h("../signature");function c(l,g,p,d){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=p,this.encodeFileName=d,this.streamFiles=l,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(c,n),c.prototype.push=function(l){var g=l.meta.percent||0,p=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(l):(this.bytesWritten+=l.data.length,n.prototype.push.call(this,{data:l.data,meta:{currentFile:this.currentFile,percent:p?(g+100*(p-d-1))/p:100}}))},c.prototype.openedSource=function(l){this.currentSourceOffset=this.bytesWritten,this.currentFile=l.file.name;var g=this.streamFiles&&!l.file.dir;if(g){var p=i(l,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},c.prototype.closedSource=function(l){this.accumulate=!1;var g=this.streamFiles&&!l.file.dir,p=i(l,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),g)this.push({data:function(d){return r.DATA_DESCRIPTOR+e(d.crc32,4)+e(d.compressedSize,4)+e(d.uncompressedSize,4)}(l),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},c.prototype.flush=function(){for(var l=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var p=this.bytesWritten-l,d=function(I,u,f,C,m){var E=s.transformTo("string",m(C));return r.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(I,2)+e(I,2)+e(u,4)+e(f,4)+e(E.length,2)+E}(this.dirRecords.length,p,l,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},c.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},c.prototype.registerPrevious=function(l){this._sources.push(l);var g=this;return l.on("data",function(p){g.processChunk(p)}),l.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),l.on("error",function(p){g.error(p)}),this},c.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))},c.prototype.error=function(l){var g=this._sources;if(!n.prototype.error.call(this,l))return!1;for(var p=0;p<g.length;p++)try{g[p].error(l)}catch{}return!0},c.prototype.lock=function(){n.prototype.lock.call(this);for(var l=this._sources,g=0;g<l.length;g++)l[g].lock()},A.exports=c},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(h,A,t){"use strict";var e=h("../compressions"),i=h("./ZipFileWorker");t.generateWorker=function(s,n,o){var a=new i(n.streamFiles,o,n.platform,n.encodeFileName),r=0;try{s.forEach(function(c,l){r++;var g=function(u,f){var C=u||f,m=e[C];if(!m)throw new Error(C+" is not a valid compression method !");return m}(l.options.compression,n.compression),p=l.options.compressionOptions||n.compressionOptions||{},d=l.dir,I=l.date;l._compressWorker(g,p).withStreamInfo("file",{name:c,dir:d,date:I,comment:l.comment||"",unixPermissions:l.unixPermissions,dosPermissions:l.dosPermissions}).pipe(a)}),a.entriesCount=r}catch(c){a.error(c)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(h,A,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 i=new e;for(var s in this)typeof this[s]!="function"&&(i[s]=this[s]);return i}}(e.prototype=h("./object")).loadAsync=h("./load"),e.support=h("./support"),e.defaults=h("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=h("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./external"),s=h("./utf8"),n=h("./zipEntries"),o=h("./stream/Crc32Probe"),a=h("./nodejsUtils");function r(c){return new i.Promise(function(l,g){var p=c.decompressed.getContentWorker().pipe(new o);p.on("error",function(d){g(d)}).on("end",function(){p.streamInfo.crc32!==c.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):l()}).resume()})}A.exports=function(c,l){var g=this;return l=e.extend(l||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),a.isNode&&a.isStream(c)?i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",c,!0,l.optimizedBinaryString,l.base64).then(function(p){var d=new n(l);return d.load(p),d}).then(function(p){var d=[i.Promise.resolve(p)],I=p.files;if(l.checkCRC32)for(var u=0;u<I.length;u++)d.push(r(I[u]));return i.Promise.all(d)}).then(function(p){for(var d=p.shift(),I=d.files,u=0;u<I.length;u++){var f=I[u],C=f.fileNameStr,m=e.resolve(f.fileNameStr);g.file(m,f.decompressed,{binary:!0,optimizedBinaryString:!0,date:f.date,dir:f.dir,comment:f.fileCommentStr.length?f.fileCommentStr:null,unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions,createFolders:l.createFolders}),f.dir||(g.file(m).unsafeOriginalName=C)}return d.zipComment.length&&(g.comment=d.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../stream/GenericWorker");function s(n,o){i.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(o)}e.inherits(s,i),s.prototype._bindStream=function(n){var o=this;(this._stream=n).pause(),n.on("data",function(a){o.push({data:a,meta:{percent:0}})}).on("error",function(a){o.isPaused?this.generatedError=a:o.error(a)}).on("end",function(){o.isPaused?o._upstreamEnded=!0:o.end()})},s.prototype.pause=function(){return!!i.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},A.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(h,A,t){"use strict";var e=h("readable-stream").Readable;function i(s,n,o){e.call(this,n),this._helper=s;var a=this;s.on("data",function(r,c){a.push(r)||a._helper.pause(),o&&o(c)}).on("error",function(r){a.emit("error",r)}).on("end",function(){a.push(null)})}h("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(h,A,t){"use strict";A.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,i){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,i);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,i)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var i=new Buffer(e);return i.fill(0),i},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(h,A,t){"use strict";function e(m,E,w){var y,F=s.getTypeOf(E),D=s.extend(w||{},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&&(m=I(m)),D.createFolders&&(y=d(m))&&u.call(this,y,!0);var L=F==="string"&&D.binary===!1&&D.base64===!1;w&&w.binary!==void 0||(D.binary=!L),(E instanceof r&&E.uncompressedSize===0||D.dir||!E||E.length===0)&&(D.base64=!1,D.binary=!0,E="",D.compression="STORE",F="string");var S=null;S=E instanceof r||E instanceof n?E:g.isNode&&g.isStream(E)?new p(m,E):s.prepareContent(m,E,D.binary,D.optimizedBinaryString,D.base64);var b=new c(m,S,D);this.files[m]=b}var i=h("./utf8"),s=h("./utils"),n=h("./stream/GenericWorker"),o=h("./stream/StreamHelper"),a=h("./defaults"),r=h("./compressedObject"),c=h("./zipObject"),l=h("./generate"),g=h("./nodejsUtils"),p=h("./nodejs/NodejsStreamInputAdapter"),d=function(m){m.slice(-1)==="/"&&(m=m.substring(0,m.length-1));var E=m.lastIndexOf("/");return 0<E?m.substring(0,E):""},I=function(m){return m.slice(-1)!=="/"&&(m+="/"),m},u=function(m,E){return E=E!==void 0?E:a.createFolders,m=I(m),this.files[m]||e.call(this,m,null,{dir:!0,createFolders:E}),this.files[m]};function f(m){return Object.prototype.toString.call(m)==="[object RegExp]"}var C={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(m){var E,w,y;for(E in this.files)y=this.files[E],(w=E.slice(this.root.length,E.length))&&E.slice(0,this.root.length)===this.root&&m(w,y)},filter:function(m){var E=[];return this.forEach(function(w,y){m(w,y)&&E.push(y)}),E},file:function(m,E,w){if(arguments.length!==1)return m=this.root+m,e.call(this,m,E,w),this;if(f(m)){var y=m;return this.filter(function(D,L){return!L.dir&&y.test(D)})}var F=this.files[this.root+m];return F&&!F.dir?F:null},folder:function(m){if(!m)return this;if(f(m))return this.filter(function(F,D){return D.dir&&m.test(F)});var E=this.root+m,w=u.call(this,E),y=this.clone();return y.root=w.name,y},remove:function(m){m=this.root+m;var E=this.files[m];if(E||(m.slice(-1)!=="/"&&(m+="/"),E=this.files[m]),E&&!E.dir)delete this.files[m];else for(var w=this.filter(function(F,D){return D.name.slice(0,m.length)===m}),y=0;y<w.length;y++)delete this.files[w[y].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(m){var E,w={};try{if((w=s.extend(m||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:i.utf8encode})).type=w.type.toLowerCase(),w.compression=w.compression.toUpperCase(),w.type==="binarystring"&&(w.type="string"),!w.type)throw new Error("No output type specified.");s.checkSupport(w.type),w.platform!=="darwin"&&w.platform!=="freebsd"&&w.platform!=="linux"&&w.platform!=="sunos"||(w.platform="UNIX"),w.platform==="win32"&&(w.platform="DOS");var y=w.comment||this.comment||"";E=l.generateWorker(this,w,y)}catch(F){(E=new n("error")).error(F)}return new o(E,w.type||"string",w.mimeType)},generateAsync:function(m,E){return this.generateInternalStream(m).accumulate(E)},generateNodeStream:function(m,E){return(m=m||{}).type||(m.type="nodebuffer"),this.generateInternalStream(m).toNodejsStream(E)}};A.exports=C},{"./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(h,A,t){"use strict";A.exports=h("stream")},{stream:void 0}],17:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data[this.zero+s]},i.prototype.lastIndexOfSignature=function(s){for(var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),c=this.length-4;0<=c;--c)if(this.data[c]===n&&this.data[c+1]===o&&this.data[c+2]===a&&this.data[c+3]===r)return c-this.zero;return-1},i.prototype.readAndCheckSignature=function(s){var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),c=this.readData(4);return n===c[0]&&o===c[1]&&a===c[2]&&r===c[3]},i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],18:[function(h,A,t){"use strict";var e=h("../utils");function i(s){this.data=s,this.length=s.length,this.index=0,this.zero=0}i.prototype={checkOffset:function(s){this.checkIndex(this.index+s)},checkIndex:function(s){if(this.length<this.zero+s||s<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+s+"). Corrupted zip ?")},setIndex:function(s){this.checkIndex(s),this.index=s},skip:function(s){this.setIndex(this.index+s)},byteAt:function(){},readInt:function(s){var n,o=0;for(this.checkOffset(s),n=this.index+s-1;n>=this.index;n--)o=(o<<8)+this.byteAt(n);return this.index+=s,o},readString:function(s){return e.transformTo("string",this.readData(s))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var s=this.readInt(4);return new Date(Date.UTC(1980+(s>>25&127),(s>>21&15)-1,s>>16&31,s>>11&31,s>>5&63,(31&s)<<1))}},A.exports=i},{"../utils":32}],19:[function(h,A,t){"use strict";var e=h("./Uint8ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data.charCodeAt(this.zero+s)},i.prototype.lastIndexOfSignature=function(s){return this.data.lastIndexOf(s)-this.zero},i.prototype.readAndCheckSignature=function(s){return s===this.readData(4)},i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],21:[function(h,A,t){"use strict";var e=h("./ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../support"),s=h("./ArrayReader"),n=h("./StringReader"),o=h("./NodeBufferReader"),a=h("./Uint8ArrayReader");A.exports=function(r){var c=e.getTypeOf(r);return e.checkSupport(c),c!=="string"||i.uint8array?c==="nodebuffer"?new o(r):i.uint8array?new a(e.transformTo("uint8array",r)):new s(e.transformTo("array",r)):new n(r)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(h,A,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(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../utils");function s(n){e.call(this,"ConvertWorker to "+n),this.destType=n}i.inherits(s,e),s.prototype.processChunk=function(n){this.push({data:i.transformTo(this.destType,n.data),meta:n.meta})},A.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}h("../utils").inherits(s,e),s.prototype.processChunk=function(n){this.streamInfo.crc32=i(n.data,this.streamInfo.crc32||0),this.push(n)},A.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(s,i),s.prototype.processChunk=function(n){if(n){var o=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=o+n.data.length}i.prototype.processChunk.call(this,n)},A.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataWorker");var o=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(a){o.dataIsReady=!0,o.data=a,o.max=a&&a.length||0,o.type=e.getTypeOf(a),o.isPaused||o._tickAndRepeat()},function(a){o.error(a)})}e.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,o=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,o);break;case"uint8array":n=this.data.subarray(this.index,o);break;case"array":case"nodebuffer":n=this.data.slice(this.index,o)}return this.index=o,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},A.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(h,A,t){"use strict";function e(i){this.name=i||"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(i){this.emit("data",i)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(i){this.emit("error",i)}return!0},error:function(i){return!this.isFinished&&(this.isPaused?this.generatedError=i:(this.isFinished=!0,this.emit("error",i),this.previous&&this.previous.error(i),this.cleanUp()),!0)},on:function(i,s){return this._listeners[i].push(s),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(i,s){if(this._listeners[i])for(var n=0;n<this._listeners[i].length;n++)this._listeners[i][n].call(this,s)},pipe:function(i){return i.registerPrevious(this)},registerPrevious:function(i){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=i.streamInfo,this.mergeStreamInfo(),this.previous=i;var s=this;return i.on("data",function(n){s.processChunk(n)}),i.on("end",function(){s.end()}),i.on("error",function(n){s.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 i=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),i=!0),this.previous&&this.previous.resume(),!i},flush:function(){},processChunk:function(i){this.push(i)},withStreamInfo:function(i,s){return this.extraStreamInfo[i]=s,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var i in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,i)&&(this.streamInfo[i]=this.extraStreamInfo[i])},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 i="Worker "+this.name;return this.previous?this.previous+" -> "+i:i}},A.exports=e},{}],29:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./ConvertWorker"),s=h("./GenericWorker"),n=h("../base64"),o=h("../support"),a=h("../external"),r=null;if(o.nodestream)try{r=h("../nodejs/NodejsStreamOutputAdapter")}catch{}function c(g,p){return new a.Promise(function(d,I){var u=[],f=g._internalType,C=g._outputType,m=g._mimeType;g.on("data",function(E,w){u.push(E),p&&p(w)}).on("error",function(E){u=[],I(E)}).on("end",function(){try{var E=function(w,y,F){switch(w){case"blob":return e.newBlob(e.transformTo("arraybuffer",y),F);case"base64":return n.encode(y);default:return e.transformTo(w,y)}}(C,function(w,y){var F,D=0,L=null,S=0;for(F=0;F<y.length;F++)S+=y[F].length;switch(w){case"string":return y.join("");case"array":return Array.prototype.concat.apply([],y);case"uint8array":for(L=new Uint8Array(S),F=0;F<y.length;F++)L.set(y[F],D),D+=y[F].length;return L;case"nodebuffer":return Buffer.concat(y);default:throw new Error("concat : unsupported type '"+w+"'")}}(f,u),m);d(E)}catch(w){I(w)}u=[]}).resume()})}function l(g,p,d){var I=p;switch(p){case"blob":case"arraybuffer":I="uint8array";break;case"base64":I="string"}try{this._internalType=I,this._outputType=p,this._mimeType=d,e.checkSupport(I),this._worker=g.pipe(new i(I)),g.lock()}catch(u){this._worker=new s("error"),this._worker.error(u)}}l.prototype={accumulate:function(g){return c(this,g)},on:function(g,p){var d=this;return g==="data"?this._worker.on(g,function(I){p.call(d,I.data,I.meta)}):this._worker.on(g,function(){e.delay(p,arguments,d)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(g){if(e.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new r(this,{objectMode:this._outputType!=="nodebuffer"},g)}},A.exports=l},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(h,A,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 i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(e),t.blob=i.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!h("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(h,A,t){"use strict";for(var e=h("./utils"),i=h("./support"),s=h("./nodejsUtils"),n=h("./stream/GenericWorker"),o=new Array(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;o[254]=o[254]=1;function r(){n.call(this,"utf-8 decode"),this.leftOver=null}function c(){n.call(this,"utf-8 encode")}t.utf8encode=function(l){return i.nodebuffer?s.newBufferFrom(l,"utf-8"):function(g){var p,d,I,u,f,C=g.length,m=0;for(u=0;u<C;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),m+=d<128?1:d<2048?2:d<65536?3:4;for(p=i.uint8array?new Uint8Array(m):new Array(m),u=f=0;f<m;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),d<128?p[f++]=d:(d<2048?p[f++]=192|d>>>6:(d<65536?p[f++]=224|d>>>12:(p[f++]=240|d>>>18,p[f++]=128|d>>>12&63),p[f++]=128|d>>>6&63),p[f++]=128|63&d);return p}(l)},t.utf8decode=function(l){return i.nodebuffer?e.transformTo("nodebuffer",l).toString("utf-8"):function(g){var p,d,I,u,f=g.length,C=new Array(2*f);for(p=d=0;p<f;)if((I=g[p++])<128)C[d++]=I;else if(4<(u=o[I]))C[d++]=65533,p+=u-1;else{for(I&=u===2?31:u===3?15:7;1<u&&p<f;)I=I<<6|63&g[p++],u--;1<u?C[d++]=65533:I<65536?C[d++]=I:(I-=65536,C[d++]=55296|I>>10&1023,C[d++]=56320|1023&I)}return C.length!==d&&(C.subarray?C=C.subarray(0,d):C.length=d),e.applyFromCharCode(C)}(l=e.transformTo(i.uint8array?"uint8array":"array",l))},e.inherits(r,n),r.prototype.processChunk=function(l){var g=e.transformTo(i.uint8array?"uint8array":"array",l.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var p=g;(g=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),g.set(p,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var d=function(u,f){var C;for((f=f||u.length)>u.length&&(f=u.length),C=f-1;0<=C&&(192&u[C])==128;)C--;return C<0||C===0?f:C+o[u[C]]>f?C:f}(g),I=g;d!==g.length&&(i.uint8array?(I=g.subarray(0,d),this.leftOver=g.subarray(d,g.length)):(I=g.slice(0,d),this.leftOver=g.slice(d,g.length))),this.push({data:t.utf8decode(I),meta:l.meta})},r.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=r,e.inherits(c,n),c.prototype.processChunk=function(l){this.push({data:t.utf8encode(l.data),meta:l.meta})},t.Utf8EncodeWorker=c},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(h,A,t){"use strict";var e=h("./support"),i=h("./base64"),s=h("./nodejsUtils"),n=h("./external");function o(p){return p}function a(p,d){for(var I=0;I<p.length;++I)d[I]=255&p.charCodeAt(I);return d}h("setimmediate"),t.newBlob=function(p,d){t.checkSupport("blob");try{return new Blob([p],{type:d})}catch{try{var I=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return I.append(p),I.getBlob(d)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,d,I){var u=[],f=0,C=p.length;if(C<=I)return String.fromCharCode.apply(null,p);for(;f<C;)d==="array"||d==="nodebuffer"?u.push(String.fromCharCode.apply(null,p.slice(f,Math.min(f+I,C)))):u.push(String.fromCharCode.apply(null,p.subarray(f,Math.min(f+I,C)))),f+=I;return u.join("")},stringifyByChar:function(p){for(var d="",I=0;I<p.length;I++)d+=String.fromCharCode(p[I]);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,s.allocBuffer(1)).length===1}catch{return!1}}()}};function c(p){var d=65536,I=t.getTypeOf(p),u=!0;if(I==="uint8array"?u=r.applyCanBeUsed.uint8array:I==="nodebuffer"&&(u=r.applyCanBeUsed.nodebuffer),u)for(;1<d;)try{return r.stringifyByChunk(p,I,d)}catch{d=Math.floor(d/2)}return r.stringifyByChar(p)}function l(p,d){for(var I=0;I<p.length;I++)d[I]=p[I];return d}t.applyFromCharCode=c;var g={};g.string={string:o,array:function(p){return a(p,new Array(p.length))},arraybuffer:function(p){return g.string.uint8array(p).buffer},uint8array:function(p){return a(p,new Uint8Array(p.length))},nodebuffer:function(p){return a(p,s.allocBuffer(p.length))}},g.array={string:c,array:o,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(p)}},g.arraybuffer={string:function(p){return c(new Uint8Array(p))},array:function(p){return l(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:o,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(new Uint8Array(p))}},g.uint8array={string:c,array:function(p){return l(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:o,nodebuffer:function(p){return s.newBufferFrom(p)}},g.nodebuffer={string:c,array:function(p){return l(p,new Array(p.length))},arraybuffer:function(p){return g.nodebuffer.uint8array(p).buffer},uint8array:function(p){return l(p,new Uint8Array(p.length))},nodebuffer:o},t.transformTo=function(p,d){if(d=d||"",!p)return d;t.checkSupport(p);var I=t.getTypeOf(d);return g[I][p](d)},t.resolve=function(p){for(var d=p.split("/"),I=[],u=0;u<d.length;u++){var f=d[u];f==="."||f===""&&u!==0&&u!==d.length-1||(f===".."?I.pop():I.push(f))}return I.join("/")},t.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":e.nodebuffer&&s.isBuffer(p)?"nodebuffer":e.uint8array&&p instanceof Uint8Array?"uint8array":e.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(p){if(!e[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(p){var d,I,u="";for(I=0;I<(p||"").length;I++)u+="\\x"+((d=p.charCodeAt(I))<16?"0":"")+d.toString(16).toUpperCase();return u},t.delay=function(p,d,I){setImmediate(function(){p.apply(I||null,d||[])})},t.inherits=function(p,d){function I(){}I.prototype=d.prototype,p.prototype=new I},t.extend=function(){var p,d,I={};for(p=0;p<arguments.length;p++)for(d in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],d)&&I[d]===void 0&&(I[d]=arguments[p][d]);return I},t.prepareContent=function(p,d,I,u,f){return n.Promise.resolve(d).then(function(C){return e.blob&&(C instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(C))!==-1)&&typeof FileReader<"u"?new n.Promise(function(m,E){var w=new FileReader;w.onload=function(y){m(y.target.result)},w.onerror=function(y){E(y.target.error)},w.readAsArrayBuffer(C)}):C}).then(function(C){var m=t.getTypeOf(C);return m?(m==="arraybuffer"?C=t.transformTo("uint8array",C):m==="string"&&(f?C=i.decode(C):I&&u!==!0&&(C=function(E){return a(E,e.uint8array?new Uint8Array(E.length):new Array(E.length))}(C))),C):n.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./signature"),n=h("./zipEntry"),o=h("./support");function a(r){this.files=[],this.loadOptions=r}a.prototype={checkSignature:function(r){if(!this.reader.readAndCheckSignature(r)){this.reader.index-=4;var c=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(c)+", expected "+i.pretty(r)+")")}},isSignature:function(r,c){var l=this.reader.index;this.reader.setIndex(r);var g=this.reader.readString(4)===c;return this.reader.setIndex(l),g},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 r=this.reader.readData(this.zipCommentLength),c=o.uint8array?"uint8array":"array",l=i.transformTo(c,r);this.zipComment=this.loadOptions.decodeFileName(l)},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 r,c,l,g=this.zip64EndOfCentralSize-44;0<g;)r=this.reader.readInt(2),c=this.reader.readInt(4),l=this.reader.readData(c),this.zip64ExtensibleData[r]={id:r,length:c,value:l}},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 r,c;for(r=0;r<this.files.length;r++)c=this.files[r],this.reader.setIndex(c.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),c.readLocalPart(this.reader),c.handleUTF8(),c.processAttributes()},readCentralDir:function(){var r;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(r=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(r);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 r=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(r<0)throw this.isSignature(0,s.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(r);var c=r;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===i.MAX_VALUE_16BITS||this.diskWithCentralDirStart===i.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===i.MAX_VALUE_16BITS||this.centralDirRecords===i.MAX_VALUE_16BITS||this.centralDirSize===i.MAX_VALUE_32BITS||this.centralDirOffset===i.MAX_VALUE_32BITS){if(this.zip64=!0,(r=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(r),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.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(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var l=this.centralDirOffset+this.centralDirSize;this.zip64&&(l+=20,l+=12+this.zip64EndOfCentralSize);var g=c-l;if(0<g)this.isSignature(c,s.CENTRAL_FILE_HEADER)||(this.reader.zero=g);else if(g<0)throw new Error("Corrupted zip: missing "+Math.abs(g)+" bytes.")},prepareReader:function(r){this.reader=e(r)},load:function(r){this.prepareReader(r),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},A.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./compressedObject"),n=h("./crc32"),o=h("./utf8"),a=h("./compressions"),r=h("./support");function c(l,g){this.options=l,this.loadOptions=g}c.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(l){var g,p;if(l.skip(22),this.fileNameLength=l.readInt(2),p=l.readInt(2),this.fileName=l.readData(this.fileNameLength),l.skip(p),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((g=function(d){for(var I in a)if(Object.prototype.hasOwnProperty.call(a,I)&&a[I].magic===d)return a[I];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+i.pretty(this.compressionMethod)+" unknown (inner file : "+i.transformTo("string",this.fileName)+")");this.decompressed=new s(this.compressedSize,this.uncompressedSize,this.crc32,g,l.readData(this.compressedSize))},readCentralPart:function(l){this.versionMadeBy=l.readInt(2),l.skip(2),this.bitFlag=l.readInt(2),this.compressionMethod=l.readString(2),this.date=l.readDate(),this.crc32=l.readInt(4),this.compressedSize=l.readInt(4),this.uncompressedSize=l.readInt(4);var g=l.readInt(2);if(this.extraFieldsLength=l.readInt(2),this.fileCommentLength=l.readInt(2),this.diskNumberStart=l.readInt(2),this.internalFileAttributes=l.readInt(2),this.externalFileAttributes=l.readInt(4),this.localHeaderOffset=l.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");l.skip(g),this.readExtraFields(l),this.parseZIP64ExtraField(l),this.fileComment=l.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var l=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),l==0&&(this.dosPermissions=63&this.externalFileAttributes),l==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var l=e(this.extraFields[1].value);this.uncompressedSize===i.MAX_VALUE_32BITS&&(this.uncompressedSize=l.readInt(8)),this.compressedSize===i.MAX_VALUE_32BITS&&(this.compressedSize=l.readInt(8)),this.localHeaderOffset===i.MAX_VALUE_32BITS&&(this.localHeaderOffset=l.readInt(8)),this.diskNumberStart===i.MAX_VALUE_32BITS&&(this.diskNumberStart=l.readInt(4))}},readExtraFields:function(l){var g,p,d,I=l.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});l.index+4<I;)g=l.readInt(2),p=l.readInt(2),d=l.readData(p),this.extraFields[g]={id:g,length:p,value:d};l.setIndex(I)},handleUTF8:function(){var l=r.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=o.utf8decode(this.fileName),this.fileCommentStr=o.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var p=i.transformTo(l,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var d=this.findExtraFieldUnicodeComment();if(d!==null)this.fileCommentStr=d;else{var I=i.transformTo(l,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(I)}}},findExtraFieldUnicodePath:function(){var l=this.extraFields[28789];if(l){var g=e(l.value);return g.readInt(1)!==1||n(this.fileName)!==g.readInt(4)?null:o.utf8decode(g.readData(l.length-5))}return null},findExtraFieldUnicodeComment:function(){var l=this.extraFields[25461];if(l){var g=e(l.value);return g.readInt(1)!==1||n(this.fileComment)!==g.readInt(4)?null:o.utf8decode(g.readData(l.length-5))}return null}},A.exports=c},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(h,A,t){"use strict";function e(g,p,d){this.name=g,this.dir=d.dir,this.date=d.date,this.comment=d.comment,this.unixPermissions=d.unixPermissions,this.dosPermissions=d.dosPermissions,this._data=p,this._dataBinary=d.binary,this.options={compression:d.compression,compressionOptions:d.compressionOptions}}var i=h("./stream/StreamHelper"),s=h("./stream/DataWorker"),n=h("./utf8"),o=h("./compressedObject"),a=h("./stream/GenericWorker");e.prototype={internalStream:function(g){var p=null,d="string";try{if(!g)throw new Error("No output type specified.");var I=(d=g.toLowerCase())==="string"||d==="text";d!=="binarystring"&&d!=="text"||(d="string"),p=this._decompressWorker();var u=!this._dataBinary;u&&!I&&(p=p.pipe(new n.Utf8EncodeWorker)),!u&&I&&(p=p.pipe(new n.Utf8DecodeWorker))}catch(f){(p=new a("error")).error(f)}return new i(p,d,"")},async:function(g,p){return this.internalStream(g).accumulate(p)},nodeStream:function(g,p){return this.internalStream(g||"nodebuffer").toNodejsStream(p)},_compressWorker:function(g,p){if(this._data instanceof o&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var d=this._decompressWorker();return this._dataBinary||(d=d.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(d,g,p)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof a?this._data:new s(this._data)}};for(var r=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],c=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},l=0;l<r.length;l++)e.prototype[r[l]]=c;A.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(h,A,t){(function(e){"use strict";var i,s,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var o=0,a=new n(g),r=e.document.createTextNode("");a.observe(r,{characterData:!0}),i=function(){r.data=o=++o%2}}else if(e.setImmediate||e.MessageChannel===void 0)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var p=e.document.createElement("script");p.onreadystatechange=function(){g(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},e.document.documentElement.appendChild(p)}:function(){setTimeout(g,0)};else{var c=new e.MessageChannel;c.port1.onmessage=g,i=function(){c.port2.postMessage(0)}}var l=[];function g(){var p,d;s=!0;for(var I=l.length;I;){for(d=l,l=[],p=-1;++p<I;)d[p]();I=l.length}s=!1}A.exports=function(p){l.push(p)!==1||s||i()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(h,A,t){"use strict";var e=h("immediate");function i(){}var s={},n=["REJECTED"],o=["FULFILLED"],a=["PENDING"];function r(I){if(typeof I!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,I!==i&&p(this,I)}function c(I,u,f){this.promise=I,typeof u=="function"&&(this.onFulfilled=u,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function l(I,u,f){e(function(){var C;try{C=u(f)}catch(m){return s.reject(I,m)}C===I?s.reject(I,new TypeError("Cannot resolve promise with itself")):s.resolve(I,C)})}function g(I){var u=I&&I.then;if(I&&(typeof I=="object"||typeof I=="function")&&typeof u=="function")return function(){u.apply(I,arguments)}}function p(I,u){var f=!1;function C(w){f||(f=!0,s.reject(I,w))}function m(w){f||(f=!0,s.resolve(I,w))}var E=d(function(){u(m,C)});E.status==="error"&&C(E.value)}function d(I,u){var f={};try{f.value=I(u),f.status="success"}catch(C){f.status="error",f.value=C}return f}(A.exports=r).prototype.finally=function(I){if(typeof I!="function")return this;var u=this.constructor;return this.then(function(f){return u.resolve(I()).then(function(){return f})},function(f){return u.resolve(I()).then(function(){throw f})})},r.prototype.catch=function(I){return this.then(null,I)},r.prototype.then=function(I,u){if(typeof I!="function"&&this.state===o||typeof u!="function"&&this.state===n)return this;var f=new this.constructor(i);return this.state!==a?l(f,this.state===o?I:u,this.outcome):this.queue.push(new c(f,I,u)),f},c.prototype.callFulfilled=function(I){s.resolve(this.promise,I)},c.prototype.otherCallFulfilled=function(I){l(this.promise,this.onFulfilled,I)},c.prototype.callRejected=function(I){s.reject(this.promise,I)},c.prototype.otherCallRejected=function(I){l(this.promise,this.onRejected,I)},s.resolve=function(I,u){var f=d(g,u);if(f.status==="error")return s.reject(I,f.value);var C=f.value;if(C)p(I,C);else{I.state=o,I.outcome=u;for(var m=-1,E=I.queue.length;++m<E;)I.queue[m].callFulfilled(u)}return I},s.reject=function(I,u){I.state=n,I.outcome=u;for(var f=-1,C=I.queue.length;++f<C;)I.queue[f].callRejected(u);return I},r.resolve=function(I){return I instanceof this?I:s.resolve(new this(i),I)},r.reject=function(I){var u=new this(i);return s.reject(u,I)},r.all=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=new Array(f),E=0,w=-1,y=new this(i);++w<f;)F(I[w],w);return y;function F(D,L){u.resolve(D).then(function(S){m[L]=S,++E!==f||C||(C=!0,s.resolve(y,m))},function(S){C||(C=!0,s.reject(y,S))})}},r.race=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=-1,E=new this(i);++m<f;)w=I[m],u.resolve(w).then(function(y){C||(C=!0,s.resolve(E,y))},function(y){C||(C=!0,s.reject(E,y))});var w;return E}},{immediate:36}],38:[function(h,A,t){"use strict";var e={};(0,h("./lib/utils/common").assign)(e,h("./lib/deflate"),h("./lib/inflate"),h("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(h,A,t){"use strict";var e=h("./zlib/deflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/messages"),o=h("./zlib/zstream"),a=Object.prototype.toString,r=0,c=-1,l=0,g=8;function p(I){if(!(this instanceof p))return new p(I);this.options=i.assign({level:c,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:l,to:""},I||{});var u=this.options;u.raw&&0<u.windowBits?u.windowBits=-u.windowBits:u.gzip&&0<u.windowBits&&u.windowBits<16&&(u.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var f=e.deflateInit2(this.strm,u.level,u.method,u.windowBits,u.memLevel,u.strategy);if(f!==r)throw new Error(n[f]);if(u.header&&e.deflateSetHeader(this.strm,u.header),u.dictionary){var C;if(C=typeof u.dictionary=="string"?s.string2buf(u.dictionary):a.call(u.dictionary)==="[object ArrayBuffer]"?new Uint8Array(u.dictionary):u.dictionary,(f=e.deflateSetDictionary(this.strm,C))!==r)throw new Error(n[f]);this._dict_set=!0}}function d(I,u){var f=new p(u);if(f.push(I,!0),f.err)throw f.msg||n[f.err];return f.result}p.prototype.push=function(I,u){var f,C,m=this.strm,E=this.options.chunkSize;if(this.ended)return!1;C=u===~~u?u:u===!0?4:0,typeof I=="string"?m.input=s.string2buf(I):a.call(I)==="[object ArrayBuffer]"?m.input=new Uint8Array(I):m.input=I,m.next_in=0,m.avail_in=m.input.length;do{if(m.avail_out===0&&(m.output=new i.Buf8(E),m.next_out=0,m.avail_out=E),(f=e.deflate(m,C))!==1&&f!==r)return this.onEnd(f),!(this.ended=!0);m.avail_out!==0&&(m.avail_in!==0||C!==4&&C!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(i.shrinkBuf(m.output,m.next_out))):this.onData(i.shrinkBuf(m.output,m.next_out)))}while((0<m.avail_in||m.avail_out===0)&&f!==1);return C===4?(f=e.deflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===r):C!==2||(this.onEnd(r),!(m.avail_out=0))},p.prototype.onData=function(I){this.chunks.push(I)},p.prototype.onEnd=function(I){I===r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=I,this.msg=this.strm.msg},t.Deflate=p,t.deflate=d,t.deflateRaw=function(I,u){return(u=u||{}).raw=!0,d(I,u)},t.gzip=function(I,u){return(u=u||{}).gzip=!0,d(I,u)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(h,A,t){"use strict";var e=h("./zlib/inflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/constants"),o=h("./zlib/messages"),a=h("./zlib/zstream"),r=h("./zlib/gzheader"),c=Object.prototype.toString;function l(p){if(!(this instanceof l))return new l(p);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},p||{});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)||p&&p.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 a,this.strm.avail_out=0;var I=e.inflateInit2(this.strm,d.windowBits);if(I!==n.Z_OK)throw new Error(o[I]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,d){var I=new l(d);if(I.push(p,!0),I.err)throw I.msg||o[I.err];return I.result}l.prototype.push=function(p,d){var I,u,f,C,m,E,w=this.strm,y=this.options.chunkSize,F=this.options.dictionary,D=!1;if(this.ended)return!1;u=d===~~d?d:d===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof p=="string"?w.input=s.binstring2buf(p):c.call(p)==="[object ArrayBuffer]"?w.input=new Uint8Array(p):w.input=p,w.next_in=0,w.avail_in=w.input.length;do{if(w.avail_out===0&&(w.output=new i.Buf8(y),w.next_out=0,w.avail_out=y),(I=e.inflate(w,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&F&&(E=typeof F=="string"?s.string2buf(F):c.call(F)==="[object ArrayBuffer]"?new Uint8Array(F):F,I=e.inflateSetDictionary(this.strm,E)),I===n.Z_BUF_ERROR&&D===!0&&(I=n.Z_OK,D=!1),I!==n.Z_STREAM_END&&I!==n.Z_OK)return this.onEnd(I),!(this.ended=!0);w.next_out&&(w.avail_out!==0&&I!==n.Z_STREAM_END&&(w.avail_in!==0||u!==n.Z_FINISH&&u!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(f=s.utf8border(w.output,w.next_out),C=w.next_out-f,m=s.buf2string(w.output,f),w.next_out=C,w.avail_out=y-C,C&&i.arraySet(w.output,w.output,f,C,0),this.onData(m)):this.onData(i.shrinkBuf(w.output,w.next_out)))),w.avail_in===0&&w.avail_out===0&&(D=!0)}while((0<w.avail_in||w.avail_out===0)&&I!==n.Z_STREAM_END);return I===n.Z_STREAM_END&&(u=n.Z_FINISH),u===n.Z_FINISH?(I=e.inflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===n.Z_OK):u!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(w.avail_out=0))},l.prototype.onData=function(p){this.chunks.push(p)},l.prototype.onEnd=function(p){p===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},t.Inflate=l,t.inflate=g,t.inflateRaw=function(p,d){return(d=d||{}).raw=!0,g(p,d)},t.ungzip=g},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var a=o.shift();if(a){if(typeof a!="object")throw new TypeError(a+"must be non-object");for(var r in a)a.hasOwnProperty(r)&&(n[r]=a[r])}}return n},t.shrinkBuf=function(n,o){return n.length===o?n:n.subarray?n.subarray(0,o):(n.length=o,n)};var i={arraySet:function(n,o,a,r,c){if(o.subarray&&n.subarray)n.set(o.subarray(a,a+r),c);else for(var l=0;l<r;l++)n[c+l]=o[a+l]},flattenChunks:function(n){var o,a,r,c,l,g;for(o=r=0,a=n.length;o<a;o++)r+=n[o].length;for(g=new Uint8Array(r),o=c=0,a=n.length;o<a;o++)l=n[o],g.set(l,c),c+=l.length;return g}},s={arraySet:function(n,o,a,r,c){for(var l=0;l<r;l++)n[c+l]=o[a+l]},flattenChunks:function(n){return[].concat.apply([],n)}};t.setTyped=function(n){n?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,i)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,s))},t.setTyped(e)},{}],42:[function(h,A,t){"use strict";var e=h("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch{i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{s=!1}for(var n=new e.Buf8(256),o=0;o<256;o++)n[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;function a(r,c){if(c<65537&&(r.subarray&&s||!r.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(r,c));for(var l="",g=0;g<c;g++)l+=String.fromCharCode(r[g]);return l}n[254]=n[254]=1,t.string2buf=function(r){var c,l,g,p,d,I=r.length,u=0;for(p=0;p<I;p++)(64512&(l=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(l=65536+(l-55296<<10)+(g-56320),p++),u+=l<128?1:l<2048?2:l<65536?3:4;for(c=new e.Buf8(u),p=d=0;d<u;p++)(64512&(l=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(l=65536+(l-55296<<10)+(g-56320),p++),l<128?c[d++]=l:(l<2048?c[d++]=192|l>>>6:(l<65536?c[d++]=224|l>>>12:(c[d++]=240|l>>>18,c[d++]=128|l>>>12&63),c[d++]=128|l>>>6&63),c[d++]=128|63&l);return c},t.buf2binstring=function(r){return a(r,r.length)},t.binstring2buf=function(r){for(var c=new e.Buf8(r.length),l=0,g=c.length;l<g;l++)c[l]=r.charCodeAt(l);return c},t.buf2string=function(r,c){var l,g,p,d,I=c||r.length,u=new Array(2*I);for(l=g=0;l<I;)if((p=r[l++])<128)u[g++]=p;else if(4<(d=n[p]))u[g++]=65533,l+=d-1;else{for(p&=d===2?31:d===3?15:7;1<d&&l<I;)p=p<<6|63&r[l++],d--;1<d?u[g++]=65533:p<65536?u[g++]=p:(p-=65536,u[g++]=55296|p>>10&1023,u[g++]=56320|1023&p)}return a(u,g)},t.utf8border=function(r,c){var l;for((c=c||r.length)>r.length&&(c=r.length),l=c-1;0<=l&&(192&r[l])==128;)l--;return l<0||l===0?c:l+n[r[l]]>c?l:c}},{"./common":41}],43:[function(h,A,t){"use strict";A.exports=function(e,i,s,n){for(var o=65535&e|0,a=e>>>16&65535|0,r=0;s!==0;){for(s-=r=2e3<s?2e3:s;a=a+(o=o+i[n++]|0)|0,--r;);o%=65521,a%=65521}return o|a<<16|0}},{}],44:[function(h,A,t){"use strict";A.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(h,A,t){"use strict";var e=function(){for(var i,s=[],n=0;n<256;n++){i=n;for(var o=0;o<8;o++)i=1&i?3988292384^i>>>1:i>>>1;s[n]=i}return s}();A.exports=function(i,s,n,o){var a=e,r=o+n;i^=-1;for(var c=o;c<r;c++)i=i>>>8^a[255&(i^s[c])];return-1^i}},{}],46:[function(h,A,t){"use strict";var e,i=h("../utils/common"),s=h("./trees"),n=h("./adler32"),o=h("./crc32"),a=h("./messages"),r=0,c=4,l=0,g=-2,p=-1,d=4,I=2,u=8,f=9,C=286,m=30,E=19,w=2*C+1,y=15,F=3,D=258,L=D+F+1,S=42,b=113,Q=1,H=2,$=3,M=4;function T(B,O){return B.msg=a[O],O}function J(B){return(B<<1)-(4<B?9:0)}function Z(B){for(var O=B.length;0<=--O;)B[O]=0}function G(B){var O=B.state,P=O.pending;P>B.avail_out&&(P=B.avail_out),P!==0&&(i.arraySet(B.output,O.pending_buf,O.pending_out,P,B.next_out),B.next_out+=P,O.pending_out+=P,B.total_out+=P,B.avail_out-=P,O.pending-=P,O.pending===0&&(O.pending_out=0))}function N(B,O){s._tr_flush_block(B,0<=B.block_start?B.block_start:-1,B.strstart-B.block_start,O),B.block_start=B.strstart,G(B.strm)}function _(B,O){B.pending_buf[B.pending++]=O}function K(B,O){B.pending_buf[B.pending++]=O>>>8&255,B.pending_buf[B.pending++]=255&O}function z(B,O){var P,k,v=B.max_chain_length,x=B.strstart,Y=B.prev_length,V=B.nice_match,R=B.strstart>B.w_size-L?B.strstart-(B.w_size-L):0,W=B.window,j=B.w_mask,X=B.prev,it=B.strstart+D,ut=W[x+Y-1],lt=W[x+Y];B.prev_length>=B.good_match&&(v>>=2),V>B.lookahead&&(V=B.lookahead);do if(W[(P=O)+Y]===lt&&W[P+Y-1]===ut&&W[P]===W[x]&&W[++P]===W[x+1]){x+=2,P++;do;while(W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&x<it);if(k=D-(it-x),x=it-D,Y<k){if(B.match_start=O,V<=(Y=k))break;ut=W[x+Y-1],lt=W[x+Y]}}while((O=X[O&j])>R&&--v!=0);return Y<=B.lookahead?Y:B.lookahead}function ot(B){var O,P,k,v,x,Y,V,R,W,j,X=B.w_size;do{if(v=B.window_size-B.lookahead-B.strstart,B.strstart>=X+(X-L)){for(i.arraySet(B.window,B.window,X,X,0),B.match_start-=X,B.strstart-=X,B.block_start-=X,O=P=B.hash_size;k=B.head[--O],B.head[O]=X<=k?k-X:0,--P;);for(O=P=X;k=B.prev[--O],B.prev[O]=X<=k?k-X:0,--P;);v+=X}if(B.strm.avail_in===0)break;if(Y=B.strm,V=B.window,R=B.strstart+B.lookahead,W=v,j=void 0,j=Y.avail_in,W<j&&(j=W),P=j===0?0:(Y.avail_in-=j,i.arraySet(V,Y.input,Y.next_in,j,R),Y.state.wrap===1?Y.adler=n(Y.adler,V,j,R):Y.state.wrap===2&&(Y.adler=o(Y.adler,V,j,R)),Y.next_in+=j,Y.total_in+=j,j),B.lookahead+=P,B.lookahead+B.insert>=F)for(x=B.strstart-B.insert,B.ins_h=B.window[x],B.ins_h=(B.ins_h<<B.hash_shift^B.window[x+1])&B.hash_mask;B.insert&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[x+F-1])&B.hash_mask,B.prev[x&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=x,x++,B.insert--,!(B.lookahead+B.insert<F)););}while(B.lookahead<L&&B.strm.avail_in!==0)}function pt(B,O){for(var P,k;;){if(B.lookahead<L){if(ot(B),B.lookahead<L&&O===r)return Q;if(B.lookahead===0)break}if(P=0,B.lookahead>=F&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),P!==0&&B.strstart-P<=B.w_size-L&&(B.match_length=z(B,P)),B.match_length>=F)if(k=s._tr_tally(B,B.strstart-B.match_start,B.match_length-F),B.lookahead-=B.match_length,B.match_length<=B.max_lazy_match&&B.lookahead>=F){for(B.match_length--;B.strstart++,B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart,--B.match_length!=0;);B.strstart++}else B.strstart+=B.match_length,B.match_length=0,B.ins_h=B.window[B.strstart],B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+1])&B.hash_mask;else k=s._tr_tally(B,0,B.window[B.strstart]),B.lookahead--,B.strstart++;if(k&&(N(B,!1),B.strm.avail_out===0))return Q}return B.insert=B.strstart<F-1?B.strstart:F-1,O===c?(N(B,!0),B.strm.avail_out===0?$:M):B.last_lit&&(N(B,!1),B.strm.avail_out===0)?Q:H}function st(B,O){for(var P,k,v;;){if(B.lookahead<L){if(ot(B),B.lookahead<L&&O===r)return Q;if(B.lookahead===0)break}if(P=0,B.lookahead>=F&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),B.prev_length=B.match_length,B.prev_match=B.match_start,B.match_length=F-1,P!==0&&B.prev_length<B.max_lazy_match&&B.strstart-P<=B.w_size-L&&(B.match_length=z(B,P),B.match_length<=5&&(B.strategy===1||B.match_length===F&&4096<B.strstart-B.match_start)&&(B.match_length=F-1)),B.prev_length>=F&&B.match_length<=B.prev_length){for(v=B.strstart+B.lookahead-F,k=s._tr_tally(B,B.strstart-1-B.prev_match,B.prev_length-F),B.lookahead-=B.prev_length-1,B.prev_length-=2;++B.strstart<=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),--B.prev_length!=0;);if(B.match_available=0,B.match_length=F-1,B.strstart++,k&&(N(B,!1),B.strm.avail_out===0))return Q}else if(B.match_available){if((k=s._tr_tally(B,0,B.window[B.strstart-1]))&&N(B,!1),B.strstart++,B.lookahead--,B.strm.avail_out===0)return Q}else B.match_available=1,B.strstart++,B.lookahead--}return B.match_available&&(k=s._tr_tally(B,0,B.window[B.strstart-1]),B.match_available=0),B.insert=B.strstart<F-1?B.strstart:F-1,O===c?(N(B,!0),B.strm.avail_out===0?$:M):B.last_lit&&(N(B,!1),B.strm.avail_out===0)?Q:H}function at(B,O,P,k,v){this.good_length=B,this.max_lazy=O,this.nice_length=P,this.max_chain=k,this.func=v}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=u,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 i.Buf16(2*w),this.dyn_dtree=new i.Buf16(2*(2*m+1)),this.bl_tree=new i.Buf16(2*(2*E+1)),Z(this.dyn_ltree),Z(this.dyn_dtree),Z(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(y+1),this.heap=new i.Buf16(2*C+1),Z(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*C+1),Z(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 nt(B){var O;return B&&B.state?(B.total_in=B.total_out=0,B.data_type=I,(O=B.state).pending=0,O.pending_out=0,O.wrap<0&&(O.wrap=-O.wrap),O.status=O.wrap?S:b,B.adler=O.wrap===2?0:1,O.last_flush=r,s._tr_init(O),l):T(B,g)}function Qt(B){var O=nt(B);return O===l&&function(P){P.window_size=2*P.w_size,Z(P.head),P.max_lazy_match=e[P.level].max_lazy,P.good_match=e[P.level].good_length,P.nice_match=e[P.level].nice_length,P.max_chain_length=e[P.level].max_chain,P.strstart=0,P.block_start=0,P.lookahead=0,P.insert=0,P.match_length=P.prev_length=F-1,P.match_available=0,P.ins_h=0}(B.state),O}function Ct(B,O,P,k,v,x){if(!B)return g;var Y=1;if(O===p&&(O=6),k<0?(Y=0,k=-k):15<k&&(Y=2,k-=16),v<1||f<v||P!==u||k<8||15<k||O<0||9<O||x<0||d<x)return T(B,g);k===8&&(k=9);var V=new At;return(B.state=V).strm=B,V.wrap=Y,V.gzhead=null,V.w_bits=k,V.w_size=1<<V.w_bits,V.w_mask=V.w_size-1,V.hash_bits=v+7,V.hash_size=1<<V.hash_bits,V.hash_mask=V.hash_size-1,V.hash_shift=~~((V.hash_bits+F-1)/F),V.window=new i.Buf8(2*V.w_size),V.head=new i.Buf16(V.hash_size),V.prev=new i.Buf16(V.w_size),V.lit_bufsize=1<<v+6,V.pending_buf_size=4*V.lit_bufsize,V.pending_buf=new i.Buf8(V.pending_buf_size),V.d_buf=1*V.lit_bufsize,V.l_buf=3*V.lit_bufsize,V.level=O,V.strategy=x,V.method=P,Qt(B)}e=[new at(0,0,0,0,function(B,O){var P=65535;for(P>B.pending_buf_size-5&&(P=B.pending_buf_size-5);;){if(B.lookahead<=1){if(ot(B),B.lookahead===0&&O===r)return Q;if(B.lookahead===0)break}B.strstart+=B.lookahead,B.lookahead=0;var k=B.block_start+P;if((B.strstart===0||B.strstart>=k)&&(B.lookahead=B.strstart-k,B.strstart=k,N(B,!1),B.strm.avail_out===0)||B.strstart-B.block_start>=B.w_size-L&&(N(B,!1),B.strm.avail_out===0))return Q}return B.insert=0,O===c?(N(B,!0),B.strm.avail_out===0?$:M):(B.strstart>B.block_start&&(N(B,!1),B.strm.avail_out),Q)}),new at(4,4,8,4,pt),new at(4,5,16,8,pt),new at(4,6,32,32,pt),new at(4,4,16,16,st),new at(8,16,32,32,st),new at(8,16,128,128,st),new at(8,32,128,256,st),new at(32,128,258,1024,st),new at(32,258,258,4096,st)],t.deflateInit=function(B,O){return Ct(B,O,u,15,8,0)},t.deflateInit2=Ct,t.deflateReset=Qt,t.deflateResetKeep=nt,t.deflateSetHeader=function(B,O){return B&&B.state?B.state.wrap!==2?g:(B.state.gzhead=O,l):g},t.deflate=function(B,O){var P,k,v,x;if(!B||!B.state||5<O||O<0)return B?T(B,g):g;if(k=B.state,!B.output||!B.input&&B.avail_in!==0||k.status===666&&O!==c)return T(B,B.avail_out===0?-5:g);if(k.strm=B,P=k.last_flush,k.last_flush=O,k.status===S)if(k.wrap===2)B.adler=0,_(k,31),_(k,139),_(k,8),k.gzhead?(_(k,(k.gzhead.text?1:0)+(k.gzhead.hcrc?2:0)+(k.gzhead.extra?4:0)+(k.gzhead.name?8:0)+(k.gzhead.comment?16:0)),_(k,255&k.gzhead.time),_(k,k.gzhead.time>>8&255),_(k,k.gzhead.time>>16&255),_(k,k.gzhead.time>>24&255),_(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),_(k,255&k.gzhead.os),k.gzhead.extra&&k.gzhead.extra.length&&(_(k,255&k.gzhead.extra.length),_(k,k.gzhead.extra.length>>8&255)),k.gzhead.hcrc&&(B.adler=o(B.adler,k.pending_buf,k.pending,0)),k.gzindex=0,k.status=69):(_(k,0),_(k,0),_(k,0),_(k,0),_(k,0),_(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),_(k,3),k.status=b);else{var Y=u+(k.w_bits-8<<4)<<8;Y|=(2<=k.strategy||k.level<2?0:k.level<6?1:k.level===6?2:3)<<6,k.strstart!==0&&(Y|=32),Y+=31-Y%31,k.status=b,K(k,Y),k.strstart!==0&&(K(k,B.adler>>>16),K(k,65535&B.adler)),B.adler=1}if(k.status===69)if(k.gzhead.extra){for(v=k.pending;k.gzindex<(65535&k.gzhead.extra.length)&&(k.pending!==k.pending_buf_size||(k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),G(B),v=k.pending,k.pending!==k.pending_buf_size));)_(k,255&k.gzhead.extra[k.gzindex]),k.gzindex++;k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),k.gzindex===k.gzhead.extra.length&&(k.gzindex=0,k.status=73)}else k.status=73;if(k.status===73)if(k.gzhead.name){v=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),G(B),v=k.pending,k.pending===k.pending_buf_size)){x=1;break}x=k.gzindex<k.gzhead.name.length?255&k.gzhead.name.charCodeAt(k.gzindex++):0,_(k,x)}while(x!==0);k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),x===0&&(k.gzindex=0,k.status=91)}else k.status=91;if(k.status===91)if(k.gzhead.comment){v=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),G(B),v=k.pending,k.pending===k.pending_buf_size)){x=1;break}x=k.gzindex<k.gzhead.comment.length?255&k.gzhead.comment.charCodeAt(k.gzindex++):0,_(k,x)}while(x!==0);k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),x===0&&(k.status=103)}else k.status=103;if(k.status===103&&(k.gzhead.hcrc?(k.pending+2>k.pending_buf_size&&G(B),k.pending+2<=k.pending_buf_size&&(_(k,255&B.adler),_(k,B.adler>>8&255),B.adler=0,k.status=b)):k.status=b),k.pending!==0){if(G(B),B.avail_out===0)return k.last_flush=-1,l}else if(B.avail_in===0&&J(O)<=J(P)&&O!==c)return T(B,-5);if(k.status===666&&B.avail_in!==0)return T(B,-5);if(B.avail_in!==0||k.lookahead!==0||O!==r&&k.status!==666){var V=k.strategy===2?function(R,W){for(var j;;){if(R.lookahead===0&&(ot(R),R.lookahead===0)){if(W===r)return Q;break}if(R.match_length=0,j=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++,j&&(N(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,W===c?(N(R,!0),R.strm.avail_out===0?$:M):R.last_lit&&(N(R,!1),R.strm.avail_out===0)?Q:H}(k,O):k.strategy===3?function(R,W){for(var j,X,it,ut,lt=R.window;;){if(R.lookahead<=D){if(ot(R),R.lookahead<=D&&W===r)return Q;if(R.lookahead===0)break}if(R.match_length=0,R.lookahead>=F&&0<R.strstart&&(X=lt[it=R.strstart-1])===lt[++it]&&X===lt[++it]&&X===lt[++it]){ut=R.strstart+D;do;while(X===lt[++it]&&X===lt[++it]&&X===lt[++it]&&X===lt[++it]&&X===lt[++it]&&X===lt[++it]&&X===lt[++it]&&X===lt[++it]&&it<ut);R.match_length=D-(ut-it),R.match_length>R.lookahead&&(R.match_length=R.lookahead)}if(R.match_length>=F?(j=s._tr_tally(R,1,R.match_length-F),R.lookahead-=R.match_length,R.strstart+=R.match_length,R.match_length=0):(j=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++),j&&(N(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,W===c?(N(R,!0),R.strm.avail_out===0?$:M):R.last_lit&&(N(R,!1),R.strm.avail_out===0)?Q:H}(k,O):e[k.level].func(k,O);if(V!==$&&V!==M||(k.status=666),V===Q||V===$)return B.avail_out===0&&(k.last_flush=-1),l;if(V===H&&(O===1?s._tr_align(k):O!==5&&(s._tr_stored_block(k,0,0,!1),O===3&&(Z(k.head),k.lookahead===0&&(k.strstart=0,k.block_start=0,k.insert=0))),G(B),B.avail_out===0))return k.last_flush=-1,l}return O!==c?l:k.wrap<=0?1:(k.wrap===2?(_(k,255&B.adler),_(k,B.adler>>8&255),_(k,B.adler>>16&255),_(k,B.adler>>24&255),_(k,255&B.total_in),_(k,B.total_in>>8&255),_(k,B.total_in>>16&255),_(k,B.total_in>>24&255)):(K(k,B.adler>>>16),K(k,65535&B.adler)),G(B),0<k.wrap&&(k.wrap=-k.wrap),k.pending!==0?l:1)},t.deflateEnd=function(B){var O;return B&&B.state?(O=B.state.status)!==S&&O!==69&&O!==73&&O!==91&&O!==103&&O!==b&&O!==666?T(B,g):(B.state=null,O===b?T(B,-3):l):g},t.deflateSetDictionary=function(B,O){var P,k,v,x,Y,V,R,W,j=O.length;if(!B||!B.state||(x=(P=B.state).wrap)===2||x===1&&P.status!==S||P.lookahead)return g;for(x===1&&(B.adler=n(B.adler,O,j,0)),P.wrap=0,j>=P.w_size&&(x===0&&(Z(P.head),P.strstart=0,P.block_start=0,P.insert=0),W=new i.Buf8(P.w_size),i.arraySet(W,O,j-P.w_size,P.w_size,0),O=W,j=P.w_size),Y=B.avail_in,V=B.next_in,R=B.input,B.avail_in=j,B.next_in=0,B.input=O,ot(P);P.lookahead>=F;){for(k=P.strstart,v=P.lookahead-(F-1);P.ins_h=(P.ins_h<<P.hash_shift^P.window[k+F-1])&P.hash_mask,P.prev[k&P.w_mask]=P.head[P.ins_h],P.head[P.ins_h]=k,k++,--v;);P.strstart=k,P.lookahead=F-1,ot(P)}return P.strstart+=P.lookahead,P.block_start=P.strstart,P.insert=P.lookahead,P.lookahead=0,P.match_length=P.prev_length=F-1,P.match_available=0,B.next_in=V,B.input=R,B.avail_in=Y,P.wrap=x,l},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(h,A,t){"use strict";A.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(h,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,c,l,g,p,d,I,u,f,C,m,E,w,y,F,D,L,S,b,Q,H;s=e.state,n=e.next_in,Q=e.input,o=n+(e.avail_in-5),a=e.next_out,H=e.output,r=a-(i-e.avail_out),c=a+(e.avail_out-257),l=s.dmax,g=s.wsize,p=s.whave,d=s.wnext,I=s.window,u=s.hold,f=s.bits,C=s.lencode,m=s.distcode,E=(1<<s.lenbits)-1,w=(1<<s.distbits)-1;t:do{f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=C[u&E];e:for(;;){if(u>>>=F=y>>>24,f-=F,(F=y>>>16&255)===0)H[a++]=65535&y;else{if(!(16&F)){if(!(64&F)){y=C[(65535&y)+(u&(1<<F)-1)];continue e}if(32&F){s.mode=12;break t}e.msg="invalid literal/length code",s.mode=30;break t}D=65535&y,(F&=15)&&(f<F&&(u+=Q[n++]<<f,f+=8),D+=u&(1<<F)-1,u>>>=F,f-=F),f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=m[u&w];i:for(;;){if(u>>>=F=y>>>24,f-=F,!(16&(F=y>>>16&255))){if(!(64&F)){y=m[(65535&y)+(u&(1<<F)-1)];continue i}e.msg="invalid distance code",s.mode=30;break t}if(L=65535&y,f<(F&=15)&&(u+=Q[n++]<<f,(f+=8)<F&&(u+=Q[n++]<<f,f+=8)),l<(L+=u&(1<<F)-1)){e.msg="invalid distance too far back",s.mode=30;break t}if(u>>>=F,f-=F,(F=a-r)<L){if(p<(F=L-F)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break t}if(b=I,(S=0)===d){if(S+=g-F,F<D){for(D-=F;H[a++]=I[S++],--F;);S=a-L,b=H}}else if(d<F){if(S+=g+d-F,(F-=d)<D){for(D-=F;H[a++]=I[S++],--F;);if(S=0,d<D){for(D-=F=d;H[a++]=I[S++],--F;);S=a-L,b=H}}}else if(S+=d-F,F<D){for(D-=F;H[a++]=I[S++],--F;);S=a-L,b=H}for(;2<D;)H[a++]=b[S++],H[a++]=b[S++],H[a++]=b[S++],D-=3;D&&(H[a++]=b[S++],1<D&&(H[a++]=b[S++]))}else{for(S=a-L;H[a++]=H[S++],H[a++]=H[S++],H[a++]=H[S++],2<(D-=3););D&&(H[a++]=H[S++],1<D&&(H[a++]=H[S++]))}break}}break}}while(n<o&&a<c);n-=D=f>>3,u&=(1<<(f-=D<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<c?c-a+257:257-(a-c),s.hold=u,s.bits=f}},{}],49:[function(h,A,t){"use strict";var e=h("../utils/common"),i=h("./adler32"),s=h("./crc32"),n=h("./inffast"),o=h("./inftrees"),a=1,r=2,c=0,l=-2,g=1,p=852,d=592;function I(S){return(S>>>24&255)+(S>>>8&65280)+((65280&S)<<8)+((255&S)<<24)}function u(){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 f(S){var b;return S&&S.state?(b=S.state,S.total_in=S.total_out=b.total=0,S.msg="",b.wrap&&(S.adler=1&b.wrap),b.mode=g,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new e.Buf32(p),b.distcode=b.distdyn=new e.Buf32(d),b.sane=1,b.back=-1,c):l}function C(S){var b;return S&&S.state?((b=S.state).wsize=0,b.whave=0,b.wnext=0,f(S)):l}function m(S,b){var Q,H;return S&&S.state?(H=S.state,b<0?(Q=0,b=-b):(Q=1+(b>>4),b<48&&(b&=15)),b&&(b<8||15<b)?l:(H.window!==null&&H.wbits!==b&&(H.window=null),H.wrap=Q,H.wbits=b,C(S))):l}function E(S,b){var Q,H;return S?(H=new u,(S.state=H).window=null,(Q=m(S,b))!==c&&(S.state=null),Q):l}var w,y,F=!0;function D(S){if(F){var b;for(w=new e.Buf32(512),y=new e.Buf32(32),b=0;b<144;)S.lens[b++]=8;for(;b<256;)S.lens[b++]=9;for(;b<280;)S.lens[b++]=7;for(;b<288;)S.lens[b++]=8;for(o(a,S.lens,0,288,w,0,S.work,{bits:9}),b=0;b<32;)S.lens[b++]=5;o(r,S.lens,0,32,y,0,S.work,{bits:5}),F=!1}S.lencode=w,S.lenbits=9,S.distcode=y,S.distbits=5}function L(S,b,Q,H){var $,M=S.state;return M.window===null&&(M.wsize=1<<M.wbits,M.wnext=0,M.whave=0,M.window=new e.Buf8(M.wsize)),H>=M.wsize?(e.arraySet(M.window,b,Q-M.wsize,M.wsize,0),M.wnext=0,M.whave=M.wsize):(H<($=M.wsize-M.wnext)&&($=H),e.arraySet(M.window,b,Q-H,$,M.wnext),(H-=$)?(e.arraySet(M.window,b,Q-H,H,0),M.wnext=H,M.whave=M.wsize):(M.wnext+=$,M.wnext===M.wsize&&(M.wnext=0),M.whave<M.wsize&&(M.whave+=$))),0}t.inflateReset=C,t.inflateReset2=m,t.inflateResetKeep=f,t.inflateInit=function(S){return E(S,15)},t.inflateInit2=E,t.inflate=function(S,b){var Q,H,$,M,T,J,Z,G,N,_,K,z,ot,pt,st,at,At,nt,Qt,Ct,B,O,P,k,v=0,x=new e.Buf8(4),Y=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!S||!S.state||!S.output||!S.input&&S.avail_in!==0)return l;(Q=S.state).mode===12&&(Q.mode=13),T=S.next_out,$=S.output,Z=S.avail_out,M=S.next_in,H=S.input,J=S.avail_in,G=Q.hold,N=Q.bits,_=J,K=Z,O=c;t:for(;;)switch(Q.mode){case g:if(Q.wrap===0){Q.mode=13;break}for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(2&Q.wrap&&G===35615){x[Q.check=0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0),N=G=0,Q.mode=2;break}if(Q.flags=0,Q.head&&(Q.head.done=!1),!(1&Q.wrap)||(((255&G)<<8)+(G>>8))%31){S.msg="incorrect header check",Q.mode=30;break}if((15&G)!=8){S.msg="unknown compression method",Q.mode=30;break}if(N-=4,B=8+(15&(G>>>=4)),Q.wbits===0)Q.wbits=B;else if(B>Q.wbits){S.msg="invalid window size",Q.mode=30;break}Q.dmax=1<<B,S.adler=Q.check=1,Q.mode=512&G?10:12,N=G=0;break;case 2:for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(Q.flags=G,(255&Q.flags)!=8){S.msg="unknown compression method",Q.mode=30;break}if(57344&Q.flags){S.msg="unknown header flags set",Q.mode=30;break}Q.head&&(Q.head.text=G>>8&1),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0)),N=G=0,Q.mode=3;case 3:for(;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.head&&(Q.head.time=G),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,x[2]=G>>>16&255,x[3]=G>>>24&255,Q.check=s(Q.check,x,4,0)),N=G=0,Q.mode=4;case 4:for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.head&&(Q.head.xflags=255&G,Q.head.os=G>>8),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0)),N=G=0,Q.mode=5;case 5:if(1024&Q.flags){for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.length=G,Q.head&&(Q.head.extra_len=G),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0)),N=G=0}else Q.head&&(Q.head.extra=null);Q.mode=6;case 6:if(1024&Q.flags&&(J<(z=Q.length)&&(z=J),z&&(Q.head&&(B=Q.head.extra_len-Q.length,Q.head.extra||(Q.head.extra=new Array(Q.head.extra_len)),e.arraySet(Q.head.extra,H,M,z,B)),512&Q.flags&&(Q.check=s(Q.check,H,z,M)),J-=z,M+=z,Q.length-=z),Q.length))break t;Q.length=0,Q.mode=7;case 7:if(2048&Q.flags){if(J===0)break t;for(z=0;B=H[M+z++],Q.head&&B&&Q.length<65536&&(Q.head.name+=String.fromCharCode(B)),B&&z<J;);if(512&Q.flags&&(Q.check=s(Q.check,H,z,M)),J-=z,M+=z,B)break t}else Q.head&&(Q.head.name=null);Q.length=0,Q.mode=8;case 8:if(4096&Q.flags){if(J===0)break t;for(z=0;B=H[M+z++],Q.head&&B&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(B)),B&&z<J;);if(512&Q.flags&&(Q.check=s(Q.check,H,z,M)),J-=z,M+=z,B)break t}else Q.head&&(Q.head.comment=null);Q.mode=9;case 9:if(512&Q.flags){for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(G!==(65535&Q.check)){S.msg="header crc mismatch",Q.mode=30;break}N=G=0}Q.head&&(Q.head.hcrc=Q.flags>>9&1,Q.head.done=!0),S.adler=Q.check=0,Q.mode=12;break;case 10:for(;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}S.adler=Q.check=I(G),N=G=0,Q.mode=11;case 11:if(Q.havedict===0)return S.next_out=T,S.avail_out=Z,S.next_in=M,S.avail_in=J,Q.hold=G,Q.bits=N,2;S.adler=Q.check=1,Q.mode=12;case 12:if(b===5||b===6)break t;case 13:if(Q.last){G>>>=7&N,N-=7&N,Q.mode=27;break}for(;N<3;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}switch(Q.last=1&G,N-=1,3&(G>>>=1)){case 0:Q.mode=14;break;case 1:if(D(Q),Q.mode=20,b!==6)break;G>>>=2,N-=2;break t;case 2:Q.mode=17;break;case 3:S.msg="invalid block type",Q.mode=30}G>>>=2,N-=2;break;case 14:for(G>>>=7&N,N-=7&N;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if((65535&G)!=(G>>>16^65535)){S.msg="invalid stored block lengths",Q.mode=30;break}if(Q.length=65535&G,N=G=0,Q.mode=15,b===6)break t;case 15:Q.mode=16;case 16:if(z=Q.length){if(J<z&&(z=J),Z<z&&(z=Z),z===0)break t;e.arraySet($,H,M,z,T),J-=z,M+=z,Z-=z,T+=z,Q.length-=z;break}Q.mode=12;break;case 17:for(;N<14;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(Q.nlen=257+(31&G),G>>>=5,N-=5,Q.ndist=1+(31&G),G>>>=5,N-=5,Q.ncode=4+(15&G),G>>>=4,N-=4,286<Q.nlen||30<Q.ndist){S.msg="too many length or distance symbols",Q.mode=30;break}Q.have=0,Q.mode=18;case 18:for(;Q.have<Q.ncode;){for(;N<3;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.lens[Y[Q.have++]]=7&G,G>>>=3,N-=3}for(;Q.have<19;)Q.lens[Y[Q.have++]]=0;if(Q.lencode=Q.lendyn,Q.lenbits=7,P={bits:Q.lenbits},O=o(0,Q.lens,0,19,Q.lencode,0,Q.work,P),Q.lenbits=P.bits,O){S.msg="invalid code lengths set",Q.mode=30;break}Q.have=0,Q.mode=19;case 19:for(;Q.have<Q.nlen+Q.ndist;){for(;at=(v=Q.lencode[G&(1<<Q.lenbits)-1])>>>16&255,At=65535&v,!((st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(At<16)G>>>=st,N-=st,Q.lens[Q.have++]=At;else{if(At===16){for(k=st+2;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(G>>>=st,N-=st,Q.have===0){S.msg="invalid bit length repeat",Q.mode=30;break}B=Q.lens[Q.have-1],z=3+(3&G),G>>>=2,N-=2}else if(At===17){for(k=st+3;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}N-=st,B=0,z=3+(7&(G>>>=st)),G>>>=3,N-=3}else{for(k=st+7;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}N-=st,B=0,z=11+(127&(G>>>=st)),G>>>=7,N-=7}if(Q.have+z>Q.nlen+Q.ndist){S.msg="invalid bit length repeat",Q.mode=30;break}for(;z--;)Q.lens[Q.have++]=B}}if(Q.mode===30)break;if(Q.lens[256]===0){S.msg="invalid code -- missing end-of-block",Q.mode=30;break}if(Q.lenbits=9,P={bits:Q.lenbits},O=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,P),Q.lenbits=P.bits,O){S.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,P={bits:Q.distbits},O=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,P),Q.distbits=P.bits,O){S.msg="invalid distances set",Q.mode=30;break}if(Q.mode=20,b===6)break t;case 20:Q.mode=21;case 21:if(6<=J&&258<=Z){S.next_out=T,S.avail_out=Z,S.next_in=M,S.avail_in=J,Q.hold=G,Q.bits=N,n(S,K),T=S.next_out,$=S.output,Z=S.avail_out,M=S.next_in,H=S.input,J=S.avail_in,G=Q.hold,N=Q.bits,Q.mode===12&&(Q.back=-1);break}for(Q.back=0;at=(v=Q.lencode[G&(1<<Q.lenbits)-1])>>>16&255,At=65535&v,!((st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(at&&!(240&at)){for(nt=st,Qt=at,Ct=At;at=(v=Q.lencode[Ct+((G&(1<<nt+Qt)-1)>>nt)])>>>16&255,At=65535&v,!(nt+(st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}G>>>=nt,N-=nt,Q.back+=nt}if(G>>>=st,N-=st,Q.back+=st,Q.length=At,at===0){Q.mode=26;break}if(32&at){Q.back=-1,Q.mode=12;break}if(64&at){S.msg="invalid literal/length code",Q.mode=30;break}Q.extra=15&at,Q.mode=22;case 22:if(Q.extra){for(k=Q.extra;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.length+=G&(1<<Q.extra)-1,G>>>=Q.extra,N-=Q.extra,Q.back+=Q.extra}Q.was=Q.length,Q.mode=23;case 23:for(;at=(v=Q.distcode[G&(1<<Q.distbits)-1])>>>16&255,At=65535&v,!((st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(!(240&at)){for(nt=st,Qt=at,Ct=At;at=(v=Q.distcode[Ct+((G&(1<<nt+Qt)-1)>>nt)])>>>16&255,At=65535&v,!(nt+(st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}G>>>=nt,N-=nt,Q.back+=nt}if(G>>>=st,N-=st,Q.back+=st,64&at){S.msg="invalid distance code",Q.mode=30;break}Q.offset=At,Q.extra=15&at,Q.mode=24;case 24:if(Q.extra){for(k=Q.extra;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.offset+=G&(1<<Q.extra)-1,G>>>=Q.extra,N-=Q.extra,Q.back+=Q.extra}if(Q.offset>Q.dmax){S.msg="invalid distance too far back",Q.mode=30;break}Q.mode=25;case 25:if(Z===0)break t;if(z=K-Z,Q.offset>z){if((z=Q.offset-z)>Q.whave&&Q.sane){S.msg="invalid distance too far back",Q.mode=30;break}ot=z>Q.wnext?(z-=Q.wnext,Q.wsize-z):Q.wnext-z,z>Q.length&&(z=Q.length),pt=Q.window}else pt=$,ot=T-Q.offset,z=Q.length;for(Z<z&&(z=Z),Z-=z,Q.length-=z;$[T++]=pt[ot++],--z;);Q.length===0&&(Q.mode=21);break;case 26:if(Z===0)break t;$[T++]=Q.length,Z--,Q.mode=21;break;case 27:if(Q.wrap){for(;N<32;){if(J===0)break t;J--,G|=H[M++]<<N,N+=8}if(K-=Z,S.total_out+=K,Q.total+=K,K&&(S.adler=Q.check=Q.flags?s(Q.check,$,K,T-K):i(Q.check,$,K,T-K)),K=Z,(Q.flags?G:I(G))!==Q.check){S.msg="incorrect data check",Q.mode=30;break}N=G=0}Q.mode=28;case 28:if(Q.wrap&&Q.flags){for(;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(G!==(4294967295&Q.total)){S.msg="incorrect length check",Q.mode=30;break}N=G=0}Q.mode=29;case 29:O=1;break t;case 30:O=-3;break t;case 31:return-4;case 32:default:return l}return S.next_out=T,S.avail_out=Z,S.next_in=M,S.avail_in=J,Q.hold=G,Q.bits=N,(Q.wsize||K!==S.avail_out&&Q.mode<30&&(Q.mode<27||b!==4))&&L(S,S.output,S.next_out,K-S.avail_out)?(Q.mode=31,-4):(_-=S.avail_in,K-=S.avail_out,S.total_in+=_,S.total_out+=K,Q.total+=K,Q.wrap&&K&&(S.adler=Q.check=Q.flags?s(Q.check,$,K,S.next_out-K):i(Q.check,$,K,S.next_out-K)),S.data_type=Q.bits+(Q.last?64:0)+(Q.mode===12?128:0)+(Q.mode===20||Q.mode===15?256:0),(_==0&&K===0||b===4)&&O===c&&(O=-5),O)},t.inflateEnd=function(S){if(!S||!S.state)return l;var b=S.state;return b.window&&(b.window=null),S.state=null,c},t.inflateGetHeader=function(S,b){var Q;return S&&S.state&&2&(Q=S.state).wrap?((Q.head=b).done=!1,c):l},t.inflateSetDictionary=function(S,b){var Q,H=b.length;return S&&S.state?(Q=S.state).wrap!==0&&Q.mode!==11?l:Q.mode===11&&i(1,b,H,0)!==Q.check?-3:L(S,b,H,H)?(Q.mode=31,-4):(Q.havedict=1,c):l},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(h,A,t){"use strict";var e=h("../utils/common"),i=[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],s=[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],o=[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];A.exports=function(a,r,c,l,g,p,d,I){var u,f,C,m,E,w,y,F,D,L=I.bits,S=0,b=0,Q=0,H=0,$=0,M=0,T=0,J=0,Z=0,G=0,N=null,_=0,K=new e.Buf16(16),z=new e.Buf16(16),ot=null,pt=0;for(S=0;S<=15;S++)K[S]=0;for(b=0;b<l;b++)K[r[c+b]]++;for($=L,H=15;1<=H&&K[H]===0;H--);if(H<$&&($=H),H===0)return g[p++]=20971520,g[p++]=20971520,I.bits=1,0;for(Q=1;Q<H&&K[Q]===0;Q++);for($<Q&&($=Q),S=J=1;S<=15;S++)if(J<<=1,(J-=K[S])<0)return-1;if(0<J&&(a===0||H!==1))return-1;for(z[1]=0,S=1;S<15;S++)z[S+1]=z[S]+K[S];for(b=0;b<l;b++)r[c+b]!==0&&(d[z[r[c+b]]++]=b);if(w=a===0?(N=ot=d,19):a===1?(N=i,_-=257,ot=s,pt-=257,256):(N=n,ot=o,-1),S=Q,E=p,T=b=G=0,C=-1,m=(Z=1<<(M=$))-1,a===1&&852<Z||a===2&&592<Z)return 1;for(;;){for(y=S-T,D=d[b]<w?(F=0,d[b]):d[b]>w?(F=ot[pt+d[b]],N[_+d[b]]):(F=96,0),u=1<<S-T,Q=f=1<<M;g[E+(G>>T)+(f-=u)]=y<<24|F<<16|D|0,f!==0;);for(u=1<<S-1;G&u;)u>>=1;if(u!==0?(G&=u-1,G+=u):G=0,b++,--K[S]==0){if(S===H)break;S=r[c+d[b]]}if($<S&&(G&m)!==C){for(T===0&&(T=$),E+=Q,J=1<<(M=S-T);M+T<H&&!((J-=K[M+T])<=0);)M++,J<<=1;if(Z+=1<<M,a===1&&852<Z||a===2&&592<Z)return 1;g[C=G&m]=$<<24|M<<16|E-p|0}}return G!==0&&(g[E+G]=S-T<<24|64<<16|0),I.bits=$,0}},{"../utils/common":41}],51:[function(h,A,t){"use strict";A.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(h,A,t){"use strict";var e=h("../utils/common"),i=0,s=1;function n(v){for(var x=v.length;0<=--x;)v[x]=0}var o=0,a=29,r=256,c=r+1+a,l=30,g=19,p=2*c+1,d=15,I=16,u=7,f=256,C=16,m=17,E=18,w=[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],y=[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],F=[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],L=new Array(2*(c+2));n(L);var S=new Array(2*l);n(S);var b=new Array(512);n(b);var Q=new Array(256);n(Q);var H=new Array(a);n(H);var $,M,T,J=new Array(l);function Z(v,x,Y,V,R){this.static_tree=v,this.extra_bits=x,this.extra_base=Y,this.elems=V,this.max_length=R,this.has_stree=v&&v.length}function G(v,x){this.dyn_tree=v,this.max_code=0,this.stat_desc=x}function N(v){return v<256?b[v]:b[256+(v>>>7)]}function _(v,x){v.pending_buf[v.pending++]=255&x,v.pending_buf[v.pending++]=x>>>8&255}function K(v,x,Y){v.bi_valid>I-Y?(v.bi_buf|=x<<v.bi_valid&65535,_(v,v.bi_buf),v.bi_buf=x>>I-v.bi_valid,v.bi_valid+=Y-I):(v.bi_buf|=x<<v.bi_valid&65535,v.bi_valid+=Y)}function z(v,x,Y){K(v,Y[2*x],Y[2*x+1])}function ot(v,x){for(var Y=0;Y|=1&v,v>>>=1,Y<<=1,0<--x;);return Y>>>1}function pt(v,x,Y){var V,R,W=new Array(d+1),j=0;for(V=1;V<=d;V++)W[V]=j=j+Y[V-1]<<1;for(R=0;R<=x;R++){var X=v[2*R+1];X!==0&&(v[2*R]=ot(W[X]++,X))}}function st(v){var x;for(x=0;x<c;x++)v.dyn_ltree[2*x]=0;for(x=0;x<l;x++)v.dyn_dtree[2*x]=0;for(x=0;x<g;x++)v.bl_tree[2*x]=0;v.dyn_ltree[2*f]=1,v.opt_len=v.static_len=0,v.last_lit=v.matches=0}function at(v){8<v.bi_valid?_(v,v.bi_buf):0<v.bi_valid&&(v.pending_buf[v.pending++]=v.bi_buf),v.bi_buf=0,v.bi_valid=0}function At(v,x,Y,V){var R=2*x,W=2*Y;return v[R]<v[W]||v[R]===v[W]&&V[x]<=V[Y]}function nt(v,x,Y){for(var V=v.heap[Y],R=Y<<1;R<=v.heap_len&&(R<v.heap_len&&At(x,v.heap[R+1],v.heap[R],v.depth)&&R++,!At(x,V,v.heap[R],v.depth));)v.heap[Y]=v.heap[R],Y=R,R<<=1;v.heap[Y]=V}function Qt(v,x,Y){var V,R,W,j,X=0;if(v.last_lit!==0)for(;V=v.pending_buf[v.d_buf+2*X]<<8|v.pending_buf[v.d_buf+2*X+1],R=v.pending_buf[v.l_buf+X],X++,V===0?z(v,R,x):(z(v,(W=Q[R])+r+1,x),(j=w[W])!==0&&K(v,R-=H[W],j),z(v,W=N(--V),Y),(j=y[W])!==0&&K(v,V-=J[W],j)),X<v.last_lit;);z(v,f,x)}function Ct(v,x){var Y,V,R,W=x.dyn_tree,j=x.stat_desc.static_tree,X=x.stat_desc.has_stree,it=x.stat_desc.elems,ut=-1;for(v.heap_len=0,v.heap_max=p,Y=0;Y<it;Y++)W[2*Y]!==0?(v.heap[++v.heap_len]=ut=Y,v.depth[Y]=0):W[2*Y+1]=0;for(;v.heap_len<2;)W[2*(R=v.heap[++v.heap_len]=ut<2?++ut:0)]=1,v.depth[R]=0,v.opt_len--,X&&(v.static_len-=j[2*R+1]);for(x.max_code=ut,Y=v.heap_len>>1;1<=Y;Y--)nt(v,W,Y);for(R=it;Y=v.heap[1],v.heap[1]=v.heap[v.heap_len--],nt(v,W,1),V=v.heap[1],v.heap[--v.heap_max]=Y,v.heap[--v.heap_max]=V,W[2*R]=W[2*Y]+W[2*V],v.depth[R]=(v.depth[Y]>=v.depth[V]?v.depth[Y]:v.depth[V])+1,W[2*Y+1]=W[2*V+1]=R,v.heap[1]=R++,nt(v,W,1),2<=v.heap_len;);v.heap[--v.heap_max]=v.heap[1],function(lt,xt){var He,Ut,Te,Et,ai,ns,Lt=xt.dyn_tree,Os=xt.max_code,Ao=xt.stat_desc.static_tree,co=xt.stat_desc.has_stree,lo=xt.stat_desc.extra_bits,Ks=xt.stat_desc.extra_base,Ue=xt.stat_desc.max_length,ri=0;for(Et=0;Et<=d;Et++)lt.bl_count[Et]=0;for(Lt[2*lt.heap[lt.heap_max]+1]=0,He=lt.heap_max+1;He<p;He++)Ue<(Et=Lt[2*Lt[2*(Ut=lt.heap[He])+1]+1]+1)&&(Et=Ue,ri++),Lt[2*Ut+1]=Et,Os<Ut||(lt.bl_count[Et]++,ai=0,Ks<=Ut&&(ai=lo[Ut-Ks]),ns=Lt[2*Ut],lt.opt_len+=ns*(Et+ai),co&&(lt.static_len+=ns*(Ao[2*Ut+1]+ai)));if(ri!==0){do{for(Et=Ue-1;lt.bl_count[Et]===0;)Et--;lt.bl_count[Et]--,lt.bl_count[Et+1]+=2,lt.bl_count[Ue]--,ri-=2}while(0<ri);for(Et=Ue;Et!==0;Et--)for(Ut=lt.bl_count[Et];Ut!==0;)Os<(Te=lt.heap[--He])||(Lt[2*Te+1]!==Et&&(lt.opt_len+=(Et-Lt[2*Te+1])*Lt[2*Te],Lt[2*Te+1]=Et),Ut--)}}(v,x),pt(W,ut,v.bl_count)}function B(v,x,Y){var V,R,W=-1,j=x[1],X=0,it=7,ut=4;for(j===0&&(it=138,ut=3),x[2*(Y+1)+1]=65535,V=0;V<=Y;V++)R=j,j=x[2*(V+1)+1],++X<it&&R===j||(X<ut?v.bl_tree[2*R]+=X:R!==0?(R!==W&&v.bl_tree[2*R]++,v.bl_tree[2*C]++):X<=10?v.bl_tree[2*m]++:v.bl_tree[2*E]++,W=R,ut=(X=0)===j?(it=138,3):R===j?(it=6,3):(it=7,4))}function O(v,x,Y){var V,R,W=-1,j=x[1],X=0,it=7,ut=4;for(j===0&&(it=138,ut=3),V=0;V<=Y;V++)if(R=j,j=x[2*(V+1)+1],!(++X<it&&R===j)){if(X<ut)for(;z(v,R,v.bl_tree),--X!=0;);else R!==0?(R!==W&&(z(v,R,v.bl_tree),X--),z(v,C,v.bl_tree),K(v,X-3,2)):X<=10?(z(v,m,v.bl_tree),K(v,X-3,3)):(z(v,E,v.bl_tree),K(v,X-11,7));W=R,ut=(X=0)===j?(it=138,3):R===j?(it=6,3):(it=7,4)}}n(J);var P=!1;function k(v,x,Y,V){K(v,(o<<1)+(V?1:0),3),function(R,W,j,X){at(R),X&&(_(R,j),_(R,~j)),e.arraySet(R.pending_buf,R.window,W,j,R.pending),R.pending+=j}(v,x,Y,!0)}t._tr_init=function(v){P||(function(){var x,Y,V,R,W,j=new Array(d+1);for(R=V=0;R<a-1;R++)for(H[R]=V,x=0;x<1<<w[R];x++)Q[V++]=R;for(Q[V-1]=R,R=W=0;R<16;R++)for(J[R]=W,x=0;x<1<<y[R];x++)b[W++]=R;for(W>>=7;R<l;R++)for(J[R]=W<<7,x=0;x<1<<y[R]-7;x++)b[256+W++]=R;for(Y=0;Y<=d;Y++)j[Y]=0;for(x=0;x<=143;)L[2*x+1]=8,x++,j[8]++;for(;x<=255;)L[2*x+1]=9,x++,j[9]++;for(;x<=279;)L[2*x+1]=7,x++,j[7]++;for(;x<=287;)L[2*x+1]=8,x++,j[8]++;for(pt(L,c+1,j),x=0;x<l;x++)S[2*x+1]=5,S[2*x]=ot(x,5);$=new Z(L,w,r+1,c,d),M=new Z(S,y,0,l,d),T=new Z(new Array(0),F,0,g,u)}(),P=!0),v.l_desc=new G(v.dyn_ltree,$),v.d_desc=new G(v.dyn_dtree,M),v.bl_desc=new G(v.bl_tree,T),v.bi_buf=0,v.bi_valid=0,st(v)},t._tr_stored_block=k,t._tr_flush_block=function(v,x,Y,V){var R,W,j=0;0<v.level?(v.strm.data_type===2&&(v.strm.data_type=function(X){var it,ut=4093624447;for(it=0;it<=31;it++,ut>>>=1)if(1&ut&&X.dyn_ltree[2*it]!==0)return i;if(X.dyn_ltree[18]!==0||X.dyn_ltree[20]!==0||X.dyn_ltree[26]!==0)return s;for(it=32;it<r;it++)if(X.dyn_ltree[2*it]!==0)return s;return i}(v)),Ct(v,v.l_desc),Ct(v,v.d_desc),j=function(X){var it;for(B(X,X.dyn_ltree,X.l_desc.max_code),B(X,X.dyn_dtree,X.d_desc.max_code),Ct(X,X.bl_desc),it=g-1;3<=it&&X.bl_tree[2*D[it]+1]===0;it--);return X.opt_len+=3*(it+1)+5+5+4,it}(v),R=v.opt_len+3+7>>>3,(W=v.static_len+3+7>>>3)<=R&&(R=W)):R=W=Y+5,Y+4<=R&&x!==-1?k(v,x,Y,V):v.strategy===4||W===R?(K(v,2+(V?1:0),3),Qt(v,L,S)):(K(v,4+(V?1:0),3),function(X,it,ut,lt){var xt;for(K(X,it-257,5),K(X,ut-1,5),K(X,lt-4,4),xt=0;xt<lt;xt++)K(X,X.bl_tree[2*D[xt]+1],3);O(X,X.dyn_ltree,it-1),O(X,X.dyn_dtree,ut-1)}(v,v.l_desc.max_code+1,v.d_desc.max_code+1,j+1),Qt(v,v.dyn_ltree,v.dyn_dtree)),st(v),V&&at(v)},t._tr_tally=function(v,x,Y){return v.pending_buf[v.d_buf+2*v.last_lit]=x>>>8&255,v.pending_buf[v.d_buf+2*v.last_lit+1]=255&x,v.pending_buf[v.l_buf+v.last_lit]=255&Y,v.last_lit++,x===0?v.dyn_ltree[2*Y]++:(v.matches++,x--,v.dyn_ltree[2*(Q[Y]+r+1)]++,v.dyn_dtree[2*N(x)]++),v.last_lit===v.lit_bufsize-1},t._tr_align=function(v){K(v,2,3),z(v,f,L),function(x){x.bi_valid===16?(_(x,x.bi_buf),x.bi_buf=0,x.bi_valid=0):8<=x.bi_valid&&(x.pending_buf[x.pending++]=255&x.bi_buf,x.bi_buf>>=8,x.bi_valid-=8)}(v)}},{"../utils/common":41}],53:[function(h,A,t){"use strict";A.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(h,A,t){(function(e){(function(i,s){"use strict";if(!i.setImmediate){var n,o,a,r,c=1,l={},g=!1,p=i.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(i);d=d&&d.setTimeout?d:i,n={}.toString.call(i.process)==="[object process]"?function(C){process.nextTick(function(){u(C)})}:function(){if(i.postMessage&&!i.importScripts){var C=!0,m=i.onmessage;return i.onmessage=function(){C=!1},i.postMessage("","*"),i.onmessage=m,C}}()?(r="setImmediate$"+Math.random()+"$",i.addEventListener?i.addEventListener("message",f,!1):i.attachEvent("onmessage",f),function(C){i.postMessage(r+C,"*")}):i.MessageChannel?((a=new MessageChannel).port1.onmessage=function(C){u(C.data)},function(C){a.port2.postMessage(C)}):p&&"onreadystatechange"in p.createElement("script")?(o=p.documentElement,function(C){var m=p.createElement("script");m.onreadystatechange=function(){u(C),m.onreadystatechange=null,o.removeChild(m),m=null},o.appendChild(m)}):function(C){setTimeout(u,0,C)},d.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var m=new Array(arguments.length-1),E=0;E<m.length;E++)m[E]=arguments[E+1];var w={callback:C,args:m};return l[c]=w,n(c),c++},d.clearImmediate=I}function I(C){delete l[C]}function u(C){if(g)setTimeout(u,0,C);else{var m=l[C];if(m){g=!0;try{(function(E){var w=E.callback,y=E.args;switch(y.length){case 0:w();break;case 1:w(y[0]);break;case 2:w(y[0],y[1]);break;case 3:w(y[0],y[1],y[2]);break;default:w.apply(s,y)}})(m)}finally{I(C),g=!1}}}}function f(C){C.source===i&&typeof C.data=="string"&&C.data.indexOf(r)===0&&u(+C.data.slice(r.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 va={};ci(va,{default:()=>ss});module.exports=Bo(va);var tt=require("obsidian");wt();var kt=require("obsidian");var mt=require("obsidian");wt();function di(h){let A=(h.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function Jt(h,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(h))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(h))}}function re(h,A){let t=di(A);switch(A.dateDisplayFormat??"locale"){case"iso":return $s(h,A,!0);case"us":return Jt(h,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Jt(h,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Jt(h,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Jt(h,{...t,dateStyle:"medium",timeStyle:"short"})}}function Xs(h,A){let t=di(A);switch(A.dateDisplayFormat??"locale"){case"iso":return $s(h,A,!1);case"us":return Jt(h,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Jt(h,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Jt(h,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(h).getFullYear()===e.getFullYear();return Jt(h,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Zs(h,A){let t=di(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return Jt(h,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function $s(h,A,t){let e=di(A),i=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(h)),s=o=>i.find(a=>a.type===o)?.value??"",n=`${s("year")}-${s("month")}-${s("day")}`;return t?`${n} ${s("hour")}:${s("minute")}`:n}function de(h,A,t){let e=h.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(A>99?"99+":String(A))}var Xe={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},ui=class extends mt.ItemView{constructor(t,e){super(t);this.plugin=e;this.activePanel="pinned";this.taskFilter="all";this.taskAssignFilter="all";this.taskFolderFilter="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 Vt}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()===dt&&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"}),i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(i.createSpan({cls:"stashpad-panels-global-btn-icon"}),"search"),i.createSpan({cls:"stashpad-panels-global-btn-text",text:"Search"}),i.onclick=()=>this.openSearchFromPanel();let s=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(s.createSpan({cls:"stashpad-panels-global-btn-icon"}),"folder-tree"),s.createSpan({cls:"stashpad-panels-global-btn-text",text:"Folder Switcher"}),s.onclick=()=>this.plugin.openFolderPicker();let n=e.createDiv({cls:"stashpad-panels-globals-row"}),o=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(o.createSpan({cls:"stashpad-panels-global-btn-icon"}),"scroll-text"),o.createSpan({cls:"stashpad-panels-global-btn-text",text:"Log"}),o.onclick=()=>this.openLogFromPanel();let a=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.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 r=t.createDiv({cls:"stashpad-panels-bar"});for(let l of Object.keys(Xe)){let g=Xe[l],p=r.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,mt.setIcon)(p.createSpan({cls:"stashpad-panels-bar-btn-icon"}),g.icon),p.createSpan({cls:"stashpad-panels-bar-btn-text",text:g.label}),this.activePanel===l&&p.addClass("is-active"),p.onclick=()=>{this.activePanel!==l&&(this.activePanel=l,this.render())}}let c=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(c):this.activePanel==="shared"?this.renderSharedPanel(c):this.activePanel==="tasks"&&this.renderTasksPanel(c)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new mt.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinnedPanel(t){let e=t.createDiv({cls:"stashpad-panel-pinned"});(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"&&e.addClass("is-flat");let i=e.createDiv({cls:"stashpad-pinned-headrow"}),s=i.createEl("button",{cls:"stashpad-pinned-row stashpad-pinned-home"}),n=s.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(n,"home"),s.createSpan({cls:"stashpad-pinned-label",text:"Home"}),s.onclick=()=>this.openHomeFromPanel();let o=i.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-pinned-opts"});(0,mt.setIcon)(o,"list"),o.setAttr("aria-label","Pinned view options"),o.onclick=p=>{p.stopPropagation(),this.openPinnedOptionsMenu(p)};let a=this.plugin.listPinnedNotes();if(a.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}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"){a.forEach((p,d)=>this.renderPinnedRow(e,p,d));return}let c=new Map;a.forEach((p,d)=>{let I=c.get(p.folder);I||(I=[],c.set(p.folder,I)),I.push({pin:p,idx:d})});let l=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,g=Array.from(c.keys());l&&c.has(l)&&(g.splice(g.indexOf(l),1),g.unshift(l));for(let p of g){let d=p.split("/").pop()||p,I=e.createDiv({cls:"stashpad-pinned-group-header"});p===l&&I.addClass("is-active-folder"),I.createSpan({cls:"stashpad-pinned-group-name",text:d});let u=c.get(p)??[];for(let{pin:f,idx:C}of u)this.renderPinnedRow(e,f,C)}}renderPinnedRow(t,e,i){let s=this.findFileFor(e);if(!s)return;let n=this.app.metadataCache.getFileCache(s)?.frontmatter??{},o=this.titleFromFile(s),a=typeof n.color=="string"?n.color:null,r=n.completed===!0,c=this.childrenOf(e.folder,e.id).length,l=c>0,g=this.expanded.has(`${e.folder}|${e.id}`),p=t.createDiv({cls:"stashpad-pinned-row"});a&&p.addClass("has-color"),r&&p.addClass("is-completed"),p.draggable=!0,p.dataset.pinIdx=String(i),p.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=p.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;p.toggleClass("drop-before",E),p.toggleClass("drop-after",!E)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",C=>{C.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let E=p.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?i:i+1)});let d=p.createSpan({cls:"stashpad-pinned-toggle"});l&&(de(d,c,g),d.onclick=C=>{C.stopPropagation();let m=`${e.folder}|${e.id}`;this.expanded.has(m)?this.expanded.delete(m):this.expanded.add(m),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(I,l?"folder-tree":"file-text"),a&&(I.style.color=a);let u=p.createSpan({cls:"stashpad-pinned-label",text:o});u.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(p.createSpan({cls:"stashpad-pinned-folder",text:f}),p.oncontextmenu=C=>{C.preventDefault();let m=new mt.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},l&&g){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(C,e.folder,e.id,1)}}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((l,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],c;!a&&!r?c=Date.now():a?r?c=(a.pinnedAt+r.pinnedAt)/2:c=a.pinnedAt+1e3:c=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,l=>{l.pinnedAt=c})}catch(l){console.warn("[Stashpad] pin reorder failed",l)}this.render()}renderPinnedSubtree(t,e,i,s){let n=this.childrenOf(e,i);for(let o of n){let a=this.app.metadataCache.getFileCache(o)?.frontmatter??{},r=typeof a.id=="string"?a.id:null;if(!r)continue;let c=typeof a.color=="string"?a.color:null,l=a.completed===!0,g=this.childrenOf(e,r).length,p=g>0,d=this.expanded.has(`${e}|${r}`),I=t.createDiv({cls:"stashpad-pinned-subrow"});l&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});p&&(de(u,g,d),u.onclick=m=>{m.stopPropagation();let E=`${e}|${r}`;this.expanded.has(E)?this.expanded.delete(E):this.expanded.add(E),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(f,"file-text"),c&&(f.style.color=c);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:r}),p&&d&&this.renderPinnedSubtree(t,e,r,s+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 i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===U&&(a==null||a===U)){if(o.id===U)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.created??"",c=a?.created??"";return r.localeCompare(c)}),i}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 mt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Mt(),We));new s(this.app,i,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(U)}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()===dt)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(dt);return i.length>0?(this.app.workspace.revealLeaf(i[0]),i[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===dt?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let l of s){let g=l.authorId;g&&!n.has(g)&&n.set(g,l.authorDisplay||g)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(l,g,p)=>{let d=o.createEl("button",{cls:"stashpad-shared-chip",text:l});return g&&d.addClass("is-active"),d.onclick=p,d};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 l=o.createEl("select",{cls:"stashpad-shared-author-select"}),g=l.createEl("option",{text:"Any author"});g.value="__any__";for(let[d,I]of n){let u=l.createEl("option",{text:I});u.value=d}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;l.value=p,l.onchange=()=>{let d=l.value;d==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=d,this.render()}}let r=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&r.addClass("is-active"),r.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let c=s.filter(l=>{if(this.sharedContribOnly&&l.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return l.authorId===i;case"others":return l.authorId!==i;default:return l.authorId===this.sharedAuthorFilter}});if(c.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let l of c){let g=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),p=g.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(p,"users"),l.color&&(p.style.color=l.color);let d=g.createSpan({cls:"stashpad-pinned-label",text:l.title});d.onclick=()=>this.openSharedFromPanel(l.folder,l.id);let I=l.folder.split("/").pop()||l.folder;g.createSpan({cls:"stashpad-pinned-folder",text:I}),l.authorDisplay&&g.createSpan({cls:"stashpad-shared-meta"}).setText(l.authorId===i?`you \xB7 ${l.contributorCount} contributor${l.contributorCount===1?"":"s"}`:`by ${l.authorDisplay}${l.contributorCount>0?` \xB7 ${l.contributorCount} contributor${l.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),i=new Set(e),s=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};r.id===U&&s.set(a,this.extractAuthorId(r.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a)||a.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof r.id!="string"||r.id===U)continue;let c=this.extractAuthorId(r.author),l=Array.isArray(r.contributors)?r.contributors.filter(m=>typeof m=="string"):[],g=s.get(a)??null;if(!(l.length>0||g===t&&(c!==null&&c!==t)))continue;let f=this.titleFromFile(o),C=typeof r.color=="string"?r.color:null;n.push({file:o,folder:a,id:r.id,title:f,color:C,authorId:c,authorDisplay:this.extractAuthorDisplay(r.author)||(c??""),contributorCount:l.length})}return n.sort((o,a)=>{let r=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},c=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},l=r.modified??r.created??"";return(c.modified??c.created??"").localeCompare(l)}),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 i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.activateViewForFolder(t);let i=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();i&&typeof i.navigateTo=="function"&&i.navigateTo(e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),i=this.collectTasks();if(i.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 s=(this.plugin.settings.authorId??"").trim(),n=M=>!!s&&M.assignedTo.some(T=>T.id===s),o=M=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let J=T.slice(7);return M.assignedTo.some(Z=>Z.id===J)}switch(T){case"mine":return n(M);case"others":return M.assignedTo.length>0&&!n(M);case"byme":return!!s&&M.assignedBy?.id===s;case"unassigned":return M.assignedTo.length===0;default:return!0}},a=new Map;for(let M of i){for(let T of M.assignedTo)T.id!==s&&a.set(T.id,T.name);M.assignedBy&&M.assignedBy.id!==s&&a.set(M.assignedBy.id,M.assignedBy.name)}let r=[...a.entries()].map(([M,T])=>({id:M,name:T})).sort((M,T)=>M.name.localeCompare(T.name)),c=e.createDiv({cls:"stashpad-task-assign-bar"});c.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let l=c.createEl("select",{cls:"stashpad-task-assign-select"}),g=M=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return M.startsWith("person:")?a.get(M.slice(7))??"Person":T[M]??M},p=M=>{let T=l.createEl("option",{text:g(M),value:M});this.taskAssignFilter===M&&(T.selected=!0)};for(let M of["all","mine","others","byme","unassigned"])p(M);if(r.length>0){let M=l.createEl("optgroup");M.setAttr("label","By person");for(let T of r){let J=M.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(J.selected=!0)}}l.onchange=()=>{this.taskAssignFilter=l.value,this.render()};let d=[...new Set(i.map(M=>M.folder))].sort((M,T)=>M.localeCompare(T));this.taskFolderFilter!=="all"&&!d.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let I=e.createDiv({cls:"stashpad-task-assign-bar"});I.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let u=I.createEl("select",{cls:"stashpad-task-assign-select"}),f=u.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let M of d){let T=u.createEl("option",{text:M.split("/").pop()||M,value:M});this.taskFolderFilter===M&&(T.selected=!0)}u.onchange=()=>{this.taskFolderFilter=u.value,this.render()};let C=M=>this.taskFolderFilter==="all"||M.folder===this.taskFolderFilter,m=i.filter(M=>o(M)&&C(M));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let E=new Date;E.setHours(0,0,0,0);let w=E.getTime(),y=w+24*60*60*1e3,F={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let M of m){if(M.completed){F.completed.push(M);continue}if(M.due==null){F.nodate.push(M);continue}M.due<w?F.overdue.push(M):M.due<y?F.today.push(M):F.upcoming.push(M)}let D=(M,T)=>M.due==null&&T.due==null?M.title.localeCompare(T.title):M.due==null?1:T.due==null?-1:M.due-T.due,L=[{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"}],S=e.createDiv({cls:"stashpad-task-filters"}),b=m.length,Q=(M,T,J)=>{let Z=S.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===M&&Z.addClass("is-active"),Z.createSpan({cls:"stashpad-task-filter-label",text:T}),Z.createSpan({cls:"stashpad-task-filter-count",text:String(J)}),Z.onclick=()=>{this.taskFilter=M,this.render()}};Q("all","All",b),Q("overdue","Overdue",F.overdue.length),Q("today","Today",F.today.length),Q("upcoming","Upcoming",F.upcoming.length),Q("nodate","No date",F.nodate.length),Q("completed","Done",F.completed.length);let H=this.taskFilter==="all"?L:L.filter(M=>M.key===this.taskFilter),$=!1;for(let M of H){let T=F[M.key];if(T.length!==0){if($=!0,T.sort(M.key==="completed"?(J,Z)=>D(Z,J):D),this.taskFilter==="all"){let J=e.createDiv({cls:`stashpad-task-section-header is-${M.key}`});(0,mt.setIcon)(J.createSpan({cls:"stashpad-task-section-icon"}),M.icon),J.createSpan({cls:"stashpad-task-section-name",text:M.label}),J.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let J of T)this.renderTaskRow(e,J,M.key==="today")}}if(!$&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${H[0]?.label??this.taskFilter}".`);return}$||e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks to show.")}renderTaskRow(t,e,i){let s=t.createDiv({cls:"stashpad-pinned-row stashpad-task-row"});e.color&&s.addClass("has-color"),e.completed&&s.addClass("is-completed");let n=s.createSpan({cls:"stashpad-pinned-icon stashpad-task-checkbox"});(0,mt.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 o=s.createSpan({cls:"stashpad-pinned-label",text:e.title});if(o.onclick=()=>this.openTaskFromPanel(e.folder,e.id),s.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let a=s.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,i)});e.due<Date.now()&&!e.completed&&a.addClass("is-overdue")}else e.dueRaw&&s.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let a=(this.plugin.settings.authorId??"").trim(),r=s.createSpan({cls:"stashpad-task-assignees"});for(let c of e.assignedTo){let l=r.createSpan({cls:"stashpad-task-assignee"});a&&c.id===a&&l.addClass("is-me"),l.setText(this.initials(c.name)),l.title=a&&c.id===a?`${c.name} (you)`:c.name}}s.oncontextmenu=a=>{a.preventDefault();let r=new mt.Menu;r.addItem(c=>c.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),r.showAtMouseEvent(a)}}formatDueShort(t,e){return e?Zs(t,this.plugin.settings):Xs(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.activateViewForFolder(t);let i=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();i&&typeof i.navigateTo=="function"&&i.navigateTo(e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new mt.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),i=[];for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a||a===U)continue;let r=o.completed===!0,c=Ie(o,"task")||o.task===!0||o.completed!==void 0,l=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,g=null;if(l){let p=Date.parse(l);Number.isNaN(p)||(g=p)}!c&&!r&&g==null&&!l||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:c,completed:r,due:g,dueRaw:l,color:typeof o.color=="string"?o.color:null,assignedTo:Re(o),assignedBy:Xt(o.assignedBy)})}return i}};async function fi(h){let A=h.workspace.getLeavesOfType(Vt);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new mt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:Vt,active:!0}),h.workspace.revealLeaf(t)}var un=require("obsidian");wt();var et=require("obsidian");$e();var Qi=require("obsidian");wt();var Ee=class extends Qi.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),i=o=>e.every(a=>o.toLowerCase().includes(a)),s=[],n=o=>{if(!(o.path!=="/"&&Ge.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof Qi.TFolder&&n(a)}};return n(this.app.vault.getRoot()),s.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()}};wt();Mt();var he=require("obsidian"),ps={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."}},So={info:4e3,success:4e3,warning:6e3,error:1e4},ln=5e3,Ei=class{constructor(A){this.app=A;this.history=[];this.nextId=1;this.historyLimit=ln;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(A){this.defaultAuthorId=A||null}show(A){let t=A.kind??"info",e=A.category??"system",i={id:this.nextId++,ts:Date.now(),message:A.message,kind:t,category:e,authorId:A.authorId??this.defaultAuthorId??void 0,affectedIds:A.affectedIds?A.affectedIds.slice():[],affectedPaths:A.affectedPaths?A.affectedPaths.slice():[],affectedAuthorIds:A.affectedAuthorIds?A.affectedAuthorIds.slice():[],folder:A.folder,actionLabels:(A.actions??[]).map(o=>o.label)};if(this.pushHistory(i),this.muted.has(e))return null;let s=this.buildContent(A,t),n=A.duration??So[t];return new he.Notice(s,n)}onChange(A){return this.changeListeners.add(A),()=>this.changeListeners.delete(A)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(A,t){t?this.muted.add(A):this.muted.delete(A)}isMuted(A){return this.muted.has(A)}loadMutedFromList(A){this.muted=new Set(A)}mutedList(){return Array.from(this.muted)}loadHistory(A){let t=this.applyLimit(A.slice());this.history=t;let e=0;for(let i of t)i.id>e&&(e=i.id);this.nextId=Math.max(this.nextId,e+1),this.emit()}setHistoryLimit(A){this.historyLimit=Number.isFinite(A)?A:ln,this.history=this.applyLimit(this.history),this.emit()}applyLimit(A){return this.historyLimit<=0||A.length<=this.historyLimit?A:A.slice(A.length-this.historyLimit)}pushHistory(A){this.history.push(A),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let A of this.changeListeners)try{A()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(A,t){let e=document.createDocumentFragment(),i=document.createElement("div");i.className=`stashpad-notice stashpad-notice-${t}`;let s=document.createElement("div");s.className="stashpad-notice-message";let n=A.message.split(/(`[^`\n]+`)/);for(let o of n)if(o.length>1&&o.startsWith("`")&&o.endsWith("`")){let a=document.createElement("code");a.textContent=o.slice(1,-1),s.appendChild(a)}else o.length>0&&s.appendChild(document.createTextNode(o));if(i.appendChild(s),A.actions&&A.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of A.actions){let r=document.createElement("button");r.className="stashpad-notice-action",r.textContent=a.label,r.addEventListener("click",c=>{if(c.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(l=>console.warn("[Stashpad] notification action failed",l)),!a.keepOpen){let l=r.closest(".notice");l&&l.parentElement&&l.parentElement.removeChild(l)}}),o.appendChild(r)}i.appendChild(o)}return e.appendChild(i),e}};function yi(h,A,t){let e=h.vault.getAbstractFileByPath(A);if(!(e instanceof he.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=h.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;h.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=he.Platform.isMacOS?"Finder":he.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=h.vault.adapter?.getFullPath?.(A);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var Is=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function _e(h){if(!h)return"(none)";let A=h.replace(/\bMod\b/g,Is?"Cmd":"Ctrl");return Is&&(A=A.replace(/\bAlt\b/g,"Option")),A}function dn(h,A,t={allowSingleKey:!0}){let e=h.placeholder,i=h.value;h.placeholder="Press a key\u2026 (Backspace to cancel)",h.value="",h.classList.add("is-recording");let s=!1,n=()=>{h.placeholder=e,h.classList.remove("is-recording"),s||(h.value=i),h.removeEventListener("keydown",o,!0),h.removeEventListener("blur",a)},o=r=>{if(r.key==="Control"||r.key==="Shift"||r.key==="Alt"||r.key==="Meta"||r.key==="OS")return;let c=!!r.code&&(/^Key[A-Z]$/.test(r.code)||/^Digit\d$/.test(r.code));if((r.key==="Dead"||r.key==="Process"||r.key==="Unidentified")&&!c)return;if(r.preventDefault(),r.stopPropagation(),r.key==="Backspace"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.shiftKey){n();return}let l=[];Is?(r.metaKey&&l.push("Mod"),r.ctrlKey&&l.push("Ctrl")):r.ctrlKey&&l.push("Mod"),r.altKey&&l.push("Alt"),r.shiftKey&&l.push("Shift");let g=Do(r.key,r.code);if(!g||l.length===0&&!t.allowSingleKey)return;l.push(g);let p=l.join("+");s=!0,n(),A(p)},a=()=>n();return h.addEventListener("keydown",o,!0),h.addEventListener("blur",a),n}function Do(h,A){if(!h)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return h.length===1?h.toUpperCase():h}me();Rt();var je=null,wi=new Set;function Fi(h){if(je!==h){je=h;for(let A of wi)A()}}function qt(){return je}function hn(h){if(je===h){je=null;for(let A of wi)A()}}function gn(h){return wi.add(h),()=>wi.delete(h)}function bo(){return et.Platform.isMacOS?"Finder":et.Platform.isWin?"File Explorer":"file manager"}var ye=[{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 or X \u2014 marks selected/focused notes as complete (both chords active).",defaultPrimary:"Mod+Enter",defaultSecondary:"X",defaultUseBoth:!0},{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+: or ; \u2014 open the color picker for the selection (both chords active).",defaultPrimary:"Shift+:",defaultSecondary:";",defaultUseBoth:!0},{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"},{id:"commandPalette",label:"Command palette (Stashpad only)",desc:"Default: Mod+K \u2014 open a command palette listing only Stashpad's commands, with Sift search.",defaultPrimary:"Mod+K"}];function Cs(){let h={};for(let A of ye)h[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return h}var Zt={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,searchOpensInNewTab:!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:Cs()},pn=JSON.parse(JSON.stringify(Zt)),us=new Set;function ft(){return pn}function Bs(h){pn=h;for(let A of us)A()}function In(h){return us.add(h),()=>us.delete(h)}function Si(h){try{let A=h.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var vi=[{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"}],fs=class extends et.SettingPage{constructor(t,e){super();this.renderFn=e;this.title=t}display(){this.containerEl.empty(),this.renderFn(this.containerEl)}},ki=class extends et.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if((0,et.requireApiVersion)("1.13.0")){super.display();return}let{containerEl:t}=this;t.empty();for(let e of vi){t.createEl("h2",{text:e.label});let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new et.Setting(t);typeof s.render=="function"?s.render(n):(s.name&&n.setName(s.name),s.desc&&n.setDesc(s.desc))}else this.renderTabContent(t,e.id)}}getSettingDefinitions(){return vi.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>new fs(t.label,i=>this.renderTabContent(i,t.id))}})}itemsForTab(t){switch(t){case"hotkeys":return this.hotkeyItems();case"diagnostics":return this.diagnosticsItems();case"general":return this.generalItems();default:return null}}renderTabContent(t,e){switch(e){case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break}}diagnosticsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(ps);return[this.renderDef("Write recovery navigation links","Maintain the redundant parentLink/children frontmatter so you can walk the hierarchy from raw Markdown if the index ever breaks. On a slow / network drive this is a big per-move cost (several round-trips each); turn it off there for snappier moves \u2014 Rebootstrap rebuilds the fields on demand, and your notes' canonical structure (id/parent) is unaffected either way.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async n=>{this.plugin.settings.writeRecoveryLinks=n,await this.plugin.saveSettings()})),["recovery","parentlink","children","frontmatter"]),this.renderDef("Performance profiling","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.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.enablePerfProfiling).onChange(async n=>{this.plugin.settings.enablePerfProfiling=n,await this.plugin.saveSettings()})),["perf","profiling","timing","slow"]),this.renderDef("Open log file","Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.",i=>i.addButton(s=>s.setButtonText("Open log").onClick(async()=>{let n=this.app.vault.adapter,o=this.plugin.pluginPrivatePath("log.jsonl");if(!await n.exists(o)){new et.Notice("No log yet \u2014 make some changes first.");return}let a=await n.read(o);new fe(this.app,a,o).open()})),["log","history","diagnostics"]),this.renderDef("Notification history limit","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.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.notificationHistoryLimit??5e3)).setPlaceholder("5000").onChange(async n=>{let o=parseInt(n,10);Number.isFinite(o)&&(this.plugin.settings.notificationHistoryLimit=o,this.plugin.notifications.setHistoryLimit(o),await this.plugin.saveSettings())})),["notification","history","limit"]),{type:"group",heading:"Mute notification categories",items:e.map(i=>{let s=ps[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async a=>{let r=!a;r?t.add(i):t.delete(i),this.plugin.settings.mutedNotificationCategories=Array.from(t),this.plugin.notifications.setMuted(i,r),await this.plugin.saveSettings()})),["notification","mute","toast","category"])})},this.renderDef("Notification history","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.",i=>i.addButton(s=>s.setButtonText("View notification history").onClick(()=>{new ze(this.app,this.plugin.notifications,async n=>{let o=this.app.vault.adapter,a=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(a)){new et.Notice("No log yet \u2014 make some changes first.");return}let r=await o.read(a);new fe(this.app,r,a).open()},this.plugin.settings.authorId||null,n=>this.plugin.lookupNoteAuthorIds(n)).open()})),["notification","history","panel"])]}renderTemplatesTab(t){this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t)}renderDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{n.setName(t).setDesc(e),i(n)}}}sectionDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{let o=n.settingEl;o.empty(),o.removeClass("setting-item"),o.addClass("stashpad-settings-section"),i(o)}}}generalItems(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,r)=>this.renderDef(s,n,c=>c.addToggle(l=>l.setValue(o()).onChange(async g=>{a(g),await t()})),r),i=[];i.push(this.renderDef("Stashpad notes folder","Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.",s=>{s.addText(n=>{new Ee(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||Zt.folder,r=a.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(r)){new et.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.push(e("Auto-import dropped files","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.",()=>this.plugin.settings.autoImport,s=>{this.plugin.settings.autoImport=s},["import","drop","auto"])),i.push(e("Inherit Obsidian's excluded files","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.",()=>this.plugin.settings.inheritObsidianExclusions,s=>{this.plugin.settings.inheritObsidianExclusions=s},["excluded","ignore","files"])),i.push(this.renderDef("Dedicated import subfolder (optional)","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.",s=>s.addText(n=>n.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async o=>{this.plugin.settings.importDropFolder=(o||"").trim().replace(/^\/+|\/+$/g,""),await t()})),["import","subfolder"])),i.push(this.renderDef("Stash export subfolder","Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.",s=>s.addText(n=>n.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async o=>{this.plugin.settings.exportFolder=(o||"").trim().replace(/^\/+|\/+$/g,"")||Zt.exportFolder,await t()})),["export","stash","subfolder"])),i.push(this.renderDef("Rebootstrap existing Stashpad folders","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.",s=>s.addButton(n=>n.setButtonText("Rebootstrap now").onClick(async()=>{n.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:o,fmChecked:a,fmWritten:r,slugsRenamed:c,authors:l,imported:g,attachmentsLinked:p}=await this.plugin.rebootstrapAllFolders(),d=[];d.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),g>0&&d.push(`imported ${g} loose file${g===1?"":"s"}`),p>0&&d.push(`linked attachments on ${p} note${p===1?"":"s"}`),r>0?d.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&d.push(`frontmatter already in sync (${a} notes checked)`),c>0&&d.push(`renamed ${c} note${c===1?"":"s"} to match body`),l>0&&d.push(`rebuilt author registry (${l} author${l===1?"":"s"})`),new et.Notice(`Stashpad: ${d.join("; ")}.`)}catch(o){new et.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.push(this.renderDef("Use Templates plugin date/time formats","When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.",s=>{s.addToggle(o=>o.setValue(this.plugin.settings.useTemplatesFormat).onChange(async a=>{this.plugin.settings.useTemplatesFormat=a,await t()}));let n=Si(this.app);s.descEl.createDiv({cls:"stashpad-settings-note"}).setText(n?`Templates plugin: date = "${n.dateFormat}", time = "${n.timeFormat}"`:"Templates plugin not enabled.")},["templates","date","time","format"]));{let s=null,n=()=>{s&&s.setText(`Sample: ${re(Date.now(),this.plugin.settings)}`)};i.push(this.renderDef("Date display format","How due dates and created/modified times are shown in the Tasks and detail panels.",o=>{o.addDropdown(a=>{a.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),a.addOption("long","Locale, long (Thursday, March 5\u2026)"),a.addOption("iso","ISO (2026-03-05 09:00)"),a.addOption("us","US (3/5/2026, 9:00 AM)"),a.addOption("eu","EU (5/3/2026, 09:00)"),a.setValue(this.plugin.settings.dateDisplayFormat??"locale"),a.onChange(async r=>{this.plugin.settings.dateDisplayFormat=r,await t(),n()})})},["date","format","display"])),i.push(this.renderDef("Display timezone","IANA timezone name (e.g. America/New_York, Europe/London, Asia/Kolkata). Leave blank to use your system timezone.",o=>{o.addText(a=>{a.setPlaceholder("(system timezone)"),a.setValue(this.plugin.settings.dateDisplayTimezone??""),a.onChange(async r=>{this.plugin.settings.dateDisplayTimezone=(r||"").trim(),await t(),n()})})},["timezone","tz","date","iana"])),i.push({name:"Date sample",searchable:!1,render:o=>{let a=o.settingEl;a.empty(),a.removeClass("setting-item"),s=a.createDiv({cls:"setting-item-description stashpad-settings-note"}),n()}})}return i.push(e("Navigate into parent after moving a note IN","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.",()=>this.plugin.settings.autoNavOnMoveIn,s=>{this.plugin.settings.autoNavOnMoveIn=s},["navigate","move","in"])),i.push(e("Navigate to destination after moving a note OUT","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.",()=>this.plugin.settings.autoNavOnMoveOut,s=>{this.plugin.settings.autoNavOnMoveOut=s},["navigate","move","out"])),i.push(e("Double-click a note to open it","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.",()=>this.plugin.settings.doubleClickToFocus,s=>{this.plugin.settings.doubleClickToFocus=s},["double","click","open","focus"])),i.push(e("Auto-open the detail panel","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.",()=>this.plugin.settings.autoOpenDetailPanel,s=>{this.plugin.settings.autoOpenDetailPanel=s},["detail","panel","sidebar"])),i.push(e("Expand the cursor row's body automatically","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.",()=>this.plugin.settings.autoExpandCursorRow,s=>{this.plugin.settings.autoExpandCursorRow=s},["expand","cursor","body"])),i.push(e("Confirm cross-parent drag-and-drop","When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).",()=>this.plugin.settings.confirmCrossParentDrag,s=>{this.plugin.settings.confirmCrossParentDrag=s},["confirm","drag","drop","reparent"])),i.push(e("Confirm bulk deletes","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).",()=>this.plugin.settings.confirmBulkDelete,s=>{this.plugin.settings.confirmBulkDelete=s},["confirm","delete","bulk"])),i.push(e("Offer to delete attachments with note",`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.`,()=>this.plugin.settings.confirmAttachmentDelete,s=>{this.plugin.settings.confirmAttachmentDelete=s},["delete","attachment","orphan"])),i.push(this.renderDef("Slug stop-words","Words removed from auto-generated note titles (filenames). One per line.",s=>{let n=null,o=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:Pt).join(` -`);s.addTextArea(a=>{a.setValue(o),n=a.inputEl,n.rows=6,n.style.fontFamily="var(--font-monospace)",a.onChange(async r=>{this.plugin.settings.slugStopWords=(r||"").split(/\r?\n/).map(c=>c.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(a=>a.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Pt],n&&(n.value=Pt.join(` -`)),await t()}))},["slug","stopwords","filename","title"])),i.push(this.sectionDef("Cross-Stashpad search scope","Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations. Also: create a new Stashpad.",s=>{let n=this.plugin.discoverStashpadFolders();if(new et.Setting(s).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."),n.length===0)s.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 a=s.createDiv({cls:"stashpad-folder-list"});for(let r of n)this.renderFolderScopeRow(a,r)}let o=null;new et.Setting(s).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(a=>{a.setPlaceholder("my-stashpad"),o=a.inputEl}).addButton(a=>a.setButtonText("Create").setCta().onClick(async()=>{let r=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!r){new et.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(r),new et.Notice(`Created Stashpad "${r}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(r,2e3),this.update?.()}catch(c){new et.Notice(`Couldn't create: ${c.message}`)}}))},["search","scope","exclude","include","create","new","stashpad","folder"])),i.push(this.sectionDef("Folder panel placement","Pin, downrank, or hide folders in the Stashpad folder panel. Restore hidden folders here or from the panel's \u201CHidden\u201D section.",s=>{new et.Setting(s).setName("Folder panel placement").setDesc("Folders you've pinned, downranked, or hidden in the Stashpad folder panel. Pin/downrank from a folder's right-click menu in the panel; restore here or from the panel's \u201CHidden\u201D section."),this.renderFolderPlacementList(s)},["folder","panel","pin","pinned","downrank","hide","hidden","restore","placement"])),i.push(e("Autofocus composer after sending","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.",()=>this.plugin.settings.autofocusComposerAfterSend,s=>{this.plugin.settings.autofocusComposerAfterSend=s},["composer","focus","send"])),i.push(e("Open in new window \u2014 duplicate tab","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.",()=>this.plugin.settings.popoutDuplicates,s=>{this.plugin.settings.popoutDuplicates=s},["popout","window","duplicate"])),i.push(e("Search results open in a new tab","When you pick a result in the Search modal, open it in a new Stashpad tab instead of navigating the current tab. Applies to same-folder and cross-Stashpad results alike. On by default.",()=>this.plugin.settings.searchOpensInNewTab,s=>{this.plugin.settings.searchOpensInNewTab=s},["search","new tab","results","open"])),i.push(e("Prefix timestamps when copying","Include each note's timestamp before its body when copying with C or Y.",()=>this.plugin.settings.prefixTimestampsOnCopy,s=>{this.plugin.settings.prefixTimestampsOnCopy=s},["copy","timestamp","prefix"])),i}hotkeyItems(){let t={name:"Hotkeys",desc:"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. A \u21BA icon appears on any slot that differs from its shipped default \u2014 click it to revert that slot. When both slots are set, the pill on the right decides which one is active.",searchable:!1},e=ye.map(i=>({name:i.label,desc:i.desc,aliases:["hotkey","shortcut","keybind","binding","key"],render:s=>this.renderBindingRow(s,i)}));return[t,...e]}renderJdIndexSection(t){let e=t.createEl("h3",{text:"JD Index Builder"});e.id="stashpad-jd-index-section";let i=t.createEl("p",{cls:"setting-item-description"});i.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 s=this.plugin.discoverStashpadFolders();new et.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(r=>{r.addOption("vault","Entire vault"),r.addOption("folder","Single folder"),r.setValue(this.plugin.settings.jdIndexScope??"vault"),r.onChange(async c=>{this.plugin.settings.jdIndexScope=c==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new et.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(r=>{new Ee(this.app,r.inputEl),r.setPlaceholder("Path/To/Folder"),r.setValue(this.plugin.settings.jdIndexScopeFolder??""),r.onChange(async c=>{this.plugin.settings.jdIndexScopeFolder=(c||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new et.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(r=>{r.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),r.onChange(async c=>{this.plugin.settings.jdIndexIncludeStashpadFolders=c,await this.plugin.saveSettings(),this.display()})}),new et.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(r=>{new Ee(this.app,r.inputEl),r.setPlaceholder(s[0]??"(pick a Stashpad folder)"),r.setValue(this.plugin.settings.jdIndexStashpadFolder??""),r.onChange(async c=>{this.plugin.settings.jdIndexStashpadFolder=(c||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new et.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(r=>{r.addOption("natural","Natural (numeric \u2192 alphabetical)"),r.addOption("created","By creation time"),r.setValue(this.plugin.settings.jdIndexSort??"natural"),r.onChange(async c=>{this.plugin.settings.jdIndexSort=c==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=Qe(this.app,this.plugin,this.plugin.settings),o=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)`:"";o.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${a}.`),new et.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(r=>{r.setButtonText("Preview"),r.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),r.onClick(async()=>{try{let c=await Ci(this.app,this.plugin,this.plugin.settings);if(c.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(c.error==="no-home"){new et.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}Bi(this.app,c),this.display()}catch(c){console.error("[stashpad] preview failed",c),new et.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}).addButton(r=>{r.setButtonText("Build Stashpad notes"),r.setCta(),r.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),r.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Ze(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let g=await hs(this.app,this.plugin,this.plugin.settings);if(g.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(g.error==="dest-not-stashpad"){new et.Notice(`"${g.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 et.Notice(`Built: ${g.created} created, ${g.updated} updated, ${g.skipped} skipped \u2192 ${g.destFolder}`,6e3),this.display()}catch(g){console.error("[stashpad] build failed",g),new et.Notice(`Build failed: ${g?.message??g}`,8e3)}}).open()})}).addButton(r=>{r.setButtonText(`Reveal in ${bo()}`),r.setTooltip("Open the designated Stashpad folder in your OS file browser."),r.onClick(async()=>{let c=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!c){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(c)){new et.Notice(`Folder "${c}" doesn't exist yet.`,5e3);return}try{let g=this.app.vault.adapter.basePath;if(g){let{shell:p}=window.require?.("electron")??{},d=`${g}/${c}`;p?.openPath?.(d)}else new et.Notice("Reveal in file system not supported on this platform.",4e3)}catch(g){new et.Notice(`Couldn't open folder: ${g?.message??g}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=qt()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(o=>{for(let a of e)o.addOption(a,a);o.setValue(i),o.onChange(a=>{i=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 s=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{s.empty();let o=this.plugin.collectColorsInFolder(i),a=new Map(o.map(g=>[g.hex,g.count])),r=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},c=new Set([...a.keys(),...Object.keys(r)]);if(c.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let l=[...c].map(g=>({hex:g,count:a.get(g)??0}));l.sort((g,p)=>p.count-g.count||g.hex.localeCompare(p.hex));for(let g of l)this.renderColorAliasRow(s,i,g.hex,g.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 et.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(i=>{i.setValue(this.plugin.settings.authorName).onChange(async s=>{this.plugin.settings.authorName=s.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=yt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.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(i=>{i.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new et.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(i=>{i.setValue(this.plugin.settings.authorRole).onChange(async s=>{this.plugin.settings.authorRole=s.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(i=>{i.setValue(this.plugin.settings.authorDepartment).onChange(async s=>{this.plugin.settings.authorDepartment=s.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Show author in note footer").addToggle(i=>i.setValue(this.plugin.settings.showAuthor).onChange(async s=>{this.plugin.settings.showAuthor=s,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show contributors in note footer").addToggle(i=>i.setValue(this.plugin.settings.showContributors).onChange(async s=>{this.plugin.settings.showContributors=s,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show last edit time in note footer").addToggle(i=>i.setValue(this.plugin.settings.showLastEdit).onChange(async s=>{this.plugin.settings.showLastEdit=s,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let i=t.createDiv({cls:"stashpad-authored-folders-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-authored-folder-row"}),o=n.createEl("a",{cls:"stashpad-authored-folder-link",text:s.folder});o.onclick=r=>{r.preventDefault(),this.plugin.activateViewForFolder(s.folder)};let a=[];s.authored>0&&a.push(`authored ${s.authored}`),s.contributed>0&&a.push(`contributed to ${s.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 et.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(s=>s.setButtonText("Rebuild").onClick(async()=>{s.setDisabled(!0).setButtonText("Rebuilding\u2026");try{let n=await this.plugin.rebuildAuthorRegistry();new et.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new et.Notice(`Rebuild failed: ${n.message}`)}s.setDisabled(!1).setButtonText("Rebuild"),this.display()})).addButton(s=>s.setButtonText("Restore missing pages").onClick(async()=>{s.setDisabled(!0).setButtonText("Restoring\u2026");try{let n=await this.plugin.restoreMissingAuthorStubs();new et.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new et.Notice(`Restore failed: ${n.message}`)}s.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 i=t.createDiv({cls:"stashpad-known-authors-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-known-author-row"}),o=n.createDiv({cls:"stashpad-known-author-main"});o.createSpan({cls:"stashpad-known-author-name",text:s.name||"(unnamed)"});let a=[];if(s.role&&a.push(s.role),s.department&&a.push(s.department),a.push(`id ${s.id}`),o.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${a.join(" \xB7 ")}`}),s.renames&&s.renames.length>0){let r=n.createDiv({cls:"stashpad-known-author-history"}),c=s.renames.map(l=>`${l.from} \u2192 ${l.to}`).join(", ");r.setText(`Renamed: ${c}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new et.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 i=t.createDiv({cls:"stashpad-note-templates-list"}),s=n=>{let o=n.replace(/\/+$/,""),a=i.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let c=a.createDiv({cls:"stashpad-note-template-input-wrap"}),l=c.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});l.value=(this.plugin.settings.noteTemplates??{})[o]??"";let g=c.createDiv({cls:"stashpad-note-template-suggest"});g.style.display="none";let p=a.createDiv({cls:"stashpad-note-template-warn"});p.style.display="none";let d=()=>this.app.vault.getMarkdownFiles().map(C=>C.path).filter(C=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(C)).sort(),I=()=>{g.empty();let C=l.value.trim().toLowerCase().split(/\s+/).filter(Boolean),m=w=>{let y=w.toLowerCase();return C.every(F=>y.includes(F))},E=d().filter(w=>m(w)).slice(0,12);if(E.length===0){g.style.display="none";return}g.style.display="";for(let w of E)g.createDiv({cls:"stashpad-note-template-suggest-item",text:w}).addEventListener("mousedown",async F=>{F.preventDefault(),l.value=w,await u(),g.style.display="none"})},u=async()=>{let C=l.value.trim(),m={...this.plugin.settings.noteTemplates??{}};C?m[o]=C:delete m[o],this.plugin.settings.noteTemplates=m,await this.plugin.saveSettings(),f()},f=()=>{p.empty(),p.style.display="none";let C=l.value.trim();if(!C)return;let m=this.app.vault.getAbstractFileByPath(C);if(!m||m.extension!=="md"){p.style.display="",p.setText(`\u26A0 "${C}" is not a markdown file in this vault.`);return}let E=this.app.metadataCache.getFileCache(m)?.frontmatter??{},y=Wt.filter(F=>{let D=E[F];return!(D==null||typeof D=="string"&&D.trim()===""||Array.isArray(D)&&D.length===0)});y.length!==0&&(p.style.display="",p.setText(`\u26A0 Template defines ${y.join(", ")} \u2014 Stashpad always sets ${y.length===1?"this":"these"} on new notes, so the template value${y.length===1?"":"s"} will be ignored.`))};l.addEventListener("focus",I),l.addEventListener("input",I),l.addEventListener("blur",()=>{setTimeout(()=>{g.style.display="none"},150)}),l.addEventListener("change",()=>{u()}),f()};for(let n of e)s(n)}renderColorAliasRow(t,e,i,s,n){let o=t.createDiv({cls:"stashpad-color-alias-row"});s===0&&o.addClass("is-unused");let a=o.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=i,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let g=this.plugin.settings.customPalette??[];new le(this.app,i,g,async p=>{if((p??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(p&&p.toLowerCase()===i){n();return}let d=await this.plugin.recolorAllInFolder(e,i,p??null);if(d>0)new et.Notice(`Recolored ${d} note${d===1?"":"s"}.`);else if(s===0){let I=this.plugin.getColorAlias(e,i);I&&(await this.plugin.setColorAlias(e,i,""),p&&await this.plugin.setColorAlias(e,p,I))}n()},async p=>{let d=(this.plugin.settings.customPalette??[]).filter(I=>I.toLowerCase()!==p.toLowerCase());return this.plugin.settings.customPalette=d,await this.plugin.saveSettings(),d}).open()};let r=o.createDiv({cls:"stashpad-color-alias-meta"});r.createSpan({cls:"stashpad-color-alias-hex",text:i}),r.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let c=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});c.value=this.plugin.getColorAlias(e,i)??"",c.onchange=async()=>{await this.plugin.setColorAlias(e,i,c.value),!c.value.trim()&&s===0&&n()};let l=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});c.value||(l.style.visibility="hidden"),l.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(c.value="",l.style.visibility="hidden")}}renderFolderScopeRow(t,e){let i=t.createDiv({cls:"stashpad-folder-row"});i.createSpan({cls:"stashpad-folder-row-label",text:e});let s=i.createSpan({cls:"stashpad-folder-row-state"}),n=i.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let o=n.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),r=()=>{let l=a();n.toggleClass("is-right",l),n.setAttribute("aria-checked",String(l)),o.setText(l?"X":"\u2713"),s.setText(l?"Excluded":"Included"),s.toggleClass("is-excluded",l),n.title=l?"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."},c=async()=>{let l=new Set(this.plugin.settings.searchExcludedFolders??[]);l.has(e)?l.delete(e):l.add(e),this.plugin.settings.searchExcludedFolders=[...l].sort(),r(),await this.plugin.saveSettings()};n.onclick=()=>void c(),n.onkeydown=l=>{(l.key===" "||l.key==="Enter")&&(l.preventDefault(),c())},r()}renderFolderPlacementList(t){let e=this.plugin.settings,i=[{key:"folderPanelPinned",label:"Pinned",action:"Unpin"},{key:"folderPanelDownranked",label:"Downranked",action:"Reset"},{key:"folderPanelHidden",label:"Hidden",action:"Unhide"}];if(!i.some(o=>(e[o.key]??[]).length>0)){t.createEl("p",{cls:"setting-item-description"}).setText("No folders customized yet. Right-click a folder in the Stashpad folder panel to pin, downrank, or hide it.");return}let n=async o=>{e.folderPanelPinned=(e.folderPanelPinned??[]).filter(a=>a!==o),e.folderPanelDownranked=(e.folderPanelDownranked??[]).filter(a=>a!==o),e.folderPanelHidden=(e.folderPanelHidden??[]).filter(a=>a!==o),await this.plugin.saveSettings(),this.update?.()};for(let o of i){let a=[...e[o.key]??[]].sort();if(a.length===0)continue;t.createEl("div",{cls:"stashpad-folder-placement-group",text:`${o.label} (${a.length})`});let r=t.createDiv({cls:"stashpad-folder-list"});for(let c of a){let l=r.createDiv({cls:"stashpad-folder-row"});l.createSpan({cls:"stashpad-folder-row-label",text:c});let g=l.createEl("button",{text:o.action});g.onclick=()=>void n(c)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=d=>{let I=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=I.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=_e(i()[d]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=d==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{dn(u,async y=>{this.plugin.settings.bindings[e.id][d]=y,u.value=_e(y),f(),await this.plugin.saveSettings(),o(),w()})};let m=I.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][d]="",u.value="",f(),await this.plugin.saveSettings(),o(),w()};let E=I.createEl("button",{cls:"stashpad-binding-revert"});(0,et.setIcon)(E,"rotate-ccw");let w=()=>{let F=i()[d]!==C;E.toggleClass("is-hidden",!F),E.title=C?`Revert to default (${_e(C)})`:"Revert to default (no binding)"};return E.onclick=async()=>{this.plugin.settings.bindings[e.id][d]=C,u.value=_e(C),f(),await this.plugin.saveSettings(),o(),w()},w(),u};s=a("primary"),n=a("secondary");let r=t.controlEl.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let c=r.createDiv({cls:"stashpad-binding-pill-knob"}),l=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),g=l.createEl("input",{type:"checkbox"});g.title="Use both bindings simultaneously (overrides the L/R toggle)",l.createSpan({text:"Use both"}),g.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=g.checked,await this.plugin.saveSettings(),o()},o=()=>{let d=i(),I=!!(d.primary&&d.secondary);g.checked=!!d.useBoth,g.disabled=!I,l.toggleClass("is-disabled",!I);let u=!!d.useBoth&&I;r.toggleClass("is-disabled",!I||u),r.toggleClass("is-right",d.preferRight),r.setAttribute("aria-checked",String(d.preferRight)),r.setAttribute("aria-disabled",String(!I||u)),c.setText(d.preferRight?"R":"L"),r.title=I?u?'Overridden by "Use both"':d.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let p=async()=>{let d=i();!d.primary||!d.secondary||(this.plugin.settings.bindings[e.id].preferRight=!d.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void p(),r.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),p())},o()}};var we=class{constructor(A,t){this.app=A;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 A=this.detectTrigger();if(!A){this.close();return}this.openFor(A)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=A=>{A.key==="Escape"&&(!this.state||!this.items.length||(A.preventDefault(),A.stopPropagation(),A.stopImmediatePropagation(),this.close()))};this.onKeyDown=A=>{!this.state||!this.items.length||(A.key==="ArrowDown"?(A.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):A.key==="ArrowUp"?(A.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):A.key==="Enter"||A.key==="Tab"?(A.preventDefault(),A.stopPropagation(),this.commit()):A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),A.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let A=this.ta.ownerDocument??document;A.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>A.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 A of this.vaultListeners)A();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let A=ft().inheritObsidianExclusions,t=A?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!zs(i.path)&&!Vs(i.path)&&!(A&&Ws(i.path,t))).map(i=>{let s=i.extension==="md",n=s?i.basename:i.name,o=s?i.basename:i.name;return{label:n,lower:n.toLowerCase(),insertText:o,file:i}});let e=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(e).sort((i,s)=>(e[s]||0)-(e[i]||0)),this.indexBuilt=!0}detectTrigger(){let A=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=A.slice(0,t),i=e.match(/\[\[([^\]\[\n]*)$/);if(i){let n=i[1];return{kind:"link",query:n,replaceStart:t-n.length-2,replaceEnd:t}}let s=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(s){let n=s[2];return{kind:"tag",query:n,replaceStart:t-n.length-1,replaceEnd:t}}return null}buildItems(A){this.buildIndex();let t=A.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],i=s=>{if(!e.length)return!0;for(let n of e)if(!s.includes(n))return!1;return!0};return A.kind==="link"?this.fileIndex.filter(n=>i(n.lower)).slice(0,50).map(n=>({label:n.label,insert:`[[${n.insertText}]]`,subtitle:n.file.path})):this.tagIndex.filter(n=>i(n.toLowerCase())).slice(0,30).map(n=>({label:n,insert:n,subtitle:""}))}openFor(A){if(this.state=A,this.items=this.buildItems(A),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let A=new un.Scope(this.app.scope);A.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=A,this.app.keymap?.pushScope(A)}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 A=this.popupEl;A.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],i=A.createDiv({cls:"stashpad-composer-suggest-row"});t===this.activeIdx&&i.addClass("is-active"),i.createSpan({cls:"stashpad-composer-suggest-label",text:e.label}),e.subtitle&&i.createSpan({cls:"stashpad-composer-suggest-sub",text:e.subtitle}),i.onmousedown=s=>{s.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let A=this.popupEl.children;for(let e=0;e<A.length;e++)A[e].toggleClass("is-active",e===this.activeIdx);let t=A[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let A=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=A.top-t-4,i=A.left;this.popupEl.style.left=`${Math.max(8,i)}px`,this.popupEl.style.top=`${Math.max(8,e)}px`,this.popupEl.style.minWidth=`${Math.min(360,A.width)}px`}commit(){if(!this.state||!this.items.length)return;let A=this.items[this.activeIdx];if(!A)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),i=A.insert;this.ta.value=t+i+e;let s=t.length+i.length;this.ta.setSelectionRange(s,s),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()}};wt();var Di=class extends kt.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 oe}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?.()===dt&&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?.()===dt&&e.tree?.get){let i=e.tree.get(this.displayedId);if(i?.file)return{folder:e.noteFolder,id:this.displayedId,file:i.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,i=this.composerInputEl?.selectionStart??null;this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,t.empty(),t.addClass("stashpad-detail-root");let s=this.resolveDisplayed();if(!s){this.displayedPath=null;let d=t.createDiv({cls:"stashpad-detail-empty"});(0,kt.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=s.file;this.displayedPath=n.path;let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=t.createDiv({cls:"stashpad-detail-scroll"}),r=a.createDiv({cls:"stashpad-detail-header"}),c=r.createDiv({cls:"stashpad-detail-titlerow"});c.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let l=c.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,kt.setIcon)(l,"arrow-up-right"),l.title="Open this note in a new Stashpad tab",l.onclick=()=>{this.openInStashpad(s.folder,s.id)};let g=r.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&g.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let d=g.createSpan({cls:"stashpad-detail-meta-color"});d.style.background=o.color,d.title=o.color}if(o.completed===!0&&g.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let d=Date.parse(String(o.due)),I=Number.isNaN(d)?String(o.due):re(d,this.plugin.settings);g.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${I}`})}if(Array.isArray(o.tags))for(let d of o.tags.filter(I=>typeof I=="string"))g.createSpan({cls:"stashpad-detail-meta-tag",text:`#${d.replace(/^#/,"")}`});let p=a.createDiv({cls:"stashpad-detail-body"});try{let d=await this.app.vault.cachedRead(n),I=this.stripFrontmatter(d);await kt.MarkdownRenderer.render(this.app,I,p,n.path,this)}catch(d){p.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${d.message}`})}if(this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s),e&&this.composerInputEl&&(this.composerInputEl.focus(),i!=null)){let d=Math.min(i,this.composerInputEl.value.length);try{this.composerInputEl.setSelectionRange(d,d)}catch{}}}renderComposer(t,e){let i=t.createDiv({cls:"stashpad-detail-composer"}),s=i.createEl("textarea",{cls:"stashpad-detail-composer-input",attr:{placeholder:"Add a child note\u2026",rows:"2"}});this.composerInputEl=s,this.composerDraftForId===e.id?s.value=this.composerDraft:(this.composerDraft="",this.composerDraftForId=e.id),s.addEventListener("input",()=>{this.composerDraft=s.value,this.composerDraftForId=e.id}),s.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey&&!o.isComposing){if(this.composerAutocomplete?.isOpen?.())return;o.preventDefault(),this.submitComposer(e)}});let n=i.createEl("button",{cls:"stashpad-detail-composer-send",attr:{"aria-label":"Add child note"}});(0,kt.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 we(this.app,s),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==dt||typeof i.createNoteUnder!="function"){new kt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new kt.Notice(`Couldn't add note: ${s.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,i){let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==dt)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let r=a.createDiv({cls:"stashpad-detail-children-list"});for(let c of o)c.file&&this.renderDetailChildRow(r,s,n,e,c,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},r=typeof a.color=="string"?a.color:null,c=a.completed===!0,l=i.getChildren(n.id),g=l.length>0,p=`${s}|${n.id}`,d=this.expanded.has(p),I=t.createDiv({cls:"stashpad-detail-child-row"});c&&I.addClass("is-completed"),o>0&&(I.style.paddingLeft=`${o*16}px`),I.draggable=!0,I.dataset.id=n.id,I.addEventListener("dragstart",E=>{E.dataTransfer?.setData("text/plain",n.id),E.dataTransfer&&(E.dataTransfer.effectAllowed="move"),I.addClass("is-dragging")}),I.addEventListener("dragend",()=>I.removeClass("is-dragging")),I.addEventListener("dragover",E=>{E.preventDefault(),E.dataTransfer&&(E.dataTransfer.dropEffect="move");let w=I.getBoundingClientRect(),y=E.clientY-w.top<w.height/2;I.toggleClass("drop-before",y),I.toggleClass("drop-after",!y)}),I.addEventListener("dragleave",()=>{I.removeClass("drop-before"),I.removeClass("drop-after")}),I.addEventListener("drop",E=>{E.preventDefault(),I.removeClass("drop-before"),I.removeClass("drop-after");let w=E.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let y=I.getBoundingClientRect(),F=E.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,F?"before":"after")}),I.oncontextmenu=E=>{E.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(E,w)};let u=I.createSpan({cls:"stashpad-detail-child-toggle"});if(g&&(de(u,l.length,d),u.onclick=E=>{E.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Ie(a,"task")||a.task===!0||a.completed!==void 0){let E=I.createSpan({cls:"stashpad-detail-child-checkbox"});(0,kt.setIcon)(E,c?"check-square":"square"),E.title=c?"Mark not done":"Mark done",E.addEventListener("mousedown",w=>w.stopPropagation()),E.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),E.onclick=w=>{w.preventDefault(),w.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let C=I.createSpan({cls:"stashpad-detail-child-icon"});(0,kt.setIcon)(C,g?"folder-tree":"file-text"),r&&(C.style.color=r);let m=I.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},g&&d)for(let E of l)this.renderDetailChildRow(t,e,i,s,E,o+1)}renderFooterMeta(t,e,i,s){let n=t.createDiv({cls:"stashpad-detail-footer-meta"}),o=[];if(typeof i.author=="string"&&i.author&&o.push({label:"Author",value:this.stripWikiLink(i.author)}),Array.isArray(i.contributors)){let a=i.contributors.filter(r=>typeof r=="string").map(r=>this.stripWikiLink(r));a.length>0&&o.push({label:"Contributors",value:a.join(", ")})}if(typeof i.modified=="string"&&o.push({label:"Modified",value:this.formatTime(i.modified)}),typeof i.created=="string"&&o.push({label:"Created",value:this.formatTime(i.created)}),o.push({label:"Path",value:e.path}),o.push({label:"ID",value:s.id}),o.length===0){n.remove();return}for(let a of o){let r=n.createDiv({cls:"stashpad-detail-meta-line"});r.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),r.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)?re(e,this.plugin.settings):t}async openInStashpad(t,e){try{await this.plugin.activateViewForFolder(t);let i=this.plugin.lastActiveStashpadLeaf?.view;i?.navigateTo&&e!==U&&i.navigateTo(e)}catch(i){new kt.Notice(`Couldn't open: ${i.message}`)}}};async function bi(h){let A=h.workspace.getLeavesOfType(oe);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getRightLeaf(!1);if(!t){new kt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:oe,active:!0}),h.workspace.revealLeaf(t)}var q=require("obsidian");wt();var $t=require("obsidian");wt();function No(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof $t.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof $t.TFile?n.extension==="md"&&e.push(n):n instanceof $t.TFolder&&(Ge.has(n.name)||i.push(n))}return e}var Ni=class{constructor(A){this.app=A;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(U,{id:U,parent:null,children:[],file:null,created:""})}setOrderProvider(A){this.orderProvider=A}onChange(A){return this.listeners.add(A),()=>this.listeners.delete(A)}emit(){for(let A of this.listeners)A()}rebuild(A){A!==void 0&&(this.currentFolder=A);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(U,{id:U,parent:null,children:[],file:null,created:""});let s=t?No(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=o?.id;if(!a){let c=e.get(n.path),l=c?i.get(c):void 0,g=this.synthetic.get(n.path),p=l??g;p&&(this.nodes.set(p.id,{...p,children:[],file:n}),this.byPath.set(n.path,p.id));continue}if(this.synthetic.delete(n.path),a===U){let c=this.nodes.get(U);c.file=n,c.created=o?.created??"",this.byPath.set(n.path,U);continue}let r=o?.parent??null;r===a&&(r=null),this.nodes.set(a,{id:a,parent:r??U,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===U)continue;let o=n.parent??U;(this.nodes.get(o)??this.nodes.get(U)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let r=this.nodes.get(o),c=this.nodes.get(a);return(r.created||"").localeCompare(c.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((r,c)=>a.set(r,c)),n.children.sort((r,c)=>{let l=a.has(r)?a.get(r):1/0,g=a.has(c)?a.get(c):1/0;return l===g?0:l-g})}}this.emit()}insertSynthetic(A){if(!A.file)return;let t=A.file.path;this.synthetic.set(t,A),this.nodes.set(A.id,A),this.byPath.set(t,A.id);let e=A.parent??U,i=this.nodes.get(e);i&&!i.children.includes(A.id)&&i.children.push(A.id),this.emit()}get(A){return this.nodes.get(A)}getRoot(){return this.nodes.get(U)}getChildren(A){let t=this.nodes.get(A);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let A=0;for(let t of this.nodes.values())t.file&&A++;return A}pathTo(A){let t=[],e=new Set,i=this.nodes.get(A);for(;i&&i.id!==U&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(A){return this.byPath.get(A)}snapshot(){let A={};for(let t of this.nodes.values())t.id===U||!t.file||(A[t.id]={parent:t.parent===U?null:t.parent,path:t.file.path});return A}hookMetadataCache(A){let t=r=>{let c=this.currentFolder;return c?typeof r!="string"?!1:r===c||r.startsWith(c+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),A())},16))},s=r=>{r instanceof $t.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof $t.TFile&&t(r.path)&&r.extension==="md"&&this.applyChange(r)&&i()},o=r=>{let c=r?.path;typeof c=="string"&&t(c)&&this.applyDelete(c)&&i()},a=(r,c)=>{if(!(r instanceof $t.TFile))return;let l=typeof c=="string"?c:null;!t(r.path)&&!t(l)||this.applyRename(r,l??"")&&i()};return this.app.metadataCache.on("changed",s),this.app.vault.on("create",n),this.app.vault.on("delete",o),this.app.vault.on("rename",a),()=>{this.app.metadataCache.off("changed",s),this.app.vault.off("create",n),this.app.vault.off("delete",o),this.app.vault.off("rename",a),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(A){if(ue(A.path))return this.byPath.has(A.path)?this.applyDelete(A.path):!1;let t=this.app.metadataCache.getFileCache(A)?.frontmatter,e=t?.id,i=this.byPath.get(A.path);if(!e){if(i){let c=this.nodes.get(i);if(c&&c.file!==A)return c.file=A,!0}return!1}if(this.synthetic.delete(A.path),e===U){let c=this.nodes.get(U),l=t?.created??"",g=!1;return c.file!==A&&(c.file=A,g=!0),c.created!==l&&(c.created=l,g=!0),this.byPath.get(A.path)!==U&&(this.byPath.set(A.path,U),g=!0),g}let s=t?.parent??U,n=t?.created??"";if(!(s===U||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let c={id:e,parent:s,children:[],file:A,created:n};return this.nodes.set(e,c),this.byPath.set(A.path,e),this.attachToParent(c),this.resortChildrenOf(s),!0}let r=!1;if(a.file!==A&&(a.file=A,r=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??U),r=!0),a.parent!==s){let c=a.parent??U;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(c),this.resortChildrenOf(s),r=!0}return r}applyDelete(A){let t=this.byPath.get(A);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(A),this.synthetic.delete(A),!0;this.detachFromParent(e);let i=this.nodes.get(U);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=U,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(U),this.nodes.delete(t),this.byPath.delete(A),this.synthetic.delete(A),!0}applyRename(A,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||A.path===e||A.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(A);if(ue(A.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(A);this.byPath.delete(t),this.byPath.set(A.path,n);let o=this.nodes.get(n);return o&&(o.file=A),!0}detachFromParent(A){let t=this.nodes.get(A.parent??U);if(!t)return;let e=t.children.indexOf(A.id);e>=0&&t.children.splice(e,1)}attachToParent(A){let t=this.nodes.get(A.parent??U);t||(t=this.nodes.get(U)),t.children.includes(A.id)||t.children.push(A.id)}resortChildrenOf(A){let t=this.nodes.get(A);if(t&&(t.children.sort((e,i)=>{let s=this.nodes.get(e),n=this.nodes.get(i);return(s.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(A);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,a=i.has(n)?i.get(n):1/0;return o===a?0:o-a})}}}};var ms=class{constructor(){this.enabled=!1;this.buckets=new Map}record(A,t){if(!this.enabled)return;let e=this.buckets.get(A);e||(e={count:0,total:0,max:0},this.buckets.set(A,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(A,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(A,performance.now()-e)}}async timeAsync(A,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(A,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let A=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(A.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 A)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` -`)}},St=new ms;var fn=".stashpad-order.json",xi=class{constructor(A){this.app=A;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(A){if(this.cache.has(A))return this.cache.get(A);let t=`${A}/${fn}`,e=this.app.vault.adapter,i={};try{if(await e.exists(t)){let s=await e.read(t),n=JSON.parse(s);if(n&&typeof n=="object"&&!Array.isArray(n))for(let[o,a]of Object.entries(n))Array.isArray(a)&&a.every(r=>typeof r=="string")&&(i[o]=a)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(A,i),i}async save(A){this.scheduleWrite(A)}async flush(A){let t=this.pendingTimers.get(A);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(A)),await this.writeNow(A)}scheduleWrite(A){let t=this.pendingTimers.get(A);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(A),this.writeNow(A)},150);this.pendingTimers.set(A,e)}async writeNow(A){let e=(this.writeInFlight.get(A)??Promise.resolve()).then(()=>this.doWrite(A));this.writeInFlight.set(A,e);try{await e}finally{this.writeInFlight.get(A)===e&&this.writeInFlight.delete(A)}}async doWrite(A){let t=this.cache.get(A)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(A,e);let i=`${A}/${fn}`,s=this.app.vault.adapter;try{if(Object.keys(e).length===0)try{await s.remove(i)}catch{}else await s.write(i,JSON.stringify(e,null,2))}catch(n){console.warn("Stashpad: order save failed",n)}}getOrder(A,t){return this.cache.get(A)?.[t]?.slice()??[]}setOrder(A,t,e){let i=this.cache.get(A)??{};i[t]=e.slice(),this.cache.set(A,i)}appendChild(A,t,e){let i=this.cache.get(A)??{},s=i[t]??[];s.includes(e)||s.push(e),i[t]=s,this.cache.set(A,i)}removeChild(A,t){let e=this.cache.get(A);if(e)for(let i of Object.values(e)){let s=i.indexOf(t);s>=0&&i.splice(s,1)}}invalidate(A){this.cache.delete(A)}};var ti={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"},Qs=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],xo=new Set(Qs),Cn=".stashpad-sort.json",Mi=class{constructor(A){this.app=A;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(A){if(this.cache.has(A))return this.cache.get(A);let t=`${A}/${Cn}`,e=this.app.vault.adapter,i={};try{if(await e.exists(t)){let s=JSON.parse(await e.read(t));if(s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s))typeof o=="string"&&xo.has(o)&&(i[n]=o)}}catch(s){console.warn("Stashpad: sort load failed",s)}return this.cache.set(A,i),i}async save(A){this.scheduleWrite(A)}async flush(A){let t=this.pendingTimers.get(A);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(A)),await this.writeNow(A)}scheduleWrite(A){let t=this.pendingTimers.get(A);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(A),this.writeNow(A)},150);this.pendingTimers.set(A,e)}async writeNow(A){let e=(this.writeInFlight.get(A)??Promise.resolve()).then(()=>this.doWrite(A));this.writeInFlight.set(A,e);try{await e}finally{this.writeInFlight.get(A)===e&&this.writeInFlight.delete(A)}}async doWrite(A){let t=this.cache.get(A)??{},e=`${A}/${Cn}`,i=this.app.vault.adapter;try{if(Object.keys(t).length===0)try{await i.remove(e)}catch{}else await i.write(e,JSON.stringify(t,null,2))}catch(s){console.warn("Stashpad: sort save failed",s)}}getMode(A,t){return this.cache.get(A)?.[t]??"manual"}setMode(A,t,e){let i=this.cache.get(A)??{};e==="manual"?delete i[t]:i[t]=e,this.cache.set(A,i)}removeParent(A,t){let e=this.cache.get(A);e&&delete e[t]}invalidate(A){this.cache.delete(A)}};wt();var _t="parentLink",Fe="children";var Ui=class Ui{constructor(A,t){this.app=A;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(A){return this.activityListeners.add(A),()=>this.activityListeners.delete(A)}emitActivity(){let A=this.pending.size;for(let t of this.activityListeners)try{t(A)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(A){if(!A||!ft().writeRecoveryLinks)return;let t=this.pending.size;this.pending.add(A),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(A,t,e){this.schedule(A),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(A){let t=this.getTree(),e=i=>{this.schedule(i);for(let s of t.getChildren(i))e(s.id)};e(A)}scheduleParentOfDeleted(A){A&&this.schedule(A)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let A=this.pending.values().next().value;if(A===void 0)break;this.pending.delete(A),this.emitActivity(),await this.syncOne(A)}}pendingCount(){return this.pending.size}onError(A){return this.errorListeners.add(A),()=>this.errorListeners.delete(A)}emitError(A,t){for(let e of this.errorListeners)try{e(A,t)}catch(i){console.warn("[Stashpad] fmSync error listener failed",i)}}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(),Ui.PACING_MS))}async tick(){this.timer=null;let A=this.pending.values().next().value;if(A!==void 0){this.pending.delete(A),this.emitActivity();try{await this.syncOne(A)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(A){let e=this.getTree().get(A);if(!e||!e.file)return!1;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e),n=this.app.metadataCache.getFileCache(e.file)?.frontmatter,o=n&&typeof n[_t]=="string"?n[_t]:null,a=n?.[Fe],r=Array.isArray(a)?a.filter(c=>typeof c=="string"):[];if((o??null)!==(i??null)||r.length!==s.length)return!0;for(let c=0;c<r.length;c++)if(r[c]!==s[c])return!0;return!1}async syncOne(A){let e=this.getTree().get(A);if(!e||!e.file||!this.wouldWrite(A))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await St.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[_t]=i:delete n[_t],s.length>0?n[Fe]=s:delete n[Fe]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(A){if(A.id===U)return null;let t=this.getTree();if(!A.parent||A.parent===U){let i=t.getRoot();return i&&i.id!==A.id&&i.file?Hi(i.file.path):null}let e=t.get(A.parent);return e?.file?Hi(e.file.path):null}computeChildrenLinks(A){return this.getTree().getChildren(A.id).filter(e=>!!e.file).map(e=>Hi(e.file.path))}};Ui.PACING_MS=100;var Ti=Ui;async function ve(h,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let c of h.vault.getMarkdownFiles()){if(c.path!==A&&!c.path.startsWith(t))continue;let l=h.metadataCache.getFileCache(c)?.frontmatter,g=typeof l?.id=="string"?l.id:null;if(!g)continue;let p=typeof l?.parent=="string"?l.parent:U;e.set(g,{file:c,id:g,parent:p});let d=i.get(p)??[];d.push(g),i.set(p,d)}let s=c=>Hi(c.file.path),n=c=>{if(c.id===U)return null;if(c.parent===U||!c.parent){let g=e.get(U);return g?s(g):null}let l=e.get(c.parent);return l?s(l):null},o=c=>{let l=i.get(c.id)??[],g=[];for(let p of l){let d=e.get(p);d&&g.push(s(d))}return g},a=0,r=0;for(let c of e.values()){a+=1;let l=n(c),g=o(c),p=h.metadataCache.getFileCache(c.file)?.frontmatter,d=p&&typeof p[_t]=="string"?p[_t]:null,I=p?.[Fe],u=Array.isArray(I)?I.filter(m=>typeof m=="string"):[],f=(d??null)===(l??null),C=u.length===g.length&&u.every((m,E)=>m===g[E]);if(!(f&&C))try{await h.fileManager.processFrontMatter(c.file,m=>{l?m[_t]=l:delete m[_t],g.length>0?m[Fe]=g:delete m[Fe]}),r+=1,await new Promise(m=>setTimeout(m,50))}catch(m){console.warn("[Stashpad] rebootstrap fm sync failed",c.file.path,m)}}return{checked:a,written:r}}function Hi(h){return`[[${h.replace(/\.md$/i,"")}]]`}Rt();me();var Gi=class{constructor(A,t){this.tree=A;this.log=t}async sweep(A){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!A)return!0;let o=A.replace(/\/+$/,"");return n===o||n.startsWith(o+"/")};for(let[n,o]of Object.entries(e)){let a=t[n];a?a.parent!==o.parent?await this.log.append({type:"parent_change",id:n,payload:{from:a.parent,to:o.parent}}):a.path!==o.path&&await this.log.append({type:"rename",id:n,payload:{from:a.path,to:o.path}}):await this.log.append({type:"create",id:n,payload:{path:o.path,parent:o.parent}})}for(let[n,o]of Object.entries(t))!e[n]&&i(o.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:o.path}});let s={};for(let[n,o]of Object.entries(t))i(o.path)||(s[n]=o);for(let[n,o]of Object.entries(e))s[n]=o;await this.log.writeState(s)}};var gt=require("obsidian");wt();As();function Es(h){let A=h.trim().toLowerCase();if(!A)return null;let t=Date.now(),e=I=>(0,gt.moment)(I).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=A,a=i.exec(A);if(a&&(a[3]||a[2])){let I=parseInt(a[1],10),u=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&I<12&&(I+=12),f==="am"&&I===12&&(I=0),I>=0&&I<24&&u>=0&&u<60&&(s=(I*3600+u*60)*1e3,n=!0,o=A.replace(a[0]," ").replace(/\s+/g," ").trim())}let r=I=>n?I+s:I;if(o===""||o==="today")return r(e(t));if(o==="yesterday")return r(e(t)-864e5);if(o==="tomorrow")return r(e(t)+864e5);let c=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],l=["sun","mon","tue","wed","thu","fri","sat"],g=c.indexOf(o)>=0?c.indexOf(o):l.indexOf(o);if(g>=0){let I=(0,gt.moment)().startOf("day"),f=(I.day()-g+7)%7;return r(I.subtract(f,"days").valueOf())}let p=/^(\d+)\s*([dwmy])$/.exec(o);if(p){let I=parseInt(p[1],10),u={d:"days",w:"weeks",m:"months",y:"years"}[p[2]];return r((0,gt.moment)().subtract(I,u).startOf("day").valueOf())}let d=(0,gt.moment)(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return d.isValid()?r(d.startOf("day").valueOf()):null}function Bn(h){let A={text:[],filters:{}},t=(h||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let a=Es(o);a!=null&&(A.filters.before=a)}else if(n==="after"){let a=Es(o);a!=null&&(A.filters.after=a)}else if(n==="on"){let a=Es(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))A.filters.on={start:a-6e4,end:a+6e4};else{let c=(0,gt.moment)(a).startOf("day").valueOf();A.filters.on={start:c,end:c+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&A.text.push(n.toLowerCase());return A}var Ot=class h extends gt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.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{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==U?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===U&&this.notes.push({node:a,title:i,body:""});for(let r of this.tree.getChildren(n))s(r.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(U))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(a=>{o.body=this.stripFm(a)})}}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(),i=Bn(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=C=>{if(!s.length)return!0;for(let m of s)if(!C.includes(m))return!1;return!0},o=null,a=null;if(i.filters.in){let C=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,a=new Map;let m=y=>C.every(F=>y.toLowerCase().includes(F)),E=y=>{if(!o.has(y)){o.add(y);for(let F of this.tree.getChildren(y))E(F.id)}};for(let y of this.notes)!y.node||y.cross||m(y.title)&&E(y.node.id);let w=new Map;for(let y of this.notes){if(!y.cross)continue;let F=w.get(y.cross.folder)??[];F.push(y),w.set(y.cross.folder,F)}for(let[y,F]of w){let D=new Map;for(let b of F){let Q=b.cross?.parentId??null;if(!Q)continue;let H=D.get(Q)??[];H.push(b.cross.id),D.set(Q,H)}let L=new Set;a.set(y,L);let S=b=>{if(!L.has(b)){L.add(b);for(let Q of D.get(b)??[])S(Q)}};for(let b of F)m(b.title)&&S(b.cross.id)}}let r=C=>{let m=i.filters;if(o||a)if(C.cross){let E=a?.get(C.cross.folder);if(!E||!E.has(C.cross.id))return!1}else if(C.node){if(!o||!o.has(C.node.id))return!1}else return!1;if(m.before||m.after||m.on){let E=this.createdMsFor(C);if(E==null||m.before!=null&&E>=m.before||m.after!=null&&E<=m.after||m.on&&(E<m.on.start||E>=m.on.end))return!1}return!0},c=C=>n(C.toLowerCase()),l=this.notes.filter(C=>!C.cross),g=this.notes.filter(C=>C.cross),p=(C,m)=>({id:C.cross?`cross:${C.cross.id}`:C.node.id,label:C.title,node:C.node,kind:"note",bodyPreview:this.previewFromBody(C.body,m),matchLine:m,crossFolder:C.cross?.folder,crossFile:C.cross?.file}),d=C=>{let m=[];for(let E of C)if(r(E))if(this.opts.mode==="search"){if(!e){m.push(p(E,-1));continue}let w=n(E.title.toLowerCase()),y=E.body.split(/\r?\n/),F=[];for(let L=0;L<y.length;L++)c(y[L])&&F.push(L);let D=F.length>0||n(E.body.toLowerCase());if(!w&&!D)continue;if(F.length===0)m.push(p(E,-1));else{let L=[],S=-100;for(let Q of F)Q-S>5&&L.push(Q),S=Q;let b=5;for(let Q of L.slice(0,b))m.push(p(E,Q))}}else{if(e&&!n(E.title.toLowerCase())&&!n(E.body.toLowerCase()))continue;m.push(p(E,-1))}return m},I=d(l),u=[...I];if(this.opts.mode==="search"?e?!0:I.length<10:!!e){let C=d(g);this.opts.mode==="search"&&!e&&(u.length=Math.min(u.length,50)),u.push(...C)}if(this.opts.folderResults){let C=this.opts.folderResults(),m={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};C.length>0&&(e?C.some(E=>{let w=E.split("/").pop()??E;return n(`${E.toLowerCase()} ${w.toLowerCase()}`)})&&u.push(m):u.unshift(m))}if(this.opts.allowCreate&&e&&!u.some(C=>C.label.trim().toLowerCase()===e)&&u.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let C=E=>E.kind==="note"&&(E.id===U||E.id===`cross:${U}`)&&n(E.label.toLowerCase()),m=u.filter(C);if(m.length>0){let E=u.filter(w=>!C(w));u.splice(0,u.length,...m,...E)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&u.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),u}loadExcludedNotes(){if(this.includeExcluded||!this.opts.excludedFolderNotes)return;this.includeExcluded=!0;for(let e of this.opts.excludedFolderNotes())this.notes.push({node:null,title:e.title,body:e.body,cross:e});for(let e of this.notes)!e.cross||e.body||!e.cross.file||this.app.vault.cachedRead(e.cross.file).then(i=>{e.body=this.stripFm(i)});let t=this.inputEl;t&&(t.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(()=>t.dispatchEvent(new Event("input",{bubbles:!0})),250))}previewFromBody(t,e){let i=t.split(/\r?\n/);if(e<0)return i.filter(a=>a.trim().length>0).slice(0,3).join(` +`}function Bi(h,A){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let i=t.createEl("ul");i.style.margin="0 0 8px 0",i.style.paddingLeft="18px",i.createEl("li",{text:`${A.indexed.length} indexed`}),i.createEl("li",{text:`${A.nonIndex.length+A.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.style.padding="2px 10px",s.style.fontSize="var(--font-ui-smaller)";let n;return s.onclick=async o=>{if(o.stopPropagation(),A.previewPath){let a=h.vault.getAbstractFileByPath(A.previewPath);a instanceof Ft.TFile&&await h.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new Ft.Notice(t,0),n}var Ft,an,Ze,$e=se(()=>{"use strict";Ft=require("obsidian");Rt();me();wt();an=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ze=class extends Ft.Modal{constructor(t,e,i,s,n){super(t);this.plugin=e;this.settings=i;this.indexedCount=s;this.onBuild=n;this.LARGE_BUILD=50;this.previewRan=!1;this.previewPath=null}onOpen(){let{contentEl:t,titleEl:e}=this,i=!this.settings.jdIndexHasBuilt,s=this.indexedCount>this.LARGE_BUILD;e.setText(i?"Build JD index \u2014 first time?":"Build JD index");let n=this.settings.jdIndexStashpadFolder,o=t.createEl("p"),a=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;i?(o.appendText(`Stashpad is about to create ${a} (plus synthetic parents as needed) inside "`),o.createEl("code",{text:n}),o.appendText('". Existing notes with the same '),o.createEl("code",{text:"jdPrefix"}),o.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.")):s?(o.appendText(`You're about to create ${this.indexedCount} notes in "`),o.createEl("code",{text:n}),o.appendText(`". That's a big batch \u2014 if anything looks off, Preview the single-file output first.`)):(o.appendText('Build the JD index into "'),o.createEl("code",{text:n}),o.appendText(`"? Stashpad will create / update ${a}. Existing notes with matching `),o.createEl("code",{text:"jdPrefix"}),o.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 r=new Ft.Setting(t);(i||s)&&r.addButton(l=>{l.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),l.setCta(),l.onClick(async()=>{try{let c=await Ci(this.app,this.plugin,this.settings);if(c.error==="no-dest"){new Ft.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(c.error==="no-home"){new Ft.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,Bi(this.app,c),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(c){new Ft.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}),r.addButton(l=>{l.setButtonText(i?"Build anyway":"Build"),!i&&!s&&l.setCta(),l.onClick(async()=>{this.close(),await this.onBuild()})}),r.addButton(l=>{l.setButtonText("Cancel"),l.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var Mn=fo((xn,vs)=>{(function(h){typeof xn=="object"&&typeof vs<"u"?vs.exports=h():typeof define=="function"&&define.amd?define([],h):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=h()})(function(){return function h(A,t,e){function i(o,a){if(!t[o]){if(!A[o]){var r=typeof require=="function"&&require;if(!a&&r)return r(o,!0);if(s)return s(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[o]={exports:{}};A[o][0].call(c.exports,function(g){var p=A[o][1][g];return i(p||g)},c,c.exports,h,A,t,e)}return t[o].exports}for(var s=typeof require=="function"&&require,n=0;n<e.length;n++)i(e[n]);return i}({1:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,l,c,g,p,d=[],I=0,u=n.length,f=u,C=e.getTypeOf(n)!=="string";I<n.length;)f=u-I,r=C?(o=n[I++],a=I<u?n[I++]:0,I<u?n[I++]:0):(o=n.charCodeAt(I++),a=I<u?n.charCodeAt(I++):0,I<u?n.charCodeAt(I++):0),l=o>>2,c=(3&o)<<4|a>>4,g=1<f?(15&a)<<2|r>>6:64,p=2<f?63&r:64,d.push(s.charAt(l)+s.charAt(c)+s.charAt(g)+s.charAt(p));return d.join("")},t.decode=function(n){var o,a,r,l,c,g,p=0,d=0,I="data:";if(n.substr(0,I.length)===I)throw new Error("Invalid base64 input, it looks like a data url.");var u,f=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===s.charAt(64)&&f--,n.charAt(n.length-2)===s.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=i.uint8array?new Uint8Array(0|f):new Array(0|f);p<n.length;)o=s.indexOf(n.charAt(p++))<<2|(l=s.indexOf(n.charAt(p++)))>>4,a=(15&l)<<4|(c=s.indexOf(n.charAt(p++)))>>2,r=(3&c)<<6|(g=s.indexOf(n.charAt(p++))),u[d++]=o,c!==64&&(u[d++]=a),g!==64&&(u[d++]=r);return u}},{"./support":30,"./utils":32}],2:[function(h,A,t){"use strict";var e=h("./external"),i=h("./stream/DataWorker"),s=h("./stream/Crc32Probe"),n=h("./stream/DataLengthProbe");function o(a,r,l,c,g){this.compressedSize=a,this.uncompressedSize=r,this.crc32=l,this.compression=c,this.compressedContent=g}o.prototype={getContentWorker:function(){var a=new i(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),r=this;return a.on("end",function(){if(this.streamInfo.data_length!==r.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new i(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(a,r,l){return a.pipe(new s).pipe(new n("uncompressedSize")).pipe(r.compressWorker(l)).pipe(new n("compressedSize")).withStreamInfo("compression",r)},A.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(h,A,t){"use strict";var e=h("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=h("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(h,A,t){"use strict";var e=h("./utils"),i=function(){for(var s,n=[],o=0;o<256;o++){s=o;for(var a=0;a<8;a++)s=1&s?3988292384^s>>>1:s>>>1;n[o]=s}return n}();A.exports=function(s,n){return s!==void 0&&s.length?e.getTypeOf(s)!=="string"?function(o,a,r,l){var c=i,g=l+r;o^=-1;for(var p=l;p<g;p++)o=o>>>8^c[255&(o^a[p])];return-1^o}(0|n,s,s.length,0):function(o,a,r,l){var c=i,g=l+r;o^=-1;for(var p=l;p<g;p++)o=o>>>8^c[255&(o^a.charCodeAt(p))];return-1^o}(0|n,s,s.length,0):0}},{"./utils":32}],5:[function(h,A,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(h,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:h("lie"),A.exports={Promise:e}},{lie:37}],7:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=h("pako"),s=h("./utils"),n=h("./stream/GenericWorker"),o=e?"uint8array":"array";function a(r,l){n.call(this,"FlateWorker/"+r),this._pako=null,this._pakoAction=r,this._pakoOptions=l,this.meta={}}t.magic="\b\0",s.inherits(a,n),a.prototype.processChunk=function(r){this.meta=r.meta,this._pako===null&&this._createPako(),this._pako.push(s.transformTo(o,r.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 i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var r=this;this._pako.onData=function(l){r.push({data:l,meta:r.meta})}},t.compressWorker=function(r){return new a("Deflate",r)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(h,A,t){"use strict";function e(c,g){var p,d="";for(p=0;p<g;p++)d+=String.fromCharCode(255&c),c>>>=8;return d}function i(c,g,p,d,I,u){var f,C,m=c.file,E=c.compression,w=u!==o.utf8encode,y=s.transformTo("string",u(m.name)),F=s.transformTo("string",o.utf8encode(m.name)),D=m.comment,L=s.transformTo("string",u(D)),S=s.transformTo("string",o.utf8encode(D)),b=F.length!==m.name.length,Q=S.length!==D.length,H="",$="",M="",T=m.dir,J=m.date,Z={crc32:0,compressedSize:0,uncompressedSize:0};g&&!p||(Z.crc32=c.crc32,Z.compressedSize=c.compressedSize,Z.uncompressedSize=c.uncompressedSize);var G=0;g&&(G|=8),w||!b&&!Q||(G|=2048);var N=0,_=0;T&&(N|=16),I==="UNIX"?(_=798,N|=function(z,ot){var pt=z;return z||(pt=ot?16893:33204),(65535&pt)<<16}(m.unixPermissions,T)):(_=20,N|=function(z){return 63&(z||0)}(m.dosPermissions)),f=J.getUTCHours(),f<<=6,f|=J.getUTCMinutes(),f<<=5,f|=J.getUTCSeconds()/2,C=J.getUTCFullYear()-1980,C<<=4,C|=J.getUTCMonth()+1,C<<=5,C|=J.getUTCDate(),b&&($=e(1,1)+e(a(y),4)+F,H+="up"+e($.length,2)+$),Q&&(M=e(1,1)+e(a(L),4)+S,H+="uc"+e(M.length,2)+M);var K="";return K+=` +\0`,K+=e(G,2),K+=E.magic,K+=e(f,2),K+=e(C,2),K+=e(Z.crc32,4),K+=e(Z.compressedSize,4),K+=e(Z.uncompressedSize,4),K+=e(y.length,2),K+=e(H.length,2),{fileRecord:r.LOCAL_FILE_HEADER+K+y+H,dirRecord:r.CENTRAL_FILE_HEADER+e(_,2)+K+e(L.length,2)+"\0\0\0\0"+e(N,4)+e(d,4)+y+H+L}}var s=h("../utils"),n=h("../stream/GenericWorker"),o=h("../utf8"),a=h("../crc32"),r=h("../signature");function l(c,g,p,d){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=p,this.encodeFileName=d,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(l,n),l.prototype.push=function(c){var g=c.meta.percent||0,p=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:p?(g+100*(p-d-1))/p:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var g=this.streamFiles&&!c.file.dir;if(g){var p=i(c,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var g=this.streamFiles&&!c.file.dir,p=i(c,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),g)this.push({data:function(d){return r.DATA_DESCRIPTOR+e(d.crc32,4)+e(d.compressedSize,4)+e(d.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var p=this.bytesWritten-c,d=function(I,u,f,C,m){var E=s.transformTo("string",m(C));return r.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(I,2)+e(I,2)+e(u,4)+e(f,4)+e(E.length,2)+E}(this.dirRecords.length,p,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 g=this;return c.on("data",function(p){g.processChunk(p)}),c.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),c.on("error",function(p){g.error(p)}),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 g=this._sources;if(!n.prototype.error.call(this,c))return!1;for(var p=0;p<g.length;p++)try{g[p].error(c)}catch{}return!0},l.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,g=0;g<c.length;g++)c[g].lock()},A.exports=l},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(h,A,t){"use strict";var e=h("../compressions"),i=h("./ZipFileWorker");t.generateWorker=function(s,n,o){var a=new i(n.streamFiles,o,n.platform,n.encodeFileName),r=0;try{s.forEach(function(l,c){r++;var g=function(u,f){var C=u||f,m=e[C];if(!m)throw new Error(C+" is not a valid compression method !");return m}(c.options.compression,n.compression),p=c.options.compressionOptions||n.compressionOptions||{},d=c.dir,I=c.date;c._compressWorker(g,p).withStreamInfo("file",{name:l,dir:d,date:I,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(a)}),a.entriesCount=r}catch(l){a.error(l)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(h,A,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 i=new e;for(var s in this)typeof this[s]!="function"&&(i[s]=this[s]);return i}}(e.prototype=h("./object")).loadAsync=h("./load"),e.support=h("./support"),e.defaults=h("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=h("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./external"),s=h("./utf8"),n=h("./zipEntries"),o=h("./stream/Crc32Probe"),a=h("./nodejsUtils");function r(l){return new i.Promise(function(c,g){var p=l.decompressed.getContentWorker().pipe(new o);p.on("error",function(d){g(d)}).on("end",function(){p.streamInfo.crc32!==l.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}A.exports=function(l,c){var g=this;return c=e.extend(c||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),a.isNode&&a.isStream(l)?i.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(p){var d=new n(c);return d.load(p),d}).then(function(p){var d=[i.Promise.resolve(p)],I=p.files;if(c.checkCRC32)for(var u=0;u<I.length;u++)d.push(r(I[u]));return i.Promise.all(d)}).then(function(p){for(var d=p.shift(),I=d.files,u=0;u<I.length;u++){var f=I[u],C=f.fileNameStr,m=e.resolve(f.fileNameStr);g.file(m,f.decompressed,{binary:!0,optimizedBinaryString:!0,date:f.date,dir:f.dir,comment:f.fileCommentStr.length?f.fileCommentStr:null,unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions,createFolders:c.createFolders}),f.dir||(g.file(m).unsafeOriginalName=C)}return d.zipComment.length&&(g.comment=d.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../stream/GenericWorker");function s(n,o){i.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(o)}e.inherits(s,i),s.prototype._bindStream=function(n){var o=this;(this._stream=n).pause(),n.on("data",function(a){o.push({data:a,meta:{percent:0}})}).on("error",function(a){o.isPaused?this.generatedError=a:o.error(a)}).on("end",function(){o.isPaused?o._upstreamEnded=!0:o.end()})},s.prototype.pause=function(){return!!i.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},A.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(h,A,t){"use strict";var e=h("readable-stream").Readable;function i(s,n,o){e.call(this,n),this._helper=s;var a=this;s.on("data",function(r,l){a.push(r)||a._helper.pause(),o&&o(l)}).on("error",function(r){a.emit("error",r)}).on("end",function(){a.push(null)})}h("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(h,A,t){"use strict";A.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,i){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,i);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,i)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var i=new Buffer(e);return i.fill(0),i},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(h,A,t){"use strict";function e(m,E,w){var y,F=s.getTypeOf(E),D=s.extend(w||{},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&&(m=I(m)),D.createFolders&&(y=d(m))&&u.call(this,y,!0);var L=F==="string"&&D.binary===!1&&D.base64===!1;w&&w.binary!==void 0||(D.binary=!L),(E instanceof r&&E.uncompressedSize===0||D.dir||!E||E.length===0)&&(D.base64=!1,D.binary=!0,E="",D.compression="STORE",F="string");var S=null;S=E instanceof r||E instanceof n?E:g.isNode&&g.isStream(E)?new p(m,E):s.prepareContent(m,E,D.binary,D.optimizedBinaryString,D.base64);var b=new l(m,S,D);this.files[m]=b}var i=h("./utf8"),s=h("./utils"),n=h("./stream/GenericWorker"),o=h("./stream/StreamHelper"),a=h("./defaults"),r=h("./compressedObject"),l=h("./zipObject"),c=h("./generate"),g=h("./nodejsUtils"),p=h("./nodejs/NodejsStreamInputAdapter"),d=function(m){m.slice(-1)==="/"&&(m=m.substring(0,m.length-1));var E=m.lastIndexOf("/");return 0<E?m.substring(0,E):""},I=function(m){return m.slice(-1)!=="/"&&(m+="/"),m},u=function(m,E){return E=E!==void 0?E:a.createFolders,m=I(m),this.files[m]||e.call(this,m,null,{dir:!0,createFolders:E}),this.files[m]};function f(m){return Object.prototype.toString.call(m)==="[object RegExp]"}var C={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(m){var E,w,y;for(E in this.files)y=this.files[E],(w=E.slice(this.root.length,E.length))&&E.slice(0,this.root.length)===this.root&&m(w,y)},filter:function(m){var E=[];return this.forEach(function(w,y){m(w,y)&&E.push(y)}),E},file:function(m,E,w){if(arguments.length!==1)return m=this.root+m,e.call(this,m,E,w),this;if(f(m)){var y=m;return this.filter(function(D,L){return!L.dir&&y.test(D)})}var F=this.files[this.root+m];return F&&!F.dir?F:null},folder:function(m){if(!m)return this;if(f(m))return this.filter(function(F,D){return D.dir&&m.test(F)});var E=this.root+m,w=u.call(this,E),y=this.clone();return y.root=w.name,y},remove:function(m){m=this.root+m;var E=this.files[m];if(E||(m.slice(-1)!=="/"&&(m+="/"),E=this.files[m]),E&&!E.dir)delete this.files[m];else for(var w=this.filter(function(F,D){return D.name.slice(0,m.length)===m}),y=0;y<w.length;y++)delete this.files[w[y].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(m){var E,w={};try{if((w=s.extend(m||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:i.utf8encode})).type=w.type.toLowerCase(),w.compression=w.compression.toUpperCase(),w.type==="binarystring"&&(w.type="string"),!w.type)throw new Error("No output type specified.");s.checkSupport(w.type),w.platform!=="darwin"&&w.platform!=="freebsd"&&w.platform!=="linux"&&w.platform!=="sunos"||(w.platform="UNIX"),w.platform==="win32"&&(w.platform="DOS");var y=w.comment||this.comment||"";E=c.generateWorker(this,w,y)}catch(F){(E=new n("error")).error(F)}return new o(E,w.type||"string",w.mimeType)},generateAsync:function(m,E){return this.generateInternalStream(m).accumulate(E)},generateNodeStream:function(m,E){return(m=m||{}).type||(m.type="nodebuffer"),this.generateInternalStream(m).toNodejsStream(E)}};A.exports=C},{"./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(h,A,t){"use strict";A.exports=h("stream")},{stream:void 0}],17:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data[this.zero+s]},i.prototype.lastIndexOfSignature=function(s){for(var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.length-4;0<=l;--l)if(this.data[l]===n&&this.data[l+1]===o&&this.data[l+2]===a&&this.data[l+3]===r)return l-this.zero;return-1},i.prototype.readAndCheckSignature=function(s){var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.readData(4);return n===l[0]&&o===l[1]&&a===l[2]&&r===l[3]},i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],18:[function(h,A,t){"use strict";var e=h("../utils");function i(s){this.data=s,this.length=s.length,this.index=0,this.zero=0}i.prototype={checkOffset:function(s){this.checkIndex(this.index+s)},checkIndex:function(s){if(this.length<this.zero+s||s<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+s+"). Corrupted zip ?")},setIndex:function(s){this.checkIndex(s),this.index=s},skip:function(s){this.setIndex(this.index+s)},byteAt:function(){},readInt:function(s){var n,o=0;for(this.checkOffset(s),n=this.index+s-1;n>=this.index;n--)o=(o<<8)+this.byteAt(n);return this.index+=s,o},readString:function(s){return e.transformTo("string",this.readData(s))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var s=this.readInt(4);return new Date(Date.UTC(1980+(s>>25&127),(s>>21&15)-1,s>>16&31,s>>11&31,s>>5&63,(31&s)<<1))}},A.exports=i},{"../utils":32}],19:[function(h,A,t){"use strict";var e=h("./Uint8ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data.charCodeAt(this.zero+s)},i.prototype.lastIndexOfSignature=function(s){return this.data.lastIndexOf(s)-this.zero},i.prototype.readAndCheckSignature=function(s){return s===this.readData(4)},i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],21:[function(h,A,t){"use strict";var e=h("./ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../support"),s=h("./ArrayReader"),n=h("./StringReader"),o=h("./NodeBufferReader"),a=h("./Uint8ArrayReader");A.exports=function(r){var l=e.getTypeOf(r);return e.checkSupport(l),l!=="string"||i.uint8array?l==="nodebuffer"?new o(r):i.uint8array?new a(e.transformTo("uint8array",r)):new s(e.transformTo("array",r)):new n(r)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(h,A,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(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../utils");function s(n){e.call(this,"ConvertWorker to "+n),this.destType=n}i.inherits(s,e),s.prototype.processChunk=function(n){this.push({data:i.transformTo(this.destType,n.data),meta:n.meta})},A.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}h("../utils").inherits(s,e),s.prototype.processChunk=function(n){this.streamInfo.crc32=i(n.data,this.streamInfo.crc32||0),this.push(n)},A.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(s,i),s.prototype.processChunk=function(n){if(n){var o=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=o+n.data.length}i.prototype.processChunk.call(this,n)},A.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataWorker");var o=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(a){o.dataIsReady=!0,o.data=a,o.max=a&&a.length||0,o.type=e.getTypeOf(a),o.isPaused||o._tickAndRepeat()},function(a){o.error(a)})}e.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,o=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,o);break;case"uint8array":n=this.data.subarray(this.index,o);break;case"array":case"nodebuffer":n=this.data.slice(this.index,o)}return this.index=o,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},A.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(h,A,t){"use strict";function e(i){this.name=i||"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(i){this.emit("data",i)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(i){this.emit("error",i)}return!0},error:function(i){return!this.isFinished&&(this.isPaused?this.generatedError=i:(this.isFinished=!0,this.emit("error",i),this.previous&&this.previous.error(i),this.cleanUp()),!0)},on:function(i,s){return this._listeners[i].push(s),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(i,s){if(this._listeners[i])for(var n=0;n<this._listeners[i].length;n++)this._listeners[i][n].call(this,s)},pipe:function(i){return i.registerPrevious(this)},registerPrevious:function(i){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=i.streamInfo,this.mergeStreamInfo(),this.previous=i;var s=this;return i.on("data",function(n){s.processChunk(n)}),i.on("end",function(){s.end()}),i.on("error",function(n){s.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 i=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),i=!0),this.previous&&this.previous.resume(),!i},flush:function(){},processChunk:function(i){this.push(i)},withStreamInfo:function(i,s){return this.extraStreamInfo[i]=s,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var i in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,i)&&(this.streamInfo[i]=this.extraStreamInfo[i])},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 i="Worker "+this.name;return this.previous?this.previous+" -> "+i:i}},A.exports=e},{}],29:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./ConvertWorker"),s=h("./GenericWorker"),n=h("../base64"),o=h("../support"),a=h("../external"),r=null;if(o.nodestream)try{r=h("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(g,p){return new a.Promise(function(d,I){var u=[],f=g._internalType,C=g._outputType,m=g._mimeType;g.on("data",function(E,w){u.push(E),p&&p(w)}).on("error",function(E){u=[],I(E)}).on("end",function(){try{var E=function(w,y,F){switch(w){case"blob":return e.newBlob(e.transformTo("arraybuffer",y),F);case"base64":return n.encode(y);default:return e.transformTo(w,y)}}(C,function(w,y){var F,D=0,L=null,S=0;for(F=0;F<y.length;F++)S+=y[F].length;switch(w){case"string":return y.join("");case"array":return Array.prototype.concat.apply([],y);case"uint8array":for(L=new Uint8Array(S),F=0;F<y.length;F++)L.set(y[F],D),D+=y[F].length;return L;case"nodebuffer":return Buffer.concat(y);default:throw new Error("concat : unsupported type '"+w+"'")}}(f,u),m);d(E)}catch(w){I(w)}u=[]}).resume()})}function c(g,p,d){var I=p;switch(p){case"blob":case"arraybuffer":I="uint8array";break;case"base64":I="string"}try{this._internalType=I,this._outputType=p,this._mimeType=d,e.checkSupport(I),this._worker=g.pipe(new i(I)),g.lock()}catch(u){this._worker=new s("error"),this._worker.error(u)}}c.prototype={accumulate:function(g){return l(this,g)},on:function(g,p){var d=this;return g==="data"?this._worker.on(g,function(I){p.call(d,I.data,I.meta)}):this._worker.on(g,function(){e.delay(p,arguments,d)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(g){if(e.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new r(this,{objectMode:this._outputType!=="nodebuffer"},g)}},A.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(h,A,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 i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(e),t.blob=i.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!h("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(h,A,t){"use strict";for(var e=h("./utils"),i=h("./support"),s=h("./nodejsUtils"),n=h("./stream/GenericWorker"),o=new Array(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;o[254]=o[254]=1;function r(){n.call(this,"utf-8 decode"),this.leftOver=null}function l(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return i.nodebuffer?s.newBufferFrom(c,"utf-8"):function(g){var p,d,I,u,f,C=g.length,m=0;for(u=0;u<C;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),m+=d<128?1:d<2048?2:d<65536?3:4;for(p=i.uint8array?new Uint8Array(m):new Array(m),u=f=0;f<m;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),d<128?p[f++]=d:(d<2048?p[f++]=192|d>>>6:(d<65536?p[f++]=224|d>>>12:(p[f++]=240|d>>>18,p[f++]=128|d>>>12&63),p[f++]=128|d>>>6&63),p[f++]=128|63&d);return p}(c)},t.utf8decode=function(c){return i.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(g){var p,d,I,u,f=g.length,C=new Array(2*f);for(p=d=0;p<f;)if((I=g[p++])<128)C[d++]=I;else if(4<(u=o[I]))C[d++]=65533,p+=u-1;else{for(I&=u===2?31:u===3?15:7;1<u&&p<f;)I=I<<6|63&g[p++],u--;1<u?C[d++]=65533:I<65536?C[d++]=I:(I-=65536,C[d++]=55296|I>>10&1023,C[d++]=56320|1023&I)}return C.length!==d&&(C.subarray?C=C.subarray(0,d):C.length=d),e.applyFromCharCode(C)}(c=e.transformTo(i.uint8array?"uint8array":"array",c))},e.inherits(r,n),r.prototype.processChunk=function(c){var g=e.transformTo(i.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var p=g;(g=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),g.set(p,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var d=function(u,f){var C;for((f=f||u.length)>u.length&&(f=u.length),C=f-1;0<=C&&(192&u[C])==128;)C--;return C<0||C===0?f:C+o[u[C]]>f?C:f}(g),I=g;d!==g.length&&(i.uint8array?(I=g.subarray(0,d),this.leftOver=g.subarray(d,g.length)):(I=g.slice(0,d),this.leftOver=g.slice(d,g.length))),this.push({data:t.utf8decode(I),meta:c.meta})},r.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=r,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(h,A,t){"use strict";var e=h("./support"),i=h("./base64"),s=h("./nodejsUtils"),n=h("./external");function o(p){return p}function a(p,d){for(var I=0;I<p.length;++I)d[I]=255&p.charCodeAt(I);return d}h("setimmediate"),t.newBlob=function(p,d){t.checkSupport("blob");try{return new Blob([p],{type:d})}catch{try{var I=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return I.append(p),I.getBlob(d)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,d,I){var u=[],f=0,C=p.length;if(C<=I)return String.fromCharCode.apply(null,p);for(;f<C;)d==="array"||d==="nodebuffer"?u.push(String.fromCharCode.apply(null,p.slice(f,Math.min(f+I,C)))):u.push(String.fromCharCode.apply(null,p.subarray(f,Math.min(f+I,C)))),f+=I;return u.join("")},stringifyByChar:function(p){for(var d="",I=0;I<p.length;I++)d+=String.fromCharCode(p[I]);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,s.allocBuffer(1)).length===1}catch{return!1}}()}};function l(p){var d=65536,I=t.getTypeOf(p),u=!0;if(I==="uint8array"?u=r.applyCanBeUsed.uint8array:I==="nodebuffer"&&(u=r.applyCanBeUsed.nodebuffer),u)for(;1<d;)try{return r.stringifyByChunk(p,I,d)}catch{d=Math.floor(d/2)}return r.stringifyByChar(p)}function c(p,d){for(var I=0;I<p.length;I++)d[I]=p[I];return d}t.applyFromCharCode=l;var g={};g.string={string:o,array:function(p){return a(p,new Array(p.length))},arraybuffer:function(p){return g.string.uint8array(p).buffer},uint8array:function(p){return a(p,new Uint8Array(p.length))},nodebuffer:function(p){return a(p,s.allocBuffer(p.length))}},g.array={string:l,array:o,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(p)}},g.arraybuffer={string:function(p){return l(new Uint8Array(p))},array:function(p){return c(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:o,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(new Uint8Array(p))}},g.uint8array={string:l,array:function(p){return c(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:o,nodebuffer:function(p){return s.newBufferFrom(p)}},g.nodebuffer={string:l,array:function(p){return c(p,new Array(p.length))},arraybuffer:function(p){return g.nodebuffer.uint8array(p).buffer},uint8array:function(p){return c(p,new Uint8Array(p.length))},nodebuffer:o},t.transformTo=function(p,d){if(d=d||"",!p)return d;t.checkSupport(p);var I=t.getTypeOf(d);return g[I][p](d)},t.resolve=function(p){for(var d=p.split("/"),I=[],u=0;u<d.length;u++){var f=d[u];f==="."||f===""&&u!==0&&u!==d.length-1||(f===".."?I.pop():I.push(f))}return I.join("/")},t.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":e.nodebuffer&&s.isBuffer(p)?"nodebuffer":e.uint8array&&p instanceof Uint8Array?"uint8array":e.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(p){if(!e[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(p){var d,I,u="";for(I=0;I<(p||"").length;I++)u+="\\x"+((d=p.charCodeAt(I))<16?"0":"")+d.toString(16).toUpperCase();return u},t.delay=function(p,d,I){setImmediate(function(){p.apply(I||null,d||[])})},t.inherits=function(p,d){function I(){}I.prototype=d.prototype,p.prototype=new I},t.extend=function(){var p,d,I={};for(p=0;p<arguments.length;p++)for(d in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],d)&&I[d]===void 0&&(I[d]=arguments[p][d]);return I},t.prepareContent=function(p,d,I,u,f){return n.Promise.resolve(d).then(function(C){return e.blob&&(C instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(C))!==-1)&&typeof FileReader<"u"?new n.Promise(function(m,E){var w=new FileReader;w.onload=function(y){m(y.target.result)},w.onerror=function(y){E(y.target.error)},w.readAsArrayBuffer(C)}):C}).then(function(C){var m=t.getTypeOf(C);return m?(m==="arraybuffer"?C=t.transformTo("uint8array",C):m==="string"&&(f?C=i.decode(C):I&&u!==!0&&(C=function(E){return a(E,e.uint8array?new Uint8Array(E.length):new Array(E.length))}(C))),C):n.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./signature"),n=h("./zipEntry"),o=h("./support");function a(r){this.files=[],this.loadOptions=r}a.prototype={checkSignature:function(r){if(!this.reader.readAndCheckSignature(r)){this.reader.index-=4;var l=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(l)+", expected "+i.pretty(r)+")")}},isSignature:function(r,l){var c=this.reader.index;this.reader.setIndex(r);var g=this.reader.readString(4)===l;return this.reader.setIndex(c),g},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 r=this.reader.readData(this.zipCommentLength),l=o.uint8array?"uint8array":"array",c=i.transformTo(l,r);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 r,l,c,g=this.zip64EndOfCentralSize-44;0<g;)r=this.reader.readInt(2),l=this.reader.readInt(4),c=this.reader.readData(l),this.zip64ExtensibleData[r]={id:r,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 r,l;for(r=0;r<this.files.length;r++)l=this.files[r],this.reader.setIndex(l.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),l.readLocalPart(this.reader),l.handleUTF8(),l.processAttributes()},readCentralDir:function(){var r;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(r=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(r);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 r=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(r<0)throw this.isSignature(0,s.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(r);var l=r;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===i.MAX_VALUE_16BITS||this.diskWithCentralDirStart===i.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===i.MAX_VALUE_16BITS||this.centralDirRecords===i.MAX_VALUE_16BITS||this.centralDirSize===i.MAX_VALUE_32BITS||this.centralDirOffset===i.MAX_VALUE_32BITS){if(this.zip64=!0,(r=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(r),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.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(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var c=this.centralDirOffset+this.centralDirSize;this.zip64&&(c+=20,c+=12+this.zip64EndOfCentralSize);var g=l-c;if(0<g)this.isSignature(l,s.CENTRAL_FILE_HEADER)||(this.reader.zero=g);else if(g<0)throw new Error("Corrupted zip: missing "+Math.abs(g)+" bytes.")},prepareReader:function(r){this.reader=e(r)},load:function(r){this.prepareReader(r),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},A.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./compressedObject"),n=h("./crc32"),o=h("./utf8"),a=h("./compressions"),r=h("./support");function l(c,g){this.options=c,this.loadOptions=g}l.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(c){var g,p;if(c.skip(22),this.fileNameLength=c.readInt(2),p=c.readInt(2),this.fileName=c.readData(this.fileNameLength),c.skip(p),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((g=function(d){for(var I in a)if(Object.prototype.hasOwnProperty.call(a,I)&&a[I].magic===d)return a[I];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+i.pretty(this.compressionMethod)+" unknown (inner file : "+i.transformTo("string",this.fileName)+")");this.decompressed=new s(this.compressedSize,this.uncompressedSize,this.crc32,g,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 g=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(g),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===i.MAX_VALUE_32BITS&&(this.uncompressedSize=c.readInt(8)),this.compressedSize===i.MAX_VALUE_32BITS&&(this.compressedSize=c.readInt(8)),this.localHeaderOffset===i.MAX_VALUE_32BITS&&(this.localHeaderOffset=c.readInt(8)),this.diskNumberStart===i.MAX_VALUE_32BITS&&(this.diskNumberStart=c.readInt(4))}},readExtraFields:function(c){var g,p,d,I=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<I;)g=c.readInt(2),p=c.readInt(2),d=c.readData(p),this.extraFields[g]={id:g,length:p,value:d};c.setIndex(I)},handleUTF8:function(){var c=r.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=o.utf8decode(this.fileName),this.fileCommentStr=o.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var p=i.transformTo(c,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var d=this.findExtraFieldUnicodeComment();if(d!==null)this.fileCommentStr=d;else{var I=i.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(I)}}},findExtraFieldUnicodePath:function(){var c=this.extraFields[28789];if(c){var g=e(c.value);return g.readInt(1)!==1||n(this.fileName)!==g.readInt(4)?null:o.utf8decode(g.readData(c.length-5))}return null},findExtraFieldUnicodeComment:function(){var c=this.extraFields[25461];if(c){var g=e(c.value);return g.readInt(1)!==1||n(this.fileComment)!==g.readInt(4)?null:o.utf8decode(g.readData(c.length-5))}return null}},A.exports=l},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(h,A,t){"use strict";function e(g,p,d){this.name=g,this.dir=d.dir,this.date=d.date,this.comment=d.comment,this.unixPermissions=d.unixPermissions,this.dosPermissions=d.dosPermissions,this._data=p,this._dataBinary=d.binary,this.options={compression:d.compression,compressionOptions:d.compressionOptions}}var i=h("./stream/StreamHelper"),s=h("./stream/DataWorker"),n=h("./utf8"),o=h("./compressedObject"),a=h("./stream/GenericWorker");e.prototype={internalStream:function(g){var p=null,d="string";try{if(!g)throw new Error("No output type specified.");var I=(d=g.toLowerCase())==="string"||d==="text";d!=="binarystring"&&d!=="text"||(d="string"),p=this._decompressWorker();var u=!this._dataBinary;u&&!I&&(p=p.pipe(new n.Utf8EncodeWorker)),!u&&I&&(p=p.pipe(new n.Utf8DecodeWorker))}catch(f){(p=new a("error")).error(f)}return new i(p,d,"")},async:function(g,p){return this.internalStream(g).accumulate(p)},nodeStream:function(g,p){return this.internalStream(g||"nodebuffer").toNodejsStream(p)},_compressWorker:function(g,p){if(this._data instanceof o&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var d=this._decompressWorker();return this._dataBinary||(d=d.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(d,g,p)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof a?this._data:new s(this._data)}};for(var r=["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<r.length;c++)e.prototype[r[c]]=l;A.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(h,A,t){(function(e){"use strict";var i,s,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var o=0,a=new n(g),r=e.document.createTextNode("");a.observe(r,{characterData:!0}),i=function(){r.data=o=++o%2}}else if(e.setImmediate||e.MessageChannel===void 0)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var p=e.document.createElement("script");p.onreadystatechange=function(){g(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},e.document.documentElement.appendChild(p)}:function(){setTimeout(g,0)};else{var l=new e.MessageChannel;l.port1.onmessage=g,i=function(){l.port2.postMessage(0)}}var c=[];function g(){var p,d;s=!0;for(var I=c.length;I;){for(d=c,c=[],p=-1;++p<I;)d[p]();I=c.length}s=!1}A.exports=function(p){c.push(p)!==1||s||i()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(h,A,t){"use strict";var e=h("immediate");function i(){}var s={},n=["REJECTED"],o=["FULFILLED"],a=["PENDING"];function r(I){if(typeof I!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,I!==i&&p(this,I)}function l(I,u,f){this.promise=I,typeof u=="function"&&(this.onFulfilled=u,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function c(I,u,f){e(function(){var C;try{C=u(f)}catch(m){return s.reject(I,m)}C===I?s.reject(I,new TypeError("Cannot resolve promise with itself")):s.resolve(I,C)})}function g(I){var u=I&&I.then;if(I&&(typeof I=="object"||typeof I=="function")&&typeof u=="function")return function(){u.apply(I,arguments)}}function p(I,u){var f=!1;function C(w){f||(f=!0,s.reject(I,w))}function m(w){f||(f=!0,s.resolve(I,w))}var E=d(function(){u(m,C)});E.status==="error"&&C(E.value)}function d(I,u){var f={};try{f.value=I(u),f.status="success"}catch(C){f.status="error",f.value=C}return f}(A.exports=r).prototype.finally=function(I){if(typeof I!="function")return this;var u=this.constructor;return this.then(function(f){return u.resolve(I()).then(function(){return f})},function(f){return u.resolve(I()).then(function(){throw f})})},r.prototype.catch=function(I){return this.then(null,I)},r.prototype.then=function(I,u){if(typeof I!="function"&&this.state===o||typeof u!="function"&&this.state===n)return this;var f=new this.constructor(i);return this.state!==a?c(f,this.state===o?I:u,this.outcome):this.queue.push(new l(f,I,u)),f},l.prototype.callFulfilled=function(I){s.resolve(this.promise,I)},l.prototype.otherCallFulfilled=function(I){c(this.promise,this.onFulfilled,I)},l.prototype.callRejected=function(I){s.reject(this.promise,I)},l.prototype.otherCallRejected=function(I){c(this.promise,this.onRejected,I)},s.resolve=function(I,u){var f=d(g,u);if(f.status==="error")return s.reject(I,f.value);var C=f.value;if(C)p(I,C);else{I.state=o,I.outcome=u;for(var m=-1,E=I.queue.length;++m<E;)I.queue[m].callFulfilled(u)}return I},s.reject=function(I,u){I.state=n,I.outcome=u;for(var f=-1,C=I.queue.length;++f<C;)I.queue[f].callRejected(u);return I},r.resolve=function(I){return I instanceof this?I:s.resolve(new this(i),I)},r.reject=function(I){var u=new this(i);return s.reject(u,I)},r.all=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=new Array(f),E=0,w=-1,y=new this(i);++w<f;)F(I[w],w);return y;function F(D,L){u.resolve(D).then(function(S){m[L]=S,++E!==f||C||(C=!0,s.resolve(y,m))},function(S){C||(C=!0,s.reject(y,S))})}},r.race=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=-1,E=new this(i);++m<f;)w=I[m],u.resolve(w).then(function(y){C||(C=!0,s.resolve(E,y))},function(y){C||(C=!0,s.reject(E,y))});var w;return E}},{immediate:36}],38:[function(h,A,t){"use strict";var e={};(0,h("./lib/utils/common").assign)(e,h("./lib/deflate"),h("./lib/inflate"),h("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(h,A,t){"use strict";var e=h("./zlib/deflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/messages"),o=h("./zlib/zstream"),a=Object.prototype.toString,r=0,l=-1,c=0,g=8;function p(I){if(!(this instanceof p))return new p(I);this.options=i.assign({level:l,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},I||{});var u=this.options;u.raw&&0<u.windowBits?u.windowBits=-u.windowBits:u.gzip&&0<u.windowBits&&u.windowBits<16&&(u.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var f=e.deflateInit2(this.strm,u.level,u.method,u.windowBits,u.memLevel,u.strategy);if(f!==r)throw new Error(n[f]);if(u.header&&e.deflateSetHeader(this.strm,u.header),u.dictionary){var C;if(C=typeof u.dictionary=="string"?s.string2buf(u.dictionary):a.call(u.dictionary)==="[object ArrayBuffer]"?new Uint8Array(u.dictionary):u.dictionary,(f=e.deflateSetDictionary(this.strm,C))!==r)throw new Error(n[f]);this._dict_set=!0}}function d(I,u){var f=new p(u);if(f.push(I,!0),f.err)throw f.msg||n[f.err];return f.result}p.prototype.push=function(I,u){var f,C,m=this.strm,E=this.options.chunkSize;if(this.ended)return!1;C=u===~~u?u:u===!0?4:0,typeof I=="string"?m.input=s.string2buf(I):a.call(I)==="[object ArrayBuffer]"?m.input=new Uint8Array(I):m.input=I,m.next_in=0,m.avail_in=m.input.length;do{if(m.avail_out===0&&(m.output=new i.Buf8(E),m.next_out=0,m.avail_out=E),(f=e.deflate(m,C))!==1&&f!==r)return this.onEnd(f),!(this.ended=!0);m.avail_out!==0&&(m.avail_in!==0||C!==4&&C!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(i.shrinkBuf(m.output,m.next_out))):this.onData(i.shrinkBuf(m.output,m.next_out)))}while((0<m.avail_in||m.avail_out===0)&&f!==1);return C===4?(f=e.deflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===r):C!==2||(this.onEnd(r),!(m.avail_out=0))},p.prototype.onData=function(I){this.chunks.push(I)},p.prototype.onEnd=function(I){I===r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=I,this.msg=this.strm.msg},t.Deflate=p,t.deflate=d,t.deflateRaw=function(I,u){return(u=u||{}).raw=!0,d(I,u)},t.gzip=function(I,u){return(u=u||{}).gzip=!0,d(I,u)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(h,A,t){"use strict";var e=h("./zlib/inflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/constants"),o=h("./zlib/messages"),a=h("./zlib/zstream"),r=h("./zlib/gzheader"),l=Object.prototype.toString;function c(p){if(!(this instanceof c))return new c(p);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},p||{});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)||p&&p.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 a,this.strm.avail_out=0;var I=e.inflateInit2(this.strm,d.windowBits);if(I!==n.Z_OK)throw new Error(o[I]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,d){var I=new c(d);if(I.push(p,!0),I.err)throw I.msg||o[I.err];return I.result}c.prototype.push=function(p,d){var I,u,f,C,m,E,w=this.strm,y=this.options.chunkSize,F=this.options.dictionary,D=!1;if(this.ended)return!1;u=d===~~d?d:d===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof p=="string"?w.input=s.binstring2buf(p):l.call(p)==="[object ArrayBuffer]"?w.input=new Uint8Array(p):w.input=p,w.next_in=0,w.avail_in=w.input.length;do{if(w.avail_out===0&&(w.output=new i.Buf8(y),w.next_out=0,w.avail_out=y),(I=e.inflate(w,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&F&&(E=typeof F=="string"?s.string2buf(F):l.call(F)==="[object ArrayBuffer]"?new Uint8Array(F):F,I=e.inflateSetDictionary(this.strm,E)),I===n.Z_BUF_ERROR&&D===!0&&(I=n.Z_OK,D=!1),I!==n.Z_STREAM_END&&I!==n.Z_OK)return this.onEnd(I),!(this.ended=!0);w.next_out&&(w.avail_out!==0&&I!==n.Z_STREAM_END&&(w.avail_in!==0||u!==n.Z_FINISH&&u!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(f=s.utf8border(w.output,w.next_out),C=w.next_out-f,m=s.buf2string(w.output,f),w.next_out=C,w.avail_out=y-C,C&&i.arraySet(w.output,w.output,f,C,0),this.onData(m)):this.onData(i.shrinkBuf(w.output,w.next_out)))),w.avail_in===0&&w.avail_out===0&&(D=!0)}while((0<w.avail_in||w.avail_out===0)&&I!==n.Z_STREAM_END);return I===n.Z_STREAM_END&&(u=n.Z_FINISH),u===n.Z_FINISH?(I=e.inflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===n.Z_OK):u!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(w.avail_out=0))},c.prototype.onData=function(p){this.chunks.push(p)},c.prototype.onEnd=function(p){p===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},t.Inflate=c,t.inflate=g,t.inflateRaw=function(p,d){return(d=d||{}).raw=!0,g(p,d)},t.ungzip=g},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var a=o.shift();if(a){if(typeof a!="object")throw new TypeError(a+"must be non-object");for(var r in a)a.hasOwnProperty(r)&&(n[r]=a[r])}}return n},t.shrinkBuf=function(n,o){return n.length===o?n:n.subarray?n.subarray(0,o):(n.length=o,n)};var i={arraySet:function(n,o,a,r,l){if(o.subarray&&n.subarray)n.set(o.subarray(a,a+r),l);else for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){var o,a,r,l,c,g;for(o=r=0,a=n.length;o<a;o++)r+=n[o].length;for(g=new Uint8Array(r),o=l=0,a=n.length;o<a;o++)c=n[o],g.set(c,l),l+=c.length;return g}},s={arraySet:function(n,o,a,r,l){for(var c=0;c<r;c++)n[l+c]=o[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,i)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,s))},t.setTyped(e)},{}],42:[function(h,A,t){"use strict";var e=h("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch{i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{s=!1}for(var n=new e.Buf8(256),o=0;o<256;o++)n[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;function a(r,l){if(l<65537&&(r.subarray&&s||!r.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(r,l));for(var c="",g=0;g<l;g++)c+=String.fromCharCode(r[g]);return c}n[254]=n[254]=1,t.string2buf=function(r){var l,c,g,p,d,I=r.length,u=0;for(p=0;p<I;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),u+=c<128?1:c<2048?2:c<65536?3:4;for(l=new e.Buf8(u),p=d=0;d<u;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),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(r){return a(r,r.length)},t.binstring2buf=function(r){for(var l=new e.Buf8(r.length),c=0,g=l.length;c<g;c++)l[c]=r.charCodeAt(c);return l},t.buf2string=function(r,l){var c,g,p,d,I=l||r.length,u=new Array(2*I);for(c=g=0;c<I;)if((p=r[c++])<128)u[g++]=p;else if(4<(d=n[p]))u[g++]=65533,c+=d-1;else{for(p&=d===2?31:d===3?15:7;1<d&&c<I;)p=p<<6|63&r[c++],d--;1<d?u[g++]=65533:p<65536?u[g++]=p:(p-=65536,u[g++]=55296|p>>10&1023,u[g++]=56320|1023&p)}return a(u,g)},t.utf8border=function(r,l){var c;for((l=l||r.length)>r.length&&(l=r.length),c=l-1;0<=c&&(192&r[c])==128;)c--;return c<0||c===0?l:c+n[r[c]]>l?c:l}},{"./common":41}],43:[function(h,A,t){"use strict";A.exports=function(e,i,s,n){for(var o=65535&e|0,a=e>>>16&65535|0,r=0;s!==0;){for(s-=r=2e3<s?2e3:s;a=a+(o=o+i[n++]|0)|0,--r;);o%=65521,a%=65521}return o|a<<16|0}},{}],44:[function(h,A,t){"use strict";A.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(h,A,t){"use strict";var e=function(){for(var i,s=[],n=0;n<256;n++){i=n;for(var o=0;o<8;o++)i=1&i?3988292384^i>>>1:i>>>1;s[n]=i}return s}();A.exports=function(i,s,n,o){var a=e,r=o+n;i^=-1;for(var l=o;l<r;l++)i=i>>>8^a[255&(i^s[l])];return-1^i}},{}],46:[function(h,A,t){"use strict";var e,i=h("../utils/common"),s=h("./trees"),n=h("./adler32"),o=h("./crc32"),a=h("./messages"),r=0,l=4,c=0,g=-2,p=-1,d=4,I=2,u=8,f=9,C=286,m=30,E=19,w=2*C+1,y=15,F=3,D=258,L=D+F+1,S=42,b=113,Q=1,H=2,$=3,M=4;function T(B,O){return B.msg=a[O],O}function J(B){return(B<<1)-(4<B?9:0)}function Z(B){for(var O=B.length;0<=--O;)B[O]=0}function G(B){var O=B.state,P=O.pending;P>B.avail_out&&(P=B.avail_out),P!==0&&(i.arraySet(B.output,O.pending_buf,O.pending_out,P,B.next_out),B.next_out+=P,O.pending_out+=P,B.total_out+=P,B.avail_out-=P,O.pending-=P,O.pending===0&&(O.pending_out=0))}function N(B,O){s._tr_flush_block(B,0<=B.block_start?B.block_start:-1,B.strstart-B.block_start,O),B.block_start=B.strstart,G(B.strm)}function _(B,O){B.pending_buf[B.pending++]=O}function K(B,O){B.pending_buf[B.pending++]=O>>>8&255,B.pending_buf[B.pending++]=255&O}function z(B,O){var P,k,v=B.max_chain_length,x=B.strstart,Y=B.prev_length,V=B.nice_match,R=B.strstart>B.w_size-L?B.strstart-(B.w_size-L):0,W=B.window,j=B.w_mask,X=B.prev,it=B.strstart+D,ut=W[x+Y-1],ct=W[x+Y];B.prev_length>=B.good_match&&(v>>=2),V>B.lookahead&&(V=B.lookahead);do if(W[(P=O)+Y]===ct&&W[P+Y-1]===ut&&W[P]===W[x]&&W[++P]===W[x+1]){x+=2,P++;do;while(W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&W[++x]===W[++P]&&x<it);if(k=D-(it-x),x=it-D,Y<k){if(B.match_start=O,V<=(Y=k))break;ut=W[x+Y-1],ct=W[x+Y]}}while((O=X[O&j])>R&&--v!=0);return Y<=B.lookahead?Y:B.lookahead}function ot(B){var O,P,k,v,x,Y,V,R,W,j,X=B.w_size;do{if(v=B.window_size-B.lookahead-B.strstart,B.strstart>=X+(X-L)){for(i.arraySet(B.window,B.window,X,X,0),B.match_start-=X,B.strstart-=X,B.block_start-=X,O=P=B.hash_size;k=B.head[--O],B.head[O]=X<=k?k-X:0,--P;);for(O=P=X;k=B.prev[--O],B.prev[O]=X<=k?k-X:0,--P;);v+=X}if(B.strm.avail_in===0)break;if(Y=B.strm,V=B.window,R=B.strstart+B.lookahead,W=v,j=void 0,j=Y.avail_in,W<j&&(j=W),P=j===0?0:(Y.avail_in-=j,i.arraySet(V,Y.input,Y.next_in,j,R),Y.state.wrap===1?Y.adler=n(Y.adler,V,j,R):Y.state.wrap===2&&(Y.adler=o(Y.adler,V,j,R)),Y.next_in+=j,Y.total_in+=j,j),B.lookahead+=P,B.lookahead+B.insert>=F)for(x=B.strstart-B.insert,B.ins_h=B.window[x],B.ins_h=(B.ins_h<<B.hash_shift^B.window[x+1])&B.hash_mask;B.insert&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[x+F-1])&B.hash_mask,B.prev[x&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=x,x++,B.insert--,!(B.lookahead+B.insert<F)););}while(B.lookahead<L&&B.strm.avail_in!==0)}function pt(B,O){for(var P,k;;){if(B.lookahead<L){if(ot(B),B.lookahead<L&&O===r)return Q;if(B.lookahead===0)break}if(P=0,B.lookahead>=F&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),P!==0&&B.strstart-P<=B.w_size-L&&(B.match_length=z(B,P)),B.match_length>=F)if(k=s._tr_tally(B,B.strstart-B.match_start,B.match_length-F),B.lookahead-=B.match_length,B.match_length<=B.max_lazy_match&&B.lookahead>=F){for(B.match_length--;B.strstart++,B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart,--B.match_length!=0;);B.strstart++}else B.strstart+=B.match_length,B.match_length=0,B.ins_h=B.window[B.strstart],B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+1])&B.hash_mask;else k=s._tr_tally(B,0,B.window[B.strstart]),B.lookahead--,B.strstart++;if(k&&(N(B,!1),B.strm.avail_out===0))return Q}return B.insert=B.strstart<F-1?B.strstart:F-1,O===l?(N(B,!0),B.strm.avail_out===0?$:M):B.last_lit&&(N(B,!1),B.strm.avail_out===0)?Q:H}function st(B,O){for(var P,k,v;;){if(B.lookahead<L){if(ot(B),B.lookahead<L&&O===r)return Q;if(B.lookahead===0)break}if(P=0,B.lookahead>=F&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),B.prev_length=B.match_length,B.prev_match=B.match_start,B.match_length=F-1,P!==0&&B.prev_length<B.max_lazy_match&&B.strstart-P<=B.w_size-L&&(B.match_length=z(B,P),B.match_length<=5&&(B.strategy===1||B.match_length===F&&4096<B.strstart-B.match_start)&&(B.match_length=F-1)),B.prev_length>=F&&B.match_length<=B.prev_length){for(v=B.strstart+B.lookahead-F,k=s._tr_tally(B,B.strstart-1-B.prev_match,B.prev_length-F),B.lookahead-=B.prev_length-1,B.prev_length-=2;++B.strstart<=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+F-1])&B.hash_mask,P=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),--B.prev_length!=0;);if(B.match_available=0,B.match_length=F-1,B.strstart++,k&&(N(B,!1),B.strm.avail_out===0))return Q}else if(B.match_available){if((k=s._tr_tally(B,0,B.window[B.strstart-1]))&&N(B,!1),B.strstart++,B.lookahead--,B.strm.avail_out===0)return Q}else B.match_available=1,B.strstart++,B.lookahead--}return B.match_available&&(k=s._tr_tally(B,0,B.window[B.strstart-1]),B.match_available=0),B.insert=B.strstart<F-1?B.strstart:F-1,O===l?(N(B,!0),B.strm.avail_out===0?$:M):B.last_lit&&(N(B,!1),B.strm.avail_out===0)?Q:H}function at(B,O,P,k,v){this.good_length=B,this.max_lazy=O,this.nice_length=P,this.max_chain=k,this.func=v}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=u,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 i.Buf16(2*w),this.dyn_dtree=new i.Buf16(2*(2*m+1)),this.bl_tree=new i.Buf16(2*(2*E+1)),Z(this.dyn_ltree),Z(this.dyn_dtree),Z(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(y+1),this.heap=new i.Buf16(2*C+1),Z(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*C+1),Z(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 nt(B){var O;return B&&B.state?(B.total_in=B.total_out=0,B.data_type=I,(O=B.state).pending=0,O.pending_out=0,O.wrap<0&&(O.wrap=-O.wrap),O.status=O.wrap?S:b,B.adler=O.wrap===2?0:1,O.last_flush=r,s._tr_init(O),c):T(B,g)}function Qt(B){var O=nt(B);return O===c&&function(P){P.window_size=2*P.w_size,Z(P.head),P.max_lazy_match=e[P.level].max_lazy,P.good_match=e[P.level].good_length,P.nice_match=e[P.level].nice_length,P.max_chain_length=e[P.level].max_chain,P.strstart=0,P.block_start=0,P.lookahead=0,P.insert=0,P.match_length=P.prev_length=F-1,P.match_available=0,P.ins_h=0}(B.state),O}function Ct(B,O,P,k,v,x){if(!B)return g;var Y=1;if(O===p&&(O=6),k<0?(Y=0,k=-k):15<k&&(Y=2,k-=16),v<1||f<v||P!==u||k<8||15<k||O<0||9<O||x<0||d<x)return T(B,g);k===8&&(k=9);var V=new At;return(B.state=V).strm=B,V.wrap=Y,V.gzhead=null,V.w_bits=k,V.w_size=1<<V.w_bits,V.w_mask=V.w_size-1,V.hash_bits=v+7,V.hash_size=1<<V.hash_bits,V.hash_mask=V.hash_size-1,V.hash_shift=~~((V.hash_bits+F-1)/F),V.window=new i.Buf8(2*V.w_size),V.head=new i.Buf16(V.hash_size),V.prev=new i.Buf16(V.w_size),V.lit_bufsize=1<<v+6,V.pending_buf_size=4*V.lit_bufsize,V.pending_buf=new i.Buf8(V.pending_buf_size),V.d_buf=1*V.lit_bufsize,V.l_buf=3*V.lit_bufsize,V.level=O,V.strategy=x,V.method=P,Qt(B)}e=[new at(0,0,0,0,function(B,O){var P=65535;for(P>B.pending_buf_size-5&&(P=B.pending_buf_size-5);;){if(B.lookahead<=1){if(ot(B),B.lookahead===0&&O===r)return Q;if(B.lookahead===0)break}B.strstart+=B.lookahead,B.lookahead=0;var k=B.block_start+P;if((B.strstart===0||B.strstart>=k)&&(B.lookahead=B.strstart-k,B.strstart=k,N(B,!1),B.strm.avail_out===0)||B.strstart-B.block_start>=B.w_size-L&&(N(B,!1),B.strm.avail_out===0))return Q}return B.insert=0,O===l?(N(B,!0),B.strm.avail_out===0?$:M):(B.strstart>B.block_start&&(N(B,!1),B.strm.avail_out),Q)}),new at(4,4,8,4,pt),new at(4,5,16,8,pt),new at(4,6,32,32,pt),new at(4,4,16,16,st),new at(8,16,32,32,st),new at(8,16,128,128,st),new at(8,32,128,256,st),new at(32,128,258,1024,st),new at(32,258,258,4096,st)],t.deflateInit=function(B,O){return Ct(B,O,u,15,8,0)},t.deflateInit2=Ct,t.deflateReset=Qt,t.deflateResetKeep=nt,t.deflateSetHeader=function(B,O){return B&&B.state?B.state.wrap!==2?g:(B.state.gzhead=O,c):g},t.deflate=function(B,O){var P,k,v,x;if(!B||!B.state||5<O||O<0)return B?T(B,g):g;if(k=B.state,!B.output||!B.input&&B.avail_in!==0||k.status===666&&O!==l)return T(B,B.avail_out===0?-5:g);if(k.strm=B,P=k.last_flush,k.last_flush=O,k.status===S)if(k.wrap===2)B.adler=0,_(k,31),_(k,139),_(k,8),k.gzhead?(_(k,(k.gzhead.text?1:0)+(k.gzhead.hcrc?2:0)+(k.gzhead.extra?4:0)+(k.gzhead.name?8:0)+(k.gzhead.comment?16:0)),_(k,255&k.gzhead.time),_(k,k.gzhead.time>>8&255),_(k,k.gzhead.time>>16&255),_(k,k.gzhead.time>>24&255),_(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),_(k,255&k.gzhead.os),k.gzhead.extra&&k.gzhead.extra.length&&(_(k,255&k.gzhead.extra.length),_(k,k.gzhead.extra.length>>8&255)),k.gzhead.hcrc&&(B.adler=o(B.adler,k.pending_buf,k.pending,0)),k.gzindex=0,k.status=69):(_(k,0),_(k,0),_(k,0),_(k,0),_(k,0),_(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),_(k,3),k.status=b);else{var Y=u+(k.w_bits-8<<4)<<8;Y|=(2<=k.strategy||k.level<2?0:k.level<6?1:k.level===6?2:3)<<6,k.strstart!==0&&(Y|=32),Y+=31-Y%31,k.status=b,K(k,Y),k.strstart!==0&&(K(k,B.adler>>>16),K(k,65535&B.adler)),B.adler=1}if(k.status===69)if(k.gzhead.extra){for(v=k.pending;k.gzindex<(65535&k.gzhead.extra.length)&&(k.pending!==k.pending_buf_size||(k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),G(B),v=k.pending,k.pending!==k.pending_buf_size));)_(k,255&k.gzhead.extra[k.gzindex]),k.gzindex++;k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),k.gzindex===k.gzhead.extra.length&&(k.gzindex=0,k.status=73)}else k.status=73;if(k.status===73)if(k.gzhead.name){v=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),G(B),v=k.pending,k.pending===k.pending_buf_size)){x=1;break}x=k.gzindex<k.gzhead.name.length?255&k.gzhead.name.charCodeAt(k.gzindex++):0,_(k,x)}while(x!==0);k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),x===0&&(k.gzindex=0,k.status=91)}else k.status=91;if(k.status===91)if(k.gzhead.comment){v=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),G(B),v=k.pending,k.pending===k.pending_buf_size)){x=1;break}x=k.gzindex<k.gzhead.comment.length?255&k.gzhead.comment.charCodeAt(k.gzindex++):0,_(k,x)}while(x!==0);k.gzhead.hcrc&&k.pending>v&&(B.adler=o(B.adler,k.pending_buf,k.pending-v,v)),x===0&&(k.status=103)}else k.status=103;if(k.status===103&&(k.gzhead.hcrc?(k.pending+2>k.pending_buf_size&&G(B),k.pending+2<=k.pending_buf_size&&(_(k,255&B.adler),_(k,B.adler>>8&255),B.adler=0,k.status=b)):k.status=b),k.pending!==0){if(G(B),B.avail_out===0)return k.last_flush=-1,c}else if(B.avail_in===0&&J(O)<=J(P)&&O!==l)return T(B,-5);if(k.status===666&&B.avail_in!==0)return T(B,-5);if(B.avail_in!==0||k.lookahead!==0||O!==r&&k.status!==666){var V=k.strategy===2?function(R,W){for(var j;;){if(R.lookahead===0&&(ot(R),R.lookahead===0)){if(W===r)return Q;break}if(R.match_length=0,j=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++,j&&(N(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,W===l?(N(R,!0),R.strm.avail_out===0?$:M):R.last_lit&&(N(R,!1),R.strm.avail_out===0)?Q:H}(k,O):k.strategy===3?function(R,W){for(var j,X,it,ut,ct=R.window;;){if(R.lookahead<=D){if(ot(R),R.lookahead<=D&&W===r)return Q;if(R.lookahead===0)break}if(R.match_length=0,R.lookahead>=F&&0<R.strstart&&(X=ct[it=R.strstart-1])===ct[++it]&&X===ct[++it]&&X===ct[++it]){ut=R.strstart+D;do;while(X===ct[++it]&&X===ct[++it]&&X===ct[++it]&&X===ct[++it]&&X===ct[++it]&&X===ct[++it]&&X===ct[++it]&&X===ct[++it]&&it<ut);R.match_length=D-(ut-it),R.match_length>R.lookahead&&(R.match_length=R.lookahead)}if(R.match_length>=F?(j=s._tr_tally(R,1,R.match_length-F),R.lookahead-=R.match_length,R.strstart+=R.match_length,R.match_length=0):(j=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++),j&&(N(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,W===l?(N(R,!0),R.strm.avail_out===0?$:M):R.last_lit&&(N(R,!1),R.strm.avail_out===0)?Q:H}(k,O):e[k.level].func(k,O);if(V!==$&&V!==M||(k.status=666),V===Q||V===$)return B.avail_out===0&&(k.last_flush=-1),c;if(V===H&&(O===1?s._tr_align(k):O!==5&&(s._tr_stored_block(k,0,0,!1),O===3&&(Z(k.head),k.lookahead===0&&(k.strstart=0,k.block_start=0,k.insert=0))),G(B),B.avail_out===0))return k.last_flush=-1,c}return O!==l?c:k.wrap<=0?1:(k.wrap===2?(_(k,255&B.adler),_(k,B.adler>>8&255),_(k,B.adler>>16&255),_(k,B.adler>>24&255),_(k,255&B.total_in),_(k,B.total_in>>8&255),_(k,B.total_in>>16&255),_(k,B.total_in>>24&255)):(K(k,B.adler>>>16),K(k,65535&B.adler)),G(B),0<k.wrap&&(k.wrap=-k.wrap),k.pending!==0?c:1)},t.deflateEnd=function(B){var O;return B&&B.state?(O=B.state.status)!==S&&O!==69&&O!==73&&O!==91&&O!==103&&O!==b&&O!==666?T(B,g):(B.state=null,O===b?T(B,-3):c):g},t.deflateSetDictionary=function(B,O){var P,k,v,x,Y,V,R,W,j=O.length;if(!B||!B.state||(x=(P=B.state).wrap)===2||x===1&&P.status!==S||P.lookahead)return g;for(x===1&&(B.adler=n(B.adler,O,j,0)),P.wrap=0,j>=P.w_size&&(x===0&&(Z(P.head),P.strstart=0,P.block_start=0,P.insert=0),W=new i.Buf8(P.w_size),i.arraySet(W,O,j-P.w_size,P.w_size,0),O=W,j=P.w_size),Y=B.avail_in,V=B.next_in,R=B.input,B.avail_in=j,B.next_in=0,B.input=O,ot(P);P.lookahead>=F;){for(k=P.strstart,v=P.lookahead-(F-1);P.ins_h=(P.ins_h<<P.hash_shift^P.window[k+F-1])&P.hash_mask,P.prev[k&P.w_mask]=P.head[P.ins_h],P.head[P.ins_h]=k,k++,--v;);P.strstart=k,P.lookahead=F-1,ot(P)}return P.strstart+=P.lookahead,P.block_start=P.strstart,P.insert=P.lookahead,P.lookahead=0,P.match_length=P.prev_length=F-1,P.match_available=0,B.next_in=V,B.input=R,B.avail_in=Y,P.wrap=x,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(h,A,t){"use strict";A.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(h,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,l,c,g,p,d,I,u,f,C,m,E,w,y,F,D,L,S,b,Q,H;s=e.state,n=e.next_in,Q=e.input,o=n+(e.avail_in-5),a=e.next_out,H=e.output,r=a-(i-e.avail_out),l=a+(e.avail_out-257),c=s.dmax,g=s.wsize,p=s.whave,d=s.wnext,I=s.window,u=s.hold,f=s.bits,C=s.lencode,m=s.distcode,E=(1<<s.lenbits)-1,w=(1<<s.distbits)-1;t:do{f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=C[u&E];e:for(;;){if(u>>>=F=y>>>24,f-=F,(F=y>>>16&255)===0)H[a++]=65535&y;else{if(!(16&F)){if(!(64&F)){y=C[(65535&y)+(u&(1<<F)-1)];continue e}if(32&F){s.mode=12;break t}e.msg="invalid literal/length code",s.mode=30;break t}D=65535&y,(F&=15)&&(f<F&&(u+=Q[n++]<<f,f+=8),D+=u&(1<<F)-1,u>>>=F,f-=F),f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=m[u&w];i:for(;;){if(u>>>=F=y>>>24,f-=F,!(16&(F=y>>>16&255))){if(!(64&F)){y=m[(65535&y)+(u&(1<<F)-1)];continue i}e.msg="invalid distance code",s.mode=30;break t}if(L=65535&y,f<(F&=15)&&(u+=Q[n++]<<f,(f+=8)<F&&(u+=Q[n++]<<f,f+=8)),c<(L+=u&(1<<F)-1)){e.msg="invalid distance too far back",s.mode=30;break t}if(u>>>=F,f-=F,(F=a-r)<L){if(p<(F=L-F)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break t}if(b=I,(S=0)===d){if(S+=g-F,F<D){for(D-=F;H[a++]=I[S++],--F;);S=a-L,b=H}}else if(d<F){if(S+=g+d-F,(F-=d)<D){for(D-=F;H[a++]=I[S++],--F;);if(S=0,d<D){for(D-=F=d;H[a++]=I[S++],--F;);S=a-L,b=H}}}else if(S+=d-F,F<D){for(D-=F;H[a++]=I[S++],--F;);S=a-L,b=H}for(;2<D;)H[a++]=b[S++],H[a++]=b[S++],H[a++]=b[S++],D-=3;D&&(H[a++]=b[S++],1<D&&(H[a++]=b[S++]))}else{for(S=a-L;H[a++]=H[S++],H[a++]=H[S++],H[a++]=H[S++],2<(D-=3););D&&(H[a++]=H[S++],1<D&&(H[a++]=H[S++]))}break}}break}}while(n<o&&a<l);n-=D=f>>3,u&=(1<<(f-=D<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<l?l-a+257:257-(a-l),s.hold=u,s.bits=f}},{}],49:[function(h,A,t){"use strict";var e=h("../utils/common"),i=h("./adler32"),s=h("./crc32"),n=h("./inffast"),o=h("./inftrees"),a=1,r=2,l=0,c=-2,g=1,p=852,d=592;function I(S){return(S>>>24&255)+(S>>>8&65280)+((65280&S)<<8)+((255&S)<<24)}function u(){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 f(S){var b;return S&&S.state?(b=S.state,S.total_in=S.total_out=b.total=0,S.msg="",b.wrap&&(S.adler=1&b.wrap),b.mode=g,b.last=0,b.havedict=0,b.dmax=32768,b.head=null,b.hold=0,b.bits=0,b.lencode=b.lendyn=new e.Buf32(p),b.distcode=b.distdyn=new e.Buf32(d),b.sane=1,b.back=-1,l):c}function C(S){var b;return S&&S.state?((b=S.state).wsize=0,b.whave=0,b.wnext=0,f(S)):c}function m(S,b){var Q,H;return S&&S.state?(H=S.state,b<0?(Q=0,b=-b):(Q=1+(b>>4),b<48&&(b&=15)),b&&(b<8||15<b)?c:(H.window!==null&&H.wbits!==b&&(H.window=null),H.wrap=Q,H.wbits=b,C(S))):c}function E(S,b){var Q,H;return S?(H=new u,(S.state=H).window=null,(Q=m(S,b))!==l&&(S.state=null),Q):c}var w,y,F=!0;function D(S){if(F){var b;for(w=new e.Buf32(512),y=new e.Buf32(32),b=0;b<144;)S.lens[b++]=8;for(;b<256;)S.lens[b++]=9;for(;b<280;)S.lens[b++]=7;for(;b<288;)S.lens[b++]=8;for(o(a,S.lens,0,288,w,0,S.work,{bits:9}),b=0;b<32;)S.lens[b++]=5;o(r,S.lens,0,32,y,0,S.work,{bits:5}),F=!1}S.lencode=w,S.lenbits=9,S.distcode=y,S.distbits=5}function L(S,b,Q,H){var $,M=S.state;return M.window===null&&(M.wsize=1<<M.wbits,M.wnext=0,M.whave=0,M.window=new e.Buf8(M.wsize)),H>=M.wsize?(e.arraySet(M.window,b,Q-M.wsize,M.wsize,0),M.wnext=0,M.whave=M.wsize):(H<($=M.wsize-M.wnext)&&($=H),e.arraySet(M.window,b,Q-H,$,M.wnext),(H-=$)?(e.arraySet(M.window,b,Q-H,H,0),M.wnext=H,M.whave=M.wsize):(M.wnext+=$,M.wnext===M.wsize&&(M.wnext=0),M.whave<M.wsize&&(M.whave+=$))),0}t.inflateReset=C,t.inflateReset2=m,t.inflateResetKeep=f,t.inflateInit=function(S){return E(S,15)},t.inflateInit2=E,t.inflate=function(S,b){var Q,H,$,M,T,J,Z,G,N,_,K,z,ot,pt,st,at,At,nt,Qt,Ct,B,O,P,k,v=0,x=new e.Buf8(4),Y=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!S||!S.state||!S.output||!S.input&&S.avail_in!==0)return c;(Q=S.state).mode===12&&(Q.mode=13),T=S.next_out,$=S.output,Z=S.avail_out,M=S.next_in,H=S.input,J=S.avail_in,G=Q.hold,N=Q.bits,_=J,K=Z,O=l;t:for(;;)switch(Q.mode){case g:if(Q.wrap===0){Q.mode=13;break}for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(2&Q.wrap&&G===35615){x[Q.check=0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0),N=G=0,Q.mode=2;break}if(Q.flags=0,Q.head&&(Q.head.done=!1),!(1&Q.wrap)||(((255&G)<<8)+(G>>8))%31){S.msg="incorrect header check",Q.mode=30;break}if((15&G)!=8){S.msg="unknown compression method",Q.mode=30;break}if(N-=4,B=8+(15&(G>>>=4)),Q.wbits===0)Q.wbits=B;else if(B>Q.wbits){S.msg="invalid window size",Q.mode=30;break}Q.dmax=1<<B,S.adler=Q.check=1,Q.mode=512&G?10:12,N=G=0;break;case 2:for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(Q.flags=G,(255&Q.flags)!=8){S.msg="unknown compression method",Q.mode=30;break}if(57344&Q.flags){S.msg="unknown header flags set",Q.mode=30;break}Q.head&&(Q.head.text=G>>8&1),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0)),N=G=0,Q.mode=3;case 3:for(;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.head&&(Q.head.time=G),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,x[2]=G>>>16&255,x[3]=G>>>24&255,Q.check=s(Q.check,x,4,0)),N=G=0,Q.mode=4;case 4:for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.head&&(Q.head.xflags=255&G,Q.head.os=G>>8),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0)),N=G=0,Q.mode=5;case 5:if(1024&Q.flags){for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.length=G,Q.head&&(Q.head.extra_len=G),512&Q.flags&&(x[0]=255&G,x[1]=G>>>8&255,Q.check=s(Q.check,x,2,0)),N=G=0}else Q.head&&(Q.head.extra=null);Q.mode=6;case 6:if(1024&Q.flags&&(J<(z=Q.length)&&(z=J),z&&(Q.head&&(B=Q.head.extra_len-Q.length,Q.head.extra||(Q.head.extra=new Array(Q.head.extra_len)),e.arraySet(Q.head.extra,H,M,z,B)),512&Q.flags&&(Q.check=s(Q.check,H,z,M)),J-=z,M+=z,Q.length-=z),Q.length))break t;Q.length=0,Q.mode=7;case 7:if(2048&Q.flags){if(J===0)break t;for(z=0;B=H[M+z++],Q.head&&B&&Q.length<65536&&(Q.head.name+=String.fromCharCode(B)),B&&z<J;);if(512&Q.flags&&(Q.check=s(Q.check,H,z,M)),J-=z,M+=z,B)break t}else Q.head&&(Q.head.name=null);Q.length=0,Q.mode=8;case 8:if(4096&Q.flags){if(J===0)break t;for(z=0;B=H[M+z++],Q.head&&B&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(B)),B&&z<J;);if(512&Q.flags&&(Q.check=s(Q.check,H,z,M)),J-=z,M+=z,B)break t}else Q.head&&(Q.head.comment=null);Q.mode=9;case 9:if(512&Q.flags){for(;N<16;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(G!==(65535&Q.check)){S.msg="header crc mismatch",Q.mode=30;break}N=G=0}Q.head&&(Q.head.hcrc=Q.flags>>9&1,Q.head.done=!0),S.adler=Q.check=0,Q.mode=12;break;case 10:for(;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}S.adler=Q.check=I(G),N=G=0,Q.mode=11;case 11:if(Q.havedict===0)return S.next_out=T,S.avail_out=Z,S.next_in=M,S.avail_in=J,Q.hold=G,Q.bits=N,2;S.adler=Q.check=1,Q.mode=12;case 12:if(b===5||b===6)break t;case 13:if(Q.last){G>>>=7&N,N-=7&N,Q.mode=27;break}for(;N<3;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}switch(Q.last=1&G,N-=1,3&(G>>>=1)){case 0:Q.mode=14;break;case 1:if(D(Q),Q.mode=20,b!==6)break;G>>>=2,N-=2;break t;case 2:Q.mode=17;break;case 3:S.msg="invalid block type",Q.mode=30}G>>>=2,N-=2;break;case 14:for(G>>>=7&N,N-=7&N;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if((65535&G)!=(G>>>16^65535)){S.msg="invalid stored block lengths",Q.mode=30;break}if(Q.length=65535&G,N=G=0,Q.mode=15,b===6)break t;case 15:Q.mode=16;case 16:if(z=Q.length){if(J<z&&(z=J),Z<z&&(z=Z),z===0)break t;e.arraySet($,H,M,z,T),J-=z,M+=z,Z-=z,T+=z,Q.length-=z;break}Q.mode=12;break;case 17:for(;N<14;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(Q.nlen=257+(31&G),G>>>=5,N-=5,Q.ndist=1+(31&G),G>>>=5,N-=5,Q.ncode=4+(15&G),G>>>=4,N-=4,286<Q.nlen||30<Q.ndist){S.msg="too many length or distance symbols",Q.mode=30;break}Q.have=0,Q.mode=18;case 18:for(;Q.have<Q.ncode;){for(;N<3;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.lens[Y[Q.have++]]=7&G,G>>>=3,N-=3}for(;Q.have<19;)Q.lens[Y[Q.have++]]=0;if(Q.lencode=Q.lendyn,Q.lenbits=7,P={bits:Q.lenbits},O=o(0,Q.lens,0,19,Q.lencode,0,Q.work,P),Q.lenbits=P.bits,O){S.msg="invalid code lengths set",Q.mode=30;break}Q.have=0,Q.mode=19;case 19:for(;Q.have<Q.nlen+Q.ndist;){for(;at=(v=Q.lencode[G&(1<<Q.lenbits)-1])>>>16&255,At=65535&v,!((st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(At<16)G>>>=st,N-=st,Q.lens[Q.have++]=At;else{if(At===16){for(k=st+2;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(G>>>=st,N-=st,Q.have===0){S.msg="invalid bit length repeat",Q.mode=30;break}B=Q.lens[Q.have-1],z=3+(3&G),G>>>=2,N-=2}else if(At===17){for(k=st+3;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}N-=st,B=0,z=3+(7&(G>>>=st)),G>>>=3,N-=3}else{for(k=st+7;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}N-=st,B=0,z=11+(127&(G>>>=st)),G>>>=7,N-=7}if(Q.have+z>Q.nlen+Q.ndist){S.msg="invalid bit length repeat",Q.mode=30;break}for(;z--;)Q.lens[Q.have++]=B}}if(Q.mode===30)break;if(Q.lens[256]===0){S.msg="invalid code -- missing end-of-block",Q.mode=30;break}if(Q.lenbits=9,P={bits:Q.lenbits},O=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,P),Q.lenbits=P.bits,O){S.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,P={bits:Q.distbits},O=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,P),Q.distbits=P.bits,O){S.msg="invalid distances set",Q.mode=30;break}if(Q.mode=20,b===6)break t;case 20:Q.mode=21;case 21:if(6<=J&&258<=Z){S.next_out=T,S.avail_out=Z,S.next_in=M,S.avail_in=J,Q.hold=G,Q.bits=N,n(S,K),T=S.next_out,$=S.output,Z=S.avail_out,M=S.next_in,H=S.input,J=S.avail_in,G=Q.hold,N=Q.bits,Q.mode===12&&(Q.back=-1);break}for(Q.back=0;at=(v=Q.lencode[G&(1<<Q.lenbits)-1])>>>16&255,At=65535&v,!((st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(at&&!(240&at)){for(nt=st,Qt=at,Ct=At;at=(v=Q.lencode[Ct+((G&(1<<nt+Qt)-1)>>nt)])>>>16&255,At=65535&v,!(nt+(st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}G>>>=nt,N-=nt,Q.back+=nt}if(G>>>=st,N-=st,Q.back+=st,Q.length=At,at===0){Q.mode=26;break}if(32&at){Q.back=-1,Q.mode=12;break}if(64&at){S.msg="invalid literal/length code",Q.mode=30;break}Q.extra=15&at,Q.mode=22;case 22:if(Q.extra){for(k=Q.extra;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.length+=G&(1<<Q.extra)-1,G>>>=Q.extra,N-=Q.extra,Q.back+=Q.extra}Q.was=Q.length,Q.mode=23;case 23:for(;at=(v=Q.distcode[G&(1<<Q.distbits)-1])>>>16&255,At=65535&v,!((st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(!(240&at)){for(nt=st,Qt=at,Ct=At;at=(v=Q.distcode[Ct+((G&(1<<nt+Qt)-1)>>nt)])>>>16&255,At=65535&v,!(nt+(st=v>>>24)<=N);){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}G>>>=nt,N-=nt,Q.back+=nt}if(G>>>=st,N-=st,Q.back+=st,64&at){S.msg="invalid distance code",Q.mode=30;break}Q.offset=At,Q.extra=15&at,Q.mode=24;case 24:if(Q.extra){for(k=Q.extra;N<k;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}Q.offset+=G&(1<<Q.extra)-1,G>>>=Q.extra,N-=Q.extra,Q.back+=Q.extra}if(Q.offset>Q.dmax){S.msg="invalid distance too far back",Q.mode=30;break}Q.mode=25;case 25:if(Z===0)break t;if(z=K-Z,Q.offset>z){if((z=Q.offset-z)>Q.whave&&Q.sane){S.msg="invalid distance too far back",Q.mode=30;break}ot=z>Q.wnext?(z-=Q.wnext,Q.wsize-z):Q.wnext-z,z>Q.length&&(z=Q.length),pt=Q.window}else pt=$,ot=T-Q.offset,z=Q.length;for(Z<z&&(z=Z),Z-=z,Q.length-=z;$[T++]=pt[ot++],--z;);Q.length===0&&(Q.mode=21);break;case 26:if(Z===0)break t;$[T++]=Q.length,Z--,Q.mode=21;break;case 27:if(Q.wrap){for(;N<32;){if(J===0)break t;J--,G|=H[M++]<<N,N+=8}if(K-=Z,S.total_out+=K,Q.total+=K,K&&(S.adler=Q.check=Q.flags?s(Q.check,$,K,T-K):i(Q.check,$,K,T-K)),K=Z,(Q.flags?G:I(G))!==Q.check){S.msg="incorrect data check",Q.mode=30;break}N=G=0}Q.mode=28;case 28:if(Q.wrap&&Q.flags){for(;N<32;){if(J===0)break t;J--,G+=H[M++]<<N,N+=8}if(G!==(4294967295&Q.total)){S.msg="incorrect length check",Q.mode=30;break}N=G=0}Q.mode=29;case 29:O=1;break t;case 30:O=-3;break t;case 31:return-4;case 32:default:return c}return S.next_out=T,S.avail_out=Z,S.next_in=M,S.avail_in=J,Q.hold=G,Q.bits=N,(Q.wsize||K!==S.avail_out&&Q.mode<30&&(Q.mode<27||b!==4))&&L(S,S.output,S.next_out,K-S.avail_out)?(Q.mode=31,-4):(_-=S.avail_in,K-=S.avail_out,S.total_in+=_,S.total_out+=K,Q.total+=K,Q.wrap&&K&&(S.adler=Q.check=Q.flags?s(Q.check,$,K,S.next_out-K):i(Q.check,$,K,S.next_out-K)),S.data_type=Q.bits+(Q.last?64:0)+(Q.mode===12?128:0)+(Q.mode===20||Q.mode===15?256:0),(_==0&&K===0||b===4)&&O===l&&(O=-5),O)},t.inflateEnd=function(S){if(!S||!S.state)return c;var b=S.state;return b.window&&(b.window=null),S.state=null,l},t.inflateGetHeader=function(S,b){var Q;return S&&S.state&&2&(Q=S.state).wrap?((Q.head=b).done=!1,l):c},t.inflateSetDictionary=function(S,b){var Q,H=b.length;return S&&S.state?(Q=S.state).wrap!==0&&Q.mode!==11?c:Q.mode===11&&i(1,b,H,0)!==Q.check?-3:L(S,b,H,H)?(Q.mode=31,-4):(Q.havedict=1,l):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(h,A,t){"use strict";var e=h("../utils/common"),i=[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],s=[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],o=[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];A.exports=function(a,r,l,c,g,p,d,I){var u,f,C,m,E,w,y,F,D,L=I.bits,S=0,b=0,Q=0,H=0,$=0,M=0,T=0,J=0,Z=0,G=0,N=null,_=0,K=new e.Buf16(16),z=new e.Buf16(16),ot=null,pt=0;for(S=0;S<=15;S++)K[S]=0;for(b=0;b<c;b++)K[r[l+b]]++;for($=L,H=15;1<=H&&K[H]===0;H--);if(H<$&&($=H),H===0)return g[p++]=20971520,g[p++]=20971520,I.bits=1,0;for(Q=1;Q<H&&K[Q]===0;Q++);for($<Q&&($=Q),S=J=1;S<=15;S++)if(J<<=1,(J-=K[S])<0)return-1;if(0<J&&(a===0||H!==1))return-1;for(z[1]=0,S=1;S<15;S++)z[S+1]=z[S]+K[S];for(b=0;b<c;b++)r[l+b]!==0&&(d[z[r[l+b]]++]=b);if(w=a===0?(N=ot=d,19):a===1?(N=i,_-=257,ot=s,pt-=257,256):(N=n,ot=o,-1),S=Q,E=p,T=b=G=0,C=-1,m=(Z=1<<(M=$))-1,a===1&&852<Z||a===2&&592<Z)return 1;for(;;){for(y=S-T,D=d[b]<w?(F=0,d[b]):d[b]>w?(F=ot[pt+d[b]],N[_+d[b]]):(F=96,0),u=1<<S-T,Q=f=1<<M;g[E+(G>>T)+(f-=u)]=y<<24|F<<16|D|0,f!==0;);for(u=1<<S-1;G&u;)u>>=1;if(u!==0?(G&=u-1,G+=u):G=0,b++,--K[S]==0){if(S===H)break;S=r[l+d[b]]}if($<S&&(G&m)!==C){for(T===0&&(T=$),E+=Q,J=1<<(M=S-T);M+T<H&&!((J-=K[M+T])<=0);)M++,J<<=1;if(Z+=1<<M,a===1&&852<Z||a===2&&592<Z)return 1;g[C=G&m]=$<<24|M<<16|E-p|0}}return G!==0&&(g[E+G]=S-T<<24|64<<16|0),I.bits=$,0}},{"../utils/common":41}],51:[function(h,A,t){"use strict";A.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(h,A,t){"use strict";var e=h("../utils/common"),i=0,s=1;function n(v){for(var x=v.length;0<=--x;)v[x]=0}var o=0,a=29,r=256,l=r+1+a,c=30,g=19,p=2*l+1,d=15,I=16,u=7,f=256,C=16,m=17,E=18,w=[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],y=[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],F=[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],L=new Array(2*(l+2));n(L);var S=new Array(2*c);n(S);var b=new Array(512);n(b);var Q=new Array(256);n(Q);var H=new Array(a);n(H);var $,M,T,J=new Array(c);function Z(v,x,Y,V,R){this.static_tree=v,this.extra_bits=x,this.extra_base=Y,this.elems=V,this.max_length=R,this.has_stree=v&&v.length}function G(v,x){this.dyn_tree=v,this.max_code=0,this.stat_desc=x}function N(v){return v<256?b[v]:b[256+(v>>>7)]}function _(v,x){v.pending_buf[v.pending++]=255&x,v.pending_buf[v.pending++]=x>>>8&255}function K(v,x,Y){v.bi_valid>I-Y?(v.bi_buf|=x<<v.bi_valid&65535,_(v,v.bi_buf),v.bi_buf=x>>I-v.bi_valid,v.bi_valid+=Y-I):(v.bi_buf|=x<<v.bi_valid&65535,v.bi_valid+=Y)}function z(v,x,Y){K(v,Y[2*x],Y[2*x+1])}function ot(v,x){for(var Y=0;Y|=1&v,v>>>=1,Y<<=1,0<--x;);return Y>>>1}function pt(v,x,Y){var V,R,W=new Array(d+1),j=0;for(V=1;V<=d;V++)W[V]=j=j+Y[V-1]<<1;for(R=0;R<=x;R++){var X=v[2*R+1];X!==0&&(v[2*R]=ot(W[X]++,X))}}function st(v){var x;for(x=0;x<l;x++)v.dyn_ltree[2*x]=0;for(x=0;x<c;x++)v.dyn_dtree[2*x]=0;for(x=0;x<g;x++)v.bl_tree[2*x]=0;v.dyn_ltree[2*f]=1,v.opt_len=v.static_len=0,v.last_lit=v.matches=0}function at(v){8<v.bi_valid?_(v,v.bi_buf):0<v.bi_valid&&(v.pending_buf[v.pending++]=v.bi_buf),v.bi_buf=0,v.bi_valid=0}function At(v,x,Y,V){var R=2*x,W=2*Y;return v[R]<v[W]||v[R]===v[W]&&V[x]<=V[Y]}function nt(v,x,Y){for(var V=v.heap[Y],R=Y<<1;R<=v.heap_len&&(R<v.heap_len&&At(x,v.heap[R+1],v.heap[R],v.depth)&&R++,!At(x,V,v.heap[R],v.depth));)v.heap[Y]=v.heap[R],Y=R,R<<=1;v.heap[Y]=V}function Qt(v,x,Y){var V,R,W,j,X=0;if(v.last_lit!==0)for(;V=v.pending_buf[v.d_buf+2*X]<<8|v.pending_buf[v.d_buf+2*X+1],R=v.pending_buf[v.l_buf+X],X++,V===0?z(v,R,x):(z(v,(W=Q[R])+r+1,x),(j=w[W])!==0&&K(v,R-=H[W],j),z(v,W=N(--V),Y),(j=y[W])!==0&&K(v,V-=J[W],j)),X<v.last_lit;);z(v,f,x)}function Ct(v,x){var Y,V,R,W=x.dyn_tree,j=x.stat_desc.static_tree,X=x.stat_desc.has_stree,it=x.stat_desc.elems,ut=-1;for(v.heap_len=0,v.heap_max=p,Y=0;Y<it;Y++)W[2*Y]!==0?(v.heap[++v.heap_len]=ut=Y,v.depth[Y]=0):W[2*Y+1]=0;for(;v.heap_len<2;)W[2*(R=v.heap[++v.heap_len]=ut<2?++ut:0)]=1,v.depth[R]=0,v.opt_len--,X&&(v.static_len-=j[2*R+1]);for(x.max_code=ut,Y=v.heap_len>>1;1<=Y;Y--)nt(v,W,Y);for(R=it;Y=v.heap[1],v.heap[1]=v.heap[v.heap_len--],nt(v,W,1),V=v.heap[1],v.heap[--v.heap_max]=Y,v.heap[--v.heap_max]=V,W[2*R]=W[2*Y]+W[2*V],v.depth[R]=(v.depth[Y]>=v.depth[V]?v.depth[Y]:v.depth[V])+1,W[2*Y+1]=W[2*V+1]=R,v.heap[1]=R++,nt(v,W,1),2<=v.heap_len;);v.heap[--v.heap_max]=v.heap[1],function(ct,xt){var He,Ut,Te,Et,ai,ns,Lt=xt.dyn_tree,Os=xt.max_code,Ao=xt.stat_desc.static_tree,lo=xt.stat_desc.has_stree,co=xt.stat_desc.extra_bits,Ks=xt.stat_desc.extra_base,Ue=xt.stat_desc.max_length,ri=0;for(Et=0;Et<=d;Et++)ct.bl_count[Et]=0;for(Lt[2*ct.heap[ct.heap_max]+1]=0,He=ct.heap_max+1;He<p;He++)Ue<(Et=Lt[2*Lt[2*(Ut=ct.heap[He])+1]+1]+1)&&(Et=Ue,ri++),Lt[2*Ut+1]=Et,Os<Ut||(ct.bl_count[Et]++,ai=0,Ks<=Ut&&(ai=co[Ut-Ks]),ns=Lt[2*Ut],ct.opt_len+=ns*(Et+ai),lo&&(ct.static_len+=ns*(Ao[2*Ut+1]+ai)));if(ri!==0){do{for(Et=Ue-1;ct.bl_count[Et]===0;)Et--;ct.bl_count[Et]--,ct.bl_count[Et+1]+=2,ct.bl_count[Ue]--,ri-=2}while(0<ri);for(Et=Ue;Et!==0;Et--)for(Ut=ct.bl_count[Et];Ut!==0;)Os<(Te=ct.heap[--He])||(Lt[2*Te+1]!==Et&&(ct.opt_len+=(Et-Lt[2*Te+1])*Lt[2*Te],Lt[2*Te+1]=Et),Ut--)}}(v,x),pt(W,ut,v.bl_count)}function B(v,x,Y){var V,R,W=-1,j=x[1],X=0,it=7,ut=4;for(j===0&&(it=138,ut=3),x[2*(Y+1)+1]=65535,V=0;V<=Y;V++)R=j,j=x[2*(V+1)+1],++X<it&&R===j||(X<ut?v.bl_tree[2*R]+=X:R!==0?(R!==W&&v.bl_tree[2*R]++,v.bl_tree[2*C]++):X<=10?v.bl_tree[2*m]++:v.bl_tree[2*E]++,W=R,ut=(X=0)===j?(it=138,3):R===j?(it=6,3):(it=7,4))}function O(v,x,Y){var V,R,W=-1,j=x[1],X=0,it=7,ut=4;for(j===0&&(it=138,ut=3),V=0;V<=Y;V++)if(R=j,j=x[2*(V+1)+1],!(++X<it&&R===j)){if(X<ut)for(;z(v,R,v.bl_tree),--X!=0;);else R!==0?(R!==W&&(z(v,R,v.bl_tree),X--),z(v,C,v.bl_tree),K(v,X-3,2)):X<=10?(z(v,m,v.bl_tree),K(v,X-3,3)):(z(v,E,v.bl_tree),K(v,X-11,7));W=R,ut=(X=0)===j?(it=138,3):R===j?(it=6,3):(it=7,4)}}n(J);var P=!1;function k(v,x,Y,V){K(v,(o<<1)+(V?1:0),3),function(R,W,j,X){at(R),X&&(_(R,j),_(R,~j)),e.arraySet(R.pending_buf,R.window,W,j,R.pending),R.pending+=j}(v,x,Y,!0)}t._tr_init=function(v){P||(function(){var x,Y,V,R,W,j=new Array(d+1);for(R=V=0;R<a-1;R++)for(H[R]=V,x=0;x<1<<w[R];x++)Q[V++]=R;for(Q[V-1]=R,R=W=0;R<16;R++)for(J[R]=W,x=0;x<1<<y[R];x++)b[W++]=R;for(W>>=7;R<c;R++)for(J[R]=W<<7,x=0;x<1<<y[R]-7;x++)b[256+W++]=R;for(Y=0;Y<=d;Y++)j[Y]=0;for(x=0;x<=143;)L[2*x+1]=8,x++,j[8]++;for(;x<=255;)L[2*x+1]=9,x++,j[9]++;for(;x<=279;)L[2*x+1]=7,x++,j[7]++;for(;x<=287;)L[2*x+1]=8,x++,j[8]++;for(pt(L,l+1,j),x=0;x<c;x++)S[2*x+1]=5,S[2*x]=ot(x,5);$=new Z(L,w,r+1,l,d),M=new Z(S,y,0,c,d),T=new Z(new Array(0),F,0,g,u)}(),P=!0),v.l_desc=new G(v.dyn_ltree,$),v.d_desc=new G(v.dyn_dtree,M),v.bl_desc=new G(v.bl_tree,T),v.bi_buf=0,v.bi_valid=0,st(v)},t._tr_stored_block=k,t._tr_flush_block=function(v,x,Y,V){var R,W,j=0;0<v.level?(v.strm.data_type===2&&(v.strm.data_type=function(X){var it,ut=4093624447;for(it=0;it<=31;it++,ut>>>=1)if(1&ut&&X.dyn_ltree[2*it]!==0)return i;if(X.dyn_ltree[18]!==0||X.dyn_ltree[20]!==0||X.dyn_ltree[26]!==0)return s;for(it=32;it<r;it++)if(X.dyn_ltree[2*it]!==0)return s;return i}(v)),Ct(v,v.l_desc),Ct(v,v.d_desc),j=function(X){var it;for(B(X,X.dyn_ltree,X.l_desc.max_code),B(X,X.dyn_dtree,X.d_desc.max_code),Ct(X,X.bl_desc),it=g-1;3<=it&&X.bl_tree[2*D[it]+1]===0;it--);return X.opt_len+=3*(it+1)+5+5+4,it}(v),R=v.opt_len+3+7>>>3,(W=v.static_len+3+7>>>3)<=R&&(R=W)):R=W=Y+5,Y+4<=R&&x!==-1?k(v,x,Y,V):v.strategy===4||W===R?(K(v,2+(V?1:0),3),Qt(v,L,S)):(K(v,4+(V?1:0),3),function(X,it,ut,ct){var xt;for(K(X,it-257,5),K(X,ut-1,5),K(X,ct-4,4),xt=0;xt<ct;xt++)K(X,X.bl_tree[2*D[xt]+1],3);O(X,X.dyn_ltree,it-1),O(X,X.dyn_dtree,ut-1)}(v,v.l_desc.max_code+1,v.d_desc.max_code+1,j+1),Qt(v,v.dyn_ltree,v.dyn_dtree)),st(v),V&&at(v)},t._tr_tally=function(v,x,Y){return v.pending_buf[v.d_buf+2*v.last_lit]=x>>>8&255,v.pending_buf[v.d_buf+2*v.last_lit+1]=255&x,v.pending_buf[v.l_buf+v.last_lit]=255&Y,v.last_lit++,x===0?v.dyn_ltree[2*Y]++:(v.matches++,x--,v.dyn_ltree[2*(Q[Y]+r+1)]++,v.dyn_dtree[2*N(x)]++),v.last_lit===v.lit_bufsize-1},t._tr_align=function(v){K(v,2,3),z(v,f,L),function(x){x.bi_valid===16?(_(x,x.bi_buf),x.bi_buf=0,x.bi_valid=0):8<=x.bi_valid&&(x.pending_buf[x.pending++]=255&x.bi_buf,x.bi_buf>>=8,x.bi_valid-=8)}(v)}},{"../utils/common":41}],53:[function(h,A,t){"use strict";A.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(h,A,t){(function(e){(function(i,s){"use strict";if(!i.setImmediate){var n,o,a,r,l=1,c={},g=!1,p=i.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(i);d=d&&d.setTimeout?d:i,n={}.toString.call(i.process)==="[object process]"?function(C){process.nextTick(function(){u(C)})}:function(){if(i.postMessage&&!i.importScripts){var C=!0,m=i.onmessage;return i.onmessage=function(){C=!1},i.postMessage("","*"),i.onmessage=m,C}}()?(r="setImmediate$"+Math.random()+"$",i.addEventListener?i.addEventListener("message",f,!1):i.attachEvent("onmessage",f),function(C){i.postMessage(r+C,"*")}):i.MessageChannel?((a=new MessageChannel).port1.onmessage=function(C){u(C.data)},function(C){a.port2.postMessage(C)}):p&&"onreadystatechange"in p.createElement("script")?(o=p.documentElement,function(C){var m=p.createElement("script");m.onreadystatechange=function(){u(C),m.onreadystatechange=null,o.removeChild(m),m=null},o.appendChild(m)}):function(C){setTimeout(u,0,C)},d.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var m=new Array(arguments.length-1),E=0;E<m.length;E++)m[E]=arguments[E+1];var w={callback:C,args:m};return c[l]=w,n(l),l++},d.clearImmediate=I}function I(C){delete c[C]}function u(C){if(g)setTimeout(u,0,C);else{var m=c[C];if(m){g=!0;try{(function(E){var w=E.callback,y=E.args;switch(y.length){case 0:w();break;case 1:w(y[0]);break;case 2:w(y[0],y[1]);break;case 3:w(y[0],y[1],y[2]);break;default:w.apply(s,y)}})(m)}finally{I(C),g=!1}}}}function f(C){C.source===i&&typeof C.data=="string"&&C.data.indexOf(r)===0&&u(+C.data.slice(r.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 ka={};li(ka,{default:()=>ss});module.exports=Bo(ka);var tt=require("obsidian");wt();var kt=require("obsidian");var mt=require("obsidian");wt();function di(h){let A=(h.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function Jt(h,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(h))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(h))}}function re(h,A){let t=di(A);switch(A.dateDisplayFormat??"locale"){case"iso":return $s(h,A,!0);case"us":return Jt(h,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Jt(h,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Jt(h,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Jt(h,{...t,dateStyle:"medium",timeStyle:"short"})}}function Xs(h,A){let t=di(A);switch(A.dateDisplayFormat??"locale"){case"iso":return $s(h,A,!1);case"us":return Jt(h,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Jt(h,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Jt(h,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(h).getFullYear()===e.getFullYear();return Jt(h,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Zs(h,A){let t=di(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return Jt(h,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function $s(h,A,t){let e=di(A),i=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(h)),s=o=>i.find(a=>a.type===o)?.value??"",n=`${s("year")}-${s("month")}-${s("day")}`;return t?`${n} ${s("hour")}:${s("minute")}`:n}function de(h,A,t){let e=h.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(A>99?"99+":String(A))}var Xe={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},ui=class extends mt.ItemView{constructor(t,e){super(t);this.plugin=e;this.activePanel="pinned";this.taskFilter="all";this.taskAssignFilter="all";this.taskFolderFilter="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 Vt}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()===dt&&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"}),i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(i.createSpan({cls:"stashpad-panels-global-btn-icon"}),"search"),i.createSpan({cls:"stashpad-panels-global-btn-text",text:"Search"}),i.onclick=()=>this.openSearchFromPanel();let s=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(s.createSpan({cls:"stashpad-panels-global-btn-icon"}),"folder-tree"),s.createSpan({cls:"stashpad-panels-global-btn-text",text:"Folder Switcher"}),s.onclick=()=>this.plugin.openFolderPicker();let n=e.createDiv({cls:"stashpad-panels-globals-row"}),o=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(o.createSpan({cls:"stashpad-panels-global-btn-icon"}),"scroll-text"),o.createSpan({cls:"stashpad-panels-global-btn-text",text:"Log"}),o.onclick=()=>this.openLogFromPanel();let a=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.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 r=t.createDiv({cls:"stashpad-panels-bar"});for(let c of Object.keys(Xe)){let g=Xe[c],p=r.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,mt.setIcon)(p.createSpan({cls:"stashpad-panels-bar-btn-icon"}),g.icon),p.createSpan({cls:"stashpad-panels-bar-btn-text",text:g.label}),this.activePanel===c&&p.addClass("is-active"),p.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)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new mt.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinnedPanel(t){let e=t.createDiv({cls:"stashpad-panel-pinned"});(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"&&e.addClass("is-flat");let i=e.createDiv({cls:"stashpad-pinned-headrow"}),s=i.createEl("button",{cls:"stashpad-pinned-row stashpad-pinned-home"}),n=s.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(n,"home"),s.createSpan({cls:"stashpad-pinned-label",text:"Home"}),s.onclick=()=>this.openHomeFromPanel();let o=i.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-pinned-opts"});(0,mt.setIcon)(o,"list"),o.setAttr("aria-label","Pinned view options"),o.onclick=p=>{p.stopPropagation(),this.openPinnedOptionsMenu(p)};let a=this.plugin.listPinnedNotes();if(a.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}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"){a.forEach((p,d)=>this.renderPinnedRow(e,p,d));return}let l=new Map;a.forEach((p,d)=>{let I=l.get(p.folder);I||(I=[],l.set(p.folder,I)),I.push({pin:p,idx:d})});let c=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,g=Array.from(l.keys());c&&l.has(c)&&(g.splice(g.indexOf(c),1),g.unshift(c));for(let p of g){let d=p.split("/").pop()||p,I=e.createDiv({cls:"stashpad-pinned-group-header"});p===c&&I.addClass("is-active-folder"),I.createSpan({cls:"stashpad-pinned-group-name",text:d});let u=l.get(p)??[];for(let{pin:f,idx:C}of u)this.renderPinnedRow(e,f,C)}}renderPinnedRow(t,e,i){let s=this.findFileFor(e);if(!s)return;let n=this.app.metadataCache.getFileCache(s)?.frontmatter??{},o=this.titleFromFile(s),a=typeof n.color=="string"?n.color:null,r=n.completed===!0,l=this.childrenOf(e.folder,e.id).length,c=l>0,g=this.expanded.has(`${e.folder}|${e.id}`),p=t.createDiv({cls:"stashpad-pinned-row"});a&&p.addClass("has-color"),r&&p.addClass("is-completed"),p.draggable=!0,p.dataset.pinIdx=String(i),p.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=p.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;p.toggleClass("drop-before",E),p.toggleClass("drop-after",!E)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",C=>{C.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let E=p.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?i:i+1)});let d=p.createSpan({cls:"stashpad-pinned-toggle"});c&&(de(d,l,g),d.onclick=C=>{C.stopPropagation();let m=`${e.folder}|${e.id}`;this.expanded.has(m)?this.expanded.delete(m):this.expanded.add(m),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(I,c?"folder-tree":"file-text"),a&&(I.style.color=a);let u=p.createSpan({cls:"stashpad-pinned-label",text:o});u.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(p.createSpan({cls:"stashpad-pinned-folder",text:f}),p.oncontextmenu=C=>{C.preventDefault();let m=new mt.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},c&&g){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(C,e.folder,e.id,1)}}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],l;!a&&!r?l=Date.now():a?r?l=(a.pinnedAt+r.pinnedAt)/2:l=a.pinnedAt+1e3:l=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=l})}catch(c){console.warn("[Stashpad] pin reorder failed",c)}this.render()}renderPinnedSubtree(t,e,i,s){let n=this.childrenOf(e,i);for(let o of n){let a=this.app.metadataCache.getFileCache(o)?.frontmatter??{},r=typeof a.id=="string"?a.id:null;if(!r)continue;let l=typeof a.color=="string"?a.color:null,c=a.completed===!0,g=this.childrenOf(e,r).length,p=g>0,d=this.expanded.has(`${e}|${r}`),I=t.createDiv({cls:"stashpad-pinned-subrow"});c&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});p&&(de(u,g,d),u.onclick=m=>{m.stopPropagation();let E=`${e}|${r}`;this.expanded.has(E)?this.expanded.delete(E):this.expanded.add(E),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(f,"file-text"),l&&(f.style.color=l);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:r}),p&&d&&this.renderPinnedSubtree(t,e,r,s+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 i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===U&&(a==null||a===U)){if(o.id===U)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.created??"",l=a?.created??"";return r.localeCompare(l)}),i}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 mt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Mt(),We));new s(this.app,i,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(U)}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()===dt)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(dt);return i.length>0?(this.app.workspace.revealLeaf(i[0]),i[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===dt?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let c of s){let g=c.authorId;g&&!n.has(g)&&n.set(g,c.authorDisplay||g)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(c,g,p)=>{let d=o.createEl("button",{cls:"stashpad-shared-chip",text:c});return g&&d.addClass("is-active"),d.onclick=p,d};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=o.createEl("select",{cls:"stashpad-shared-author-select"}),g=c.createEl("option",{text:"Any author"});g.value="__any__";for(let[d,I]of n){let u=c.createEl("option",{text:I});u.value=d}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=p,c.onchange=()=>{let d=c.value;d==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=d,this.render()}}let r=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&r.addClass("is-active"),r.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let l=s.filter(c=>{if(this.sharedContribOnly&&c.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return c.authorId===i;case"others":return c.authorId!==i;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 g=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),p=g.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(p,"users"),c.color&&(p.style.color=c.color);let d=g.createSpan({cls:"stashpad-pinned-label",text:c.title});d.onclick=()=>this.openSharedFromPanel(c.folder,c.id);let I=c.folder.split("/").pop()||c.folder;g.createSpan({cls:"stashpad-pinned-folder",text:I}),c.authorDisplay&&g.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===i?`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(),i=new Set(e),s=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};r.id===U&&s.set(a,this.extractAuthorId(r.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a)||a.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof r.id!="string"||r.id===U)continue;let l=this.extractAuthorId(r.author),c=Array.isArray(r.contributors)?r.contributors.filter(m=>typeof m=="string"):[],g=s.get(a)??null;if(!(c.length>0||g===t&&(l!==null&&l!==t)))continue;let f=this.titleFromFile(o),C=typeof r.color=="string"?r.color:null;n.push({file:o,folder:a,id:r.id,title:f,color:C,authorId:l,authorDisplay:this.extractAuthorDisplay(r.author)||(l??""),contributorCount:c.length})}return n.sort((o,a)=>{let r=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},l=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},c=r.modified??r.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 i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.activateViewForFolder(t);let i=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();i&&typeof i.navigateTo=="function"&&i.navigateTo(e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),i=this.collectTasks();if(i.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 s=(this.plugin.settings.authorId??"").trim(),n=M=>!!s&&M.assignedTo.some(T=>T.id===s),o=M=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let J=T.slice(7);return M.assignedTo.some(Z=>Z.id===J)}switch(T){case"mine":return n(M);case"others":return M.assignedTo.length>0&&!n(M);case"byme":return!!s&&M.assignedBy?.id===s;case"unassigned":return M.assignedTo.length===0;default:return!0}},a=new Map;for(let M of i){for(let T of M.assignedTo)T.id!==s&&a.set(T.id,T.name);M.assignedBy&&M.assignedBy.id!==s&&a.set(M.assignedBy.id,M.assignedBy.name)}let r=[...a.entries()].map(([M,T])=>({id:M,name:T})).sort((M,T)=>M.name.localeCompare(T.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"}),g=M=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return M.startsWith("person:")?a.get(M.slice(7))??"Person":T[M]??M},p=M=>{let T=c.createEl("option",{text:g(M),value:M});this.taskAssignFilter===M&&(T.selected=!0)};for(let M of["all","mine","others","byme","unassigned"])p(M);if(r.length>0){let M=c.createEl("optgroup");M.setAttr("label","By person");for(let T of r){let J=M.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(J.selected=!0)}}c.onchange=()=>{this.taskAssignFilter=c.value,this.render()};let d=[...new Set(i.map(M=>M.folder))].sort((M,T)=>M.localeCompare(T));this.taskFolderFilter!=="all"&&!d.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let I=e.createDiv({cls:"stashpad-task-assign-bar"});I.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let u=I.createEl("select",{cls:"stashpad-task-assign-select"}),f=u.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let M of d){let T=u.createEl("option",{text:M.split("/").pop()||M,value:M});this.taskFolderFilter===M&&(T.selected=!0)}u.onchange=()=>{this.taskFolderFilter=u.value,this.render()};let C=M=>this.taskFolderFilter==="all"||M.folder===this.taskFolderFilter,m=i.filter(M=>o(M)&&C(M));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let E=new Date;E.setHours(0,0,0,0);let w=E.getTime(),y=w+24*60*60*1e3,F={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let M of m){if(M.completed){F.completed.push(M);continue}if(M.due==null){F.nodate.push(M);continue}M.due<w?F.overdue.push(M):M.due<y?F.today.push(M):F.upcoming.push(M)}let D=(M,T)=>M.due==null&&T.due==null?M.title.localeCompare(T.title):M.due==null?1:T.due==null?-1:M.due-T.due,L=[{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"}],S=e.createDiv({cls:"stashpad-task-filters"}),b=m.length,Q=(M,T,J)=>{let Z=S.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===M&&Z.addClass("is-active"),Z.createSpan({cls:"stashpad-task-filter-label",text:T}),Z.createSpan({cls:"stashpad-task-filter-count",text:String(J)}),Z.onclick=()=>{this.taskFilter=M,this.render()}};Q("all","All",b),Q("overdue","Overdue",F.overdue.length),Q("today","Today",F.today.length),Q("upcoming","Upcoming",F.upcoming.length),Q("nodate","No date",F.nodate.length),Q("completed","Done",F.completed.length);let H=this.taskFilter==="all"?L:L.filter(M=>M.key===this.taskFilter),$=!1;for(let M of H){let T=F[M.key];if(T.length!==0){if($=!0,T.sort(M.key==="completed"?(J,Z)=>D(Z,J):D),this.taskFilter==="all"){let J=e.createDiv({cls:`stashpad-task-section-header is-${M.key}`});(0,mt.setIcon)(J.createSpan({cls:"stashpad-task-section-icon"}),M.icon),J.createSpan({cls:"stashpad-task-section-name",text:M.label}),J.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let J of T)this.renderTaskRow(e,J,M.key==="today")}}if(!$&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${H[0]?.label??this.taskFilter}".`);return}$||e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks to show.")}renderTaskRow(t,e,i){let s=t.createDiv({cls:"stashpad-pinned-row stashpad-task-row"});e.color&&s.addClass("has-color"),e.completed&&s.addClass("is-completed");let n=s.createSpan({cls:"stashpad-pinned-icon stashpad-task-checkbox"});(0,mt.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 o=s.createSpan({cls:"stashpad-pinned-label",text:e.title});if(o.onclick=()=>this.openTaskFromPanel(e.folder,e.id),s.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let a=s.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,i)});e.due<Date.now()&&!e.completed&&a.addClass("is-overdue")}else e.dueRaw&&s.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let a=(this.plugin.settings.authorId??"").trim(),r=s.createSpan({cls:"stashpad-task-assignees"});for(let l of e.assignedTo){let c=r.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}}s.oncontextmenu=a=>{a.preventDefault();let r=new mt.Menu;r.addItem(l=>l.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),r.showAtMouseEvent(a)}}formatDueShort(t,e){return e?Zs(t,this.plugin.settings):Xs(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.activateViewForFolder(t);let i=this.plugin.lastActiveStashpadLeaf?.view??this.findActiveStashpad();i&&typeof i.navigateTo=="function"&&i.navigateTo(e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new mt.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),i=[];for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a||a===U)continue;let r=o.completed===!0,l=Ie(o,"task")||o.task===!0||o.completed!==void 0,c=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,g=null;if(c){let p=Date.parse(c);Number.isNaN(p)||(g=p)}!l&&!r&&g==null&&!c||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:l,completed:r,due:g,dueRaw:c,color:typeof o.color=="string"?o.color:null,assignedTo:Re(o),assignedBy:Xt(o.assignedBy)})}return i}};async function fi(h){let A=h.workspace.getLeavesOfType(Vt);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new mt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:Vt,active:!0}),h.workspace.revealLeaf(t)}var un=require("obsidian");wt();var et=require("obsidian");$e();var Qi=require("obsidian");wt();var Ee=class extends Qi.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),i=o=>e.every(a=>o.toLowerCase().includes(a)),s=[],n=o=>{if(!(o.path!=="/"&&Ge.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof Qi.TFolder&&n(a)}};return n(this.app.vault.getRoot()),s.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()}};wt();Mt();var he=require("obsidian"),ps={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."}},So={info:4e3,success:4e3,warning:6e3,error:1e4},cn=5e3,Ei=class{constructor(A){this.app=A;this.history=[];this.nextId=1;this.historyLimit=cn;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(A){this.defaultAuthorId=A||null}show(A){let t=A.kind??"info",e=A.category??"system",i={id:this.nextId++,ts:Date.now(),message:A.message,kind:t,category:e,authorId:A.authorId??this.defaultAuthorId??void 0,affectedIds:A.affectedIds?A.affectedIds.slice():[],affectedPaths:A.affectedPaths?A.affectedPaths.slice():[],affectedAuthorIds:A.affectedAuthorIds?A.affectedAuthorIds.slice():[],folder:A.folder,actionLabels:(A.actions??[]).map(o=>o.label)};if(this.pushHistory(i),this.muted.has(e))return null;let s=this.buildContent(A,t),n=A.duration??So[t];return new he.Notice(s,n)}onChange(A){return this.changeListeners.add(A),()=>this.changeListeners.delete(A)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(A,t){t?this.muted.add(A):this.muted.delete(A)}isMuted(A){return this.muted.has(A)}loadMutedFromList(A){this.muted=new Set(A)}mutedList(){return Array.from(this.muted)}loadHistory(A){let t=this.applyLimit(A.slice());this.history=t;let e=0;for(let i of t)i.id>e&&(e=i.id);this.nextId=Math.max(this.nextId,e+1),this.emit()}setHistoryLimit(A){this.historyLimit=Number.isFinite(A)?A:cn,this.history=this.applyLimit(this.history),this.emit()}applyLimit(A){return this.historyLimit<=0||A.length<=this.historyLimit?A:A.slice(A.length-this.historyLimit)}pushHistory(A){this.history.push(A),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let A of this.changeListeners)try{A()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(A,t){let e=document.createDocumentFragment(),i=document.createElement("div");i.className=`stashpad-notice stashpad-notice-${t}`;let s=document.createElement("div");s.className="stashpad-notice-message";let n=A.message.split(/(`[^`\n]+`)/);for(let o of n)if(o.length>1&&o.startsWith("`")&&o.endsWith("`")){let a=document.createElement("code");a.textContent=o.slice(1,-1),s.appendChild(a)}else o.length>0&&s.appendChild(document.createTextNode(o));if(i.appendChild(s),A.actions&&A.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of A.actions){let r=document.createElement("button");r.className="stashpad-notice-action",r.textContent=a.label,r.addEventListener("click",l=>{if(l.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(c=>console.warn("[Stashpad] notification action failed",c)),!a.keepOpen){let c=r.closest(".notice");c&&c.parentElement&&c.parentElement.removeChild(c)}}),o.appendChild(r)}i.appendChild(o)}return e.appendChild(i),e}};function yi(h,A,t){let e=h.vault.getAbstractFileByPath(A);if(!(e instanceof he.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=h.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;h.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=he.Platform.isMacOS?"Finder":he.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=h.vault.adapter?.getFullPath?.(A);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var Is=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function _e(h){if(!h)return"(none)";let A=h.replace(/\bMod\b/g,Is?"Cmd":"Ctrl");return Is&&(A=A.replace(/\bAlt\b/g,"Option")),A}function dn(h,A,t={allowSingleKey:!0}){let e=h.placeholder,i=h.value;h.placeholder="Press a key\u2026 (Backspace to cancel)",h.value="",h.classList.add("is-recording");let s=!1,n=()=>{h.placeholder=e,h.classList.remove("is-recording"),s||(h.value=i),h.removeEventListener("keydown",o,!0),h.removeEventListener("blur",a)},o=r=>{if(r.key==="Control"||r.key==="Shift"||r.key==="Alt"||r.key==="Meta"||r.key==="OS")return;let l=!!r.code&&(/^Key[A-Z]$/.test(r.code)||/^Digit\d$/.test(r.code));if((r.key==="Dead"||r.key==="Process"||r.key==="Unidentified")&&!l)return;if(r.preventDefault(),r.stopPropagation(),r.key==="Backspace"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.shiftKey){n();return}let c=[];Is?(r.metaKey&&c.push("Mod"),r.ctrlKey&&c.push("Ctrl")):r.ctrlKey&&c.push("Mod"),r.altKey&&c.push("Alt"),r.shiftKey&&c.push("Shift");let g=Do(r.key,r.code);if(!g||c.length===0&&!t.allowSingleKey)return;c.push(g);let p=c.join("+");s=!0,n(),A(p)},a=()=>n();return h.addEventListener("keydown",o,!0),h.addEventListener("blur",a),n}function Do(h,A){if(!h)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return h.length===1?h.toUpperCase():h}me();Rt();var je=null,wi=new Set;function Fi(h){if(je!==h){je=h;for(let A of wi)A()}}function qt(){return je}function hn(h){if(je===h){je=null;for(let A of wi)A()}}function gn(h){return wi.add(h),()=>wi.delete(h)}function bo(){return et.Platform.isMacOS?"Finder":et.Platform.isWin?"File Explorer":"file manager"}var ye=[{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 or X \u2014 marks selected/focused notes as complete (both chords active).",defaultPrimary:"Mod+Enter",defaultSecondary:"X",defaultUseBoth:!0},{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+: or ; \u2014 open the color picker for the selection (both chords active).",defaultPrimary:"Shift+:",defaultSecondary:";",defaultUseBoth:!0},{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"},{id:"commandPalette",label:"Command palette (Stashpad only)",desc:"Default: Mod+K \u2014 open a command palette listing only Stashpad's commands, with Sift search.",defaultPrimary:"Mod+K"}];function Cs(){let h={};for(let A of ye)h[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return h}var Zt={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,searchOpensInNewTab:!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:Cs()},pn=JSON.parse(JSON.stringify(Zt)),fs=new Set;function ft(){return pn}function Bs(h){pn=h;for(let A of fs)A()}function In(h){return fs.add(h),()=>fs.delete(h)}function Si(h){try{let A=h.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var vi=[{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"}],us=null;function No(h,A){return us||(us=class extends et.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new us(h,A)}var ki=class extends et.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if(et.SettingPage){super.display();return}let{containerEl:t}=this;t.empty();for(let e of vi){t.createEl("h2",{text:e.label});let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new et.Setting(t);typeof s.render=="function"?s.render(n):(s.name&&n.setName(s.name),s.desc&&n.setDesc(s.desc))}else this.renderTabContent(t,e.id)}}getSettingDefinitions(){return vi.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>No(t.label,i=>this.renderTabContent(i,t.id))}})}itemsForTab(t){switch(t){case"hotkeys":return this.hotkeyItems();case"diagnostics":return this.diagnosticsItems();case"general":return this.generalItems();default:return null}}renderTabContent(t,e){switch(e){case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break}}diagnosticsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(ps);return[this.renderDef("Write recovery navigation links","Maintain the redundant parentLink/children frontmatter so you can walk the hierarchy from raw Markdown if the index ever breaks. On a slow / network drive this is a big per-move cost (several round-trips each); turn it off there for snappier moves \u2014 Rebootstrap rebuilds the fields on demand, and your notes' canonical structure (id/parent) is unaffected either way.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async n=>{this.plugin.settings.writeRecoveryLinks=n,await this.plugin.saveSettings()})),["recovery","parentlink","children","frontmatter"]),this.renderDef("Performance profiling","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.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.enablePerfProfiling).onChange(async n=>{this.plugin.settings.enablePerfProfiling=n,await this.plugin.saveSettings()})),["perf","profiling","timing","slow"]),this.renderDef("Open log file","Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.",i=>i.addButton(s=>s.setButtonText("Open log").onClick(async()=>{let n=this.app.vault.adapter,o=this.plugin.pluginPrivatePath("log.jsonl");if(!await n.exists(o)){new et.Notice("No log yet \u2014 make some changes first.");return}let a=await n.read(o);new fe(this.app,a,o).open()})),["log","history","diagnostics"]),this.renderDef("Notification history limit","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.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.notificationHistoryLimit??5e3)).setPlaceholder("5000").onChange(async n=>{let o=parseInt(n,10);Number.isFinite(o)&&(this.plugin.settings.notificationHistoryLimit=o,this.plugin.notifications.setHistoryLimit(o),await this.plugin.saveSettings())})),["notification","history","limit"]),{type:"group",heading:"Mute notification categories",items:e.map(i=>{let s=ps[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async a=>{let r=!a;r?t.add(i):t.delete(i),this.plugin.settings.mutedNotificationCategories=Array.from(t),this.plugin.notifications.setMuted(i,r),await this.plugin.saveSettings()})),["notification","mute","toast","category"])})},this.renderDef("Notification history","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.",i=>i.addButton(s=>s.setButtonText("View notification history").onClick(()=>{new ze(this.app,this.plugin.notifications,async n=>{let o=this.app.vault.adapter,a=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(a)){new et.Notice("No log yet \u2014 make some changes first.");return}let r=await o.read(a);new fe(this.app,r,a).open()},this.plugin.settings.authorId||null,n=>this.plugin.lookupNoteAuthorIds(n)).open()})),["notification","history","panel"])]}renderTemplatesTab(t){this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t)}renderDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{n.setName(t).setDesc(e),i(n)}}}sectionDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{let o=n.settingEl;o.empty(),o.removeClass("setting-item"),o.addClass("stashpad-settings-section"),i(o)}}}generalItems(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,r)=>this.renderDef(s,n,l=>l.addToggle(c=>c.setValue(o()).onChange(async g=>{a(g),await t()})),r),i=[];i.push(this.renderDef("Stashpad notes folder","Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.",s=>{s.addText(n=>{new Ee(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||Zt.folder,r=a.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(c=>(c??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(r)){new et.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.push(e("Auto-import dropped files","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.",()=>this.plugin.settings.autoImport,s=>{this.plugin.settings.autoImport=s},["import","drop","auto"])),i.push(e("Inherit Obsidian's excluded files","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.",()=>this.plugin.settings.inheritObsidianExclusions,s=>{this.plugin.settings.inheritObsidianExclusions=s},["excluded","ignore","files"])),i.push(this.renderDef("Dedicated import subfolder (optional)","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.",s=>s.addText(n=>n.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async o=>{this.plugin.settings.importDropFolder=(o||"").trim().replace(/^\/+|\/+$/g,""),await t()})),["import","subfolder"])),i.push(this.renderDef("Stash export subfolder","Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.",s=>s.addText(n=>n.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async o=>{this.plugin.settings.exportFolder=(o||"").trim().replace(/^\/+|\/+$/g,"")||Zt.exportFolder,await t()})),["export","stash","subfolder"])),i.push(this.renderDef("Rebootstrap existing Stashpad folders","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.",s=>s.addButton(n=>n.setButtonText("Rebootstrap now").onClick(async()=>{n.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:o,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:c,imported:g,attachmentsLinked:p}=await this.plugin.rebootstrapAllFolders(),d=[];d.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),g>0&&d.push(`imported ${g} loose file${g===1?"":"s"}`),p>0&&d.push(`linked attachments on ${p} note${p===1?"":"s"}`),r>0?d.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&d.push(`frontmatter already in sync (${a} notes checked)`),l>0&&d.push(`renamed ${l} note${l===1?"":"s"} to match body`),c>0&&d.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new et.Notice(`Stashpad: ${d.join("; ")}.`)}catch(o){new et.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.push(this.renderDef("Use Templates plugin date/time formats","When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.",s=>{s.addToggle(o=>o.setValue(this.plugin.settings.useTemplatesFormat).onChange(async a=>{this.plugin.settings.useTemplatesFormat=a,await t()}));let n=Si(this.app);s.descEl.createDiv({cls:"stashpad-settings-note"}).setText(n?`Templates plugin: date = "${n.dateFormat}", time = "${n.timeFormat}"`:"Templates plugin not enabled.")},["templates","date","time","format"]));{let s=null,n=()=>{s&&s.setText(`Sample: ${re(Date.now(),this.plugin.settings)}`)};i.push(this.renderDef("Date display format","How due dates and created/modified times are shown in the Tasks and detail panels.",o=>{o.addDropdown(a=>{a.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),a.addOption("long","Locale, long (Thursday, March 5\u2026)"),a.addOption("iso","ISO (2026-03-05 09:00)"),a.addOption("us","US (3/5/2026, 9:00 AM)"),a.addOption("eu","EU (5/3/2026, 09:00)"),a.setValue(this.plugin.settings.dateDisplayFormat??"locale"),a.onChange(async r=>{this.plugin.settings.dateDisplayFormat=r,await t(),n()})})},["date","format","display"])),i.push(this.renderDef("Display timezone","IANA timezone name (e.g. America/New_York, Europe/London, Asia/Kolkata). Leave blank to use your system timezone.",o=>{o.addText(a=>{a.setPlaceholder("(system timezone)"),a.setValue(this.plugin.settings.dateDisplayTimezone??""),a.onChange(async r=>{this.plugin.settings.dateDisplayTimezone=(r||"").trim(),await t(),n()})})},["timezone","tz","date","iana"])),i.push({name:"Date sample",searchable:!1,render:o=>{let a=o.settingEl;a.empty(),a.removeClass("setting-item"),s=a.createDiv({cls:"setting-item-description stashpad-settings-note"}),n()}})}return i.push(e("Navigate into parent after moving a note IN","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.",()=>this.plugin.settings.autoNavOnMoveIn,s=>{this.plugin.settings.autoNavOnMoveIn=s},["navigate","move","in"])),i.push(e("Navigate to destination after moving a note OUT","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.",()=>this.plugin.settings.autoNavOnMoveOut,s=>{this.plugin.settings.autoNavOnMoveOut=s},["navigate","move","out"])),i.push(e("Double-click a note to open it","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.",()=>this.plugin.settings.doubleClickToFocus,s=>{this.plugin.settings.doubleClickToFocus=s},["double","click","open","focus"])),i.push(e("Auto-open the detail panel","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.",()=>this.plugin.settings.autoOpenDetailPanel,s=>{this.plugin.settings.autoOpenDetailPanel=s},["detail","panel","sidebar"])),i.push(e("Expand the cursor row's body automatically","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.",()=>this.plugin.settings.autoExpandCursorRow,s=>{this.plugin.settings.autoExpandCursorRow=s},["expand","cursor","body"])),i.push(e("Confirm cross-parent drag-and-drop","When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).",()=>this.plugin.settings.confirmCrossParentDrag,s=>{this.plugin.settings.confirmCrossParentDrag=s},["confirm","drag","drop","reparent"])),i.push(e("Confirm bulk deletes","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).",()=>this.plugin.settings.confirmBulkDelete,s=>{this.plugin.settings.confirmBulkDelete=s},["confirm","delete","bulk"])),i.push(e("Offer to delete attachments with note",`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.`,()=>this.plugin.settings.confirmAttachmentDelete,s=>{this.plugin.settings.confirmAttachmentDelete=s},["delete","attachment","orphan"])),i.push(this.renderDef("Slug stop-words","Words removed from auto-generated note titles (filenames). One per line.",s=>{let n=null,o=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:Pt).join(` +`);s.addTextArea(a=>{a.setValue(o),n=a.inputEl,n.rows=6,n.style.fontFamily="var(--font-monospace)",a.onChange(async r=>{this.plugin.settings.slugStopWords=(r||"").split(/\r?\n/).map(l=>l.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(a=>a.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Pt],n&&(n.value=Pt.join(` +`)),await t()}))},["slug","stopwords","filename","title"])),i.push(this.sectionDef("Cross-Stashpad search scope","Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations. Also: create a new Stashpad.",s=>{let n=this.plugin.discoverStashpadFolders();if(new et.Setting(s).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."),n.length===0)s.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 a=s.createDiv({cls:"stashpad-folder-list"});for(let r of n)this.renderFolderScopeRow(a,r)}let o=null;new et.Setting(s).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(a=>{a.setPlaceholder("my-stashpad"),o=a.inputEl}).addButton(a=>a.setButtonText("Create").setCta().onClick(async()=>{let r=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!r){new et.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(r),new et.Notice(`Created Stashpad "${r}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(r,2e3),this.update?.()}catch(l){new et.Notice(`Couldn't create: ${l.message}`)}}))},["search","scope","exclude","include","create","new","stashpad","folder"])),i.push(this.sectionDef("Folder panel placement","Pin, downrank, or hide folders in the Stashpad folder panel. Restore hidden folders here or from the panel's \u201CHidden\u201D section.",s=>{new et.Setting(s).setName("Folder panel placement").setDesc("Folders you've pinned, downranked, or hidden in the Stashpad folder panel. Pin/downrank from a folder's right-click menu in the panel; restore here or from the panel's \u201CHidden\u201D section."),this.renderFolderPlacementList(s)},["folder","panel","pin","pinned","downrank","hide","hidden","restore","placement"])),i.push(e("Autofocus composer after sending","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.",()=>this.plugin.settings.autofocusComposerAfterSend,s=>{this.plugin.settings.autofocusComposerAfterSend=s},["composer","focus","send"])),i.push(e("Open in new window \u2014 duplicate tab","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.",()=>this.plugin.settings.popoutDuplicates,s=>{this.plugin.settings.popoutDuplicates=s},["popout","window","duplicate"])),i.push(e("Search results open in a new tab","When you pick a result in the Search modal, open it in a new Stashpad tab instead of navigating the current tab. Applies to same-folder and cross-Stashpad results alike. On by default.",()=>this.plugin.settings.searchOpensInNewTab,s=>{this.plugin.settings.searchOpensInNewTab=s},["search","new tab","results","open"])),i.push(e("Prefix timestamps when copying","Include each note's timestamp before its body when copying with C or Y.",()=>this.plugin.settings.prefixTimestampsOnCopy,s=>{this.plugin.settings.prefixTimestampsOnCopy=s},["copy","timestamp","prefix"])),i}hotkeyItems(){let t={name:"Hotkeys",desc:"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. A \u21BA icon appears on any slot that differs from its shipped default \u2014 click it to revert that slot. When both slots are set, the pill on the right decides which one is active.",searchable:!1},e=ye.map(i=>({name:i.label,desc:i.desc,aliases:["hotkey","shortcut","keybind","binding","key"],render:s=>this.renderBindingRow(s,i)}));return[t,...e]}renderJdIndexSection(t){let e=t.createEl("h3",{text:"JD Index Builder"});e.id="stashpad-jd-index-section";let i=t.createEl("p",{cls:"setting-item-description"});i.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 s=this.plugin.discoverStashpadFolders();new et.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(r=>{r.addOption("vault","Entire vault"),r.addOption("folder","Single folder"),r.setValue(this.plugin.settings.jdIndexScope??"vault"),r.onChange(async l=>{this.plugin.settings.jdIndexScope=l==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new et.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(r=>{new Ee(this.app,r.inputEl),r.setPlaceholder("Path/To/Folder"),r.setValue(this.plugin.settings.jdIndexScopeFolder??""),r.onChange(async l=>{this.plugin.settings.jdIndexScopeFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new et.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(r=>{r.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),r.onChange(async l=>{this.plugin.settings.jdIndexIncludeStashpadFolders=l,await this.plugin.saveSettings(),this.display()})}),new et.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(r=>{new Ee(this.app,r.inputEl),r.setPlaceholder(s[0]??"(pick a Stashpad folder)"),r.setValue(this.plugin.settings.jdIndexStashpadFolder??""),r.onChange(async l=>{this.plugin.settings.jdIndexStashpadFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new et.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(r=>{r.addOption("natural","Natural (numeric \u2192 alphabetical)"),r.addOption("created","By creation time"),r.setValue(this.plugin.settings.jdIndexSort??"natural"),r.onChange(async l=>{this.plugin.settings.jdIndexSort=l==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=Qe(this.app,this.plugin,this.plugin.settings),o=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)`:"";o.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${a}.`),new et.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(r=>{r.setButtonText("Preview"),r.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),r.onClick(async()=>{try{let l=await Ci(this.app,this.plugin,this.plugin.settings);if(l.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(l.error==="no-home"){new et.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}Bi(this.app,l),this.display()}catch(l){console.error("[stashpad] preview failed",l),new et.Notice(`Preview failed: ${l?.message??l}`,8e3)}})}).addButton(r=>{r.setButtonText("Build Stashpad notes"),r.setCta(),r.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),r.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Ze(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let g=await hs(this.app,this.plugin,this.plugin.settings);if(g.error==="no-dest"){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(g.error==="dest-not-stashpad"){new et.Notice(`"${g.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 et.Notice(`Built: ${g.created} created, ${g.updated} updated, ${g.skipped} skipped \u2192 ${g.destFolder}`,6e3),this.display()}catch(g){console.error("[stashpad] build failed",g),new et.Notice(`Build failed: ${g?.message??g}`,8e3)}}).open()})}).addButton(r=>{r.setButtonText(`Reveal in ${bo()}`),r.setTooltip("Open the designated Stashpad folder in your OS file browser."),r.onClick(async()=>{let l=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new et.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(l)){new et.Notice(`Folder "${l}" doesn't exist yet.`,5e3);return}try{let g=this.app.vault.adapter.basePath;if(g){let{shell:p}=window.require?.("electron")??{},d=`${g}/${l}`;p?.openPath?.(d)}else new et.Notice("Reveal in file system not supported on this platform.",4e3)}catch(g){new et.Notice(`Couldn't open folder: ${g?.message??g}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=qt()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(o=>{for(let a of e)o.addOption(a,a);o.setValue(i),o.onChange(a=>{i=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 s=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{s.empty();let o=this.plugin.collectColorsInFolder(i),a=new Map(o.map(g=>[g.hex,g.count])),r=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},l=new Set([...a.keys(),...Object.keys(r)]);if(l.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...l].map(g=>({hex:g,count:a.get(g)??0}));c.sort((g,p)=>p.count-g.count||g.hex.localeCompare(p.hex));for(let g of c)this.renderColorAliasRow(s,i,g.hex,g.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 et.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(i=>{i.setValue(this.plugin.settings.authorName).onChange(async s=>{this.plugin.settings.authorName=s.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=yt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.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(i=>{i.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new et.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(i=>{i.setValue(this.plugin.settings.authorRole).onChange(async s=>{this.plugin.settings.authorRole=s.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(i=>{i.setValue(this.plugin.settings.authorDepartment).onChange(async s=>{this.plugin.settings.authorDepartment=s.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Show author in note footer").addToggle(i=>i.setValue(this.plugin.settings.showAuthor).onChange(async s=>{this.plugin.settings.showAuthor=s,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show contributors in note footer").addToggle(i=>i.setValue(this.plugin.settings.showContributors).onChange(async s=>{this.plugin.settings.showContributors=s,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show last edit time in note footer").addToggle(i=>i.setValue(this.plugin.settings.showLastEdit).onChange(async s=>{this.plugin.settings.showLastEdit=s,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let i=t.createDiv({cls:"stashpad-authored-folders-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-authored-folder-row"}),o=n.createEl("a",{cls:"stashpad-authored-folder-link",text:s.folder});o.onclick=r=>{r.preventDefault(),this.plugin.activateViewForFolder(s.folder)};let a=[];s.authored>0&&a.push(`authored ${s.authored}`),s.contributed>0&&a.push(`contributed to ${s.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 et.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(s=>s.setButtonText("Rebuild").onClick(async()=>{s.setDisabled(!0).setButtonText("Rebuilding\u2026");try{let n=await this.plugin.rebuildAuthorRegistry();new et.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new et.Notice(`Rebuild failed: ${n.message}`)}s.setDisabled(!1).setButtonText("Rebuild"),this.display()})).addButton(s=>s.setButtonText("Restore missing pages").onClick(async()=>{s.setDisabled(!0).setButtonText("Restoring\u2026");try{let n=await this.plugin.restoreMissingAuthorStubs();new et.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new et.Notice(`Restore failed: ${n.message}`)}s.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 i=t.createDiv({cls:"stashpad-known-authors-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-known-author-row"}),o=n.createDiv({cls:"stashpad-known-author-main"});o.createSpan({cls:"stashpad-known-author-name",text:s.name||"(unnamed)"});let a=[];if(s.role&&a.push(s.role),s.department&&a.push(s.department),a.push(`id ${s.id}`),o.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${a.join(" \xB7 ")}`}),s.renames&&s.renames.length>0){let r=n.createDiv({cls:"stashpad-known-author-history"}),l=s.renames.map(c=>`${c.from} \u2192 ${c.to}`).join(", ");r.setText(`Renamed: ${l}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new et.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 i=t.createDiv({cls:"stashpad-note-templates-list"}),s=n=>{let o=n.replace(/\/+$/,""),a=i.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??{})[o]??"";let g=l.createDiv({cls:"stashpad-note-template-suggest"});g.style.display="none";let p=a.createDiv({cls:"stashpad-note-template-warn"});p.style.display="none";let d=()=>this.app.vault.getMarkdownFiles().map(C=>C.path).filter(C=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(C)).sort(),I=()=>{g.empty();let C=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),m=w=>{let y=w.toLowerCase();return C.every(F=>y.includes(F))},E=d().filter(w=>m(w)).slice(0,12);if(E.length===0){g.style.display="none";return}g.style.display="";for(let w of E)g.createDiv({cls:"stashpad-note-template-suggest-item",text:w}).addEventListener("mousedown",async F=>{F.preventDefault(),c.value=w,await u(),g.style.display="none"})},u=async()=>{let C=c.value.trim(),m={...this.plugin.settings.noteTemplates??{}};C?m[o]=C:delete m[o],this.plugin.settings.noteTemplates=m,await this.plugin.saveSettings(),f()},f=()=>{p.empty(),p.style.display="none";let C=c.value.trim();if(!C)return;let m=this.app.vault.getAbstractFileByPath(C);if(!m||m.extension!=="md"){p.style.display="",p.setText(`\u26A0 "${C}" is not a markdown file in this vault.`);return}let E=this.app.metadataCache.getFileCache(m)?.frontmatter??{},y=Wt.filter(F=>{let D=E[F];return!(D==null||typeof D=="string"&&D.trim()===""||Array.isArray(D)&&D.length===0)});y.length!==0&&(p.style.display="",p.setText(`\u26A0 Template defines ${y.join(", ")} \u2014 Stashpad always sets ${y.length===1?"this":"these"} on new notes, so the template value${y.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",I),c.addEventListener("input",I),c.addEventListener("blur",()=>{setTimeout(()=>{g.style.display="none"},150)}),c.addEventListener("change",()=>{u()}),f()};for(let n of e)s(n)}renderColorAliasRow(t,e,i,s,n){let o=t.createDiv({cls:"stashpad-color-alias-row"});s===0&&o.addClass("is-unused");let a=o.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=i,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let g=this.plugin.settings.customPalette??[];new ce(this.app,i,g,async p=>{if((p??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(p&&p.toLowerCase()===i){n();return}let d=await this.plugin.recolorAllInFolder(e,i,p??null);if(d>0)new et.Notice(`Recolored ${d} note${d===1?"":"s"}.`);else if(s===0){let I=this.plugin.getColorAlias(e,i);I&&(await this.plugin.setColorAlias(e,i,""),p&&await this.plugin.setColorAlias(e,p,I))}n()},async p=>{let d=(this.plugin.settings.customPalette??[]).filter(I=>I.toLowerCase()!==p.toLowerCase());return this.plugin.settings.customPalette=d,await this.plugin.saveSettings(),d}).open()};let r=o.createDiv({cls:"stashpad-color-alias-meta"});r.createSpan({cls:"stashpad-color-alias-hex",text:i}),r.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let l=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,i)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,i,l.value),!l.value.trim()&&s===0&&n()};let c=o.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,i,""),s===0?n():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let i=t.createDiv({cls:"stashpad-folder-row"});i.createSpan({cls:"stashpad-folder-row-label",text:e});let s=i.createSpan({cls:"stashpad-folder-row-state"}),n=i.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let o=n.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),r=()=>{let c=a();n.toggleClass("is-right",c),n.setAttribute("aria-checked",String(c)),o.setText(c?"X":"\u2713"),s.setText(c?"Excluded":"Included"),s.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(),r(),await this.plugin.saveSettings()};n.onclick=()=>void l(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},r()}renderFolderPlacementList(t){let e=this.plugin.settings,i=[{key:"folderPanelPinned",label:"Pinned",action:"Unpin"},{key:"folderPanelDownranked",label:"Downranked",action:"Reset"},{key:"folderPanelHidden",label:"Hidden",action:"Unhide"}];if(!i.some(o=>(e[o.key]??[]).length>0)){t.createEl("p",{cls:"setting-item-description"}).setText("No folders customized yet. Right-click a folder in the Stashpad folder panel to pin, downrank, or hide it.");return}let n=async o=>{e.folderPanelPinned=(e.folderPanelPinned??[]).filter(a=>a!==o),e.folderPanelDownranked=(e.folderPanelDownranked??[]).filter(a=>a!==o),e.folderPanelHidden=(e.folderPanelHidden??[]).filter(a=>a!==o),await this.plugin.saveSettings(),this.update?.()};for(let o of i){let a=[...e[o.key]??[]].sort();if(a.length===0)continue;t.createEl("div",{cls:"stashpad-folder-placement-group",text:`${o.label} (${a.length})`});let r=t.createDiv({cls:"stashpad-folder-list"});for(let l of a){let c=r.createDiv({cls:"stashpad-folder-row"});c.createSpan({cls:"stashpad-folder-row-label",text:l});let g=c.createEl("button",{text:o.action});g.onclick=()=>void n(l)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=d=>{let I=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=I.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=_e(i()[d]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=d==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{dn(u,async y=>{this.plugin.settings.bindings[e.id][d]=y,u.value=_e(y),f(),await this.plugin.saveSettings(),o(),w()})};let m=I.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][d]="",u.value="",f(),await this.plugin.saveSettings(),o(),w()};let E=I.createEl("button",{cls:"stashpad-binding-revert"});(0,et.setIcon)(E,"rotate-ccw");let w=()=>{let F=i()[d]!==C;E.toggleClass("is-hidden",!F),E.title=C?`Revert to default (${_e(C)})`:"Revert to default (no binding)"};return E.onclick=async()=>{this.plugin.settings.bindings[e.id][d]=C,u.value=_e(C),f(),await this.plugin.saveSettings(),o(),w()},w(),u};s=a("primary"),n=a("secondary");let r=t.controlEl.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let l=r.createDiv({cls:"stashpad-binding-pill-knob"}),c=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),g=c.createEl("input",{type:"checkbox"});g.title="Use both bindings simultaneously (overrides the L/R toggle)",c.createSpan({text:"Use both"}),g.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=g.checked,await this.plugin.saveSettings(),o()},o=()=>{let d=i(),I=!!(d.primary&&d.secondary);g.checked=!!d.useBoth,g.disabled=!I,c.toggleClass("is-disabled",!I);let u=!!d.useBoth&&I;r.toggleClass("is-disabled",!I||u),r.toggleClass("is-right",d.preferRight),r.setAttribute("aria-checked",String(d.preferRight)),r.setAttribute("aria-disabled",String(!I||u)),l.setText(d.preferRight?"R":"L"),r.title=I?u?'Overridden by "Use both"':d.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let p=async()=>{let d=i();!d.primary||!d.secondary||(this.plugin.settings.bindings[e.id].preferRight=!d.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void p(),r.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),p())},o()}};var we=class{constructor(A,t){this.app=A;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 A=this.detectTrigger();if(!A){this.close();return}this.openFor(A)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=A=>{A.key==="Escape"&&(!this.state||!this.items.length||(A.preventDefault(),A.stopPropagation(),A.stopImmediatePropagation(),this.close()))};this.onKeyDown=A=>{!this.state||!this.items.length||(A.key==="ArrowDown"?(A.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):A.key==="ArrowUp"?(A.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):A.key==="Enter"||A.key==="Tab"?(A.preventDefault(),A.stopPropagation(),this.commit()):A.key==="Escape"&&(A.preventDefault(),A.stopPropagation(),A.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let A=this.ta.ownerDocument??document;A.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>A.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 A of this.vaultListeners)A();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let A=ft().inheritObsidianExclusions,t=A?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!zs(i.path)&&!Vs(i.path)&&!(A&&Ws(i.path,t))).map(i=>{let s=i.extension==="md",n=s?i.basename:i.name,o=s?i.basename:i.name;return{label:n,lower:n.toLowerCase(),insertText:o,file:i}});let e=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(e).sort((i,s)=>(e[s]||0)-(e[i]||0)),this.indexBuilt=!0}detectTrigger(){let A=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=A.slice(0,t),i=e.match(/\[\[([^\]\[\n]*)$/);if(i){let n=i[1];return{kind:"link",query:n,replaceStart:t-n.length-2,replaceEnd:t}}let s=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(s){let n=s[2];return{kind:"tag",query:n,replaceStart:t-n.length-1,replaceEnd:t}}return null}buildItems(A){this.buildIndex();let t=A.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],i=s=>{if(!e.length)return!0;for(let n of e)if(!s.includes(n))return!1;return!0};return A.kind==="link"?this.fileIndex.filter(n=>i(n.lower)).slice(0,50).map(n=>({label:n.label,insert:`[[${n.insertText}]]`,subtitle:n.file.path})):this.tagIndex.filter(n=>i(n.toLowerCase())).slice(0,30).map(n=>({label:n,insert:n,subtitle:""}))}openFor(A){if(this.state=A,this.items=this.buildItems(A),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let A=new un.Scope(this.app.scope);A.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=A,this.app.keymap?.pushScope(A)}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 A=this.popupEl;A.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],i=A.createDiv({cls:"stashpad-composer-suggest-row"});t===this.activeIdx&&i.addClass("is-active"),i.createSpan({cls:"stashpad-composer-suggest-label",text:e.label}),e.subtitle&&i.createSpan({cls:"stashpad-composer-suggest-sub",text:e.subtitle}),i.onmousedown=s=>{s.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let A=this.popupEl.children;for(let e=0;e<A.length;e++)A[e].toggleClass("is-active",e===this.activeIdx);let t=A[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let A=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=A.top-t-4,i=A.left;this.popupEl.style.left=`${Math.max(8,i)}px`,this.popupEl.style.top=`${Math.max(8,e)}px`,this.popupEl.style.minWidth=`${Math.min(360,A.width)}px`}commit(){if(!this.state||!this.items.length)return;let A=this.items[this.activeIdx];if(!A)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),i=A.insert;this.ta.value=t+i+e;let s=t.length+i.length;this.ta.setSelectionRange(s,s),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()}};wt();var Di=class extends kt.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 oe}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?.()===dt&&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?.()===dt&&e.tree?.get){let i=e.tree.get(this.displayedId);if(i?.file)return{folder:e.noteFolder,id:this.displayedId,file:i.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,i=this.composerInputEl?.selectionStart??null;this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,t.empty(),t.addClass("stashpad-detail-root");let s=this.resolveDisplayed();if(!s){this.displayedPath=null;let d=t.createDiv({cls:"stashpad-detail-empty"});(0,kt.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=s.file;this.displayedPath=n.path;let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=t.createDiv({cls:"stashpad-detail-scroll"}),r=a.createDiv({cls:"stashpad-detail-header"}),l=r.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,kt.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(s.folder,s.id)};let g=r.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&g.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let d=g.createSpan({cls:"stashpad-detail-meta-color"});d.style.background=o.color,d.title=o.color}if(o.completed===!0&&g.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let d=Date.parse(String(o.due)),I=Number.isNaN(d)?String(o.due):re(d,this.plugin.settings);g.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${I}`})}if(Array.isArray(o.tags))for(let d of o.tags.filter(I=>typeof I=="string"))g.createSpan({cls:"stashpad-detail-meta-tag",text:`#${d.replace(/^#/,"")}`});let p=a.createDiv({cls:"stashpad-detail-body"});try{let d=await this.app.vault.cachedRead(n),I=this.stripFrontmatter(d);await kt.MarkdownRenderer.render(this.app,I,p,n.path,this)}catch(d){p.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${d.message}`})}if(this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s),e&&this.composerInputEl&&(this.composerInputEl.focus(),i!=null)){let d=Math.min(i,this.composerInputEl.value.length);try{this.composerInputEl.setSelectionRange(d,d)}catch{}}}renderComposer(t,e){let i=t.createDiv({cls:"stashpad-detail-composer"}),s=i.createEl("textarea",{cls:"stashpad-detail-composer-input",attr:{placeholder:"Add a child note\u2026",rows:"2"}});this.composerInputEl=s,this.composerDraftForId===e.id?s.value=this.composerDraft:(this.composerDraft="",this.composerDraftForId=e.id),s.addEventListener("input",()=>{this.composerDraft=s.value,this.composerDraftForId=e.id}),s.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey&&!o.isComposing){if(this.composerAutocomplete?.isOpen?.())return;o.preventDefault(),this.submitComposer(e)}});let n=i.createEl("button",{cls:"stashpad-detail-composer-send",attr:{"aria-label":"Add child note"}});(0,kt.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 we(this.app,s),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==dt||typeof i.createNoteUnder!="function"){new kt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new kt.Notice(`Couldn't add note: ${s.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,i){let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==dt)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let r=a.createDiv({cls:"stashpad-detail-children-list"});for(let l of o)l.file&&this.renderDetailChildRow(r,s,n,e,l,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},r=typeof a.color=="string"?a.color:null,l=a.completed===!0,c=i.getChildren(n.id),g=c.length>0,p=`${s}|${n.id}`,d=this.expanded.has(p),I=t.createDiv({cls:"stashpad-detail-child-row"});l&&I.addClass("is-completed"),o>0&&(I.style.paddingLeft=`${o*16}px`),I.draggable=!0,I.dataset.id=n.id,I.addEventListener("dragstart",E=>{E.dataTransfer?.setData("text/plain",n.id),E.dataTransfer&&(E.dataTransfer.effectAllowed="move"),I.addClass("is-dragging")}),I.addEventListener("dragend",()=>I.removeClass("is-dragging")),I.addEventListener("dragover",E=>{E.preventDefault(),E.dataTransfer&&(E.dataTransfer.dropEffect="move");let w=I.getBoundingClientRect(),y=E.clientY-w.top<w.height/2;I.toggleClass("drop-before",y),I.toggleClass("drop-after",!y)}),I.addEventListener("dragleave",()=>{I.removeClass("drop-before"),I.removeClass("drop-after")}),I.addEventListener("drop",E=>{E.preventDefault(),I.removeClass("drop-before"),I.removeClass("drop-after");let w=E.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let y=I.getBoundingClientRect(),F=E.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,F?"before":"after")}),I.oncontextmenu=E=>{E.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(E,w)};let u=I.createSpan({cls:"stashpad-detail-child-toggle"});if(g&&(de(u,c.length,d),u.onclick=E=>{E.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Ie(a,"task")||a.task===!0||a.completed!==void 0){let E=I.createSpan({cls:"stashpad-detail-child-checkbox"});(0,kt.setIcon)(E,l?"check-square":"square"),E.title=l?"Mark not done":"Mark done",E.addEventListener("mousedown",w=>w.stopPropagation()),E.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),E.onclick=w=>{w.preventDefault(),w.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let C=I.createSpan({cls:"stashpad-detail-child-icon"});(0,kt.setIcon)(C,g?"folder-tree":"file-text"),r&&(C.style.color=r);let m=I.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},g&&d)for(let E of c)this.renderDetailChildRow(t,e,i,s,E,o+1)}renderFooterMeta(t,e,i,s){let n=t.createDiv({cls:"stashpad-detail-footer-meta"}),o=[];if(typeof i.author=="string"&&i.author&&o.push({label:"Author",value:this.stripWikiLink(i.author)}),Array.isArray(i.contributors)){let a=i.contributors.filter(r=>typeof r=="string").map(r=>this.stripWikiLink(r));a.length>0&&o.push({label:"Contributors",value:a.join(", ")})}if(typeof i.modified=="string"&&o.push({label:"Modified",value:this.formatTime(i.modified)}),typeof i.created=="string"&&o.push({label:"Created",value:this.formatTime(i.created)}),o.push({label:"Path",value:e.path}),o.push({label:"ID",value:s.id}),o.length===0){n.remove();return}for(let a of o){let r=n.createDiv({cls:"stashpad-detail-meta-line"});r.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),r.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)?re(e,this.plugin.settings):t}async openInStashpad(t,e){try{await this.plugin.activateViewForFolder(t);let i=this.plugin.lastActiveStashpadLeaf?.view;i?.navigateTo&&e!==U&&i.navigateTo(e)}catch(i){new kt.Notice(`Couldn't open: ${i.message}`)}}};async function bi(h){let A=h.workspace.getLeavesOfType(oe);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getRightLeaf(!1);if(!t){new kt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:oe,active:!0}),h.workspace.revealLeaf(t)}var q=require("obsidian");wt();var $t=require("obsidian");wt();function xo(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof $t.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof $t.TFile?n.extension==="md"&&e.push(n):n instanceof $t.TFolder&&(Ge.has(n.name)||i.push(n))}return e}var Ni=class{constructor(A){this.app=A;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(U,{id:U,parent:null,children:[],file:null,created:""})}setOrderProvider(A){this.orderProvider=A}onChange(A){return this.listeners.add(A),()=>this.listeners.delete(A)}emit(){for(let A of this.listeners)A()}rebuild(A){A!==void 0&&(this.currentFolder=A);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(U,{id:U,parent:null,children:[],file:null,created:""});let s=t?xo(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=o?.id;if(!a){let l=e.get(n.path),c=l?i.get(l):void 0,g=this.synthetic.get(n.path),p=c??g;p&&(this.nodes.set(p.id,{...p,children:[],file:n}),this.byPath.set(n.path,p.id));continue}if(this.synthetic.delete(n.path),a===U){let l=this.nodes.get(U);l.file=n,l.created=o?.created??"",this.byPath.set(n.path,U);continue}let r=o?.parent??null;r===a&&(r=null),this.nodes.set(a,{id:a,parent:r??U,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===U)continue;let o=n.parent??U;(this.nodes.get(o)??this.nodes.get(U)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let r=this.nodes.get(o),l=this.nodes.get(a);return(r.created||"").localeCompare(l.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((r,l)=>a.set(r,l)),n.children.sort((r,l)=>{let c=a.has(r)?a.get(r):1/0,g=a.has(l)?a.get(l):1/0;return c===g?0:c-g})}}this.emit()}insertSynthetic(A){if(!A.file)return;let t=A.file.path;this.synthetic.set(t,A),this.nodes.set(A.id,A),this.byPath.set(t,A.id);let e=A.parent??U,i=this.nodes.get(e);i&&!i.children.includes(A.id)&&i.children.push(A.id),this.emit()}get(A){return this.nodes.get(A)}getRoot(){return this.nodes.get(U)}getChildren(A){let t=this.nodes.get(A);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let A=0;for(let t of this.nodes.values())t.file&&A++;return A}pathTo(A){let t=[],e=new Set,i=this.nodes.get(A);for(;i&&i.id!==U&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(A){return this.byPath.get(A)}snapshot(){let A={};for(let t of this.nodes.values())t.id===U||!t.file||(A[t.id]={parent:t.parent===U?null:t.parent,path:t.file.path});return A}hookMetadataCache(A){let t=r=>{let l=this.currentFolder;return l?typeof r!="string"?!1:r===l||r.startsWith(l+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),A())},16))},s=r=>{r instanceof $t.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof $t.TFile&&t(r.path)&&r.extension==="md"&&this.applyChange(r)&&i()},o=r=>{let l=r?.path;typeof l=="string"&&t(l)&&this.applyDelete(l)&&i()},a=(r,l)=>{if(!(r instanceof $t.TFile))return;let c=typeof l=="string"?l:null;!t(r.path)&&!t(c)||this.applyRename(r,c??"")&&i()};return this.app.metadataCache.on("changed",s),this.app.vault.on("create",n),this.app.vault.on("delete",o),this.app.vault.on("rename",a),()=>{this.app.metadataCache.off("changed",s),this.app.vault.off("create",n),this.app.vault.off("delete",o),this.app.vault.off("rename",a),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(A){if(ue(A.path))return this.byPath.has(A.path)?this.applyDelete(A.path):!1;let t=this.app.metadataCache.getFileCache(A)?.frontmatter,e=t?.id,i=this.byPath.get(A.path);if(!e){if(i){let l=this.nodes.get(i);if(l&&l.file!==A)return l.file=A,!0}return!1}if(this.synthetic.delete(A.path),e===U){let l=this.nodes.get(U),c=t?.created??"",g=!1;return l.file!==A&&(l.file=A,g=!0),l.created!==c&&(l.created=c,g=!0),this.byPath.get(A.path)!==U&&(this.byPath.set(A.path,U),g=!0),g}let s=t?.parent??U,n=t?.created??"";if(!(s===U||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let l={id:e,parent:s,children:[],file:A,created:n};return this.nodes.set(e,l),this.byPath.set(A.path,e),this.attachToParent(l),this.resortChildrenOf(s),!0}let r=!1;if(a.file!==A&&(a.file=A,r=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??U),r=!0),a.parent!==s){let l=a.parent??U;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(l),this.resortChildrenOf(s),r=!0}return r}applyDelete(A){let t=this.byPath.get(A);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(A),this.synthetic.delete(A),!0;this.detachFromParent(e);let i=this.nodes.get(U);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=U,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(U),this.nodes.delete(t),this.byPath.delete(A),this.synthetic.delete(A),!0}applyRename(A,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||A.path===e||A.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(A);if(ue(A.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(A);this.byPath.delete(t),this.byPath.set(A.path,n);let o=this.nodes.get(n);return o&&(o.file=A),!0}detachFromParent(A){let t=this.nodes.get(A.parent??U);if(!t)return;let e=t.children.indexOf(A.id);e>=0&&t.children.splice(e,1)}attachToParent(A){let t=this.nodes.get(A.parent??U);t||(t=this.nodes.get(U)),t.children.includes(A.id)||t.children.push(A.id)}resortChildrenOf(A){let t=this.nodes.get(A);if(t&&(t.children.sort((e,i)=>{let s=this.nodes.get(e),n=this.nodes.get(i);return(s.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(A);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,a=i.has(n)?i.get(n):1/0;return o===a?0:o-a})}}}};var ms=class{constructor(){this.enabled=!1;this.buckets=new Map}record(A,t){if(!this.enabled)return;let e=this.buckets.get(A);e||(e={count:0,total:0,max:0},this.buckets.set(A,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(A,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(A,performance.now()-e)}}async timeAsync(A,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(A,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let A=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(A.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 A)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` +`)}},St=new ms;var fn=".stashpad-order.json",xi=class{constructor(A){this.app=A;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(A){if(this.cache.has(A))return this.cache.get(A);let t=`${A}/${fn}`,e=this.app.vault.adapter,i={};try{if(await e.exists(t)){let s=await e.read(t),n=JSON.parse(s);if(n&&typeof n=="object"&&!Array.isArray(n))for(let[o,a]of Object.entries(n))Array.isArray(a)&&a.every(r=>typeof r=="string")&&(i[o]=a)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(A,i),i}async save(A){this.scheduleWrite(A)}async flush(A){let t=this.pendingTimers.get(A);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(A)),await this.writeNow(A)}scheduleWrite(A){let t=this.pendingTimers.get(A);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(A),this.writeNow(A)},150);this.pendingTimers.set(A,e)}async writeNow(A){let e=(this.writeInFlight.get(A)??Promise.resolve()).then(()=>this.doWrite(A));this.writeInFlight.set(A,e);try{await e}finally{this.writeInFlight.get(A)===e&&this.writeInFlight.delete(A)}}async doWrite(A){let t=this.cache.get(A)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(A,e);let i=`${A}/${fn}`,s=this.app.vault.adapter;try{if(Object.keys(e).length===0)try{await s.remove(i)}catch{}else await s.write(i,JSON.stringify(e,null,2))}catch(n){console.warn("Stashpad: order save failed",n)}}getOrder(A,t){return this.cache.get(A)?.[t]?.slice()??[]}setOrder(A,t,e){let i=this.cache.get(A)??{};i[t]=e.slice(),this.cache.set(A,i)}appendChild(A,t,e){let i=this.cache.get(A)??{},s=i[t]??[];s.includes(e)||s.push(e),i[t]=s,this.cache.set(A,i)}removeChild(A,t){let e=this.cache.get(A);if(e)for(let i of Object.values(e)){let s=i.indexOf(t);s>=0&&i.splice(s,1)}}invalidate(A){this.cache.delete(A)}};var ti={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"},Qs=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],Mo=new Set(Qs),Cn=".stashpad-sort.json",Mi=class{constructor(A){this.app=A;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(A){if(this.cache.has(A))return this.cache.get(A);let t=`${A}/${Cn}`,e=this.app.vault.adapter,i={};try{if(await e.exists(t)){let s=JSON.parse(await e.read(t));if(s&&typeof s=="object"&&!Array.isArray(s))for(let[n,o]of Object.entries(s))typeof o=="string"&&Mo.has(o)&&(i[n]=o)}}catch(s){console.warn("Stashpad: sort load failed",s)}return this.cache.set(A,i),i}async save(A){this.scheduleWrite(A)}async flush(A){let t=this.pendingTimers.get(A);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(A)),await this.writeNow(A)}scheduleWrite(A){let t=this.pendingTimers.get(A);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(A),this.writeNow(A)},150);this.pendingTimers.set(A,e)}async writeNow(A){let e=(this.writeInFlight.get(A)??Promise.resolve()).then(()=>this.doWrite(A));this.writeInFlight.set(A,e);try{await e}finally{this.writeInFlight.get(A)===e&&this.writeInFlight.delete(A)}}async doWrite(A){let t=this.cache.get(A)??{},e=`${A}/${Cn}`,i=this.app.vault.adapter;try{if(Object.keys(t).length===0)try{await i.remove(e)}catch{}else await i.write(e,JSON.stringify(t,null,2))}catch(s){console.warn("Stashpad: sort save failed",s)}}getMode(A,t){return this.cache.get(A)?.[t]??"manual"}setMode(A,t,e){let i=this.cache.get(A)??{};e==="manual"?delete i[t]:i[t]=e,this.cache.set(A,i)}removeParent(A,t){let e=this.cache.get(A);e&&delete e[t]}invalidate(A){this.cache.delete(A)}};wt();var _t="parentLink",Fe="children";var Ui=class Ui{constructor(A,t){this.app=A;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(A){return this.activityListeners.add(A),()=>this.activityListeners.delete(A)}emitActivity(){let A=this.pending.size;for(let t of this.activityListeners)try{t(A)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(A){if(!A||!ft().writeRecoveryLinks)return;let t=this.pending.size;this.pending.add(A),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(A,t,e){this.schedule(A),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(A){let t=this.getTree(),e=i=>{this.schedule(i);for(let s of t.getChildren(i))e(s.id)};e(A)}scheduleParentOfDeleted(A){A&&this.schedule(A)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let A=this.pending.values().next().value;if(A===void 0)break;this.pending.delete(A),this.emitActivity(),await this.syncOne(A)}}pendingCount(){return this.pending.size}onError(A){return this.errorListeners.add(A),()=>this.errorListeners.delete(A)}emitError(A,t){for(let e of this.errorListeners)try{e(A,t)}catch(i){console.warn("[Stashpad] fmSync error listener failed",i)}}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(),Ui.PACING_MS))}async tick(){this.timer=null;let A=this.pending.values().next().value;if(A!==void 0){this.pending.delete(A),this.emitActivity();try{await this.syncOne(A)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(A){let e=this.getTree().get(A);if(!e||!e.file)return!1;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e),n=this.app.metadataCache.getFileCache(e.file)?.frontmatter,o=n&&typeof n[_t]=="string"?n[_t]:null,a=n?.[Fe],r=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];if((o??null)!==(i??null)||r.length!==s.length)return!0;for(let l=0;l<r.length;l++)if(r[l]!==s[l])return!0;return!1}async syncOne(A){let e=this.getTree().get(A);if(!e||!e.file||!this.wouldWrite(A))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await St.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[_t]=i:delete n[_t],s.length>0?n[Fe]=s:delete n[Fe]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(A){if(A.id===U)return null;let t=this.getTree();if(!A.parent||A.parent===U){let i=t.getRoot();return i&&i.id!==A.id&&i.file?Hi(i.file.path):null}let e=t.get(A.parent);return e?.file?Hi(e.file.path):null}computeChildrenLinks(A){return this.getTree().getChildren(A.id).filter(e=>!!e.file).map(e=>Hi(e.file.path))}};Ui.PACING_MS=100;var Ti=Ui;async function ve(h,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let l of h.vault.getMarkdownFiles()){if(l.path!==A&&!l.path.startsWith(t))continue;let c=h.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id:null;if(!g)continue;let p=typeof c?.parent=="string"?c.parent:U;e.set(g,{file:l,id:g,parent:p});let d=i.get(p)??[];d.push(g),i.set(p,d)}let s=l=>Hi(l.file.path),n=l=>{if(l.id===U)return null;if(l.parent===U||!l.parent){let g=e.get(U);return g?s(g):null}let c=e.get(l.parent);return c?s(c):null},o=l=>{let c=i.get(l.id)??[],g=[];for(let p of c){let d=e.get(p);d&&g.push(s(d))}return g},a=0,r=0;for(let l of e.values()){a+=1;let c=n(l),g=o(l),p=h.metadataCache.getFileCache(l.file)?.frontmatter,d=p&&typeof p[_t]=="string"?p[_t]:null,I=p?.[Fe],u=Array.isArray(I)?I.filter(m=>typeof m=="string"):[],f=(d??null)===(c??null),C=u.length===g.length&&u.every((m,E)=>m===g[E]);if(!(f&&C))try{await h.fileManager.processFrontMatter(l.file,m=>{c?m[_t]=c:delete m[_t],g.length>0?m[Fe]=g:delete m[Fe]}),r+=1,await new Promise(m=>setTimeout(m,50))}catch(m){console.warn("[Stashpad] rebootstrap fm sync failed",l.file.path,m)}}return{checked:a,written:r}}function Hi(h){return`[[${h.replace(/\.md$/i,"")}]]`}Rt();me();var Gi=class{constructor(A,t){this.tree=A;this.log=t}async sweep(A){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!A)return!0;let o=A.replace(/\/+$/,"");return n===o||n.startsWith(o+"/")};for(let[n,o]of Object.entries(e)){let a=t[n];a?a.parent!==o.parent?await this.log.append({type:"parent_change",id:n,payload:{from:a.parent,to:o.parent}}):a.path!==o.path&&await this.log.append({type:"rename",id:n,payload:{from:a.path,to:o.path}}):await this.log.append({type:"create",id:n,payload:{path:o.path,parent:o.parent}})}for(let[n,o]of Object.entries(t))!e[n]&&i(o.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:o.path}});let s={};for(let[n,o]of Object.entries(t))i(o.path)||(s[n]=o);for(let[n,o]of Object.entries(e))s[n]=o;await this.log.writeState(s)}};var gt=require("obsidian");wt();As();function Es(h){let A=h.trim().toLowerCase();if(!A)return null;let t=Date.now(),e=I=>(0,gt.moment)(I).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=A,a=i.exec(A);if(a&&(a[3]||a[2])){let I=parseInt(a[1],10),u=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&I<12&&(I+=12),f==="am"&&I===12&&(I=0),I>=0&&I<24&&u>=0&&u<60&&(s=(I*3600+u*60)*1e3,n=!0,o=A.replace(a[0]," ").replace(/\s+/g," ").trim())}let r=I=>n?I+s:I;if(o===""||o==="today")return r(e(t));if(o==="yesterday")return r(e(t)-864e5);if(o==="tomorrow")return r(e(t)+864e5);let l=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],c=["sun","mon","tue","wed","thu","fri","sat"],g=l.indexOf(o)>=0?l.indexOf(o):c.indexOf(o);if(g>=0){let I=(0,gt.moment)().startOf("day"),f=(I.day()-g+7)%7;return r(I.subtract(f,"days").valueOf())}let p=/^(\d+)\s*([dwmy])$/.exec(o);if(p){let I=parseInt(p[1],10),u={d:"days",w:"weeks",m:"months",y:"years"}[p[2]];return r((0,gt.moment)().subtract(I,u).startOf("day").valueOf())}let d=(0,gt.moment)(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return d.isValid()?r(d.startOf("day").valueOf()):null}function Bn(h){let A={text:[],filters:{}},t=(h||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let a=Es(o);a!=null&&(A.filters.before=a)}else if(n==="after"){let a=Es(o);a!=null&&(A.filters.after=a)}else if(n==="on"){let a=Es(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))A.filters.on={start:a-6e4,end:a+6e4};else{let l=(0,gt.moment)(a).startOf("day").valueOf();A.filters.on={start:l,end:l+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&A.text.push(n.toLowerCase());return A}var Ot=class h extends gt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.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{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==U?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===U&&this.notes.push({node:a,title:i,body:""});for(let r of this.tree.getChildren(n))s(r.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(U))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(a=>{o.body=this.stripFm(a)})}}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(),i=Bn(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=C=>{if(!s.length)return!0;for(let m of s)if(!C.includes(m))return!1;return!0},o=null,a=null;if(i.filters.in){let C=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,a=new Map;let m=y=>C.every(F=>y.toLowerCase().includes(F)),E=y=>{if(!o.has(y)){o.add(y);for(let F of this.tree.getChildren(y))E(F.id)}};for(let y of this.notes)!y.node||y.cross||m(y.title)&&E(y.node.id);let w=new Map;for(let y of this.notes){if(!y.cross)continue;let F=w.get(y.cross.folder)??[];F.push(y),w.set(y.cross.folder,F)}for(let[y,F]of w){let D=new Map;for(let b of F){let Q=b.cross?.parentId??null;if(!Q)continue;let H=D.get(Q)??[];H.push(b.cross.id),D.set(Q,H)}let L=new Set;a.set(y,L);let S=b=>{if(!L.has(b)){L.add(b);for(let Q of D.get(b)??[])S(Q)}};for(let b of F)m(b.title)&&S(b.cross.id)}}let r=C=>{let m=i.filters;if(o||a)if(C.cross){let E=a?.get(C.cross.folder);if(!E||!E.has(C.cross.id))return!1}else if(C.node){if(!o||!o.has(C.node.id))return!1}else return!1;if(m.before||m.after||m.on){let E=this.createdMsFor(C);if(E==null||m.before!=null&&E>=m.before||m.after!=null&&E<=m.after||m.on&&(E<m.on.start||E>=m.on.end))return!1}return!0},l=C=>n(C.toLowerCase()),c=this.notes.filter(C=>!C.cross),g=this.notes.filter(C=>C.cross),p=(C,m)=>({id:C.cross?`cross:${C.cross.id}`:C.node.id,label:C.title,node:C.node,kind:"note",bodyPreview:this.previewFromBody(C.body,m),matchLine:m,crossFolder:C.cross?.folder,crossFile:C.cross?.file}),d=C=>{let m=[];for(let E of C)if(r(E))if(this.opts.mode==="search"){if(!e){m.push(p(E,-1));continue}let w=n(E.title.toLowerCase()),y=E.body.split(/\r?\n/),F=[];for(let L=0;L<y.length;L++)l(y[L])&&F.push(L);let D=F.length>0||n(E.body.toLowerCase());if(!w&&!D)continue;if(F.length===0)m.push(p(E,-1));else{let L=[],S=-100;for(let Q of F)Q-S>5&&L.push(Q),S=Q;let b=5;for(let Q of L.slice(0,b))m.push(p(E,Q))}}else{if(e&&!n(E.title.toLowerCase())&&!n(E.body.toLowerCase()))continue;m.push(p(E,-1))}return m},I=d(c),u=[...I];if(this.opts.mode==="search"?e?!0:I.length<10:!!e){let C=d(g);this.opts.mode==="search"&&!e&&(u.length=Math.min(u.length,50)),u.push(...C)}if(this.opts.folderResults){let C=this.opts.folderResults(),m={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};C.length>0&&(e?C.some(E=>{let w=E.split("/").pop()??E;return n(`${E.toLowerCase()} ${w.toLowerCase()}`)})&&u.push(m):u.unshift(m))}if(this.opts.allowCreate&&e&&!u.some(C=>C.label.trim().toLowerCase()===e)&&u.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let C=E=>E.kind==="note"&&(E.id===U||E.id===`cross:${U}`)&&n(E.label.toLowerCase()),m=u.filter(C);if(m.length>0){let E=u.filter(w=>!C(w));u.splice(0,u.length,...m,...E)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&u.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),u}loadExcludedNotes(){if(this.includeExcluded||!this.opts.excludedFolderNotes)return;this.includeExcluded=!0;for(let e of this.opts.excludedFolderNotes())this.notes.push({node:null,title:e.title,body:e.body,cross:e});for(let e of this.notes)!e.cross||e.body||!e.cross.file||this.app.vault.cachedRead(e.cross.file).then(i=>{e.body=this.stripFm(i)});let t=this.inputEl;t&&(t.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(()=>t.dispatchEvent(new Event("input",{bubbles:!0})),250))}previewFromBody(t,e){let i=t.split(/\r?\n/);if(e<0)return i.filter(a=>a.trim().length>0).slice(0,3).join(` `);let s=Math.max(0,e-2),n=Math.min(i.length,e+3);return i.slice(s,n).filter(o=>o.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}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let d=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),I=d.createSpan({cls:"stashpad-search-excluded-icon"});(0,gt.setIcon)(I,"folder-search"),d.createSpan({text:t.label}),e.createDiv({cls:"stashpad-suggest-preview",text:"Include folders you've excluded from search (e.g. to move a note there)."});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let i=e.createDiv({cls:"stashpad-suggest-body"}),s=this.notes.find(d=>t.crossFolder?d.cross?.id===t.id.replace(/^cross:/,""):d.node?.id===t.id),n=Bn(this.inputEl?.value??"").text,o=this.firstLineOfBody(s?.body??"")||t.label.trim(),a=i.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(a,o,n);let r=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let d=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(d,t.bodyPreview,n)}let c="";if(t.crossFolder?c=s?.cross?.parentBlurb??"":c=this.parentBlurbFor(t.node),c){let d=i.createDiv({cls:"stashpad-suggest-preview"});d.appendText("Parent: "),this.highlightInto(d,c,n)}let l=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),g=t.crossFolder??this.opts.localFolder??null;if(g||l){let d=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[g?g.split("/").pop()||g:"",l].filter(f=>f&&f.length>0).join(" \u203A ");u&&d.setText(u)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let d=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let I=d.createDiv({cls:"stashpad-suggest-time"});I.setText(this.formatRelativeTime(p)),I.title=(0,gt.moment)(p).format("YYYY-MM-DD HH:mm")}r&&d.createDiv({cls:"stashpad-suggest-folder-badge",text:r.split("/").pop()||r})}}formatRelativeTime(t){let e=(0,gt.moment)(t),i=(0,gt.moment)().startOf("day").diff((0,gt.moment)(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(c=>c&&c.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let c of s){let l=0;for(;(l=n.indexOf(c,l))!==-1;)o.push([l,l+c.length]),l+=c.length}if(!o.length){t.appendText(e);return}o.sort((c,l)=>c[0]-l[0]);let a=[];for(let c of o){let l=a[a.length-1];l&&c[0]<=l[1]?l[1]=Math.max(l[1],c[1]):a.push([c[0],c[1]])}let r=0;for(let[c,l]of a)c>r&&t.appendText(e.slice(r,c)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(c,l)}),r=l;r<e.length&&t.appendText(e.slice(r))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===U)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==U&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==U?this.tree.get(s.parent):null;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let r of this.notes){if(!r.cross)continue;let c=this.crossFolderIndex.get(r.cross.folder);c||(c=new Map,this.crossFolderIndex.set(r.cross.folder,c)),c.set(r.cross.id,r.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.id.replace(/^cross:/,""),s=e.get(i);if(!s)return"";let n=[],o=new Set([s.id]),a=s.parentId?e.get(s.parentId):null;for(;a&&!o.has(a.id);)o.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 i of e){let s=i.trim();if(s)return s}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===U)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!gt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(gt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",c=>{if(c.key==="["){c.preventDefault();let l=t.selectionStart??t.value.length,g=t.selectionEnd??l,p=t.value.slice(0,l),d=t.value.slice(l,g),I=t.value.slice(g);t.value=`${p}[${d}]${I}`;let u=l+1+d.length;t.setSelectionRange(u,u),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(c.key==="]"){let l=t.selectionStart??-1;l>=0&&t.value[l]==="]"&&(c.preventDefault(),t.setSelectionRange(l+1,l+1));return}if(c.key==="Backspace"&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&t.selectionStart===t.selectionEnd){let l=t.selectionStart??-1;if(l>0&&t.value[l-1]==="["&&t.value[l]==="]"){c.preventDefault();let g=t.value.slice(0,l-1),p=t.value.slice(l+1);t.value=`${g}${p}`,t.setSelectionRange(l-1,l-1),t.dispatchEvent(new Event("input",{bubbles:!0}))}}});let i=document.createElement("div");i.className="stashpad-search-filter-row";let s=document.createElement("span");s.className="stashpad-search-filter-label",s.textContent="Filters:",i.appendChild(s);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",c=>{c.preventDefault()}),n.addEventListener("click",c=>{c.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),n.click())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",c=>{c.preventDefault()}),o.addEventListener("click",c=>{c.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new gt.Scope(this.scope),r=c=>{let l=document.activeElement;return l?.classList?.contains("stashpad-search-filter-chip")?(c.preventDefault(),l.click(),!1):c.key==="Enter"&&!c.isComposing?(c.preventDefault(),this.selectActiveSuggestion?.(c),!1):!0};a.register([],"Enter",r),a.register([]," ",r),a.register(["Mod"],"f",c=>{c.preventDefault();let l=this.inputEl;return l&&(l.focus(),l.select()),!1}),a.register([],"Tab",c=>{let l=this.modalEl,g=this.inputEl;if(!l)return!0;let p=Array.from(l.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1&&u.offsetParent!==null);if(p.length===0)return!0;let d=document.activeElement,I=d?p.indexOf(d):-1;if(c.shiftKey){if(I<=0)return c.preventDefault(),p[p.length-1].focus(),!1}else if(I===p.length-1)return c.preventDefault(),(g??p[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(a),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(a)}catch{}})}appendFilterToInput(t,e,i){let s=t.value,o=`${s.length>0&&!/\s$/.test(s)?" ":""}${e}: [`,a="]",r=i;t.value=`${s}${o}${r}${a}`;let c=s.length+o.length+r.length;if(t.setSelectionRange(c,c+0),!r){let l=s.length+o.length;t.setSelectionRange(l,l)}t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}toggleWhenBuilder(t,e){let i=this.modalEl;if(this.whenBuilderEl){this.whenBuilderEl.remove(),this.whenBuilderEl=null,i?.removeClass("is-when-builder-open");return}i?.addClass("is-when-builder-open");let s=document.createElement("div");s.className="stashpad-when-builder";let n=document.createElement("div");n.className="stashpad-when-tabs";let o=[{id:"before",label:"Before"},{id:"on",label:"On"},{id:"after",label:"After"},{id:"between",label:"Between"}],a={};for(let u of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=u.label,this.whenMode===u.id&&f.addClass("is-active"),f.addEventListener("mousedown",C=>C.preventDefault()),f.addEventListener("click",C=>{if(C.preventDefault(),this.whenMode===u.id)return;let m=this.whenMode;m!=="between"&&u.id==="between"?(this.whenBetweenEndText="",this.whenBetweenEndDate="",this.whenBetweenEndTime=""):m==="between"&&u.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=u.id;for(let E in a)a[E].toggleClass("is-active",E===u.id);I()}),a[u.id]=f,n.appendChild(f)}s.appendChild(n);let r=document.createElement("div");r.className="stashpad-when-body",s.appendChild(r);let c=(u,f,C="single")=>{let m=(0,gt.moment)().format("YYYY-MM-DD"),E=!f||f===m;if(C==="betweenStart")return"00:00";if(C==="betweenEnd")return"23:59";switch(u){case"after":return"00:00";case"on":return E?(0,gt.moment)().format("HH:mm"):"23:59";case"before":return E?(0,gt.moment)().format("HH:mm"):"23:59";default:return"23:59"}},l=(u,f)=>{u.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},g=(u,f)=>{let C=u.selectionStart??u.value.length,m=u.selectionEnd??u.value.length,w=`${C>0&&!/\s$/.test(u.value.slice(0,C))?" ":""}${f}`,y=u.value.slice(0,C)+w+u.value.slice(m);u.value=y;let F=C+w.length;u.setSelectionRange(F,F),u.focus(),u.dispatchEvent(new Event("input",{bubbles:!0}))},p=(u,f)=>{let m=u.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return m?m[1]:null},d=(u,f,C,m)=>{let E=r.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=E.createDiv({cls:"stashpad-when-icon-slot"}),y=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,gt.setIcon)(y,"calendar-days");let F=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});F.tabIndex=-1;let D=E.createDiv({cls:"stashpad-when-icon-slot"}),L=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});L.type="button",L.title="Pick time",(0,gt.setIcon)(L,"clock");let S=E.createDiv({cls:"stashpad-when-icon-slot"}),b=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});b.type="button",b.title="Pick day",(0,gt.setIcon)(b,"calendar");let Q=E.createDiv({cls:"stashpad-when-icon-slot"}),H=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});H.type="button",H.title="Pick timeframe",(0,gt.setIcon)(H,"history");let $=E.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:u}});$.value=f(),$.addEventListener("input",()=>C($.value));let M=E.createEl("button",{cls:"stashpad-when-clear"});M.type="button",M.textContent="\xD7",M.title="Clear";for(let N of[y,L,b,H,M])N.addEventListener("mousedown",_=>_.preventDefault());let T=null,J=(N,_)=>{T&&T();let K=N.createDiv({cls:"stashpad-when-popover"}),z=new gt.Scope(this.scope),ot=null,pt=nt=>{ot=nt},st=!1,at=nt=>{!K.contains(nt.target)&&nt.target!==N&&!N.contains(nt.target)&&At()},At=()=>{if(!st){st=!0,K.remove(),document.removeEventListener("mousedown",at,!0);try{this.app.keymap?.popScope(z)}catch{}T===At&&(T=null)}};T=At,z.register([],"Escape",nt=>(nt.preventDefault(),At(),!1)),z.register([],"Enter",nt=>(nt.preventDefault(),ot&&ot(),!1));try{_(K,At,pt)}catch(nt){console.error("[stashpad] popover fill threw:",nt),K.remove(),T=null;return}this.app.keymap?.pushScope(z),this.pendingCleanups.push(At),setTimeout(()=>document.addEventListener("mousedown",at,!0),0)};H.addEventListener("click",N=>{N.preventDefault(),J(Q,(_,K,z)=>{let ot=this.whenMode==="on",pt=(O,P)=>{if(!ot)return`${O}${P}`;let k={d:"days",w:"weeks",m:"months",y:"years"}[P];return(0,gt.moment)().subtract(O,k).format("YYYY-MM-DD")},st=_.createDiv({cls:"stashpad-when-pop-row"}),at=[{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 O of at){let P=st.createEl("button",{cls:"stashpad-when-pop-chip",text:O.label});P.type="button",P.addEventListener("mousedown",k=>k.preventDefault()),P.addEventListener("click",k=>{k.preventDefault(),g($,pt(O.n,O.unit)),K()})}let At=_.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});At.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let nt=At.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),Qt=At.createEl("select",{cls:"stashpad-when-pop-unit"});for(let O of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let P=Qt.createEl("option",{text:O.label});P.value=O.v}let Ct=At.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});Ct.type="button";let B=()=>{let O=parseInt(nt.value,10);!Number.isFinite(O)||O<1||(g($,pt(O,Qt.value)),K())};Ct.addEventListener("mousedown",O=>O.preventDefault()),Ct.addEventListener("click",O=>{O.preventDefault(),B()}),z(B),nt.focus(),nt.select()})});let Z=(N,_,K,z,ot)=>{J(_,(pt,st,at)=>{hi(pt,{seedH:K,seedM:z,seedPeriod:ot,close:st,setOnEnter:at,onFinalize:At=>g(N,js(At))})})};b.addEventListener("click",N=>{N.preventDefault(),J(S,(_,K,z)=>{let ot=_.createDiv({cls:"stashpad-when-pop-row"});for(let nt of["Today","Yesterday"]){let Qt=ot.createEl("button",{cls:"stashpad-when-pop-chip",text:nt});Qt.type="button",Qt.addEventListener("mousedown",Ct=>Ct.preventDefault()),Qt.addEventListener("click",Ct=>{Ct.preventDefault(),g($,nt),K()})}let pt=_.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),st=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],At=((0,gt.moment)().day()+6)%7;for(let nt=0;nt<st.length;nt++){let Qt=st[nt],Ct=pt.createEl("button",{cls:"stashpad-when-pop-chip",text:Qt.slice(0,3)});Ct.type="button",Ct.title=Qt,nt===At&&Ct.addClass("is-today"),Ct.addEventListener("mousedown",B=>B.preventDefault()),Ct.addEventListener("click",B=>{if(B.preventDefault(),m==="betweenEnd"){let O=nt,P=(0,gt.moment)().startOf("day"),k=(P.day()+6)%7,v=(O-k+7)%7;v===0&&(v=7);let x=P.clone().add(v,"days").format("YYYY-MM-DD");g($,x)}else g($,Qt);K()})}})});let G=(N,_)=>{N.value||(N.value=_);let K=N;if(typeof K.showPicker=="function")try{K.showPicker();return}catch{}N.focus(),N.click()};return y.addEventListener("click",N=>{N.preventDefault(),G(F,(0,gt.moment)().format("YYYY-MM-DD"))}),F.addEventListener("change",()=>{F.value&&g($,F.value)}),L.addEventListener("click",N=>{N.preventDefault();let _=$.selectionStart??$.value.length,K=p($.value,_),z=c(this.whenMode,K,m),[ot,pt]=z.split(":"),st=parseInt(ot,10),at=parseInt(pt,10),At=st%12;At===0&&(At=12);let nt=st>=12?"pm":"am";Z($,D,At,at,nt)}),M.addEventListener("click",N=>{N.preventDefault(),$.value="",C(""),$.focus()}),$},I=()=>{if(r.empty(),this.whenMode==="between"){let u=d("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=d("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),C=r.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",y=>y.preventDefault());let E=()=>{let y=u.value.trim(),F=f.value.trim();y&&this.appendFilterToInput(t,"after",y),F&&this.appendFilterToInput(t,"before",F),this.closeWhenBuilder()};m.addEventListener("click",y=>{y.preventDefault(),E()});let w=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),l(u,E),l(f,E),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}else{let u=d("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),f=r.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",w=>w.preventDefault());let m=()=>{let w=u.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};C.addEventListener("click",w=>{w.preventDefault(),m()});let E=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});E.type="button",E.addEventListener("mousedown",w=>w.preventDefault()),E.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),l(u,m),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}};I(),e.parentElement?.insertBefore(s,e.nextSibling),this.whenBuilderEl=s}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}selectSuggestion(t,e){if(t&&t.kind==="search-excluded"){this.loadExcludedNotes();return}super.selectSuggestion(t,e)}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 i=this.inputEl?.value??"",s=!1,n=p=>{s=!0;let d=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${d}\u201D in a new tab`,node:null,kind:"folder-open",folder:p})},o=new ys(this.app,e,n),a=o.onClose.bind(o),r=this.tree,c=this.titleFn,l=this.opts,g=this.app;o.onClose=()=>{if(a(),!s){let p=new h(g,r,c,l);p.open(),setTimeout(()=>{let d=p.inputEl;d&&(i&&(d.value=i,d.dispatchEvent(new Event("input",{bubbles:!0}))),d.focus(),d.setSelectionRange(d.value.length,d.value.length))},0)}},o.open();return}this.opts.onPick(t)}},ys=class extends gt.FuzzySuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onChosen=i;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)}};var mn=require("obsidian");wt();var Ri=class extends mn.SuggestModal{constructor(A){super(A),this.setPlaceholder("Run a Stashpad command\u2026");let t=this.app.commands?.commands??{};this.commands=Object.keys(t).filter(e=>e.startsWith("stashpad:")).filter(e=>e!=="stashpad:stashpad-command-palette").map(e=>({id:e,name:Mo(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(A){return this.commands.filter(t=>li(A,t.name))}renderSuggestion(A,t){t.createDiv({text:A.name,cls:"stashpad-cmd-palette-name"})}onChooseSuggestion(A){this.app.commands?.executeCommandById?.(A.id)}};function Mo(h){return h.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||h}Mt();var ws=require("obsidian");function Ho(h,A){return!A||h.metaKey||h.ctrlKey||h.altKey?!1:h.key.toLowerCase()===A.toLowerCase()}function ke(h,A){return A?A.includes("+")?To(h,A):Ho(h,A):!1}function rt(h,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?ke(h,t)||ke(h,e):i?ke(h,e):ke(h,t):ke(h,t)||ke(h,e)}function ei(h){if(!h)return"";let A=ws.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return h.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function To(h,A){if(!A)return!1;let t=A.split("+").map(g=>g.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(g=>g.toLowerCase())),s=i.has("mod"),n=i.has("ctrl")||i.has("control"),o=i.has("cmd")||i.has("meta")||i.has("command"),a=i.has("alt")||i.has("option"),r=i.has("shift"),l=ws.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?h.metaKey:h.ctrlKey;return s&&!l||n&&!h.ctrlKey||o&&!h.metaKey||a!==h.altKey||r!==h.shiftKey||!s&&(!n&&h.ctrlKey||!o&&h.metaKey)?!1:h.key.toLowerCase()===e}var ge=require("obsidian");Mt();var Ht=class Ht{constructor(A){this.host=A;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let A of this.contribTimers.values())clearTimeout(A);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let A=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!A||!t)return null;let e=A.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=A.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:A,id:t}}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 A=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==A&&!e.startsWith(A+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(A,t){for(let s=0;s<A.length;s++){let n=this.host.app.vault.getAbstractFileByPath(A[s]);if(n instanceof ge.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,A[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",A[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(A){let t=this.currentAuthorLink();if(!t){new ge.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=A.scope==="selection"?this.host.getActionTargets().map(p=>p.file).filter(p=>!!p):this.fileBackedNotesInFolder();if(i.length===0){new ge.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let d=this.host.app.metadataCache.getFileCache(p)?.frontmatter,I=typeof d?.author=="string"?d.author:"";if(!I.trim()){s.push(p.path);continue}if(I.includes(e)||!A.contributorMode)continue;(Array.isArray(d?.contributors)?d.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(p.path)}let o=s.length+n.length;if(o===0){new ge.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(A.scope==="folder"){let p=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&p.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(I=>{new vt(this.host.app,"Claim authorship",`${p.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",I).open()}))return}let a=this.host.noteFolder,r=t.link,c=new Set,l=async()=>{await this.pacedFrontmatter(s,(p,d)=>{typeof p.author=="string"&&p.author.trim()||(p.author=r),Array.isArray(p.contributors)&&p.contributors.some(I=>typeof I=="string"&&I.includes(e))&&(p.contributors=p.contributors.filter(I=>!(typeof I=="string"&&I.includes(e))),c.add(d))}),await this.pacedFrontmatter(n,p=>{let d=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];d.some(I=>I.includes(e))||d.push(r),p.contributors=d})};this.ensureAuthorFile(t),await l(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(p,d)=>{if(typeof p.author=="string"&&p.author.includes(e)&&delete p.author,c.has(d)){let I=Array.isArray(p.contributors)?p.contributors.filter(u=>typeof u=="string"):[];I.some(u=>u.includes(e))||I.push(r),p.contributors=I}}),await this.pacedFrontmatter(n,p=>{Array.isArray(p.contributors)&&(p.contributors=p.contributors.filter(d=>!(typeof d=="string"&&d.includes(e))))}),this.host.debouncedRender()},redo:async()=>{c.clear(),await l(),this.host.debouncedRender()}});let g=[];s.length&&g.push(`authored ${s.length}`),n.length&&g.push(`contributing to ${n.length}`),new ge.Notice(`Claimed authorship: ${g.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(A){try{A.id&&this.host.plugin.authorRegistry.record({id:A.id,name:A.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(A.path))return;let e=A.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:A.id,name:A.name,role:e?this.host.plugin.settings.authorRole:void 0,department:e?this.host.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.host.app.vault.create(A.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(A){let t=new Set,e=i=>{if(typeof i!="string")return null;let s=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return s?s[1]:null};for(let i of A){if(!i.file)continue;let s=this.host.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!s)continue;let n=e(s.author);if(n&&t.add(n),Array.isArray(s.contributors))for(let o of s.contributors){let a=e(o);a&&t.add(a)}}return Array.from(t)}pruneContribMaps(){let A=Date.now(),t=Ht.EXTERNAL_WRITE_GRACE_MS*20,e=Ht.EXTERNAL_QUIESCENCE_MS*12;for(let[i,s]of this.recentSelfWrites)A-s>t&&this.recentSelfWrites.delete(i);for(let[i,s]of this.lastExternalModify)A-s>e&&this.lastExternalModify.delete(i);if(this.knownBodies.size>64)for(let i of this.knownBodies.keys())this.host.tree.idForPath(i)||this.knownBodies.delete(i)}noteModify(A){let t=Date.now(),e=this.recentSelfWrites.get(A.path);e!==void 0&&t-e<Ht.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(A.path,t),this.scheduleContribution(A)}scheduleContribution(A){let t=this.contribTimers.get(A.path);t&&clearTimeout(t);let e=this.isFileActivelyEdited(A),i=Ht.CONTRIB_DEBOUNCE_MS+(e?Ht.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),s=setTimeout(()=>{if(this.contribTimers.delete(A.path),this.isFileActivelyEdited(A)){this.scheduleContribution(A);return}let n=this.lastExternalModify.get(A.path);if(n!==void 0&&Date.now()-n<Ht.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(A);return}this.maybeRecordContribution(A)},i);this.contribTimers.set(A.path,s)}isFileActivelyEdited(A){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==A.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(A){let t="";try{t=await this.host.app.vault.cachedRead(A)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(A.path);if(this.knownBodies.set(A.path,e),i===void 0||i===e||this.host.plugin.rebootstrapInProgress)return;let s=this.currentAuthorLink();if(!s)return;this.ensureAuthorFile(s);let n=new Date().toISOString();this.recentSelfWrites.set(A.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(A,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],c=`-${s.id}`,l=a.includes(c),g=r.some(p=>p.includes(c));!l&&!g&&r.push(s.link),o.contributors=r})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Ht.CONTRIB_DEBOUNCE_MS=4e3,Ht.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Ht.EXTERNAL_WRITE_GRACE_MS=1500,Ht.EXTERNAL_QUIESCENCE_MS=5e3;var Pi=Ht;var Li=class{constructor(A){this.host=A;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(A,t,e){A.addEventListener("dragstart",i=>{let s=this.host.selection.has(t.id)&&this.host.selection.size>1?[...this.host.selection]:[t.id];if(this.dragSourceIds=s,this.dragRowHeight=A.offsetHeight,A.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.style.height="0px",this.dragPlaceholder.addEventListener("dragover",n=>{this.dragSourceIds&&(n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect="move"))}),this.dragPlaceholder.addEventListener("drop",n=>{if(!this.dragSourceIds||!this.dragPlaceholder)return;n.preventDefault(),n.stopPropagation();let o=this.dragSourceIds.slice();this.dragSourceIds=null;let a=this.dragPlaceholder.nextElementSibling,r=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let c,l="before";a&&a.classList.contains("stashpad-note")?(c=a.dataset.id,l="before"):r&&r.classList.contains("stashpad-note")&&(c=r.dataset.id,l="after"),c&&this.host.reorderToTarget(o,c,l)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(A,12,12)}catch{}}}),A.addEventListener("dragend",()=>{A.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),A.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,A);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),A.addClass("drop-into")):(A.removeClass("drop-into"),this.placePlaceholder(A,s==="drop-above"?"before":"after"))}),A.addEventListener("dragleave",i=>{let s=A.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&A.removeClass("drop-into")}),A.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,A);this.clearDropIndicators(),this.removeDragPlaceholder(),A.removeClass("is-dragging"),n==="drop-into"?this.host.reorderToTarget(s,t.id,"into"):this.host.reorderToTarget(s,t.id,n==="drop-above"?"before":"after")})}attachListDnD(A){A.addEventListener("dragover",t=>{if(!this.dragSourceIds)return;let e=t.target;if(e&&e.closest&&e.closest(".stashpad-note"))return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move");let i=Array.from(A.querySelectorAll(".stashpad-note"));if(i.length!==0){for(let s of i){let n=s.getBoundingClientRect();if(t.clientY<n.top+n.height/2){this.placePlaceholder(s,"before");return}}this.placePlaceholder(i[i.length-1],"after")}}),A.addEventListener("drop",t=>{if(!this.dragSourceIds)return;t.preventDefault();let e=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let i=this.dragPlaceholder.nextElementSibling,s=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),i&&i.classList.contains("stashpad-note")){let n=i.dataset.id;n&&this.host.reorderToTarget(e,n,"before")}else if(s&&s.classList.contains("stashpad-note")){let n=s.dataset.id;n&&this.host.reorderToTarget(e,n,"after")}})}placePlaceholder(A,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?A:A.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===A||t==="after"&&this.dragPlaceholder.previousSibling===A)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),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 A=this.dragPlaceholder;A.style.height="0px",A.style.opacity="0",setTimeout(()=>{A.parentElement&&A.remove()},150)}dropZone(A,t){let e=t.getBoundingClientRect(),i=A.clientY-e.top;return i<e.height*.3?"drop-above":i>e.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.host.listEl)for(let A of Array.from(this.host.listEl.querySelectorAll(".drop-into")))A.removeClass("drop-into")}};var Qn=require("obsidian");var Ji=class{constructor(A,t,e){this.host=A;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(A){let t=this.renderCache.get(A.path);if(t&&t.mtime===A.stat.mtime)return St.record("render.row.cacheHit",0),t;let e=await St.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(A)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await St.timeAsync("render.row.markdown",()=>Qn.MarkdownRenderer.render(this.host.app,s,o,A.path,this.component));let a=o.innerHTML,r={mtime:A.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(A.path,r),r}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(A=>{for(let t of A){if(!t.isIntersecting)continue;let e=t.target,i=this.lazyBodies.get(e);this.bodyObserver?.unobserve(e),this.lazyBodies.delete(e),i&&i()}},{root:this.host.contentEl,rootMargin:"1400px 0px"})}dispose(){this.bodyObserver?.disconnect(),this.bodyObserver=null}isArmed(){return!!this.bodyObserver}hasFreshRenderCache(A){let t=this.renderCache.get(A.path);return!!t&&t.mtime===A.stat.mtime}defer(A,t){this.lazyBodies.set(A,t),this.bodyObserver?.observe(A)}splitAttachments(A){let t=[];return{text:A.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` +`)}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}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let d=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),I=d.createSpan({cls:"stashpad-search-excluded-icon"});(0,gt.setIcon)(I,"folder-search"),d.createSpan({text:t.label}),e.createDiv({cls:"stashpad-suggest-preview",text:"Include folders you've excluded from search (e.g. to move a note there)."});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let i=e.createDiv({cls:"stashpad-suggest-body"}),s=this.notes.find(d=>t.crossFolder?d.cross?.id===t.id.replace(/^cross:/,""):d.node?.id===t.id),n=Bn(this.inputEl?.value??"").text,o=this.firstLineOfBody(s?.body??"")||t.label.trim(),a=i.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(a,o,n);let r=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let d=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(d,t.bodyPreview,n)}let l="";if(t.crossFolder?l=s?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let d=i.createDiv({cls:"stashpad-suggest-preview"});d.appendText("Parent: "),this.highlightInto(d,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),g=t.crossFolder??this.opts.localFolder??null;if(g||c){let d=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[g?g.split("/").pop()||g:"",c].filter(f=>f&&f.length>0).join(" \u203A ");u&&d.setText(u)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let d=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let I=d.createDiv({cls:"stashpad-suggest-time"});I.setText(this.formatRelativeTime(p)),I.title=(0,gt.moment)(p).format("YYYY-MM-DD HH:mm")}r&&d.createDiv({cls:"stashpad-suggest-folder-badge",text:r.split("/").pop()||r})}}formatRelativeTime(t){let e=(0,gt.moment)(t),i=(0,gt.moment)().startOf("day").diff((0,gt.moment)(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(l=>l&&l.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let l of s){let c=0;for(;(c=n.indexOf(l,c))!==-1;)o.push([c,c+l.length]),c+=l.length}if(!o.length){t.appendText(e);return}o.sort((l,c)=>l[0]-c[0]);let a=[];for(let l of o){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 r=0;for(let[l,c]of a)l>r&&t.appendText(e.slice(r,l)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(l,c)}),r=c;r<e.length&&t.appendText(e.slice(r))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===U)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==U&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==U?this.tree.get(s.parent):null;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let r of this.notes){if(!r.cross)continue;let l=this.crossFolderIndex.get(r.cross.folder);l||(l=new Map,this.crossFolderIndex.set(r.cross.folder,l)),l.set(r.cross.id,r.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.id.replace(/^cross:/,""),s=e.get(i);if(!s)return"";let n=[],o=new Set([s.id]),a=s.parentId?e.get(s.parentId):null;for(;a&&!o.has(a.id);)o.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 i of e){let s=i.trim();if(s)return s}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===U)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!gt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(gt.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,g=t.selectionEnd??c,p=t.value.slice(0,c),d=t.value.slice(c,g),I=t.value.slice(g);t.value=`${p}[${d}]${I}`;let u=c+1+d.length;t.setSelectionRange(u,u),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 g=t.value.slice(0,c-1),p=t.value.slice(c+1);t.value=`${g}${p}`,t.setSelectionRange(c-1,c-1),t.dispatchEvent(new Event("input",{bubbles:!0}))}}});let i=document.createElement("div");i.className="stashpad-search-filter-row";let s=document.createElement("span");s.className="stashpad-search-filter-label",s.textContent="Filters:",i.appendChild(s);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())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",l=>{l.preventDefault()}),o.addEventListener("click",l=>{l.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new gt.Scope(this.scope),r=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",r),a.register([]," ",r),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,g=this.inputEl;if(!c)return!0;let p=Array.from(c.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1&&u.offsetParent!==null);if(p.length===0)return!0;let d=document.activeElement,I=d?p.indexOf(d):-1;if(l.shiftKey){if(I<=0)return l.preventDefault(),p[p.length-1].focus(),!1}else if(I===p.length-1)return l.preventDefault(),(g??p[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(a),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(a)}catch{}})}appendFilterToInput(t,e,i){let s=t.value,o=`${s.length>0&&!/\s$/.test(s)?" ":""}${e}: [`,a="]",r=i;t.value=`${s}${o}${r}${a}`;let l=s.length+o.length+r.length;if(t.setSelectionRange(l,l+0),!r){let c=s.length+o.length;t.setSelectionRange(c,c)}t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}toggleWhenBuilder(t,e){let i=this.modalEl;if(this.whenBuilderEl){this.whenBuilderEl.remove(),this.whenBuilderEl=null,i?.removeClass("is-when-builder-open");return}i?.addClass("is-when-builder-open");let s=document.createElement("div");s.className="stashpad-when-builder";let n=document.createElement("div");n.className="stashpad-when-tabs";let o=[{id:"before",label:"Before"},{id:"on",label:"On"},{id:"after",label:"After"},{id:"between",label:"Between"}],a={};for(let u of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=u.label,this.whenMode===u.id&&f.addClass("is-active"),f.addEventListener("mousedown",C=>C.preventDefault()),f.addEventListener("click",C=>{if(C.preventDefault(),this.whenMode===u.id)return;let m=this.whenMode;m!=="between"&&u.id==="between"?(this.whenBetweenEndText="",this.whenBetweenEndDate="",this.whenBetweenEndTime=""):m==="between"&&u.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=u.id;for(let E in a)a[E].toggleClass("is-active",E===u.id);I()}),a[u.id]=f,n.appendChild(f)}s.appendChild(n);let r=document.createElement("div");r.className="stashpad-when-body",s.appendChild(r);let l=(u,f,C="single")=>{let m=(0,gt.moment)().format("YYYY-MM-DD"),E=!f||f===m;if(C==="betweenStart")return"00:00";if(C==="betweenEnd")return"23:59";switch(u){case"after":return"00:00";case"on":return E?(0,gt.moment)().format("HH:mm"):"23:59";case"before":return E?(0,gt.moment)().format("HH:mm"):"23:59";default:return"23:59"}},c=(u,f)=>{u.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},g=(u,f)=>{let C=u.selectionStart??u.value.length,m=u.selectionEnd??u.value.length,w=`${C>0&&!/\s$/.test(u.value.slice(0,C))?" ":""}${f}`,y=u.value.slice(0,C)+w+u.value.slice(m);u.value=y;let F=C+w.length;u.setSelectionRange(F,F),u.focus(),u.dispatchEvent(new Event("input",{bubbles:!0}))},p=(u,f)=>{let m=u.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return m?m[1]:null},d=(u,f,C,m)=>{let E=r.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=E.createDiv({cls:"stashpad-when-icon-slot"}),y=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,gt.setIcon)(y,"calendar-days");let F=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});F.tabIndex=-1;let D=E.createDiv({cls:"stashpad-when-icon-slot"}),L=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});L.type="button",L.title="Pick time",(0,gt.setIcon)(L,"clock");let S=E.createDiv({cls:"stashpad-when-icon-slot"}),b=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});b.type="button",b.title="Pick day",(0,gt.setIcon)(b,"calendar");let Q=E.createDiv({cls:"stashpad-when-icon-slot"}),H=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});H.type="button",H.title="Pick timeframe",(0,gt.setIcon)(H,"history");let $=E.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:u}});$.value=f(),$.addEventListener("input",()=>C($.value));let M=E.createEl("button",{cls:"stashpad-when-clear"});M.type="button",M.textContent="\xD7",M.title="Clear";for(let N of[y,L,b,H,M])N.addEventListener("mousedown",_=>_.preventDefault());let T=null,J=(N,_)=>{T&&T();let K=N.createDiv({cls:"stashpad-when-popover"}),z=new gt.Scope(this.scope),ot=null,pt=nt=>{ot=nt},st=!1,at=nt=>{!K.contains(nt.target)&&nt.target!==N&&!N.contains(nt.target)&&At()},At=()=>{if(!st){st=!0,K.remove(),document.removeEventListener("mousedown",at,!0);try{this.app.keymap?.popScope(z)}catch{}T===At&&(T=null)}};T=At,z.register([],"Escape",nt=>(nt.preventDefault(),At(),!1)),z.register([],"Enter",nt=>(nt.preventDefault(),ot&&ot(),!1));try{_(K,At,pt)}catch(nt){console.error("[stashpad] popover fill threw:",nt),K.remove(),T=null;return}this.app.keymap?.pushScope(z),this.pendingCleanups.push(At),setTimeout(()=>document.addEventListener("mousedown",at,!0),0)};H.addEventListener("click",N=>{N.preventDefault(),J(Q,(_,K,z)=>{let ot=this.whenMode==="on",pt=(O,P)=>{if(!ot)return`${O}${P}`;let k={d:"days",w:"weeks",m:"months",y:"years"}[P];return(0,gt.moment)().subtract(O,k).format("YYYY-MM-DD")},st=_.createDiv({cls:"stashpad-when-pop-row"}),at=[{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 O of at){let P=st.createEl("button",{cls:"stashpad-when-pop-chip",text:O.label});P.type="button",P.addEventListener("mousedown",k=>k.preventDefault()),P.addEventListener("click",k=>{k.preventDefault(),g($,pt(O.n,O.unit)),K()})}let At=_.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});At.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let nt=At.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),Qt=At.createEl("select",{cls:"stashpad-when-pop-unit"});for(let O of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let P=Qt.createEl("option",{text:O.label});P.value=O.v}let Ct=At.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});Ct.type="button";let B=()=>{let O=parseInt(nt.value,10);!Number.isFinite(O)||O<1||(g($,pt(O,Qt.value)),K())};Ct.addEventListener("mousedown",O=>O.preventDefault()),Ct.addEventListener("click",O=>{O.preventDefault(),B()}),z(B),nt.focus(),nt.select()})});let Z=(N,_,K,z,ot)=>{J(_,(pt,st,at)=>{hi(pt,{seedH:K,seedM:z,seedPeriod:ot,close:st,setOnEnter:at,onFinalize:At=>g(N,js(At))})})};b.addEventListener("click",N=>{N.preventDefault(),J(S,(_,K,z)=>{let ot=_.createDiv({cls:"stashpad-when-pop-row"});for(let nt of["Today","Yesterday"]){let Qt=ot.createEl("button",{cls:"stashpad-when-pop-chip",text:nt});Qt.type="button",Qt.addEventListener("mousedown",Ct=>Ct.preventDefault()),Qt.addEventListener("click",Ct=>{Ct.preventDefault(),g($,nt),K()})}let pt=_.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),st=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],At=((0,gt.moment)().day()+6)%7;for(let nt=0;nt<st.length;nt++){let Qt=st[nt],Ct=pt.createEl("button",{cls:"stashpad-when-pop-chip",text:Qt.slice(0,3)});Ct.type="button",Ct.title=Qt,nt===At&&Ct.addClass("is-today"),Ct.addEventListener("mousedown",B=>B.preventDefault()),Ct.addEventListener("click",B=>{if(B.preventDefault(),m==="betweenEnd"){let O=nt,P=(0,gt.moment)().startOf("day"),k=(P.day()+6)%7,v=(O-k+7)%7;v===0&&(v=7);let x=P.clone().add(v,"days").format("YYYY-MM-DD");g($,x)}else g($,Qt);K()})}})});let G=(N,_)=>{N.value||(N.value=_);let K=N;if(typeof K.showPicker=="function")try{K.showPicker();return}catch{}N.focus(),N.click()};return y.addEventListener("click",N=>{N.preventDefault(),G(F,(0,gt.moment)().format("YYYY-MM-DD"))}),F.addEventListener("change",()=>{F.value&&g($,F.value)}),L.addEventListener("click",N=>{N.preventDefault();let _=$.selectionStart??$.value.length,K=p($.value,_),z=l(this.whenMode,K,m),[ot,pt]=z.split(":"),st=parseInt(ot,10),at=parseInt(pt,10),At=st%12;At===0&&(At=12);let nt=st>=12?"pm":"am";Z($,D,At,at,nt)}),M.addEventListener("click",N=>{N.preventDefault(),$.value="",C(""),$.focus()}),$},I=()=>{if(r.empty(),this.whenMode==="between"){let u=d("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=d("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),C=r.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",y=>y.preventDefault());let E=()=>{let y=u.value.trim(),F=f.value.trim();y&&this.appendFilterToInput(t,"after",y),F&&this.appendFilterToInput(t,"before",F),this.closeWhenBuilder()};m.addEventListener("click",y=>{y.preventDefault(),E()});let w=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),c(u,E),c(f,E),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}else{let u=d("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),f=r.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",w=>w.preventDefault());let m=()=>{let w=u.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};C.addEventListener("click",w=>{w.preventDefault(),m()});let E=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});E.type="button",E.addEventListener("mousedown",w=>w.preventDefault()),E.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),c(u,m),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}};I(),e.parentElement?.insertBefore(s,e.nextSibling),this.whenBuilderEl=s}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}selectSuggestion(t,e){if(t&&t.kind==="search-excluded"){this.loadExcludedNotes();return}super.selectSuggestion(t,e)}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 i=this.inputEl?.value??"",s=!1,n=p=>{s=!0;let d=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${d}\u201D in a new tab`,node:null,kind:"folder-open",folder:p})},o=new ys(this.app,e,n),a=o.onClose.bind(o),r=this.tree,l=this.titleFn,c=this.opts,g=this.app;o.onClose=()=>{if(a(),!s){let p=new h(g,r,l,c);p.open(),setTimeout(()=>{let d=p.inputEl;d&&(i&&(d.value=i,d.dispatchEvent(new Event("input",{bubbles:!0}))),d.focus(),d.setSelectionRange(d.value.length,d.value.length))},0)}},o.open();return}this.opts.onPick(t)}},ys=class extends gt.FuzzySuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onChosen=i;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)}};var mn=require("obsidian");wt();var Ri=class extends mn.SuggestModal{constructor(A){super(A),this.setPlaceholder("Run a Stashpad command\u2026");let t=this.app.commands?.commands??{};this.commands=Object.keys(t).filter(e=>e.startsWith("stashpad:")).filter(e=>e!=="stashpad:stashpad-command-palette").map(e=>({id:e,name:Ho(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(A){return this.commands.filter(t=>ci(A,t.name))}renderSuggestion(A,t){t.createDiv({text:A.name,cls:"stashpad-cmd-palette-name"})}onChooseSuggestion(A){this.app.commands?.executeCommandById?.(A.id)}};function Ho(h){return h.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||h}Mt();var ws=require("obsidian");function To(h,A){return!A||h.metaKey||h.ctrlKey||h.altKey?!1:h.key.toLowerCase()===A.toLowerCase()}function ke(h,A){return A?A.includes("+")?Uo(h,A):To(h,A):!1}function rt(h,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?ke(h,t)||ke(h,e):i?ke(h,e):ke(h,t):ke(h,t)||ke(h,e)}function ei(h){if(!h)return"";let A=ws.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return h.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function Uo(h,A){if(!A)return!1;let t=A.split("+").map(g=>g.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(g=>g.toLowerCase())),s=i.has("mod"),n=i.has("ctrl")||i.has("control"),o=i.has("cmd")||i.has("meta")||i.has("command"),a=i.has("alt")||i.has("option"),r=i.has("shift"),c=ws.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?h.metaKey:h.ctrlKey;return s&&!c||n&&!h.ctrlKey||o&&!h.metaKey||a!==h.altKey||r!==h.shiftKey||!s&&(!n&&h.ctrlKey||!o&&h.metaKey)?!1:h.key.toLowerCase()===e}var ge=require("obsidian");Mt();var Ht=class Ht{constructor(A){this.host=A;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let A of this.contribTimers.values())clearTimeout(A);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let A=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!A||!t)return null;let e=A.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=A.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:A,id:t}}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 A=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==A&&!e.startsWith(A+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(A,t){for(let s=0;s<A.length;s++){let n=this.host.app.vault.getAbstractFileByPath(A[s]);if(n instanceof ge.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,A[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",A[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(A){let t=this.currentAuthorLink();if(!t){new ge.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=A.scope==="selection"?this.host.getActionTargets().map(p=>p.file).filter(p=>!!p):this.fileBackedNotesInFolder();if(i.length===0){new ge.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let d=this.host.app.metadataCache.getFileCache(p)?.frontmatter,I=typeof d?.author=="string"?d.author:"";if(!I.trim()){s.push(p.path);continue}if(I.includes(e)||!A.contributorMode)continue;(Array.isArray(d?.contributors)?d.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(p.path)}let o=s.length+n.length;if(o===0){new ge.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(A.scope==="folder"){let p=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&p.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(I=>{new vt(this.host.app,"Claim authorship",`${p.join(" ")}? +Existing authors are never overwritten. This can be undone.`,"Claim",I).open()}))return}let a=this.host.noteFolder,r=t.link,l=new Set,c=async()=>{await this.pacedFrontmatter(s,(p,d)=>{typeof p.author=="string"&&p.author.trim()||(p.author=r),Array.isArray(p.contributors)&&p.contributors.some(I=>typeof I=="string"&&I.includes(e))&&(p.contributors=p.contributors.filter(I=>!(typeof I=="string"&&I.includes(e))),l.add(d))}),await this.pacedFrontmatter(n,p=>{let d=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];d.some(I=>I.includes(e))||d.push(r),p.contributors=d})};this.ensureAuthorFile(t),await c(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(p,d)=>{if(typeof p.author=="string"&&p.author.includes(e)&&delete p.author,l.has(d)){let I=Array.isArray(p.contributors)?p.contributors.filter(u=>typeof u=="string"):[];I.some(u=>u.includes(e))||I.push(r),p.contributors=I}}),await this.pacedFrontmatter(n,p=>{Array.isArray(p.contributors)&&(p.contributors=p.contributors.filter(d=>!(typeof d=="string"&&d.includes(e))))}),this.host.debouncedRender()},redo:async()=>{l.clear(),await c(),this.host.debouncedRender()}});let g=[];s.length&&g.push(`authored ${s.length}`),n.length&&g.push(`contributing to ${n.length}`),new ge.Notice(`Claimed authorship: ${g.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(A){try{A.id&&this.host.plugin.authorRegistry.record({id:A.id,name:A.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(A.path))return;let e=A.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:A.id,name:A.name,role:e?this.host.plugin.settings.authorRole:void 0,department:e?this.host.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.host.app.vault.create(A.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(A){let t=new Set,e=i=>{if(typeof i!="string")return null;let s=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return s?s[1]:null};for(let i of A){if(!i.file)continue;let s=this.host.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!s)continue;let n=e(s.author);if(n&&t.add(n),Array.isArray(s.contributors))for(let o of s.contributors){let a=e(o);a&&t.add(a)}}return Array.from(t)}pruneContribMaps(){let A=Date.now(),t=Ht.EXTERNAL_WRITE_GRACE_MS*20,e=Ht.EXTERNAL_QUIESCENCE_MS*12;for(let[i,s]of this.recentSelfWrites)A-s>t&&this.recentSelfWrites.delete(i);for(let[i,s]of this.lastExternalModify)A-s>e&&this.lastExternalModify.delete(i);if(this.knownBodies.size>64)for(let i of this.knownBodies.keys())this.host.tree.idForPath(i)||this.knownBodies.delete(i)}noteModify(A){let t=Date.now(),e=this.recentSelfWrites.get(A.path);e!==void 0&&t-e<Ht.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(A.path,t),this.scheduleContribution(A)}scheduleContribution(A){let t=this.contribTimers.get(A.path);t&&clearTimeout(t);let e=this.isFileActivelyEdited(A),i=Ht.CONTRIB_DEBOUNCE_MS+(e?Ht.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),s=setTimeout(()=>{if(this.contribTimers.delete(A.path),this.isFileActivelyEdited(A)){this.scheduleContribution(A);return}let n=this.lastExternalModify.get(A.path);if(n!==void 0&&Date.now()-n<Ht.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(A);return}this.maybeRecordContribution(A)},i);this.contribTimers.set(A.path,s)}isFileActivelyEdited(A){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==A.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(A){let t="";try{t=await this.host.app.vault.cachedRead(A)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(A.path);if(this.knownBodies.set(A.path,e),i===void 0||i===e||this.host.plugin.rebootstrapInProgress)return;let s=this.currentAuthorLink();if(!s)return;this.ensureAuthorFile(s);let n=new Date().toISOString();this.recentSelfWrites.set(A.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(A,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],l=`-${s.id}`,c=a.includes(l),g=r.some(p=>p.includes(l));!c&&!g&&r.push(s.link),o.contributors=r})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Ht.CONTRIB_DEBOUNCE_MS=4e3,Ht.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Ht.EXTERNAL_WRITE_GRACE_MS=1500,Ht.EXTERNAL_QUIESCENCE_MS=5e3;var Pi=Ht;var Li=class{constructor(A){this.host=A;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(A,t,e){A.addEventListener("dragstart",i=>{let s=this.host.selection.has(t.id)&&this.host.selection.size>1?[...this.host.selection]:[t.id];if(this.dragSourceIds=s,this.dragRowHeight=A.offsetHeight,A.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.style.height="0px",this.dragPlaceholder.addEventListener("dragover",n=>{this.dragSourceIds&&(n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect="move"))}),this.dragPlaceholder.addEventListener("drop",n=>{if(!this.dragSourceIds||!this.dragPlaceholder)return;n.preventDefault(),n.stopPropagation();let o=this.dragSourceIds.slice();this.dragSourceIds=null;let a=this.dragPlaceholder.nextElementSibling,r=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let l,c="before";a&&a.classList.contains("stashpad-note")?(l=a.dataset.id,c="before"):r&&r.classList.contains("stashpad-note")&&(l=r.dataset.id,c="after"),l&&this.host.reorderToTarget(o,l,c)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(A,12,12)}catch{}}}),A.addEventListener("dragend",()=>{A.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),A.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,A);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),A.addClass("drop-into")):(A.removeClass("drop-into"),this.placePlaceholder(A,s==="drop-above"?"before":"after"))}),A.addEventListener("dragleave",i=>{let s=A.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&A.removeClass("drop-into")}),A.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,A);this.clearDropIndicators(),this.removeDragPlaceholder(),A.removeClass("is-dragging"),n==="drop-into"?this.host.reorderToTarget(s,t.id,"into"):this.host.reorderToTarget(s,t.id,n==="drop-above"?"before":"after")})}attachListDnD(A){A.addEventListener("dragover",t=>{if(!this.dragSourceIds)return;let e=t.target;if(e&&e.closest&&e.closest(".stashpad-note"))return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move");let i=Array.from(A.querySelectorAll(".stashpad-note"));if(i.length!==0){for(let s of i){let n=s.getBoundingClientRect();if(t.clientY<n.top+n.height/2){this.placePlaceholder(s,"before");return}}this.placePlaceholder(i[i.length-1],"after")}}),A.addEventListener("drop",t=>{if(!this.dragSourceIds)return;t.preventDefault();let e=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let i=this.dragPlaceholder.nextElementSibling,s=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),i&&i.classList.contains("stashpad-note")){let n=i.dataset.id;n&&this.host.reorderToTarget(e,n,"before")}else if(s&&s.classList.contains("stashpad-note")){let n=s.dataset.id;n&&this.host.reorderToTarget(e,n,"after")}})}placePlaceholder(A,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?A:A.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===A||t==="after"&&this.dragPlaceholder.previousSibling===A)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),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 A=this.dragPlaceholder;A.style.height="0px",A.style.opacity="0",setTimeout(()=>{A.parentElement&&A.remove()},150)}dropZone(A,t){let e=t.getBoundingClientRect(),i=A.clientY-e.top;return i<e.height*.3?"drop-above":i>e.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.host.listEl)for(let A of Array.from(this.host.listEl.querySelectorAll(".drop-into")))A.removeClass("drop-into")}};var Qn=require("obsidian");var Ji=class{constructor(A,t,e){this.host=A;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(A){let t=this.renderCache.get(A.path);if(t&&t.mtime===A.stat.mtime)return St.record("render.row.cacheHit",0),t;let e=await St.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(A)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await St.timeAsync("render.row.markdown",()=>Qn.MarkdownRenderer.render(this.host.app,s,o,A.path,this.component));let a=o.innerHTML,r={mtime:A.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(A.path,r),r}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(A=>{for(let t of A){if(!t.isIntersecting)continue;let e=t.target,i=this.lazyBodies.get(e);this.bodyObserver?.unobserve(e),this.lazyBodies.delete(e),i&&i()}},{root:this.host.contentEl,rootMargin:"1400px 0px"})}dispose(){this.bodyObserver?.disconnect(),this.bodyObserver=null}isArmed(){return!!this.bodyObserver}hasFreshRenderCache(A){let t=this.renderCache.get(A.path);return!!t&&t.mtime===A.stat.mtime}defer(A,t){this.lazyBodies.set(A,t),this.bodyObserver?.observe(A)}splitAttachments(A){let t=[];return{text:A.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` -`).trim(),attachments:t}}};function yn(h,A,t){return h.tree.getChildren(A).slice().sort((i,s)=>Uo(h,i,s,t)).map(i=>i.id)}function Uo(h,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=En(h,A)||A.created||"",s=En(h,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=h.titleForNode(A),s=h.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function En(h,A){if(!A.file)return"";let t=h.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Se=require("obsidian");var wn=require("obsidian");function jt(h,A,t){h.empty();try{(0,wn.setIcon)(h,A)}catch{}let e=h.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(h.empty(),h.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Fn(h){if(h instanceof Element&&h.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);h instanceof Element&&h.ownerDocument&&A.add(h.ownerDocument);for(let t of A)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}function vn(h){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(h))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function ii(h){return h.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function kn(h,A,t){let e=new Set(A),i=h.filter(n=>!e.has(n)),s=h.findIndex(n=>e.has(n));if(s<0)return h.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let c=-1;return h.forEach((l,g)=>{e.has(l)&&(c=g)}),c})(),o=0;for(let c=0;c<Math.min(h.length,n+2);c++)e.has(h[c])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function Fs(h,A){if(h.length!==A.length)return!1;for(let t=0;t<h.length;t++)if(h[t]!==A[t])return!1;return!0}async function Sn(h){let A=h.getActionTargets();if(!A.length)return;let t=ft().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await h.app.vault.cachedRead(i.file),n=h.stripFrontmatter(s).trim();e.push(t?`${h.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function yn(h,A,t){return h.tree.getChildren(A).slice().sort((i,s)=>Go(h,i,s,t)).map(i=>i.id)}function Go(h,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=En(h,A)||A.created||"",s=En(h,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=h.titleForNode(A),s=h.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function En(h,A){if(!A.file)return"";let t=h.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Se=require("obsidian");var wn=require("obsidian");function jt(h,A,t){h.empty();try{(0,wn.setIcon)(h,A)}catch{}let e=h.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(h.empty(),h.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Fn(h){if(h instanceof Element&&h.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);h instanceof Element&&h.ownerDocument&&A.add(h.ownerDocument);for(let t of A)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}function vn(h){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(h))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function ii(h){return h.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function kn(h,A,t){let e=new Set(A),i=h.filter(n=>!e.has(n)),s=h.findIndex(n=>e.has(n));if(s<0)return h.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let l=-1;return h.forEach((c,g)=>{e.has(c)&&(l=g)}),l})(),o=0;for(let l=0;l<Math.min(h.length,n+2);l++)e.has(h[l])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function Fs(h,A){if(h.length!==A.length)return!1;for(let t=0;t<h.length;t++)if(h[t]!==A[t])return!1;return!0}async function Sn(h){let A=h.getActionTargets();if(!A.length)return;let t=ft().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await h.app.vault.cachedRead(i.file),n=h.stripFrontmatter(s).trim();e.push(t?`${h.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` `)),h.plugin.notifications.show({message:`Copied ${h.titleList(A)} to clipboard`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}async function Dn(h){let A=h.getActionTargets();if(!A.length||!A[0].file){new Se.Notice("Nothing to copy from.");return}let t=A[0],e=await h.app.vault.cachedRead(t.file),i=h.stripFrontmatter(e),s=vn(i);if(s.length===0){h.plugin.notifications.show({message:`No codeblock found in "${h.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),h.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}let n=s.map((a,r)=>({kind:"one",idx:r,label:`${r+1}. ${a.lang||"(no language)"} \u2014 ${a.code.split(` `)[0].slice(0,60)}${a.code.includes(` -`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends Se.SuggestModal{getSuggestions(a){let r=a.trim().toLowerCase();if(!r)return n;let c=r.split(/\s+/).filter(Boolean);return n.filter(l=>{let g=l.label.toLowerCase();return c.every(p=>g.includes(p))})}renderSuggestion(a,r){r.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let r=a.kind==="all"?s.map(c=>c.code).join(` +`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends Se.SuggestModal{getSuggestions(a){let r=a.trim().toLowerCase();if(!r)return n;let l=r.split(/\s+/).filter(Boolean);return n.filter(c=>{let g=c.label.toLowerCase();return l.every(p=>g.includes(p))})}renderSuggestion(a,r){r.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let r=a.kind==="all"?s.map(l=>l.code).join(` `):s[a.idx].code;await navigator.clipboard.writeText(r),h.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${h.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder})}}(h.app);o.setPlaceholder(`${s.length} codeblocks in "${h.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function bn(h){let A=h.getActionTargets();if(A.length===0){let s=h.tree.get(h.focusId);s?.file&&(A=[s])}if(A.length===0){new Se.Notice("Nothing to copy.");return}let t=ft().prefixTimestampsOnCopy,e=[],i=async(s,n)=>{if(s.file){let o=await h.app.vault.cachedRead(s.file),a=h.stripFrontmatter(o).trim().split(/\r?\n/).join(" "),r=t?`${h.formatTimeInline(s.created)} `:"";e.push(`${" ".repeat(n)}- ${r}${a}`)}for(let o of h.tree.getChildren(s.id))await i(o,n+1)};for(let s of A)await i(s,0);await navigator.clipboard.writeText(e.join(` `)),h.plugin.notifications.show({message:`Copied tree of ${h.titleList(A)} (${e.length} entries)`,kind:"success",category:"system",affectedIds:A.map(s=>s.id),folder:h.noteFolder})}async function Nn(h){let A=h.getActionTargets();if(A.length===0){let i=h.tree.get(h.focusId);i?.file&&(A=[i])}if(A.length===0){new Se.Notice("Nothing to copy.");return}let t=[],e=(i,s)=>{if(!i.file)return;let n=" ".repeat(s);t.push(`${n}- ![[${i.file.basename}]]`);for(let o of h.tree.getChildren(i.id))e(o,s+1)};for(let i of A)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),h.plugin.notifications.show({message:`Copied outline of ${h.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}var ie=require("obsidian");wt();var Ss=Co(Mn()),qi=require("obsidian");Rt();wt();var te="stash",Un=1;function Hn(h){let t=(h.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var ks=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Gn(h,A){let t=new Ss.default,e=Ro([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await h.vault.read(o.file),r=a,c=Po(a);for(let l of c){let g=h.metadataCache.getFirstLinkpathDest(l,o.file.path);if(!g){s.push(`Missing attachment "${l}" in ${o.file.path}`);continue}let p=g.name;i.has(p)||i.set(p,await h.vault.readBinary(g)),r=Lo(r,l,p)}r=qo(r,h,o.file.path),t.file(`notes/${o.file.name}`,r)}for(let[o,a]of i)t.file(`attachments/${o}`,a);let n={stashSchema:Un,exportedAt:new Date().toISOString(),sourceFolder:A.sourceFolder,noteCount:e.length,rootIds:A.rootNotes.map(o=>o.id)};return t.file("manifest.json",JSON.stringify(n,null,2)),s.length&&t.file("warnings.txt",s.join(` -`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function De(h,A,t,e){let i=await Ss.default.loadAsync(A),s=i.file("manifest.json");if(!s)throw new Error("Not a valid .stash package: missing manifest.json");let n=JSON.parse(await s.async("string"));if(typeof n.stashSchema!="number"||n.stashSchema>Un)throw new Error(`Unsupported .stash schema: v${n.stashSchema}`);await Tn(h,t);let o=Object.values(i.files).filter(f=>!f.dir&&f.name.startsWith("notes/")&&f.name.endsWith(".md")),a=[];for(let f of o){let C=await f.async("string"),{fm:m,body:E}=be(C),w=Hn(f.name.slice(6))||`${m.id||"imported-"+yt(4)}.md`;a.push({originalName:w,fm:m,body:E})}let r=new Map,c=0;for(let f of a){let C=f.fm.id;C&&(e.has(C)||r.has(C)?(r.set(C,`${C}-${yt(4)}-Imported`),c++):r.set(C,C))}let l=new Date().toISOString(),g=[],p=`${t}/_attachments`,d=0,I=Object.values(i.files).filter(f=>!f.dir&&f.name.startsWith("attachments/"));I.length>0&&await Tn(h,p);for(let f of I){let C=Hn(f.name.slice(12));if(!C)continue;let m=`${p}/${C}`;if(await h.vault.adapter.exists(m))continue;let E=await f.async("arraybuffer");await h.vault.createBinary(m,E),d++}let u=0;for(let f of a){let C=f.fm.id;if(!C){g.push(`Skipped ${f.originalName} \u2014 no id in frontmatter`);continue}let m=r.get(C),E=f.fm.parent??null,w=E;E&&E!==U&&r.has(E)?w=r.get(E):E&&E!==U&&!r.has(E)&&(w=U);let y=Jo(f.body,p),F={...f.fm,id:m,parent:w,import_date:l};Array.isArray(F.attachments)&&(F.attachments=F.attachments.map(b=>Gt(`${p}/${Rn(ae(b))}`)));let D=ee(F,y),L=m===C?f.originalName:Ko(f.originalName,C,m),S=`${t}/${L}`;await h.vault.adapter.exists(S)&&(L=`${L.replace(/\.md$/,"")}-${yt(4)}.md`,S=`${t}/${L}`),await h.vault.create(S,D),u++}return{notesWritten:u,attachmentsWritten:d,collisionsRenamed:c,warnings:g}}function Ro(h){let A=new Set,t=[];for(let e of h)A.has(e.id)||(A.add(e.id),t.push(e));return t}function Po(h){let A=new Set,t;for(ks.lastIndex=0;(t=ks.exec(h))!==null;)A.add(t[1]);return[...A]}function Lo(h,A,t){return h.replace(new RegExp(`!\\[\\[${Oo(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function Jo(h,A){return h.replace(ks,(t,e,i)=>e.includes("/")?t:t.replace(e,`${A}/${e}`))}function qo(h,A,t){let e=be(h);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return h;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:Rn(n)}),s={...e.fm,attachments:i};return ee(s,e.body)}function Oo(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rn(h){let A=h.lastIndexOf("/");return A<0?h:h.slice(A+1)}function Ko(h,A,t){return h.includes(A)?h.replace(A,t):h.replace(/\.md$/,`-${t}.md`)}function be(h){if(!h.startsWith("---"))return{fm:{},body:h};let A=h.indexOf(` +`)),h.plugin.notifications.show({message:`Copied outline of ${h.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}var ie=require("obsidian");wt();var Ss=Co(Mn()),qi=require("obsidian");Rt();wt();var te="stash",Un=1;function Hn(h){let t=(h.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var ks=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Gn(h,A){let t=new Ss.default,e=Po([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await h.vault.read(o.file),r=a,l=Lo(a);for(let c of l){let g=h.metadataCache.getFirstLinkpathDest(c,o.file.path);if(!g){s.push(`Missing attachment "${c}" in ${o.file.path}`);continue}let p=g.name;i.has(p)||i.set(p,await h.vault.readBinary(g)),r=Jo(r,c,p)}r=Oo(r,h,o.file.path),t.file(`notes/${o.file.name}`,r)}for(let[o,a]of i)t.file(`attachments/${o}`,a);let n={stashSchema:Un,exportedAt:new Date().toISOString(),sourceFolder:A.sourceFolder,noteCount:e.length,rootIds:A.rootNotes.map(o=>o.id)};return t.file("manifest.json",JSON.stringify(n,null,2)),s.length&&t.file("warnings.txt",s.join(` +`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function De(h,A,t,e){let i=await Ss.default.loadAsync(A),s=i.file("manifest.json");if(!s)throw new Error("Not a valid .stash package: missing manifest.json");let n=JSON.parse(await s.async("string"));if(typeof n.stashSchema!="number"||n.stashSchema>Un)throw new Error(`Unsupported .stash schema: v${n.stashSchema}`);await Tn(h,t);let o=Object.values(i.files).filter(f=>!f.dir&&f.name.startsWith("notes/")&&f.name.endsWith(".md")),a=[];for(let f of o){let C=await f.async("string"),{fm:m,body:E}=be(C),w=Hn(f.name.slice(6))||`${m.id||"imported-"+yt(4)}.md`;a.push({originalName:w,fm:m,body:E})}let r=new Map,l=0;for(let f of a){let C=f.fm.id;C&&(e.has(C)||r.has(C)?(r.set(C,`${C}-${yt(4)}-Imported`),l++):r.set(C,C))}let c=new Date().toISOString(),g=[],p=`${t}/_attachments`,d=0,I=Object.values(i.files).filter(f=>!f.dir&&f.name.startsWith("attachments/"));I.length>0&&await Tn(h,p);for(let f of I){let C=Hn(f.name.slice(12));if(!C)continue;let m=`${p}/${C}`;if(await h.vault.adapter.exists(m))continue;let E=await f.async("arraybuffer");await h.vault.createBinary(m,E),d++}let u=0;for(let f of a){let C=f.fm.id;if(!C){g.push(`Skipped ${f.originalName} \u2014 no id in frontmatter`);continue}let m=r.get(C),E=f.fm.parent??null,w=E;E&&E!==U&&r.has(E)?w=r.get(E):E&&E!==U&&!r.has(E)&&(w=U);let y=qo(f.body,p),F={...f.fm,id:m,parent:w,import_date:c};Array.isArray(F.attachments)&&(F.attachments=F.attachments.map(b=>Gt(`${p}/${Rn(ae(b))}`)));let D=ee(F,y),L=m===C?f.originalName:Yo(f.originalName,C,m),S=`${t}/${L}`;await h.vault.adapter.exists(S)&&(L=`${L.replace(/\.md$/,"")}-${yt(4)}.md`,S=`${t}/${L}`),await h.vault.create(S,D),u++}return{notesWritten:u,attachmentsWritten:d,collisionsRenamed:l,warnings:g}}function Po(h){let A=new Set,t=[];for(let e of h)A.has(e.id)||(A.add(e.id),t.push(e));return t}function Lo(h){let A=new Set,t;for(ks.lastIndex=0;(t=ks.exec(h))!==null;)A.add(t[1]);return[...A]}function Jo(h,A,t){return h.replace(new RegExp(`!\\[\\[${Ko(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function qo(h,A){return h.replace(ks,(t,e,i)=>e.includes("/")?t:t.replace(e,`${A}/${e}`))}function Oo(h,A,t){let e=be(h);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return h;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:Rn(n)}),s={...e.fm,attachments:i};return ee(s,e.body)}function Ko(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Rn(h){let A=h.lastIndexOf("/");return A<0?h:h.slice(A+1)}function Yo(h,A,t){return h.includes(A)?h.replace(A,t):h.replace(/\.md$/,`-${t}.md`)}function be(h){if(!h.startsWith("---"))return{fm:{},body:h};let A=h.indexOf(` ---`,3);if(A<0)return{fm:{},body:h};let t=h.slice(3,A).replace(/^\n/,""),e=h.slice(A+4),i={};try{i=(0,qi.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` `)?e.slice(1):e;return{fm:i,body:s}}function ee(h,A){return`--- ${(0,qi.stringifyYaml)(h).trimEnd()} --- -${A}`}async function Tn(h,A){if(!(!A||await h.vault.adapter.exists(A)))try{await h.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}function pe(h,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(c){try{r(e.next(c))}catch(l){n(l)}}function a(c){try{r(e.throw(c))}catch(l){n(l)}}function r(c){c.done?s(c.value):i(c.value).then(o,a)}r((e=e.apply(h,A||[])).next())})}var Bt=class{constructor(){this.mutex=Promise.resolve()}lock(){let A=()=>{};return this.mutex=this.mutex.then(()=>new Promise(A)),new Promise(t=>{A=t})}dispatch(A){return pe(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(A())}finally{t()}})}},Ds;function Yo(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Ms=Yo(),bs=(Ds=Ms.Buffer)!==null&&Ds!==void 0?Ds:null,zo=Ms.TextEncoder?new Ms.TextEncoder:null;function Kn(h,A){return(h&15)+(h>>6|h>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function Yn(h,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;h[e]=Kn(A.charCodeAt(i),A.charCodeAt(i+1))}}function Vo(h,A){if(h.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==Kn(h.charCodeAt(e),h.charCodeAt(e+1)))return!1}return!0}var Pn=87,Ln=48;function Hs(h,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;h[e++]=s>9?s+Pn:s+Ln,s=A[i]&15,h[e++]=s>9?s+Pn:s+Ln}return String.fromCharCode.apply(null,h)}var Yt=bs!==null?h=>{if(typeof h=="string"){let A=bs.from(h,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(bs.isBuffer(h))return new Uint8Array(h.buffer,h.byteOffset,h.length);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")}:h=>{if(typeof h=="string")return zo.encode(h);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")},Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ni=new Uint8Array(256);for(let h=0;h<Tt.length;h++)ni[Tt.charCodeAt(h)]=h;function Jn(h,A=!0){let t=h.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(h[n]<<16&16711680)+(h[n+1]<<8&65280)+(h[n+2]&255),a=Tt.charAt(o>>18&63)+Tt.charAt(o>>12&63)+Tt.charAt(o>>6&63)+Tt.charAt(o&63);i.push(a)}if(e===1){let n=h[t-1],o=Tt.charAt(n>>2),a=Tt.charAt(n<<4&63);i.push(`${o}${a}`),A&&i.push("==")}else if(e===2){let n=(h[t-2]<<8)+h[t-1],o=Tt.charAt(n>>10),a=Tt.charAt(n>>4&63),r=Tt.charAt(n<<2&63);i.push(`${o}${a}${r}`),A&&i.push("=")}return i.join("")}function Wo(h){let A=Math.floor(h.length*.75),t=h.length;return h[t-1]==="="&&(A-=1,h[t-2]==="="&&(A-=1)),A}function Xo(h){let A=Wo(h),t=h.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=ni[h.charCodeAt(s)],o=ni[h.charCodeAt(s+1)],a=ni[h.charCodeAt(s+2)],r=ni[h.charCodeAt(s+3)];e[i]=n<<2|o>>4,i+=1,e[i]=(o&15)<<4|a>>2,i+=1,e[i]=(a&3)<<6|r&63,i+=1}return e}var Oi=16*1024,si=4,Zo=new Bt,Ns=new Map;function zn(h,A){return pe(this,void 0,void 0,function*(){let t=null,e=null,i=!1;if(typeof WebAssembly>"u")throw new Error("WebAssembly is not supported in this environment!");let s=(y,F=0)=>{e.set(y,F)},n=()=>e,o=()=>t.exports,a=y=>{t.exports.Hash_SetMemorySize(y);let F=t.exports.Hash_GetBuffer(),D=t.exports.memory.buffer;e=new Uint8Array(D,F,y)},r=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),c=Zo.dispatch(()=>pe(this,void 0,void 0,function*(){if(!Ns.has(h.name)){let F=Xo(h.data),D=WebAssembly.compile(F);Ns.set(h.name,D)}let y=yield Ns.get(h.name);t=yield WebAssembly.instantiate(y,{})})),l=()=>pe(this,void 0,void 0,function*(){t||(yield c);let y=t.exports.Hash_GetBuffer(),F=t.exports.memory.buffer;e=new Uint8Array(F,y,Oi)}),g=(y=null)=>{i=!0,t.exports.Hash_Init(y)},p=y=>{let F=0;for(;F<y.length;){let D=y.subarray(F,F+Oi);F+=D.length,e.set(D),t.exports.Hash_Update(D.length)}},d=y=>{if(!i)throw new Error("update() called before init()");let F=Yt(y);p(F)},I=new Uint8Array(A*2),u=(y,F=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(F),y==="binary"?e.slice(0,A):Hs(I,e,A)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),F=r(),D=t.exports.memory.buffer,L=new Uint8Array(D,y,F),S=new Uint8Array(si+F);return Yn(S,h.hash),S.set(L,si),S},C=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let F=t.exports.Hash_GetState(),D=r(),L=si+D,S=t.exports.memory.buffer;if(y.length!==L)throw new Error(`Bad state length (expected ${L} bytes, got ${y.length})`);if(!Vo(h.hash,y.subarray(0,si)))throw new Error("This state was written by an incompatible hash implementation");let b=y.subarray(si);new Uint8Array(S,F,D).set(b),i=!0},m=y=>typeof y=="string"?y.length<Oi/4:y.byteLength<Oi,E=m;switch(h.name){case"argon2":case"scrypt":E=()=>!0;break;case"blake2b":case"blake2s":E=(y,F)=>F<=512&&m(y);break;case"blake3":E=(y,F)=>F===0&&m(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":E=()=>!1;break}let w=(y,F=null,D=null)=>{if(!E(y,F))return g(F),d(y),u("hex",D);let L=Yt(y);return e.set(L),t.exports.Hash_Calculate(L.length,F,D),Hs(I,e,A)};return yield l(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:g,update:d,digest:u,save:f,load:C,calculate:w,hashLength:A}})}var lA=new Bt;var $o="argon2",_o="AGFzbQEAAAABKQVgAX8Bf2AAAX9gEH9/f39/f39/f39/f39/f38AYAR/f39/AGACf38AAwYFAAECAwQFBgEBAoCAAgYIAX8BQZCoBAsHQQQGbWVtb3J5AgASSGFzaF9TZXRNZW1vcnlTaXplAAAOSGFzaF9HZXRCdWZmZXIAAQ5IYXNoX0NhbGN1bGF0ZQAECvEyBVgBAn9BACEBAkAgAEEAKAKICCICRg0AAkAgACACayIAQRB2IABBgIB8cSAASWoiAEAAQX9HDQBB/wHADwtBACEBQQBBACkDiAggAEEQdK18NwOICAsgAcALcAECfwJAQQAoAoAIIgANAEEAPwBBEHQiADYCgAhBACgCiAgiAUGAgCBGDQACQEGAgCAgAWsiAEEQdiAAQYCAfHEgAElqIgBAAEF/Rw0AQQAPC0EAQQApA4gIIABBEHStfDcDiAhBACgCgAghAAsgAAvcDgECfiAAIAQpAwAiECAAKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAMIBAgDCkDAIVCIIkiEDcDACAIIBAgCCkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgBCAQIAQpAwCFQiiJIhA3AwAgACAQIAApAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAwgECAMKQMAhUIwiSIQNwMAIAggECAIKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAEIBAgBCkDAIVCAYk3AwAgASAFKQMAIhAgASkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDSAQIA0pAwCFQiCJIhA3AwAgCSAQIAkpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAUgECAFKQMAhUIoiSIQNwMAIAEgECABKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACANIBAgDSkDAIVCMIkiEDcDACAJIBAgCSkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBSAQIAUpAwCFQgGJNwMAIAIgBikDACIQIAIpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIA4gECAOKQMAhUIgiSIQNwMAIAogECAKKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAGIBAgBikDAIVCKIkiEDcDACACIBAgAikDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgDiAQIA4pAwCFQjCJIhA3AwAgCiAQIAopAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAYgECAGKQMAhUIBiTcDACADIAcpAwAiECADKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAPIBAgDykDAIVCIIkiEDcDACALIBAgCykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgByAQIAcpAwCFQiiJIhA3AwAgAyAQIAMpAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIA8gECAPKQMAhUIwiSIQNwMAIAsgECALKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgACAFKQMAIhAgACkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDyAQIA8pAwCFQiCJIhA3AwAgCiAQIAopAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAUgECAFKQMAhUIoiSIQNwMAIAAgECAAKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAPIBAgDykDAIVCMIkiEDcDACAKIBAgCikDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBSAQIAUpAwCFQgGJNwMAIAEgBikDACIQIAEpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAwgECAMKQMAhUIgiSIQNwMAIAsgECALKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAGIBAgBikDAIVCKIkiEDcDACABIBAgASkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgDCAQIAwpAwCFQjCJIhA3AwAgCyAQIAspAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAYgECAGKQMAhUIBiTcDACACIAcpAwAiECACKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACANIBAgDSkDAIVCIIkiEDcDACAIIBAgCCkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgByAQIAcpAwCFQiiJIhA3AwAgAiAQIAIpAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIA0gECANKQMAhUIwiSIQNwMAIAggECAIKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgAyAEKQMAIhAgAykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDiAQIA4pAwCFQiCJIhA3AwAgCSAQIAkpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAQgECAEKQMAhUIoiSIQNwMAIAMgECADKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAOIBAgDikDAIVCMIkiEDcDACAJIBAgCSkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBCAQIAQpAwCFQgGJNwMAC98aAQN/QQAhBEEAIAIpAwAgASkDAIU3A5AIQQAgAikDCCABKQMIhTcDmAhBACACKQMQIAEpAxCFNwOgCEEAIAIpAxggASkDGIU3A6gIQQAgAikDICABKQMghTcDsAhBACACKQMoIAEpAyiFNwO4CEEAIAIpAzAgASkDMIU3A8AIQQAgAikDOCABKQM4hTcDyAhBACACKQNAIAEpA0CFNwPQCEEAIAIpA0ggASkDSIU3A9gIQQAgAikDUCABKQNQhTcD4AhBACACKQNYIAEpA1iFNwPoCEEAIAIpA2AgASkDYIU3A/AIQQAgAikDaCABKQNohTcD+AhBACACKQNwIAEpA3CFNwOACUEAIAIpA3ggASkDeIU3A4gJQQAgAikDgAEgASkDgAGFNwOQCUEAIAIpA4gBIAEpA4gBhTcDmAlBACACKQOQASABKQOQAYU3A6AJQQAgAikDmAEgASkDmAGFNwOoCUEAIAIpA6ABIAEpA6ABhTcDsAlBACACKQOoASABKQOoAYU3A7gJQQAgAikDsAEgASkDsAGFNwPACUEAIAIpA7gBIAEpA7gBhTcDyAlBACACKQPAASABKQPAAYU3A9AJQQAgAikDyAEgASkDyAGFNwPYCUEAIAIpA9ABIAEpA9ABhTcD4AlBACACKQPYASABKQPYAYU3A+gJQQAgAikD4AEgASkD4AGFNwPwCUEAIAIpA+gBIAEpA+gBhTcD+AlBACACKQPwASABKQPwAYU3A4AKQQAgAikD+AEgASkD+AGFNwOICkEAIAIpA4ACIAEpA4AChTcDkApBACACKQOIAiABKQOIAoU3A5gKQQAgAikDkAIgASkDkAKFNwOgCkEAIAIpA5gCIAEpA5gChTcDqApBACACKQOgAiABKQOgAoU3A7AKQQAgAikDqAIgASkDqAKFNwO4CkEAIAIpA7ACIAEpA7AChTcDwApBACACKQO4AiABKQO4AoU3A8gKQQAgAikDwAIgASkDwAKFNwPQCkEAIAIpA8gCIAEpA8gChTcD2ApBACACKQPQAiABKQPQAoU3A+AKQQAgAikD2AIgASkD2AKFNwPoCkEAIAIpA+ACIAEpA+AChTcD8ApBACACKQPoAiABKQPoAoU3A/gKQQAgAikD8AIgASkD8AKFNwOAC0EAIAIpA/gCIAEpA/gChTcDiAtBACACKQOAAyABKQOAA4U3A5ALQQAgAikDiAMgASkDiAOFNwOYC0EAIAIpA5ADIAEpA5ADhTcDoAtBACACKQOYAyABKQOYA4U3A6gLQQAgAikDoAMgASkDoAOFNwOwC0EAIAIpA6gDIAEpA6gDhTcDuAtBACACKQOwAyABKQOwA4U3A8ALQQAgAikDuAMgASkDuAOFNwPIC0EAIAIpA8ADIAEpA8ADhTcD0AtBACACKQPIAyABKQPIA4U3A9gLQQAgAikD0AMgASkD0AOFNwPgC0EAIAIpA9gDIAEpA9gDhTcD6AtBACACKQPgAyABKQPgA4U3A/ALQQAgAikD6AMgASkD6AOFNwP4C0EAIAIpA/ADIAEpA/ADhTcDgAxBACACKQP4AyABKQP4A4U3A4gMQQAgAikDgAQgASkDgASFNwOQDEEAIAIpA4gEIAEpA4gEhTcDmAxBACACKQOQBCABKQOQBIU3A6AMQQAgAikDmAQgASkDmASFNwOoDEEAIAIpA6AEIAEpA6AEhTcDsAxBACACKQOoBCABKQOoBIU3A7gMQQAgAikDsAQgASkDsASFNwPADEEAIAIpA7gEIAEpA7gEhTcDyAxBACACKQPABCABKQPABIU3A9AMQQAgAikDyAQgASkDyASFNwPYDEEAIAIpA9AEIAEpA9AEhTcD4AxBACACKQPYBCABKQPYBIU3A+gMQQAgAikD4AQgASkD4ASFNwPwDEEAIAIpA+gEIAEpA+gEhTcD+AxBACACKQPwBCABKQPwBIU3A4ANQQAgAikD+AQgASkD+ASFNwOIDUEAIAIpA4AFIAEpA4AFhTcDkA1BACACKQOIBSABKQOIBYU3A5gNQQAgAikDkAUgASkDkAWFNwOgDUEAIAIpA5gFIAEpA5gFhTcDqA1BACACKQOgBSABKQOgBYU3A7ANQQAgAikDqAUgASkDqAWFNwO4DUEAIAIpA7AFIAEpA7AFhTcDwA1BACACKQO4BSABKQO4BYU3A8gNQQAgAikDwAUgASkDwAWFNwPQDUEAIAIpA8gFIAEpA8gFhTcD2A1BACACKQPQBSABKQPQBYU3A+ANQQAgAikD2AUgASkD2AWFNwPoDUEAIAIpA+AFIAEpA+AFhTcD8A1BACACKQPoBSABKQPoBYU3A/gNQQAgAikD8AUgASkD8AWFNwOADkEAIAIpA/gFIAEpA/gFhTcDiA5BACACKQOABiABKQOABoU3A5AOQQAgAikDiAYgASkDiAaFNwOYDkEAIAIpA5AGIAEpA5AGhTcDoA5BACACKQOYBiABKQOYBoU3A6gOQQAgAikDoAYgASkDoAaFNwOwDkEAIAIpA6gGIAEpA6gGhTcDuA5BACACKQOwBiABKQOwBoU3A8AOQQAgAikDuAYgASkDuAaFNwPIDkEAIAIpA8AGIAEpA8AGhTcD0A5BACACKQPIBiABKQPIBoU3A9gOQQAgAikD0AYgASkD0AaFNwPgDkEAIAIpA9gGIAEpA9gGhTcD6A5BACACKQPgBiABKQPgBoU3A/AOQQAgAikD6AYgASkD6AaFNwP4DkEAIAIpA/AGIAEpA/AGhTcDgA9BACACKQP4BiABKQP4BoU3A4gPQQAgAikDgAcgASkDgAeFNwOQD0EAIAIpA4gHIAEpA4gHhTcDmA9BACACKQOQByABKQOQB4U3A6APQQAgAikDmAcgASkDmAeFNwOoD0EAIAIpA6AHIAEpA6AHhTcDsA9BACACKQOoByABKQOoB4U3A7gPQQAgAikDsAcgASkDsAeFNwPAD0EAIAIpA7gHIAEpA7gHhTcDyA9BACACKQPAByABKQPAB4U3A9APQQAgAikDyAcgASkDyAeFNwPYD0EAIAIpA9AHIAEpA9AHhTcD4A9BACACKQPYByABKQPYB4U3A+gPQQAgAikD4AcgASkD4AeFNwPwD0EAIAIpA+gHIAEpA+gHhTcD+A9BACACKQPwByABKQPwB4U3A4AQQQAgAikD+AcgASkD+AeFNwOIEEGQCEGYCEGgCEGoCEGwCEG4CEHACEHICEHQCEHYCEHgCEHoCEHwCEH4CEGACUGICRACQZAJQZgJQaAJQagJQbAJQbgJQcAJQcgJQdAJQdgJQeAJQegJQfAJQfgJQYAKQYgKEAJBkApBmApBoApBqApBsApBuApBwApByApB0ApB2ApB4ApB6ApB8ApB+ApBgAtBiAsQAkGQC0GYC0GgC0GoC0GwC0G4C0HAC0HIC0HQC0HYC0HgC0HoC0HwC0H4C0GADEGIDBACQZAMQZgMQaAMQagMQbAMQbgMQcAMQcgMQdAMQdgMQeAMQegMQfAMQfgMQYANQYgNEAJBkA1BmA1BoA1BqA1BsA1BuA1BwA1ByA1B0A1B2A1B4A1B6A1B8A1B+A1BgA5BiA4QAkGQDkGYDkGgDkGoDkGwDkG4DkHADkHIDkHQDkHYDkHgDkHoDkHwDkH4DkGAD0GIDxACQZAPQZgPQaAPQagPQbAPQbgPQcAPQcgPQdAPQdgPQeAPQegPQfAPQfgPQYAQQYgQEAJBkAhBmAhBkAlBmAlBkApBmApBkAtBmAtBkAxBmAxBkA1BmA1BkA5BmA5BkA9BmA8QAkGgCEGoCEGgCUGoCUGgCkGoCkGgC0GoC0GgDEGoDEGgDUGoDUGgDkGoDkGgD0GoDxACQbAIQbgIQbAJQbgJQbAKQbgKQbALQbgLQbAMQbgMQbANQbgNQbAOQbgOQbAPQbgPEAJBwAhByAhBwAlByAlBwApByApBwAtByAtBwAxByAxBwA1ByA1BwA5ByA5BwA9ByA8QAkHQCEHYCEHQCUHYCUHQCkHYCkHQC0HYC0HQDEHYDEHQDUHYDUHQDkHYDkHQD0HYDxACQeAIQegIQeAJQegJQeAKQegKQeALQegLQeAMQegMQeANQegNQeAOQegOQeAPQegPEAJB8AhB+AhB8AlB+AlB8ApB+ApB8AtB+AtB8AxB+AxB8A1B+A1B8A5B+A5B8A9B+A8QAkGACUGICUGACkGICkGAC0GIC0GADEGIDEGADUGIDUGADkGIDkGAD0GID0GAEEGIEBACAkACQCADRQ0AA0AgACAEaiIDIAIgBGoiBSkDACABIARqIgYpAwCFIARBkAhqKQMAhSADKQMAhTcDACADQQhqIgMgBUEIaikDACAGQQhqKQMAhSAEQZgIaikDAIUgAykDAIU3AwAgBEEQaiIEQYAIRw0ADAILC0EAIQQDQCAAIARqIgMgAiAEaiIFKQMAIAEgBGoiBikDAIUgBEGQCGopAwCFNwMAIANBCGogBUEIaikDACAGQQhqKQMAhSAEQZgIaikDAIU3AwAgBEEQaiIEQYAIRw0ACwsL5QcMBX8BfgR/An4BfwF+AX8Bfgd/AX4DfwF+AkBBACgCgAgiAiABQQp0aiIDKAIIIAFHDQAgAygCDCEEIAMoAgAhBUEAIAMoAhQiBq03A7gQQQAgBK0iBzcDsBBBACAFIAEgBUECdG4iCGwiCUECdK03A6gQAkACQAJAAkAgBEUNAEF/IQogBUUNASAIQQNsIQsgCEECdCIErSEMIAWtIQ0gBkF/akECSSEOQgAhDwNAQQAgDzcDkBAgD6chEEIAIRFBACEBA0BBACARNwOgECAPIBGEUCIDIA5xIRIgBkEBRiAPUCITIAZBAkYgEUICVHFxciEUQX8gAUEBakEDcSAIbEF/aiATGyEVIAEgEHIhFiABIAhsIRcgA0EBdCEYQgAhGQNAQQBCADcDwBBBACAZNwOYECAYIQECQCASRQ0AQQBCATcDwBBBkBhBkBBBkCBBABADQZAYQZAYQZAgQQAQA0ECIQELAkAgASAITw0AIAQgGaciGmwgF2ogAWohAwNAIANBACAEIAEbQQAgEVAiGxtqQX9qIRwCQAJAIBQNAEEAKAKACCICIBxBCnQiHGohCgwBCwJAIAFB/wBxIgINAEEAQQApA8AQQgF8NwPAEEGQGEGQEEGQIEEAEANBkBhBkBhBkCBBABADCyAcQQp0IRwgAkEDdEGQGGohCkEAKAKACCECCyACIANBCnRqIAIgHGogAiAKKQMAIh1CIIinIAVwIBogFhsiHCAEbCABIAFBACAZIBytUSIcGyIKIBsbIBdqIAogC2ogExsgAUUgHHJrIhsgFWqtIB1C/////w+DIh0gHX5CIIggG61+QiCIfSAMgqdqQQp0akEBEAMgA0EBaiEDIAggAUEBaiIBRw0ACwsgGUIBfCIZIA1SDQALIBFCAXwiEachASARQgRSDQALIA9CAXwiDyAHUg0AC0EAKAKACCECCyAJQQx0QYB4aiEXIAVBf2oiCkUNAgwBC0EAQgM3A6AQQQAgBEF/aq03A5AQQYB4IRcLIAIgF2ohGyAIQQx0IQhBACEcA0AgCCAcQQFqIhxsQYB4aiEEQQAhAQNAIBsgAWoiAyADKQMAIAIgBCABamopAwCFNwMAIANBCGoiAyADKQMAIAIgBCABQQhyamopAwCFNwMAIAFBCGohAyABQRBqIQEgA0H4B0kNAAsgHCAKRw0ACwsgAiAXaiEbQXghAQNAIAIgAWoiA0EIaiAbIAFqIgRBCGopAwA3AwAgA0EQaiAEQRBqKQMANwMAIANBGGogBEEYaikDADcDACADQSBqIARBIGopAwA3AwAgAUEgaiIBQfgHSQ0ACwsL",jo="e4cdc523",ta={name:$o,data:_o,hash:jo},ea="blake2b",ia="AGFzbQEAAAABEQRgAAF/YAJ/fwBgAX8AYAAAAwoJAAECAwECAgABBQQBAQICBg4CfwFBsIsFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACkhhc2hfRmluYWwAAwlIYXNoX0luaXQABQtIYXNoX1VwZGF0ZQAGDUhhc2hfR2V0U3RhdGUABw5IYXNoX0NhbGN1bGF0ZQAIClNUQVRFX1NJWkUDAQrTOAkFAEGACQvrAgIFfwF+AkAgAUEBSA0AAkACQAJAIAFBgAFBACgC4IoBIgJrIgNKDQAgASEEDAELQQBBADYC4IoBAkAgAkH/AEoNACACQeCJAWohBSAAIQRBACEGA0AgBSAELQAAOgAAIARBAWohBCAFQQFqIQUgAyAGQQFqIgZB/wFxSg0ACwtBAEEAKQPAiQEiB0KAAXw3A8CJAUEAQQApA8iJASAHQv9+Vq18NwPIiQFB4IkBEAIgACADaiEAAkAgASADayIEQYEBSA0AIAIgAWohBQNAQQBBACkDwIkBIgdCgAF8NwPAiQFBAEEAKQPIiQEgB0L/flatfDcDyIkBIAAQAiAAQYABaiEAIAVBgH9qIgVBgAJLDQALIAVBgH9qIQQMAQsgBEEATA0BC0EAIQUDQCAFQQAoAuCKAWpB4IkBaiAAIAVqLQAAOgAAIAQgBUEBaiIFQf8BcUoNAAsLQQBBACgC4IoBIARqNgLgigELC78uASR+QQBBACkD0IkBQQApA7CJASIBQQApA5CJAXwgACkDICICfCIDhULr+obav7X2wR+FQiCJIgRCq/DT9K/uvLc8fCIFIAGFQiiJIgYgA3wgACkDKCIBfCIHIASFQjCJIgggBXwiCSAGhUIBiSIKQQApA8iJAUEAKQOoiQEiBEEAKQOIiQF8IAApAxAiA3wiBYVCn9j52cKR2oKbf4VCIIkiC0K7zqqm2NDrs7t/fCIMIASFQiiJIg0gBXwgACkDGCIEfCIOfCAAKQNQIgV8Ig9BACkDwIkBQQApA6CJASIQQQApA4CJASIRfCAAKQMAIgZ8IhKFQtGFmu/6z5SH0QCFQiCJIhNCiJLznf/M+YTqAHwiFCAQhUIoiSIVIBJ8IAApAwgiEHwiFiAThUIwiSIXhUIgiSIYQQApA9iJAUEAKQO4iQEiE0EAKQOYiQF8IAApAzAiEnwiGYVC+cL4m5Gjs/DbAIVCIIkiGkLx7fT4paf9p6V/fCIbIBOFQiiJIhwgGXwgACkDOCITfCIZIBqFQjCJIhogG3wiG3wiHSAKhUIoiSIeIA98IAApA1giCnwiDyAYhUIwiSIYIB18Ih0gDiALhUIwiSIOIAx8Ih8gDYVCAYkiDCAWfCAAKQNAIgt8Ig0gGoVCIIkiFiAJfCIaIAyFQiiJIiAgDXwgACkDSCIJfCIhIBaFQjCJIhYgGyAchUIBiSIMIAd8IAApA2AiB3wiDSAOhUIgiSIOIBcgFHwiFHwiFyAMhUIoiSIbIA18IAApA2giDHwiHCAOhUIwiSIOIBd8IhcgG4VCAYkiGyAZIBQgFYVCAYkiFHwgACkDcCINfCIVIAiFQiCJIhkgH3wiHyAUhUIoiSIUIBV8IAApA3giCHwiFXwgDHwiIoVCIIkiI3wiJCAbhUIoiSIbICJ8IBJ8IiIgFyAYIBUgGYVCMIkiFSAffCIZIBSFQgGJIhQgIXwgDXwiH4VCIIkiGHwiFyAUhUIoiSIUIB98IAV8Ih8gGIVCMIkiGCAXfCIXIBSFQgGJIhR8IAF8IiEgFiAafCIWIBUgHSAehUIBiSIaIBx8IAl8IhyFQiCJIhV8Ih0gGoVCKIkiGiAcfCAIfCIcIBWFQjCJIhWFQiCJIh4gGSAOIBYgIIVCAYkiFiAPfCACfCIPhUIgiSIOfCIZIBaFQiiJIhYgD3wgC3wiDyAOhUIwiSIOIBl8Ihl8IiAgFIVCKIkiFCAhfCAEfCIhIB6FQjCJIh4gIHwiICAiICOFQjCJIiIgJHwiIyAbhUIBiSIbIBx8IAp8IhwgDoVCIIkiDiAXfCIXIBuFQiiJIhsgHHwgE3wiHCAOhUIwiSIOIBkgFoVCAYkiFiAffCAQfCIZICKFQiCJIh8gFSAdfCIVfCIdIBaFQiiJIhYgGXwgB3wiGSAfhUIwiSIfIB18Ih0gFoVCAYkiFiAVIBqFQgGJIhUgD3wgBnwiDyAYhUIgiSIYICN8IhogFYVCKIkiFSAPfCADfCIPfCAHfCIihUIgiSIjfCIkIBaFQiiJIhYgInwgBnwiIiAjhUIwiSIjICR8IiQgFoVCAYkiFiAOIBd8Ig4gDyAYhUIwiSIPICAgFIVCAYkiFCAZfCAKfCIXhUIgiSIYfCIZIBSFQiiJIhQgF3wgC3wiF3wgBXwiICAPIBp8Ig8gHyAOIBuFQgGJIg4gIXwgCHwiGoVCIIkiG3wiHyAOhUIoiSIOIBp8IAx8IhogG4VCMIkiG4VCIIkiISAdIB4gDyAVhUIBiSIPIBx8IAF8IhWFQiCJIhx8Ih0gD4VCKIkiDyAVfCADfCIVIByFQjCJIhwgHXwiHXwiHiAWhUIoiSIWICB8IA18IiAgIYVCMIkiISAefCIeIBogFyAYhUIwiSIXIBl8IhggFIVCAYkiFHwgCXwiGSAchUIgiSIaICR8IhwgFIVCKIkiFCAZfCACfCIZIBqFQjCJIhogHSAPhUIBiSIPICJ8IAR8Ih0gF4VCIIkiFyAbIB98Iht8Ih8gD4VCKIkiDyAdfCASfCIdIBeFQjCJIhcgH3wiHyAPhUIBiSIPIBsgDoVCAYkiDiAVfCATfCIVICOFQiCJIhsgGHwiGCAOhUIoiSIOIBV8IBB8IhV8IAx8IiKFQiCJIiN8IiQgD4VCKIkiDyAifCAHfCIiICOFQjCJIiMgJHwiJCAPhUIBiSIPIBogHHwiGiAVIBuFQjCJIhUgHiAWhUIBiSIWIB18IAR8IhuFQiCJIhx8Ih0gFoVCKIkiFiAbfCAQfCIbfCABfCIeIBUgGHwiFSAXIBogFIVCAYkiFCAgfCATfCIYhUIgiSIXfCIaIBSFQiiJIhQgGHwgCXwiGCAXhUIwiSIXhUIgiSIgIB8gISAVIA6FQgGJIg4gGXwgCnwiFYVCIIkiGXwiHyAOhUIoiSIOIBV8IA18IhUgGYVCMIkiGSAffCIffCIhIA+FQiiJIg8gHnwgBXwiHiAghUIwiSIgICF8IiEgGyAchUIwiSIbIB18IhwgFoVCAYkiFiAYfCADfCIYIBmFQiCJIhkgJHwiHSAWhUIoiSIWIBh8IBJ8IhggGYVCMIkiGSAfIA6FQgGJIg4gInwgAnwiHyAbhUIgiSIbIBcgGnwiF3wiGiAOhUIoiSIOIB98IAZ8Ih8gG4VCMIkiGyAafCIaIA6FQgGJIg4gFSAXIBSFQgGJIhR8IAh8IhUgI4VCIIkiFyAcfCIcIBSFQiiJIhQgFXwgC3wiFXwgBXwiIoVCIIkiI3wiJCAOhUIoiSIOICJ8IAh8IiIgGiAgIBUgF4VCMIkiFSAcfCIXIBSFQgGJIhQgGHwgCXwiGIVCIIkiHHwiGiAUhUIoiSIUIBh8IAZ8IhggHIVCMIkiHCAafCIaIBSFQgGJIhR8IAR8IiAgGSAdfCIZIBUgISAPhUIBiSIPIB98IAN8Ih2FQiCJIhV8Ih8gD4VCKIkiDyAdfCACfCIdIBWFQjCJIhWFQiCJIiEgFyAbIBkgFoVCAYkiFiAefCABfCIZhUIgiSIbfCIXIBaFQiiJIhYgGXwgE3wiGSAbhUIwiSIbIBd8Ihd8Ih4gFIVCKIkiFCAgfCAMfCIgICGFQjCJIiEgHnwiHiAiICOFQjCJIiIgJHwiIyAOhUIBiSIOIB18IBJ8Ih0gG4VCIIkiGyAafCIaIA6FQiiJIg4gHXwgC3wiHSAbhUIwiSIbIBcgFoVCAYkiFiAYfCANfCIXICKFQiCJIhggFSAffCIVfCIfIBaFQiiJIhYgF3wgEHwiFyAYhUIwiSIYIB98Ih8gFoVCAYkiFiAVIA+FQgGJIg8gGXwgCnwiFSAchUIgiSIZICN8IhwgD4VCKIkiDyAVfCAHfCIVfCASfCIihUIgiSIjfCIkIBaFQiiJIhYgInwgBXwiIiAjhUIwiSIjICR8IiQgFoVCAYkiFiAbIBp8IhogFSAZhUIwiSIVIB4gFIVCAYkiFCAXfCADfCIXhUIgiSIZfCIbIBSFQiiJIhQgF3wgB3wiF3wgAnwiHiAVIBx8IhUgGCAaIA6FQgGJIg4gIHwgC3wiGoVCIIkiGHwiHCAOhUIoiSIOIBp8IAR8IhogGIVCMIkiGIVCIIkiICAfICEgFSAPhUIBiSIPIB18IAZ8IhWFQiCJIh18Ih8gD4VCKIkiDyAVfCAKfCIVIB2FQjCJIh0gH3wiH3wiISAWhUIoiSIWIB58IAx8Ih4gIIVCMIkiICAhfCIhIBogFyAZhUIwiSIXIBt8IhkgFIVCAYkiFHwgEHwiGiAdhUIgiSIbICR8Ih0gFIVCKIkiFCAafCAJfCIaIBuFQjCJIhsgHyAPhUIBiSIPICJ8IBN8Ih8gF4VCIIkiFyAYIBx8Ihh8IhwgD4VCKIkiDyAffCABfCIfIBeFQjCJIhcgHHwiHCAPhUIBiSIPIBggDoVCAYkiDiAVfCAIfCIVICOFQiCJIhggGXwiGSAOhUIoiSIOIBV8IA18IhV8IA18IiKFQiCJIiN8IiQgD4VCKIkiDyAifCAMfCIiICOFQjCJIiMgJHwiJCAPhUIBiSIPIBsgHXwiGyAVIBiFQjCJIhUgISAWhUIBiSIWIB98IBB8IhiFQiCJIh18Ih8gFoVCKIkiFiAYfCAIfCIYfCASfCIhIBUgGXwiFSAXIBsgFIVCAYkiFCAefCAHfCIZhUIgiSIXfCIbIBSFQiiJIhQgGXwgAXwiGSAXhUIwiSIXhUIgiSIeIBwgICAVIA6FQgGJIg4gGnwgAnwiFYVCIIkiGnwiHCAOhUIoiSIOIBV8IAV8IhUgGoVCMIkiGiAcfCIcfCIgIA+FQiiJIg8gIXwgBHwiISAehUIwiSIeICB8IiAgGCAdhUIwiSIYIB98Ih0gFoVCAYkiFiAZfCAGfCIZIBqFQiCJIhogJHwiHyAWhUIoiSIWIBl8IBN8IhkgGoVCMIkiGiAcIA6FQgGJIg4gInwgCXwiHCAYhUIgiSIYIBcgG3wiF3wiGyAOhUIoiSIOIBx8IAN8IhwgGIVCMIkiGCAbfCIbIA6FQgGJIg4gFSAXIBSFQgGJIhR8IAt8IhUgI4VCIIkiFyAdfCIdIBSFQiiJIhQgFXwgCnwiFXwgBHwiIoVCIIkiI3wiJCAOhUIoiSIOICJ8IAl8IiIgGyAeIBUgF4VCMIkiFSAdfCIXIBSFQgGJIhQgGXwgDHwiGYVCIIkiHXwiGyAUhUIoiSIUIBl8IAp8IhkgHYVCMIkiHSAbfCIbIBSFQgGJIhR8IAN8Ih4gGiAffCIaIBUgICAPhUIBiSIPIBx8IAd8IhyFQiCJIhV8Ih8gD4VCKIkiDyAcfCAQfCIcIBWFQjCJIhWFQiCJIiAgFyAYIBogFoVCAYkiFiAhfCATfCIahUIgiSIYfCIXIBaFQiiJIhYgGnwgDXwiGiAYhUIwiSIYIBd8Ihd8IiEgFIVCKIkiFCAefCAFfCIeICCFQjCJIiAgIXwiISAiICOFQjCJIiIgJHwiIyAOhUIBiSIOIBx8IAt8IhwgGIVCIIkiGCAbfCIbIA6FQiiJIg4gHHwgEnwiHCAYhUIwiSIYIBcgFoVCAYkiFiAZfCABfCIXICKFQiCJIhkgFSAffCIVfCIfIBaFQiiJIhYgF3wgBnwiFyAZhUIwiSIZIB98Ih8gFoVCAYkiFiAVIA+FQgGJIg8gGnwgCHwiFSAdhUIgiSIaICN8Ih0gD4VCKIkiDyAVfCACfCIVfCANfCIihUIgiSIjfCIkIBaFQiiJIhYgInwgCXwiIiAjhUIwiSIjICR8IiQgFoVCAYkiFiAYIBt8IhggFSAahUIwiSIVICEgFIVCAYkiFCAXfCASfCIXhUIgiSIafCIbIBSFQiiJIhQgF3wgCHwiF3wgB3wiISAVIB18IhUgGSAYIA6FQgGJIg4gHnwgBnwiGIVCIIkiGXwiHSAOhUIoiSIOIBh8IAt8IhggGYVCMIkiGYVCIIkiHiAfICAgFSAPhUIBiSIPIBx8IAp8IhWFQiCJIhx8Ih8gD4VCKIkiDyAVfCAEfCIVIByFQjCJIhwgH3wiH3wiICAWhUIoiSIWICF8IAN8IiEgHoVCMIkiHiAgfCIgIBggFyAahUIwiSIXIBt8IhogFIVCAYkiFHwgBXwiGCAchUIgiSIbICR8IhwgFIVCKIkiFCAYfCABfCIYIBuFQjCJIhsgHyAPhUIBiSIPICJ8IAx8Ih8gF4VCIIkiFyAZIB18Ihl8Ih0gD4VCKIkiDyAffCATfCIfIBeFQjCJIhcgHXwiHSAPhUIBiSIPIBkgDoVCAYkiDiAVfCAQfCIVICOFQiCJIhkgGnwiGiAOhUIoiSIOIBV8IAJ8IhV8IBN8IiKFQiCJIiN8IiQgD4VCKIkiDyAifCASfCIiICOFQjCJIiMgJHwiJCAPhUIBiSIPIBsgHHwiGyAVIBmFQjCJIhUgICAWhUIBiSIWIB98IAt8IhmFQiCJIhx8Ih8gFoVCKIkiFiAZfCACfCIZfCAJfCIgIBUgGnwiFSAXIBsgFIVCAYkiFCAhfCAFfCIahUIgiSIXfCIbIBSFQiiJIhQgGnwgA3wiGiAXhUIwiSIXhUIgiSIhIB0gHiAVIA6FQgGJIg4gGHwgEHwiFYVCIIkiGHwiHSAOhUIoiSIOIBV8IAF8IhUgGIVCMIkiGCAdfCIdfCIeIA+FQiiJIg8gIHwgDXwiICAhhUIwiSIhIB58Ih4gGSAchUIwiSIZIB98IhwgFoVCAYkiFiAafCAIfCIaIBiFQiCJIhggJHwiHyAWhUIoiSIWIBp8IAp8IhogGIVCMIkiGCAdIA6FQgGJIg4gInwgBHwiHSAZhUIgiSIZIBcgG3wiF3wiGyAOhUIoiSIOIB18IAd8Ih0gGYVCMIkiGSAbfCIbIA6FQgGJIg4gFSAXIBSFQgGJIhR8IAx8IhUgI4VCIIkiFyAcfCIcIBSFQiiJIhQgFXwgBnwiFXwgEnwiIoVCIIkiI3wiJCAOhUIoiSIOICJ8IBN8IiIgGyAhIBUgF4VCMIkiFSAcfCIXIBSFQgGJIhQgGnwgBnwiGoVCIIkiHHwiGyAUhUIoiSIUIBp8IBB8IhogHIVCMIkiHCAbfCIbIBSFQgGJIhR8IA18IiEgGCAffCIYIBUgHiAPhUIBiSIPIB18IAJ8Ih2FQiCJIhV8Ih4gD4VCKIkiDyAdfCABfCIdIBWFQjCJIhWFQiCJIh8gFyAZIBggFoVCAYkiFiAgfCADfCIYhUIgiSIZfCIXIBaFQiiJIhYgGHwgBHwiGCAZhUIwiSIZIBd8Ihd8IiAgFIVCKIkiFCAhfCAIfCIhIB+FQjCJIh8gIHwiICAiICOFQjCJIiIgJHwiIyAOhUIBiSIOIB18IAd8Ih0gGYVCIIkiGSAbfCIbIA6FQiiJIg4gHXwgDHwiHSAZhUIwiSIZIBcgFoVCAYkiFiAafCALfCIXICKFQiCJIhogFSAefCIVfCIeIBaFQiiJIhYgF3wgCXwiFyAahUIwiSIaIB58Ih4gFoVCAYkiFiAVIA+FQgGJIg8gGHwgBXwiFSAchUIgiSIYICN8IhwgD4VCKIkiDyAVfCAKfCIVfCACfCIChUIgiSIifCIjIBaFQiiJIhYgAnwgC3wiAiAihUIwiSILICN8IiIgFoVCAYkiFiAZIBt8IhkgFSAYhUIwiSIVICAgFIVCAYkiFCAXfCANfCINhUIgiSIXfCIYIBSFQiiJIhQgDXwgBXwiBXwgEHwiECAVIBx8Ig0gGiAZIA6FQgGJIg4gIXwgDHwiDIVCIIkiFXwiGSAOhUIoiSIOIAx8IBJ8IhIgFYVCMIkiDIVCIIkiFSAeIB8gDSAPhUIBiSINIB18IAl8IgmFQiCJIg98IhogDYVCKIkiDSAJfCAIfCIJIA+FQjCJIgggGnwiD3wiGiAWhUIoiSIWIBB8IAd8IhAgEYUgDCAZfCIHIA6FQgGJIgwgCXwgCnwiCiALhUIgiSILIAUgF4VCMIkiBSAYfCIJfCIOIAyFQiiJIgwgCnwgE3wiEyALhUIwiSIKIA58IguFNwOAiQFBACADIAYgDyANhUIBiSINIAJ8fCICIAWFQiCJIgUgB3wiBiANhUIoiSIHIAJ8fCICQQApA4iJAYUgBCABIBIgCSAUhUIBiSIDfHwiASAIhUIgiSISICJ8IgkgA4VCKIkiAyABfHwiASAShUIwiSIEIAl8IhKFNwOIiQFBACATQQApA5CJAYUgECAVhUIwiSIQIBp8IhOFNwOQiQFBACABQQApA5iJAYUgAiAFhUIwiSICIAZ8IgGFNwOYiQFBACASIAOFQgGJQQApA6CJAYUgAoU3A6CJAUEAIBMgFoVCAYlBACkDqIkBhSAKhTcDqIkBQQAgASAHhUIBiUEAKQOwiQGFIASFNwOwiQFBACALIAyFQgGJQQApA7iJAYUgEIU3A7iJAQvdAgUBfwF+AX8BfgJ/IwBBwABrIgAkAAJAQQApA9CJAUIAUg0AQQBBACkDwIkBIgFBACgC4IoBIgKsfCIDNwPAiQFBAEEAKQPIiQEgAyABVK18NwPIiQECQEEALQDoigFFDQBBAEJ/NwPYiQELQQBCfzcD0IkBAkAgAkH/AEoNAEEAIQQDQCACIARqQeCJAWpBADoAACAEQQFqIgRBgAFBACgC4IoBIgJrSA0ACwtB4IkBEAIgAEEAKQOAiQE3AwAgAEEAKQOIiQE3AwggAEEAKQOQiQE3AxAgAEEAKQOYiQE3AxggAEEAKQOgiQE3AyAgAEEAKQOoiQE3AyggAEEAKQOwiQE3AzAgAEEAKQO4iQE3AzhBACgC5IoBIgVBAUgNAEEAIQRBACECA0AgBEGACWogACAEai0AADoAACAEQQFqIQQgBSACQQFqIgJB/wFxSg0ACwsgAEHAAGokAAv9AwMBfwF+AX8jAEGAAWsiAiQAQQBBgQI7AfKKAUEAIAE6APGKAUEAIAA6APCKAUGQfiEAA0AgAEGAiwFqQgA3AAAgAEH4igFqQgA3AAAgAEHwigFqQgA3AAAgAEEYaiIADQALQQAhAEEAQQApA/CKASIDQoiS853/zPmE6gCFNwOAiQFBAEEAKQP4igFCu86qptjQ67O7f4U3A4iJAUEAQQApA4CLAUKr8NP0r+68tzyFNwOQiQFBAEEAKQOIiwFC8e30+KWn/aelf4U3A5iJAUEAQQApA5CLAULRhZrv+s+Uh9EAhTcDoIkBQQBBACkDmIsBQp/Y+dnCkdqCm3+FNwOoiQFBAEEAKQOgiwFC6/qG2r+19sEfhTcDsIkBQQBBACkDqIsBQvnC+JuRo7Pw2wCFNwO4iQFBACADp0H/AXE2AuSKAQJAIAFBAUgNACACQgA3A3ggAkIANwNwIAJCADcDaCACQgA3A2AgAkIANwNYIAJCADcDUCACQgA3A0ggAkIANwNAIAJCADcDOCACQgA3AzAgAkIANwMoIAJCADcDICACQgA3AxggAkIANwMQIAJCADcDCCACQgA3AwBBACEEA0AgAiAAaiAAQYAJai0AADoAACAAQQFqIQAgBEEBaiIEQf8BcSABSA0ACyACQYABEAELIAJBgAFqJAALEgAgAEEDdkH/P3EgAEEQdhAECwkAQYAJIAAQAQsGAEGAiQELGwAgAUEDdkH/P3EgAUEQdhAEQYAJIAAQARADCwsLAQBBgAgLBPAAAAA=",sa="c6f286e6",na={name:ea,data:ia,hash:sa},dA=new Bt;function qn(h){return!Number.isInteger(h)||h<8||h>512||h%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function oa(h,A){return h|A<<16}function Ts(h=512,A=null){if(qn(h))return Promise.reject(qn(h));let t=null,e=h;if(A!==null){if(t=Yt(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=oa(h,t.length)}let i=h/8;return zn(na,i).then(s=>{e>512&&s.writeMemory(t),s.init(e);let n={init:e>512?()=>(s.writeMemory(t),s.init(e),n):()=>(s.init(e),n),update:o=>(s.update(o),n),digest:o=>s.digest(o),save:()=>s.save(),load:o=>(s.load(o),n),blockSize:128,digestSize:i};return n})}function aa(h,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${Jn(h,!1)}$${Jn(t,!1)}`}var On=new DataView(new ArrayBuffer(4));function Kt(h){return On.setInt32(0,h,!0),new Uint8Array(On.buffer)}function xs(h,A,t){return pe(this,void 0,void 0,function*(){if(t<=64){let a=yield Ts(t*8);return a.update(Kt(t)),a.update(A),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);h.init(),h.update(Kt(t)),h.update(A);let s=h.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)h.init(),h.update(s),s=h.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=h,o.init()):o=yield Ts(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function ra(h){switch(h){case"d":return 0;case"i":return 1;default:return 2}}function Aa(h){return pe(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=h,s=Yt(h.password),n=Yt(h.salt),o=19,a=ra(h.hashType),{memorySize:r}=h,c=Yt((A=h.secret)!==null&&A!==void 0?A:""),[l,g]=yield Promise.all([zn(ta,1024),Ts(512)]);l.setMemorySize(r*1024+1024);let p=new Uint8Array(24),d=new DataView(p.buffer);d.setInt32(0,t,!0),d.setInt32(4,i,!0),d.setInt32(8,r,!0),d.setInt32(12,e,!0),d.setInt32(16,o,!0),d.setInt32(20,a,!0),l.writeMemory(p,r*1024),g.init(),g.update(p),g.update(Kt(s.length)),g.update(s),g.update(Kt(n.length)),g.update(n),g.update(Kt(c.length)),g.update(c),g.update(Kt(0));let u=Math.floor(r/(t*4))*4,f=new Uint8Array(72),C=g.digest("binary");f.set(C);for(let w=0;w<t;w++){f.set(Kt(0),64),f.set(Kt(w),68);let y=w*u,F=yield xs(g,f,1024);l.writeMemory(F,y*1024),y+=1,f.set(Kt(1),64),F=yield xs(g,f,1024),l.writeMemory(F,y*1024)}let m=new Uint8Array(1024);Yn(m,l.calculate(new Uint8Array([]),r));let E=yield xs(g,m,i);if(h.outputType==="hex"){let w=new Uint8Array(i*2);return Hs(w,E,i)}return h.outputType==="encoded"?aa(n,h,E):E})}var ca=h=>{var A;if(!h||typeof h!="object")throw new Error("Invalid options parameter. It requires an object.");if(!h.password)throw new Error("Password must be specified");if(h.password=Yt(h.password),h.password.length<1)throw new Error("Password must be specified");if(!h.salt)throw new Error("Salt must be specified");if(h.salt=Yt(h.salt),h.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(h.secret=Yt((A=h.secret)!==null&&A!==void 0?A:""),!Number.isInteger(h.iterations)||h.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(h.parallelism)||h.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(h.hashLength)||h.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(h.memorySize))throw new Error("Memory size should be specified.");if(h.memorySize<8*h.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(h.outputType===void 0&&(h.outputType="hex"),!["hex","binary","encoded"].includes(h.outputType))throw new Error(`Insupported output type ${h.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Us(h){return pe(this,void 0,void 0,function*(){return ca(h),Aa(Object.assign(Object.assign({},h),{hashType:"id"}))})}var hA=new Bt;var gA=new Bt;var pA=new Bt;var IA=new Bt;var uA=new Uint8Array(8);var fA=new Bt;var CA=new Bt;var BA=new Bt;var mA=new Bt;var QA=new Bt;var EA=new Bt;var yA=new Bt;var wA=new Bt;var FA=new Bt;var vA=new Bt;var kA=new Bt;var SA=new Uint8Array(8);var DA=new Bt;var bA=new Uint8Array(8);var NA=new Bt;var xA=new Uint8Array(8);var MA=new Bt;var HA=new Bt;var TA=new Bt;Mt();var zt=new Uint8Array([83,84,65,83,72,69,78,67]),$n=2,_n=1,jn=2,la=32,Gs=12,Vn=32,da=6e5,ha=47104,ga=3,pa=1,Nt=h=>h;function Ne(h){if(h.length<zt.length+1)return!1;for(let A=0;A<zt.length;A++)if(h[A]!==zt[A])return!1;return!0}function Wn(h,A,t){h[A]=t>>>24&255,h[A+1]=t>>>16&255,h[A+2]=t>>>8&255,h[A+3]=t&255}function Xn(h,A){return h[A]*16777216+(h[A+1]<<16)+(h[A+2]<<8)+h[A+3]}async function Rs(h,A,t){if(t.id===jn)return await Us({password:h,salt:A,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Vn,outputType:"binary"});if(t.id===_n){let e=await crypto.subtle.importKey("raw",Nt(new TextEncoder().encode(h)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:Nt(A),iterations:t.a,hash:"SHA-256"},e,Vn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function to(h){return crypto.subtle.importKey("raw",Nt(h),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var eo={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function io(h,A){let t=crypto.getRandomValues(new Uint8Array(la)),e=crypto.getRandomValues(new Uint8Array(Gs)),i,s,n;try{i={id:jn,a:ha,b:ga,c:pa},n=await Rs(A,t,i),s="argon2id"}catch(l){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",l),i={id:_n,a:da,b:0,c:0},n=await Rs(A,t,i),s="pbkdf2"}let o=Ia(i,t,e),a=await to(n),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Nt(e),additionalData:Nt(o)},a,Nt(h))),c=new Uint8Array(o.length+r.length);return c.set(o,0),c.set(r,o.length),{data:c,kdf:s}}var oi=null;async function so(){if(oi!==null)return oi;try{await Us({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),oi=!0}catch{oi=!1}return oi}function Ia(h,A,t){let e=new Uint8Array(zt.length+1+1+4+4+1+1+A.length+t.length),i=0;return e.set(zt,i),i+=zt.length,e[i++]=$n,e[i++]=h.id,Wn(e,i,h.a),i+=4,Wn(e,i,h.b),i+=4,e[i++]=h.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function Zn(h,A){if(!Ne(h))throw new Error("Not an encrypted Stashpad file.");let t=h[zt.length];if(t===1)return ua(h,A);if(t!==$n)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=zt.length+1,i={id:h[e++],a:0,b:0,c:0};i.a=Xn(h,e),e+=4,i.b=Xn(h,e),e+=4,i.c=h[e++];let s=h[e++],n=h.slice(e,e+s);e+=s;let o=h.slice(e,e+Gs);e+=Gs;let a=h.slice(0,e),r=h.slice(e),c=await Rs(A,n,i),l=await to(c),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:Nt(o),additionalData:Nt(a)},l,Nt(r));return new Uint8Array(g)}async function ua(h,A){let t=zt.length+1,e=h.slice(t,t+16);t+=16;let i=h.slice(t,t+12);t+=12;let s=h.slice(t),n=await crypto.subtle.importKey("raw",Nt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:Nt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:Nt(i)},o,Nt(s));return new Uint8Array(a)}async function xe(h,A,t={}){if(!Ne(A))return A;if(t.secretId){let i=h.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Zn(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new Oe(h,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Zn(A,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}gi();Mt();function fa(h){return h.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function no(h,A){let t=Ba(h,A);if(t.length===0){new ie.Notice("Nothing to export.");return}let e=ma(h,t);if(e.length===0){new ie.Notice("No exportable notes (no files attached).");return}let i=(h.noteFolder.split("/").pop()||h.noteFolder).trim(),s=t.length===1?h.titleForNode(t[0]):`${i}-${t.length}notes`;new qe(h.app,s,e.length,(n,o,a)=>{Ca(h,t,e,n,o,a)},so).open()}async function Ca(h,A,t,e,i,s=!1){try{let n=await Gn(h.app,{rootNotes:A.filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),allDescendants:t.filter(d=>!A.some(I=>I.id===d.id)).filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),sourceFolder:h.noteFolder}),o="";if(i){let d=await io(n,i);n=d.data;let I=eo[d.kdf];o=I.strong?` (encrypted \xB7 ${I.label})`:` (encrypted \xB7 ${I.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,ie.moment)().format("YYYYMMDD-HHmmss"),r=fa(e),c=(h.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),l=`${h.noteFolder}/${c}`;await h.ensureFolder(l);let g=`${r}-${a}`,p=`${l}/${g}.${te}`;if(await h.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let d=h.app.secretStorage;try{d?.setSecret(Pe(g),i)}catch(I){console.warn("[Stashpad] couldn't save export passphrase to secret storage",I)}}await h.log.append({type:"stash_export",id:A[0].id,payload:{path:p,noteCount:t.length,rootIds:A.map(d=>d.id)}}),h.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:h.noteFolder,actions:h.actionsForFile(p),duration:0})}catch(n){h.plugin.notifications.show({message:`Stashpad: export failed +${A}`}async function Tn(h,A){if(!(!A||await h.vault.adapter.exists(A)))try{await h.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}function pe(h,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(l){try{r(e.next(l))}catch(c){n(c)}}function a(l){try{r(e.throw(l))}catch(c){n(c)}}function r(l){l.done?s(l.value):i(l.value).then(o,a)}r((e=e.apply(h,A||[])).next())})}var Bt=class{constructor(){this.mutex=Promise.resolve()}lock(){let A=()=>{};return this.mutex=this.mutex.then(()=>new Promise(A)),new Promise(t=>{A=t})}dispatch(A){return pe(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(A())}finally{t()}})}},Ds;function zo(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Ms=zo(),bs=(Ds=Ms.Buffer)!==null&&Ds!==void 0?Ds:null,Vo=Ms.TextEncoder?new Ms.TextEncoder:null;function Kn(h,A){return(h&15)+(h>>6|h>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function Yn(h,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;h[e]=Kn(A.charCodeAt(i),A.charCodeAt(i+1))}}function Wo(h,A){if(h.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==Kn(h.charCodeAt(e),h.charCodeAt(e+1)))return!1}return!0}var Pn=87,Ln=48;function Hs(h,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;h[e++]=s>9?s+Pn:s+Ln,s=A[i]&15,h[e++]=s>9?s+Pn:s+Ln}return String.fromCharCode.apply(null,h)}var Yt=bs!==null?h=>{if(typeof h=="string"){let A=bs.from(h,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(bs.isBuffer(h))return new Uint8Array(h.buffer,h.byteOffset,h.length);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")}:h=>{if(typeof h=="string")return Vo.encode(h);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")},Tt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ni=new Uint8Array(256);for(let h=0;h<Tt.length;h++)ni[Tt.charCodeAt(h)]=h;function Jn(h,A=!0){let t=h.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(h[n]<<16&16711680)+(h[n+1]<<8&65280)+(h[n+2]&255),a=Tt.charAt(o>>18&63)+Tt.charAt(o>>12&63)+Tt.charAt(o>>6&63)+Tt.charAt(o&63);i.push(a)}if(e===1){let n=h[t-1],o=Tt.charAt(n>>2),a=Tt.charAt(n<<4&63);i.push(`${o}${a}`),A&&i.push("==")}else if(e===2){let n=(h[t-2]<<8)+h[t-1],o=Tt.charAt(n>>10),a=Tt.charAt(n>>4&63),r=Tt.charAt(n<<2&63);i.push(`${o}${a}${r}`),A&&i.push("=")}return i.join("")}function Xo(h){let A=Math.floor(h.length*.75),t=h.length;return h[t-1]==="="&&(A-=1,h[t-2]==="="&&(A-=1)),A}function Zo(h){let A=Xo(h),t=h.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=ni[h.charCodeAt(s)],o=ni[h.charCodeAt(s+1)],a=ni[h.charCodeAt(s+2)],r=ni[h.charCodeAt(s+3)];e[i]=n<<2|o>>4,i+=1,e[i]=(o&15)<<4|a>>2,i+=1,e[i]=(a&3)<<6|r&63,i+=1}return e}var Oi=16*1024,si=4,$o=new Bt,Ns=new Map;function zn(h,A){return pe(this,void 0,void 0,function*(){let t=null,e=null,i=!1;if(typeof WebAssembly>"u")throw new Error("WebAssembly is not supported in this environment!");let s=(y,F=0)=>{e.set(y,F)},n=()=>e,o=()=>t.exports,a=y=>{t.exports.Hash_SetMemorySize(y);let F=t.exports.Hash_GetBuffer(),D=t.exports.memory.buffer;e=new Uint8Array(D,F,y)},r=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),l=$o.dispatch(()=>pe(this,void 0,void 0,function*(){if(!Ns.has(h.name)){let F=Zo(h.data),D=WebAssembly.compile(F);Ns.set(h.name,D)}let y=yield Ns.get(h.name);t=yield WebAssembly.instantiate(y,{})})),c=()=>pe(this,void 0,void 0,function*(){t||(yield l);let y=t.exports.Hash_GetBuffer(),F=t.exports.memory.buffer;e=new Uint8Array(F,y,Oi)}),g=(y=null)=>{i=!0,t.exports.Hash_Init(y)},p=y=>{let F=0;for(;F<y.length;){let D=y.subarray(F,F+Oi);F+=D.length,e.set(D),t.exports.Hash_Update(D.length)}},d=y=>{if(!i)throw new Error("update() called before init()");let F=Yt(y);p(F)},I=new Uint8Array(A*2),u=(y,F=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(F),y==="binary"?e.slice(0,A):Hs(I,e,A)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),F=r(),D=t.exports.memory.buffer,L=new Uint8Array(D,y,F),S=new Uint8Array(si+F);return Yn(S,h.hash),S.set(L,si),S},C=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let F=t.exports.Hash_GetState(),D=r(),L=si+D,S=t.exports.memory.buffer;if(y.length!==L)throw new Error(`Bad state length (expected ${L} bytes, got ${y.length})`);if(!Wo(h.hash,y.subarray(0,si)))throw new Error("This state was written by an incompatible hash implementation");let b=y.subarray(si);new Uint8Array(S,F,D).set(b),i=!0},m=y=>typeof y=="string"?y.length<Oi/4:y.byteLength<Oi,E=m;switch(h.name){case"argon2":case"scrypt":E=()=>!0;break;case"blake2b":case"blake2s":E=(y,F)=>F<=512&&m(y);break;case"blake3":E=(y,F)=>F===0&&m(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":E=()=>!1;break}let w=(y,F=null,D=null)=>{if(!E(y,F))return g(F),d(y),u("hex",D);let L=Yt(y);return e.set(L),t.exports.Hash_Calculate(L.length,F,D),Hs(I,e,A)};return yield c(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:g,update:d,digest:u,save:f,load:C,calculate:w,hashLength:A}})}var hA=new Bt;var _o="argon2",jo="AGFzbQEAAAABKQVgAX8Bf2AAAX9gEH9/f39/f39/f39/f39/f38AYAR/f39/AGACf38AAwYFAAECAwQFBgEBAoCAAgYIAX8BQZCoBAsHQQQGbWVtb3J5AgASSGFzaF9TZXRNZW1vcnlTaXplAAAOSGFzaF9HZXRCdWZmZXIAAQ5IYXNoX0NhbGN1bGF0ZQAECvEyBVgBAn9BACEBAkAgAEEAKAKICCICRg0AAkAgACACayIAQRB2IABBgIB8cSAASWoiAEAAQX9HDQBB/wHADwtBACEBQQBBACkDiAggAEEQdK18NwOICAsgAcALcAECfwJAQQAoAoAIIgANAEEAPwBBEHQiADYCgAhBACgCiAgiAUGAgCBGDQACQEGAgCAgAWsiAEEQdiAAQYCAfHEgAElqIgBAAEF/Rw0AQQAPC0EAQQApA4gIIABBEHStfDcDiAhBACgCgAghAAsgAAvcDgECfiAAIAQpAwAiECAAKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAMIBAgDCkDAIVCIIkiEDcDACAIIBAgCCkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgBCAQIAQpAwCFQiiJIhA3AwAgACAQIAApAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAwgECAMKQMAhUIwiSIQNwMAIAggECAIKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAEIBAgBCkDAIVCAYk3AwAgASAFKQMAIhAgASkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDSAQIA0pAwCFQiCJIhA3AwAgCSAQIAkpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAUgECAFKQMAhUIoiSIQNwMAIAEgECABKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACANIBAgDSkDAIVCMIkiEDcDACAJIBAgCSkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBSAQIAUpAwCFQgGJNwMAIAIgBikDACIQIAIpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIA4gECAOKQMAhUIgiSIQNwMAIAogECAKKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAGIBAgBikDAIVCKIkiEDcDACACIBAgAikDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgDiAQIA4pAwCFQjCJIhA3AwAgCiAQIAopAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAYgECAGKQMAhUIBiTcDACADIAcpAwAiECADKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAPIBAgDykDAIVCIIkiEDcDACALIBAgCykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgByAQIAcpAwCFQiiJIhA3AwAgAyAQIAMpAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIA8gECAPKQMAhUIwiSIQNwMAIAsgECALKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgACAFKQMAIhAgACkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDyAQIA8pAwCFQiCJIhA3AwAgCiAQIAopAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAUgECAFKQMAhUIoiSIQNwMAIAAgECAAKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAPIBAgDykDAIVCMIkiEDcDACAKIBAgCikDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBSAQIAUpAwCFQgGJNwMAIAEgBikDACIQIAEpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAwgECAMKQMAhUIgiSIQNwMAIAsgECALKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACAGIBAgBikDAIVCKIkiEDcDACABIBAgASkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgDCAQIAwpAwCFQjCJIhA3AwAgCyAQIAspAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIAYgECAGKQMAhUIBiTcDACACIAcpAwAiECACKQMAIhF8IBFCAYZC/v///x+DIBBC/////w+DfnwiEDcDACANIBAgDSkDAIVCIIkiEDcDACAIIBAgCCkDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgByAQIAcpAwCFQiiJIhA3AwAgAiAQIAIpAwAiEXwgEEL/////D4MgEUIBhkL+////H4N+fCIQNwMAIA0gECANKQMAhUIwiSIQNwMAIAggECAIKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAHIBAgBykDAIVCAYk3AwAgAyAEKQMAIhAgAykDACIRfCARQgGGQv7///8fgyAQQv////8Pg358IhA3AwAgDiAQIA4pAwCFQiCJIhA3AwAgCSAQIAkpAwAiEXwgEUIBhkL+////H4MgEEL/////D4N+fCIQNwMAIAQgECAEKQMAhUIoiSIQNwMAIAMgECADKQMAIhF8IBBC/////w+DIBFCAYZC/v///x+DfnwiEDcDACAOIBAgDikDAIVCMIkiEDcDACAJIBAgCSkDACIRfCAQQv////8PgyARQgGGQv7///8fg358IhA3AwAgBCAQIAQpAwCFQgGJNwMAC98aAQN/QQAhBEEAIAIpAwAgASkDAIU3A5AIQQAgAikDCCABKQMIhTcDmAhBACACKQMQIAEpAxCFNwOgCEEAIAIpAxggASkDGIU3A6gIQQAgAikDICABKQMghTcDsAhBACACKQMoIAEpAyiFNwO4CEEAIAIpAzAgASkDMIU3A8AIQQAgAikDOCABKQM4hTcDyAhBACACKQNAIAEpA0CFNwPQCEEAIAIpA0ggASkDSIU3A9gIQQAgAikDUCABKQNQhTcD4AhBACACKQNYIAEpA1iFNwPoCEEAIAIpA2AgASkDYIU3A/AIQQAgAikDaCABKQNohTcD+AhBACACKQNwIAEpA3CFNwOACUEAIAIpA3ggASkDeIU3A4gJQQAgAikDgAEgASkDgAGFNwOQCUEAIAIpA4gBIAEpA4gBhTcDmAlBACACKQOQASABKQOQAYU3A6AJQQAgAikDmAEgASkDmAGFNwOoCUEAIAIpA6ABIAEpA6ABhTcDsAlBACACKQOoASABKQOoAYU3A7gJQQAgAikDsAEgASkDsAGFNwPACUEAIAIpA7gBIAEpA7gBhTcDyAlBACACKQPAASABKQPAAYU3A9AJQQAgAikDyAEgASkDyAGFNwPYCUEAIAIpA9ABIAEpA9ABhTcD4AlBACACKQPYASABKQPYAYU3A+gJQQAgAikD4AEgASkD4AGFNwPwCUEAIAIpA+gBIAEpA+gBhTcD+AlBACACKQPwASABKQPwAYU3A4AKQQAgAikD+AEgASkD+AGFNwOICkEAIAIpA4ACIAEpA4AChTcDkApBACACKQOIAiABKQOIAoU3A5gKQQAgAikDkAIgASkDkAKFNwOgCkEAIAIpA5gCIAEpA5gChTcDqApBACACKQOgAiABKQOgAoU3A7AKQQAgAikDqAIgASkDqAKFNwO4CkEAIAIpA7ACIAEpA7AChTcDwApBACACKQO4AiABKQO4AoU3A8gKQQAgAikDwAIgASkDwAKFNwPQCkEAIAIpA8gCIAEpA8gChTcD2ApBACACKQPQAiABKQPQAoU3A+AKQQAgAikD2AIgASkD2AKFNwPoCkEAIAIpA+ACIAEpA+AChTcD8ApBACACKQPoAiABKQPoAoU3A/gKQQAgAikD8AIgASkD8AKFNwOAC0EAIAIpA/gCIAEpA/gChTcDiAtBACACKQOAAyABKQOAA4U3A5ALQQAgAikDiAMgASkDiAOFNwOYC0EAIAIpA5ADIAEpA5ADhTcDoAtBACACKQOYAyABKQOYA4U3A6gLQQAgAikDoAMgASkDoAOFNwOwC0EAIAIpA6gDIAEpA6gDhTcDuAtBACACKQOwAyABKQOwA4U3A8ALQQAgAikDuAMgASkDuAOFNwPIC0EAIAIpA8ADIAEpA8ADhTcD0AtBACACKQPIAyABKQPIA4U3A9gLQQAgAikD0AMgASkD0AOFNwPgC0EAIAIpA9gDIAEpA9gDhTcD6AtBACACKQPgAyABKQPgA4U3A/ALQQAgAikD6AMgASkD6AOFNwP4C0EAIAIpA/ADIAEpA/ADhTcDgAxBACACKQP4AyABKQP4A4U3A4gMQQAgAikDgAQgASkDgASFNwOQDEEAIAIpA4gEIAEpA4gEhTcDmAxBACACKQOQBCABKQOQBIU3A6AMQQAgAikDmAQgASkDmASFNwOoDEEAIAIpA6AEIAEpA6AEhTcDsAxBACACKQOoBCABKQOoBIU3A7gMQQAgAikDsAQgASkDsASFNwPADEEAIAIpA7gEIAEpA7gEhTcDyAxBACACKQPABCABKQPABIU3A9AMQQAgAikDyAQgASkDyASFNwPYDEEAIAIpA9AEIAEpA9AEhTcD4AxBACACKQPYBCABKQPYBIU3A+gMQQAgAikD4AQgASkD4ASFNwPwDEEAIAIpA+gEIAEpA+gEhTcD+AxBACACKQPwBCABKQPwBIU3A4ANQQAgAikD+AQgASkD+ASFNwOIDUEAIAIpA4AFIAEpA4AFhTcDkA1BACACKQOIBSABKQOIBYU3A5gNQQAgAikDkAUgASkDkAWFNwOgDUEAIAIpA5gFIAEpA5gFhTcDqA1BACACKQOgBSABKQOgBYU3A7ANQQAgAikDqAUgASkDqAWFNwO4DUEAIAIpA7AFIAEpA7AFhTcDwA1BACACKQO4BSABKQO4BYU3A8gNQQAgAikDwAUgASkDwAWFNwPQDUEAIAIpA8gFIAEpA8gFhTcD2A1BACACKQPQBSABKQPQBYU3A+ANQQAgAikD2AUgASkD2AWFNwPoDUEAIAIpA+AFIAEpA+AFhTcD8A1BACACKQPoBSABKQPoBYU3A/gNQQAgAikD8AUgASkD8AWFNwOADkEAIAIpA/gFIAEpA/gFhTcDiA5BACACKQOABiABKQOABoU3A5AOQQAgAikDiAYgASkDiAaFNwOYDkEAIAIpA5AGIAEpA5AGhTcDoA5BACACKQOYBiABKQOYBoU3A6gOQQAgAikDoAYgASkDoAaFNwOwDkEAIAIpA6gGIAEpA6gGhTcDuA5BACACKQOwBiABKQOwBoU3A8AOQQAgAikDuAYgASkDuAaFNwPIDkEAIAIpA8AGIAEpA8AGhTcD0A5BACACKQPIBiABKQPIBoU3A9gOQQAgAikD0AYgASkD0AaFNwPgDkEAIAIpA9gGIAEpA9gGhTcD6A5BACACKQPgBiABKQPgBoU3A/AOQQAgAikD6AYgASkD6AaFNwP4DkEAIAIpA/AGIAEpA/AGhTcDgA9BACACKQP4BiABKQP4BoU3A4gPQQAgAikDgAcgASkDgAeFNwOQD0EAIAIpA4gHIAEpA4gHhTcDmA9BACACKQOQByABKQOQB4U3A6APQQAgAikDmAcgASkDmAeFNwOoD0EAIAIpA6AHIAEpA6AHhTcDsA9BACACKQOoByABKQOoB4U3A7gPQQAgAikDsAcgASkDsAeFNwPAD0EAIAIpA7gHIAEpA7gHhTcDyA9BACACKQPAByABKQPAB4U3A9APQQAgAikDyAcgASkDyAeFNwPYD0EAIAIpA9AHIAEpA9AHhTcD4A9BACACKQPYByABKQPYB4U3A+gPQQAgAikD4AcgASkD4AeFNwPwD0EAIAIpA+gHIAEpA+gHhTcD+A9BACACKQPwByABKQPwB4U3A4AQQQAgAikD+AcgASkD+AeFNwOIEEGQCEGYCEGgCEGoCEGwCEG4CEHACEHICEHQCEHYCEHgCEHoCEHwCEH4CEGACUGICRACQZAJQZgJQaAJQagJQbAJQbgJQcAJQcgJQdAJQdgJQeAJQegJQfAJQfgJQYAKQYgKEAJBkApBmApBoApBqApBsApBuApBwApByApB0ApB2ApB4ApB6ApB8ApB+ApBgAtBiAsQAkGQC0GYC0GgC0GoC0GwC0G4C0HAC0HIC0HQC0HYC0HgC0HoC0HwC0H4C0GADEGIDBACQZAMQZgMQaAMQagMQbAMQbgMQcAMQcgMQdAMQdgMQeAMQegMQfAMQfgMQYANQYgNEAJBkA1BmA1BoA1BqA1BsA1BuA1BwA1ByA1B0A1B2A1B4A1B6A1B8A1B+A1BgA5BiA4QAkGQDkGYDkGgDkGoDkGwDkG4DkHADkHIDkHQDkHYDkHgDkHoDkHwDkH4DkGAD0GIDxACQZAPQZgPQaAPQagPQbAPQbgPQcAPQcgPQdAPQdgPQeAPQegPQfAPQfgPQYAQQYgQEAJBkAhBmAhBkAlBmAlBkApBmApBkAtBmAtBkAxBmAxBkA1BmA1BkA5BmA5BkA9BmA8QAkGgCEGoCEGgCUGoCUGgCkGoCkGgC0GoC0GgDEGoDEGgDUGoDUGgDkGoDkGgD0GoDxACQbAIQbgIQbAJQbgJQbAKQbgKQbALQbgLQbAMQbgMQbANQbgNQbAOQbgOQbAPQbgPEAJBwAhByAhBwAlByAlBwApByApBwAtByAtBwAxByAxBwA1ByA1BwA5ByA5BwA9ByA8QAkHQCEHYCEHQCUHYCUHQCkHYCkHQC0HYC0HQDEHYDEHQDUHYDUHQDkHYDkHQD0HYDxACQeAIQegIQeAJQegJQeAKQegKQeALQegLQeAMQegMQeANQegNQeAOQegOQeAPQegPEAJB8AhB+AhB8AlB+AlB8ApB+ApB8AtB+AtB8AxB+AxB8A1B+A1B8A5B+A5B8A9B+A8QAkGACUGICUGACkGICkGAC0GIC0GADEGIDEGADUGIDUGADkGIDkGAD0GID0GAEEGIEBACAkACQCADRQ0AA0AgACAEaiIDIAIgBGoiBSkDACABIARqIgYpAwCFIARBkAhqKQMAhSADKQMAhTcDACADQQhqIgMgBUEIaikDACAGQQhqKQMAhSAEQZgIaikDAIUgAykDAIU3AwAgBEEQaiIEQYAIRw0ADAILC0EAIQQDQCAAIARqIgMgAiAEaiIFKQMAIAEgBGoiBikDAIUgBEGQCGopAwCFNwMAIANBCGogBUEIaikDACAGQQhqKQMAhSAEQZgIaikDAIU3AwAgBEEQaiIEQYAIRw0ACwsL5QcMBX8BfgR/An4BfwF+AX8Bfgd/AX4DfwF+AkBBACgCgAgiAiABQQp0aiIDKAIIIAFHDQAgAygCDCEEIAMoAgAhBUEAIAMoAhQiBq03A7gQQQAgBK0iBzcDsBBBACAFIAEgBUECdG4iCGwiCUECdK03A6gQAkACQAJAAkAgBEUNAEF/IQogBUUNASAIQQNsIQsgCEECdCIErSEMIAWtIQ0gBkF/akECSSEOQgAhDwNAQQAgDzcDkBAgD6chEEIAIRFBACEBA0BBACARNwOgECAPIBGEUCIDIA5xIRIgBkEBRiAPUCITIAZBAkYgEUICVHFxciEUQX8gAUEBakEDcSAIbEF/aiATGyEVIAEgEHIhFiABIAhsIRcgA0EBdCEYQgAhGQNAQQBCADcDwBBBACAZNwOYECAYIQECQCASRQ0AQQBCATcDwBBBkBhBkBBBkCBBABADQZAYQZAYQZAgQQAQA0ECIQELAkAgASAITw0AIAQgGaciGmwgF2ogAWohAwNAIANBACAEIAEbQQAgEVAiGxtqQX9qIRwCQAJAIBQNAEEAKAKACCICIBxBCnQiHGohCgwBCwJAIAFB/wBxIgINAEEAQQApA8AQQgF8NwPAEEGQGEGQEEGQIEEAEANBkBhBkBhBkCBBABADCyAcQQp0IRwgAkEDdEGQGGohCkEAKAKACCECCyACIANBCnRqIAIgHGogAiAKKQMAIh1CIIinIAVwIBogFhsiHCAEbCABIAFBACAZIBytUSIcGyIKIBsbIBdqIAogC2ogExsgAUUgHHJrIhsgFWqtIB1C/////w+DIh0gHX5CIIggG61+QiCIfSAMgqdqQQp0akEBEAMgA0EBaiEDIAggAUEBaiIBRw0ACwsgGUIBfCIZIA1SDQALIBFCAXwiEachASARQgRSDQALIA9CAXwiDyAHUg0AC0EAKAKACCECCyAJQQx0QYB4aiEXIAVBf2oiCkUNAgwBC0EAQgM3A6AQQQAgBEF/aq03A5AQQYB4IRcLIAIgF2ohGyAIQQx0IQhBACEcA0AgCCAcQQFqIhxsQYB4aiEEQQAhAQNAIBsgAWoiAyADKQMAIAIgBCABamopAwCFNwMAIANBCGoiAyADKQMAIAIgBCABQQhyamopAwCFNwMAIAFBCGohAyABQRBqIQEgA0H4B0kNAAsgHCAKRw0ACwsgAiAXaiEbQXghAQNAIAIgAWoiA0EIaiAbIAFqIgRBCGopAwA3AwAgA0EQaiAEQRBqKQMANwMAIANBGGogBEEYaikDADcDACADQSBqIARBIGopAwA3AwAgAUEgaiIBQfgHSQ0ACwsL",ta="e4cdc523",ea={name:_o,data:jo,hash:ta},ia="blake2b",sa="AGFzbQEAAAABEQRgAAF/YAJ/fwBgAX8AYAAAAwoJAAECAwECAgABBQQBAQICBg4CfwFBsIsFC38AQYAICwdwCAZtZW1vcnkCAA5IYXNoX0dldEJ1ZmZlcgAACkhhc2hfRmluYWwAAwlIYXNoX0luaXQABQtIYXNoX1VwZGF0ZQAGDUhhc2hfR2V0U3RhdGUABw5IYXNoX0NhbGN1bGF0ZQAIClNUQVRFX1NJWkUDAQrTOAkFAEGACQvrAgIFfwF+AkAgAUEBSA0AAkACQAJAIAFBgAFBACgC4IoBIgJrIgNKDQAgASEEDAELQQBBADYC4IoBAkAgAkH/AEoNACACQeCJAWohBSAAIQRBACEGA0AgBSAELQAAOgAAIARBAWohBCAFQQFqIQUgAyAGQQFqIgZB/wFxSg0ACwtBAEEAKQPAiQEiB0KAAXw3A8CJAUEAQQApA8iJASAHQv9+Vq18NwPIiQFB4IkBEAIgACADaiEAAkAgASADayIEQYEBSA0AIAIgAWohBQNAQQBBACkDwIkBIgdCgAF8NwPAiQFBAEEAKQPIiQEgB0L/flatfDcDyIkBIAAQAiAAQYABaiEAIAVBgH9qIgVBgAJLDQALIAVBgH9qIQQMAQsgBEEATA0BC0EAIQUDQCAFQQAoAuCKAWpB4IkBaiAAIAVqLQAAOgAAIAQgBUEBaiIFQf8BcUoNAAsLQQBBACgC4IoBIARqNgLgigELC78uASR+QQBBACkD0IkBQQApA7CJASIBQQApA5CJAXwgACkDICICfCIDhULr+obav7X2wR+FQiCJIgRCq/DT9K/uvLc8fCIFIAGFQiiJIgYgA3wgACkDKCIBfCIHIASFQjCJIgggBXwiCSAGhUIBiSIKQQApA8iJAUEAKQOoiQEiBEEAKQOIiQF8IAApAxAiA3wiBYVCn9j52cKR2oKbf4VCIIkiC0K7zqqm2NDrs7t/fCIMIASFQiiJIg0gBXwgACkDGCIEfCIOfCAAKQNQIgV8Ig9BACkDwIkBQQApA6CJASIQQQApA4CJASIRfCAAKQMAIgZ8IhKFQtGFmu/6z5SH0QCFQiCJIhNCiJLznf/M+YTqAHwiFCAQhUIoiSIVIBJ8IAApAwgiEHwiFiAThUIwiSIXhUIgiSIYQQApA9iJAUEAKQO4iQEiE0EAKQOYiQF8IAApAzAiEnwiGYVC+cL4m5Gjs/DbAIVCIIkiGkLx7fT4paf9p6V/fCIbIBOFQiiJIhwgGXwgACkDOCITfCIZIBqFQjCJIhogG3wiG3wiHSAKhUIoiSIeIA98IAApA1giCnwiDyAYhUIwiSIYIB18Ih0gDiALhUIwiSIOIAx8Ih8gDYVCAYkiDCAWfCAAKQNAIgt8Ig0gGoVCIIkiFiAJfCIaIAyFQiiJIiAgDXwgACkDSCIJfCIhIBaFQjCJIhYgGyAchUIBiSIMIAd8IAApA2AiB3wiDSAOhUIgiSIOIBcgFHwiFHwiFyAMhUIoiSIbIA18IAApA2giDHwiHCAOhUIwiSIOIBd8IhcgG4VCAYkiGyAZIBQgFYVCAYkiFHwgACkDcCINfCIVIAiFQiCJIhkgH3wiHyAUhUIoiSIUIBV8IAApA3giCHwiFXwgDHwiIoVCIIkiI3wiJCAbhUIoiSIbICJ8IBJ8IiIgFyAYIBUgGYVCMIkiFSAffCIZIBSFQgGJIhQgIXwgDXwiH4VCIIkiGHwiFyAUhUIoiSIUIB98IAV8Ih8gGIVCMIkiGCAXfCIXIBSFQgGJIhR8IAF8IiEgFiAafCIWIBUgHSAehUIBiSIaIBx8IAl8IhyFQiCJIhV8Ih0gGoVCKIkiGiAcfCAIfCIcIBWFQjCJIhWFQiCJIh4gGSAOIBYgIIVCAYkiFiAPfCACfCIPhUIgiSIOfCIZIBaFQiiJIhYgD3wgC3wiDyAOhUIwiSIOIBl8Ihl8IiAgFIVCKIkiFCAhfCAEfCIhIB6FQjCJIh4gIHwiICAiICOFQjCJIiIgJHwiIyAbhUIBiSIbIBx8IAp8IhwgDoVCIIkiDiAXfCIXIBuFQiiJIhsgHHwgE3wiHCAOhUIwiSIOIBkgFoVCAYkiFiAffCAQfCIZICKFQiCJIh8gFSAdfCIVfCIdIBaFQiiJIhYgGXwgB3wiGSAfhUIwiSIfIB18Ih0gFoVCAYkiFiAVIBqFQgGJIhUgD3wgBnwiDyAYhUIgiSIYICN8IhogFYVCKIkiFSAPfCADfCIPfCAHfCIihUIgiSIjfCIkIBaFQiiJIhYgInwgBnwiIiAjhUIwiSIjICR8IiQgFoVCAYkiFiAOIBd8Ig4gDyAYhUIwiSIPICAgFIVCAYkiFCAZfCAKfCIXhUIgiSIYfCIZIBSFQiiJIhQgF3wgC3wiF3wgBXwiICAPIBp8Ig8gHyAOIBuFQgGJIg4gIXwgCHwiGoVCIIkiG3wiHyAOhUIoiSIOIBp8IAx8IhogG4VCMIkiG4VCIIkiISAdIB4gDyAVhUIBiSIPIBx8IAF8IhWFQiCJIhx8Ih0gD4VCKIkiDyAVfCADfCIVIByFQjCJIhwgHXwiHXwiHiAWhUIoiSIWICB8IA18IiAgIYVCMIkiISAefCIeIBogFyAYhUIwiSIXIBl8IhggFIVCAYkiFHwgCXwiGSAchUIgiSIaICR8IhwgFIVCKIkiFCAZfCACfCIZIBqFQjCJIhogHSAPhUIBiSIPICJ8IAR8Ih0gF4VCIIkiFyAbIB98Iht8Ih8gD4VCKIkiDyAdfCASfCIdIBeFQjCJIhcgH3wiHyAPhUIBiSIPIBsgDoVCAYkiDiAVfCATfCIVICOFQiCJIhsgGHwiGCAOhUIoiSIOIBV8IBB8IhV8IAx8IiKFQiCJIiN8IiQgD4VCKIkiDyAifCAHfCIiICOFQjCJIiMgJHwiJCAPhUIBiSIPIBogHHwiGiAVIBuFQjCJIhUgHiAWhUIBiSIWIB18IAR8IhuFQiCJIhx8Ih0gFoVCKIkiFiAbfCAQfCIbfCABfCIeIBUgGHwiFSAXIBogFIVCAYkiFCAgfCATfCIYhUIgiSIXfCIaIBSFQiiJIhQgGHwgCXwiGCAXhUIwiSIXhUIgiSIgIB8gISAVIA6FQgGJIg4gGXwgCnwiFYVCIIkiGXwiHyAOhUIoiSIOIBV8IA18IhUgGYVCMIkiGSAffCIffCIhIA+FQiiJIg8gHnwgBXwiHiAghUIwiSIgICF8IiEgGyAchUIwiSIbIB18IhwgFoVCAYkiFiAYfCADfCIYIBmFQiCJIhkgJHwiHSAWhUIoiSIWIBh8IBJ8IhggGYVCMIkiGSAfIA6FQgGJIg4gInwgAnwiHyAbhUIgiSIbIBcgGnwiF3wiGiAOhUIoiSIOIB98IAZ8Ih8gG4VCMIkiGyAafCIaIA6FQgGJIg4gFSAXIBSFQgGJIhR8IAh8IhUgI4VCIIkiFyAcfCIcIBSFQiiJIhQgFXwgC3wiFXwgBXwiIoVCIIkiI3wiJCAOhUIoiSIOICJ8IAh8IiIgGiAgIBUgF4VCMIkiFSAcfCIXIBSFQgGJIhQgGHwgCXwiGIVCIIkiHHwiGiAUhUIoiSIUIBh8IAZ8IhggHIVCMIkiHCAafCIaIBSFQgGJIhR8IAR8IiAgGSAdfCIZIBUgISAPhUIBiSIPIB98IAN8Ih2FQiCJIhV8Ih8gD4VCKIkiDyAdfCACfCIdIBWFQjCJIhWFQiCJIiEgFyAbIBkgFoVCAYkiFiAefCABfCIZhUIgiSIbfCIXIBaFQiiJIhYgGXwgE3wiGSAbhUIwiSIbIBd8Ihd8Ih4gFIVCKIkiFCAgfCAMfCIgICGFQjCJIiEgHnwiHiAiICOFQjCJIiIgJHwiIyAOhUIBiSIOIB18IBJ8Ih0gG4VCIIkiGyAafCIaIA6FQiiJIg4gHXwgC3wiHSAbhUIwiSIbIBcgFoVCAYkiFiAYfCANfCIXICKFQiCJIhggFSAffCIVfCIfIBaFQiiJIhYgF3wgEHwiFyAYhUIwiSIYIB98Ih8gFoVCAYkiFiAVIA+FQgGJIg8gGXwgCnwiFSAchUIgiSIZICN8IhwgD4VCKIkiDyAVfCAHfCIVfCASfCIihUIgiSIjfCIkIBaFQiiJIhYgInwgBXwiIiAjhUIwiSIjICR8IiQgFoVCAYkiFiAbIBp8IhogFSAZhUIwiSIVIB4gFIVCAYkiFCAXfCADfCIXhUIgiSIZfCIbIBSFQiiJIhQgF3wgB3wiF3wgAnwiHiAVIBx8IhUgGCAaIA6FQgGJIg4gIHwgC3wiGoVCIIkiGHwiHCAOhUIoiSIOIBp8IAR8IhogGIVCMIkiGIVCIIkiICAfICEgFSAPhUIBiSIPIB18IAZ8IhWFQiCJIh18Ih8gD4VCKIkiDyAVfCAKfCIVIB2FQjCJIh0gH3wiH3wiISAWhUIoiSIWIB58IAx8Ih4gIIVCMIkiICAhfCIhIBogFyAZhUIwiSIXIBt8IhkgFIVCAYkiFHwgEHwiGiAdhUIgiSIbICR8Ih0gFIVCKIkiFCAafCAJfCIaIBuFQjCJIhsgHyAPhUIBiSIPICJ8IBN8Ih8gF4VCIIkiFyAYIBx8Ihh8IhwgD4VCKIkiDyAffCABfCIfIBeFQjCJIhcgHHwiHCAPhUIBiSIPIBggDoVCAYkiDiAVfCAIfCIVICOFQiCJIhggGXwiGSAOhUIoiSIOIBV8IA18IhV8IA18IiKFQiCJIiN8IiQgD4VCKIkiDyAifCAMfCIiICOFQjCJIiMgJHwiJCAPhUIBiSIPIBsgHXwiGyAVIBiFQjCJIhUgISAWhUIBiSIWIB98IBB8IhiFQiCJIh18Ih8gFoVCKIkiFiAYfCAIfCIYfCASfCIhIBUgGXwiFSAXIBsgFIVCAYkiFCAefCAHfCIZhUIgiSIXfCIbIBSFQiiJIhQgGXwgAXwiGSAXhUIwiSIXhUIgiSIeIBwgICAVIA6FQgGJIg4gGnwgAnwiFYVCIIkiGnwiHCAOhUIoiSIOIBV8IAV8IhUgGoVCMIkiGiAcfCIcfCIgIA+FQiiJIg8gIXwgBHwiISAehUIwiSIeICB8IiAgGCAdhUIwiSIYIB98Ih0gFoVCAYkiFiAZfCAGfCIZIBqFQiCJIhogJHwiHyAWhUIoiSIWIBl8IBN8IhkgGoVCMIkiGiAcIA6FQgGJIg4gInwgCXwiHCAYhUIgiSIYIBcgG3wiF3wiGyAOhUIoiSIOIBx8IAN8IhwgGIVCMIkiGCAbfCIbIA6FQgGJIg4gFSAXIBSFQgGJIhR8IAt8IhUgI4VCIIkiFyAdfCIdIBSFQiiJIhQgFXwgCnwiFXwgBHwiIoVCIIkiI3wiJCAOhUIoiSIOICJ8IAl8IiIgGyAeIBUgF4VCMIkiFSAdfCIXIBSFQgGJIhQgGXwgDHwiGYVCIIkiHXwiGyAUhUIoiSIUIBl8IAp8IhkgHYVCMIkiHSAbfCIbIBSFQgGJIhR8IAN8Ih4gGiAffCIaIBUgICAPhUIBiSIPIBx8IAd8IhyFQiCJIhV8Ih8gD4VCKIkiDyAcfCAQfCIcIBWFQjCJIhWFQiCJIiAgFyAYIBogFoVCAYkiFiAhfCATfCIahUIgiSIYfCIXIBaFQiiJIhYgGnwgDXwiGiAYhUIwiSIYIBd8Ihd8IiEgFIVCKIkiFCAefCAFfCIeICCFQjCJIiAgIXwiISAiICOFQjCJIiIgJHwiIyAOhUIBiSIOIBx8IAt8IhwgGIVCIIkiGCAbfCIbIA6FQiiJIg4gHHwgEnwiHCAYhUIwiSIYIBcgFoVCAYkiFiAZfCABfCIXICKFQiCJIhkgFSAffCIVfCIfIBaFQiiJIhYgF3wgBnwiFyAZhUIwiSIZIB98Ih8gFoVCAYkiFiAVIA+FQgGJIg8gGnwgCHwiFSAdhUIgiSIaICN8Ih0gD4VCKIkiDyAVfCACfCIVfCANfCIihUIgiSIjfCIkIBaFQiiJIhYgInwgCXwiIiAjhUIwiSIjICR8IiQgFoVCAYkiFiAYIBt8IhggFSAahUIwiSIVICEgFIVCAYkiFCAXfCASfCIXhUIgiSIafCIbIBSFQiiJIhQgF3wgCHwiF3wgB3wiISAVIB18IhUgGSAYIA6FQgGJIg4gHnwgBnwiGIVCIIkiGXwiHSAOhUIoiSIOIBh8IAt8IhggGYVCMIkiGYVCIIkiHiAfICAgFSAPhUIBiSIPIBx8IAp8IhWFQiCJIhx8Ih8gD4VCKIkiDyAVfCAEfCIVIByFQjCJIhwgH3wiH3wiICAWhUIoiSIWICF8IAN8IiEgHoVCMIkiHiAgfCIgIBggFyAahUIwiSIXIBt8IhogFIVCAYkiFHwgBXwiGCAchUIgiSIbICR8IhwgFIVCKIkiFCAYfCABfCIYIBuFQjCJIhsgHyAPhUIBiSIPICJ8IAx8Ih8gF4VCIIkiFyAZIB18Ihl8Ih0gD4VCKIkiDyAffCATfCIfIBeFQjCJIhcgHXwiHSAPhUIBiSIPIBkgDoVCAYkiDiAVfCAQfCIVICOFQiCJIhkgGnwiGiAOhUIoiSIOIBV8IAJ8IhV8IBN8IiKFQiCJIiN8IiQgD4VCKIkiDyAifCASfCIiICOFQjCJIiMgJHwiJCAPhUIBiSIPIBsgHHwiGyAVIBmFQjCJIhUgICAWhUIBiSIWIB98IAt8IhmFQiCJIhx8Ih8gFoVCKIkiFiAZfCACfCIZfCAJfCIgIBUgGnwiFSAXIBsgFIVCAYkiFCAhfCAFfCIahUIgiSIXfCIbIBSFQiiJIhQgGnwgA3wiGiAXhUIwiSIXhUIgiSIhIB0gHiAVIA6FQgGJIg4gGHwgEHwiFYVCIIkiGHwiHSAOhUIoiSIOIBV8IAF8IhUgGIVCMIkiGCAdfCIdfCIeIA+FQiiJIg8gIHwgDXwiICAhhUIwiSIhIB58Ih4gGSAchUIwiSIZIB98IhwgFoVCAYkiFiAafCAIfCIaIBiFQiCJIhggJHwiHyAWhUIoiSIWIBp8IAp8IhogGIVCMIkiGCAdIA6FQgGJIg4gInwgBHwiHSAZhUIgiSIZIBcgG3wiF3wiGyAOhUIoiSIOIB18IAd8Ih0gGYVCMIkiGSAbfCIbIA6FQgGJIg4gFSAXIBSFQgGJIhR8IAx8IhUgI4VCIIkiFyAcfCIcIBSFQiiJIhQgFXwgBnwiFXwgEnwiIoVCIIkiI3wiJCAOhUIoiSIOICJ8IBN8IiIgGyAhIBUgF4VCMIkiFSAcfCIXIBSFQgGJIhQgGnwgBnwiGoVCIIkiHHwiGyAUhUIoiSIUIBp8IBB8IhogHIVCMIkiHCAbfCIbIBSFQgGJIhR8IA18IiEgGCAffCIYIBUgHiAPhUIBiSIPIB18IAJ8Ih2FQiCJIhV8Ih4gD4VCKIkiDyAdfCABfCIdIBWFQjCJIhWFQiCJIh8gFyAZIBggFoVCAYkiFiAgfCADfCIYhUIgiSIZfCIXIBaFQiiJIhYgGHwgBHwiGCAZhUIwiSIZIBd8Ihd8IiAgFIVCKIkiFCAhfCAIfCIhIB+FQjCJIh8gIHwiICAiICOFQjCJIiIgJHwiIyAOhUIBiSIOIB18IAd8Ih0gGYVCIIkiGSAbfCIbIA6FQiiJIg4gHXwgDHwiHSAZhUIwiSIZIBcgFoVCAYkiFiAafCALfCIXICKFQiCJIhogFSAefCIVfCIeIBaFQiiJIhYgF3wgCXwiFyAahUIwiSIaIB58Ih4gFoVCAYkiFiAVIA+FQgGJIg8gGHwgBXwiFSAchUIgiSIYICN8IhwgD4VCKIkiDyAVfCAKfCIVfCACfCIChUIgiSIifCIjIBaFQiiJIhYgAnwgC3wiAiAihUIwiSILICN8IiIgFoVCAYkiFiAZIBt8IhkgFSAYhUIwiSIVICAgFIVCAYkiFCAXfCANfCINhUIgiSIXfCIYIBSFQiiJIhQgDXwgBXwiBXwgEHwiECAVIBx8Ig0gGiAZIA6FQgGJIg4gIXwgDHwiDIVCIIkiFXwiGSAOhUIoiSIOIAx8IBJ8IhIgFYVCMIkiDIVCIIkiFSAeIB8gDSAPhUIBiSINIB18IAl8IgmFQiCJIg98IhogDYVCKIkiDSAJfCAIfCIJIA+FQjCJIgggGnwiD3wiGiAWhUIoiSIWIBB8IAd8IhAgEYUgDCAZfCIHIA6FQgGJIgwgCXwgCnwiCiALhUIgiSILIAUgF4VCMIkiBSAYfCIJfCIOIAyFQiiJIgwgCnwgE3wiEyALhUIwiSIKIA58IguFNwOAiQFBACADIAYgDyANhUIBiSINIAJ8fCICIAWFQiCJIgUgB3wiBiANhUIoiSIHIAJ8fCICQQApA4iJAYUgBCABIBIgCSAUhUIBiSIDfHwiASAIhUIgiSISICJ8IgkgA4VCKIkiAyABfHwiASAShUIwiSIEIAl8IhKFNwOIiQFBACATQQApA5CJAYUgECAVhUIwiSIQIBp8IhOFNwOQiQFBACABQQApA5iJAYUgAiAFhUIwiSICIAZ8IgGFNwOYiQFBACASIAOFQgGJQQApA6CJAYUgAoU3A6CJAUEAIBMgFoVCAYlBACkDqIkBhSAKhTcDqIkBQQAgASAHhUIBiUEAKQOwiQGFIASFNwOwiQFBACALIAyFQgGJQQApA7iJAYUgEIU3A7iJAQvdAgUBfwF+AX8BfgJ/IwBBwABrIgAkAAJAQQApA9CJAUIAUg0AQQBBACkDwIkBIgFBACgC4IoBIgKsfCIDNwPAiQFBAEEAKQPIiQEgAyABVK18NwPIiQECQEEALQDoigFFDQBBAEJ/NwPYiQELQQBCfzcD0IkBAkAgAkH/AEoNAEEAIQQDQCACIARqQeCJAWpBADoAACAEQQFqIgRBgAFBACgC4IoBIgJrSA0ACwtB4IkBEAIgAEEAKQOAiQE3AwAgAEEAKQOIiQE3AwggAEEAKQOQiQE3AxAgAEEAKQOYiQE3AxggAEEAKQOgiQE3AyAgAEEAKQOoiQE3AyggAEEAKQOwiQE3AzAgAEEAKQO4iQE3AzhBACgC5IoBIgVBAUgNAEEAIQRBACECA0AgBEGACWogACAEai0AADoAACAEQQFqIQQgBSACQQFqIgJB/wFxSg0ACwsgAEHAAGokAAv9AwMBfwF+AX8jAEGAAWsiAiQAQQBBgQI7AfKKAUEAIAE6APGKAUEAIAA6APCKAUGQfiEAA0AgAEGAiwFqQgA3AAAgAEH4igFqQgA3AAAgAEHwigFqQgA3AAAgAEEYaiIADQALQQAhAEEAQQApA/CKASIDQoiS853/zPmE6gCFNwOAiQFBAEEAKQP4igFCu86qptjQ67O7f4U3A4iJAUEAQQApA4CLAUKr8NP0r+68tzyFNwOQiQFBAEEAKQOIiwFC8e30+KWn/aelf4U3A5iJAUEAQQApA5CLAULRhZrv+s+Uh9EAhTcDoIkBQQBBACkDmIsBQp/Y+dnCkdqCm3+FNwOoiQFBAEEAKQOgiwFC6/qG2r+19sEfhTcDsIkBQQBBACkDqIsBQvnC+JuRo7Pw2wCFNwO4iQFBACADp0H/AXE2AuSKAQJAIAFBAUgNACACQgA3A3ggAkIANwNwIAJCADcDaCACQgA3A2AgAkIANwNYIAJCADcDUCACQgA3A0ggAkIANwNAIAJCADcDOCACQgA3AzAgAkIANwMoIAJCADcDICACQgA3AxggAkIANwMQIAJCADcDCCACQgA3AwBBACEEA0AgAiAAaiAAQYAJai0AADoAACAAQQFqIQAgBEEBaiIEQf8BcSABSA0ACyACQYABEAELIAJBgAFqJAALEgAgAEEDdkH/P3EgAEEQdhAECwkAQYAJIAAQAQsGAEGAiQELGwAgAUEDdkH/P3EgAUEQdhAEQYAJIAAQARADCwsLAQBBgAgLBPAAAAA=",na="c6f286e6",oa={name:ia,data:sa,hash:na},gA=new Bt;function qn(h){return!Number.isInteger(h)||h<8||h>512||h%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function aa(h,A){return h|A<<16}function Ts(h=512,A=null){if(qn(h))return Promise.reject(qn(h));let t=null,e=h;if(A!==null){if(t=Yt(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=aa(h,t.length)}let i=h/8;return zn(oa,i).then(s=>{e>512&&s.writeMemory(t),s.init(e);let n={init:e>512?()=>(s.writeMemory(t),s.init(e),n):()=>(s.init(e),n),update:o=>(s.update(o),n),digest:o=>s.digest(o),save:()=>s.save(),load:o=>(s.load(o),n),blockSize:128,digestSize:i};return n})}function ra(h,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${Jn(h,!1)}$${Jn(t,!1)}`}var On=new DataView(new ArrayBuffer(4));function Kt(h){return On.setInt32(0,h,!0),new Uint8Array(On.buffer)}function xs(h,A,t){return pe(this,void 0,void 0,function*(){if(t<=64){let a=yield Ts(t*8);return a.update(Kt(t)),a.update(A),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);h.init(),h.update(Kt(t)),h.update(A);let s=h.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)h.init(),h.update(s),s=h.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=h,o.init()):o=yield Ts(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function Aa(h){switch(h){case"d":return 0;case"i":return 1;default:return 2}}function la(h){return pe(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=h,s=Yt(h.password),n=Yt(h.salt),o=19,a=Aa(h.hashType),{memorySize:r}=h,l=Yt((A=h.secret)!==null&&A!==void 0?A:""),[c,g]=yield Promise.all([zn(ea,1024),Ts(512)]);c.setMemorySize(r*1024+1024);let p=new Uint8Array(24),d=new DataView(p.buffer);d.setInt32(0,t,!0),d.setInt32(4,i,!0),d.setInt32(8,r,!0),d.setInt32(12,e,!0),d.setInt32(16,o,!0),d.setInt32(20,a,!0),c.writeMemory(p,r*1024),g.init(),g.update(p),g.update(Kt(s.length)),g.update(s),g.update(Kt(n.length)),g.update(n),g.update(Kt(l.length)),g.update(l),g.update(Kt(0));let u=Math.floor(r/(t*4))*4,f=new Uint8Array(72),C=g.digest("binary");f.set(C);for(let w=0;w<t;w++){f.set(Kt(0),64),f.set(Kt(w),68);let y=w*u,F=yield xs(g,f,1024);c.writeMemory(F,y*1024),y+=1,f.set(Kt(1),64),F=yield xs(g,f,1024),c.writeMemory(F,y*1024)}let m=new Uint8Array(1024);Yn(m,c.calculate(new Uint8Array([]),r));let E=yield xs(g,m,i);if(h.outputType==="hex"){let w=new Uint8Array(i*2);return Hs(w,E,i)}return h.outputType==="encoded"?ra(n,h,E):E})}var ca=h=>{var A;if(!h||typeof h!="object")throw new Error("Invalid options parameter. It requires an object.");if(!h.password)throw new Error("Password must be specified");if(h.password=Yt(h.password),h.password.length<1)throw new Error("Password must be specified");if(!h.salt)throw new Error("Salt must be specified");if(h.salt=Yt(h.salt),h.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(h.secret=Yt((A=h.secret)!==null&&A!==void 0?A:""),!Number.isInteger(h.iterations)||h.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(h.parallelism)||h.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(h.hashLength)||h.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(h.memorySize))throw new Error("Memory size should be specified.");if(h.memorySize<8*h.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(h.outputType===void 0&&(h.outputType="hex"),!["hex","binary","encoded"].includes(h.outputType))throw new Error(`Insupported output type ${h.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Us(h){return pe(this,void 0,void 0,function*(){return ca(h),la(Object.assign(Object.assign({},h),{hashType:"id"}))})}var pA=new Bt;var IA=new Bt;var uA=new Bt;var fA=new Bt;var CA=new Uint8Array(8);var BA=new Bt;var mA=new Bt;var QA=new Bt;var EA=new Bt;var yA=new Bt;var wA=new Bt;var FA=new Bt;var vA=new Bt;var kA=new Bt;var SA=new Bt;var DA=new Bt;var bA=new Uint8Array(8);var NA=new Bt;var xA=new Uint8Array(8);var MA=new Bt;var HA=new Uint8Array(8);var TA=new Bt;var UA=new Bt;var GA=new Bt;Mt();var zt=new Uint8Array([83,84,65,83,72,69,78,67]),$n=2,_n=1,jn=2,da=32,Gs=12,Vn=32,ha=6e5,ga=47104,pa=3,Ia=1,Nt=h=>h;function Ne(h){if(h.length<zt.length+1)return!1;for(let A=0;A<zt.length;A++)if(h[A]!==zt[A])return!1;return!0}function Wn(h,A,t){h[A]=t>>>24&255,h[A+1]=t>>>16&255,h[A+2]=t>>>8&255,h[A+3]=t&255}function Xn(h,A){return h[A]*16777216+(h[A+1]<<16)+(h[A+2]<<8)+h[A+3]}async function Rs(h,A,t){if(t.id===jn)return await Us({password:h,salt:A,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Vn,outputType:"binary"});if(t.id===_n){let e=await crypto.subtle.importKey("raw",Nt(new TextEncoder().encode(h)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:Nt(A),iterations:t.a,hash:"SHA-256"},e,Vn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function to(h){return crypto.subtle.importKey("raw",Nt(h),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var eo={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function io(h,A){let t=crypto.getRandomValues(new Uint8Array(da)),e=crypto.getRandomValues(new Uint8Array(Gs)),i,s,n;try{i={id:jn,a:ga,b:pa,c:Ia},n=await Rs(A,t,i),s="argon2id"}catch(c){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",c),i={id:_n,a:ha,b:0,c:0},n=await Rs(A,t,i),s="pbkdf2"}let o=ua(i,t,e),a=await to(n),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:Nt(e),additionalData:Nt(o)},a,Nt(h))),l=new Uint8Array(o.length+r.length);return l.set(o,0),l.set(r,o.length),{data:l,kdf:s}}var oi=null;async function so(){if(oi!==null)return oi;try{await Us({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),oi=!0}catch{oi=!1}return oi}function ua(h,A,t){let e=new Uint8Array(zt.length+1+1+4+4+1+1+A.length+t.length),i=0;return e.set(zt,i),i+=zt.length,e[i++]=$n,e[i++]=h.id,Wn(e,i,h.a),i+=4,Wn(e,i,h.b),i+=4,e[i++]=h.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function Zn(h,A){if(!Ne(h))throw new Error("Not an encrypted Stashpad file.");let t=h[zt.length];if(t===1)return fa(h,A);if(t!==$n)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=zt.length+1,i={id:h[e++],a:0,b:0,c:0};i.a=Xn(h,e),e+=4,i.b=Xn(h,e),e+=4,i.c=h[e++];let s=h[e++],n=h.slice(e,e+s);e+=s;let o=h.slice(e,e+Gs);e+=Gs;let a=h.slice(0,e),r=h.slice(e),l=await Rs(A,n,i),c=await to(l),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:Nt(o),additionalData:Nt(a)},c,Nt(r));return new Uint8Array(g)}async function fa(h,A){let t=zt.length+1,e=h.slice(t,t+16);t+=16;let i=h.slice(t,t+12);t+=12;let s=h.slice(t),n=await crypto.subtle.importKey("raw",Nt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:Nt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:Nt(i)},o,Nt(s));return new Uint8Array(a)}async function xe(h,A,t={}){if(!Ne(A))return A;if(t.secretId){let i=h.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Zn(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new Oe(h,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Zn(A,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}gi();Mt();function Ca(h){return h.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function no(h,A){let t=ma(h,A);if(t.length===0){new ie.Notice("Nothing to export.");return}let e=Qa(h,t);if(e.length===0){new ie.Notice("No exportable notes (no files attached).");return}let i=(h.noteFolder.split("/").pop()||h.noteFolder).trim(),s=t.length===1?h.titleForNode(t[0]):`${i}-${t.length}notes`;new qe(h.app,s,e.length,(n,o,a)=>{Ba(h,t,e,n,o,a)},so).open()}async function Ba(h,A,t,e,i,s=!1){try{let n=await Gn(h.app,{rootNotes:A.filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),allDescendants:t.filter(d=>!A.some(I=>I.id===d.id)).filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),sourceFolder:h.noteFolder}),o="";if(i){let d=await io(n,i);n=d.data;let I=eo[d.kdf];o=I.strong?` (encrypted \xB7 ${I.label})`:` (encrypted \xB7 ${I.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,ie.moment)().format("YYYYMMDD-HHmmss"),r=Ca(e),l=(h.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${h.noteFolder}/${l}`;await h.ensureFolder(c);let g=`${r}-${a}`,p=`${c}/${g}.${te}`;if(await h.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let d=h.app.secretStorage;try{d?.setSecret(Pe(g),i)}catch(I){console.warn("[Stashpad] couldn't save export passphrase to secret storage",I)}}await h.log.append({type:"stash_export",id:A[0].id,payload:{path:p,noteCount:t.length,rootIds:A.map(d=>d.id)}}),h.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:h.noteFolder,actions:h.actionsForFile(p),duration:0})}catch(n){h.plugin.notifications.show({message:`Stashpad: export failed Error: ${n.message} -Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function Ba(h,A){if(A?.file)return[A];if(h.selection.size>0)return[...h.selection].map(e=>h.tree.get(e)).filter(e=>!!e?.file);if(h.cursorIdx>=0&&h.currentChildren[h.cursorIdx])return[h.currentChildren[h.cursorIdx]];let t=h.tree.get(h.focusId);return t?.file?[t]:[]}function ma(h,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of h.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function oo(h){let A=h.app.vault.getFiles().filter(e=>e.extension===te);if(A.length===0){new ie.Notice("No .stash files found in this vault.");return}let t=new class extends ie.FuzzySuggestModal{getItems(){return A}getItemText(e){return e.path}onChooseItem(e){Ps(h,e)}}(h.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Ps(h,A){try{let t=new Uint8Array(await h.app.vault.readBinary(A)),e=await xe(h.app,t,{secretId:Pe(A.basename)});if(!e)return;let i=await De(h.app,e,h.noteFolder,Qa(h));h.tree.rebuild(h.noteFolder),h.render(),await h.log.append({type:"stash_import",id:U,payload:{from:A.path,into:h.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await h.app.fileManager.trashFile(A)}catch{}h.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),h.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:h.noteFolder})}catch(t){h.plugin.notifications.show({message:`Stashpad: import failed +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function ma(h,A){if(A?.file)return[A];if(h.selection.size>0)return[...h.selection].map(e=>h.tree.get(e)).filter(e=>!!e?.file);if(h.cursorIdx>=0&&h.currentChildren[h.cursorIdx])return[h.currentChildren[h.cursorIdx]];let t=h.tree.get(h.focusId);return t?.file?[t]:[]}function Qa(h,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of h.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function oo(h){let A=h.app.vault.getFiles().filter(e=>e.extension===te);if(A.length===0){new ie.Notice("No .stash files found in this vault.");return}let t=new class extends ie.FuzzySuggestModal{getItems(){return A}getItemText(e){return e.path}onChooseItem(e){Ps(h,e)}}(h.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Ps(h,A){try{let t=new Uint8Array(await h.app.vault.readBinary(A)),e=await xe(h.app,t,{secretId:Pe(A.basename)});if(!e)return;let i=await De(h.app,e,h.noteFolder,Ea(h));h.tree.rebuild(h.noteFolder),h.render(),await h.log.append({type:"stash_import",id:U,payload:{from:A.path,into:h.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await h.app.fileManager.trashFile(A)}catch{}h.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),h.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:h.noteFolder})}catch(t){h.plugin.notifications.show({message:`Stashpad: import failed File: \`${A.name}\` Error: ${t.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[A.path],actions:h.actionsForFile(A.path)}),console.error(t)}}function Qa(h){let A=new Set,t=e=>{if(A.add(e),!!h.tree.get(e))for(let s of h.tree.getChildren(e))t(s.id)};return t(U),A}var ya=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),Ki={nested:"Nested",flat:"Flat",everything:"Everything"},Yi=[{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"}],zi=class extends q.ItemView{constructor(t,e){super(t);this.focusId=U;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=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.pickerEscapeAt=0;this.composerExitAt=0;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.lastSelectionByFocus=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.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||Fn(t.target))return;let e=ft().bindings;if(rt(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(rt(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(rt(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(rt(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(rt(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(rt(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(rt(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(rt(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(rt(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let i=t.target,s=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!s){let r=this.composerInputEl;if(r){t.preventDefault(),t.stopPropagation(),r.focus();let c=r.value.length;r.setSelectionRange(c,c);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let r=this.listEl,c=!!r&&r.scrollTop+r.clientHeight>=r.scrollHeight-2,l=r?.scrollTop??0;if(this.render(),r){let g=c?r.scrollHeight:l;r.scrollTop=g,requestAnimationFrame(()=>{r.scrollTop=c?r.scrollHeight:l}),setTimeout(()=>{r.scrollTop=c?r.scrollHeight:l},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}if(rt(t,ft().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(rt(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(rt(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(rt(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(rt(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(rt(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(rt(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(rt(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(rt(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(rt(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(rt(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(rt(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(rt(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let r=this.composerInputEl;if(r){r.focus();let c=r.value.length;r.setSelectionRange(c,c)}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 r=this.currentChildren[this.cursorIdx];r&&(t.preventDefault(),this.navigateTo(r.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return;let r=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,r){let c=this.currentChildren.findIndex(l=>l.id===r);this.selection.add(r),this.lastSelected=r,c>=0&&(this.cursorIdx=c)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=ft().bindings;if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(rt(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(rt(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(rt(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(rt(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(rt(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(rt(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(rt(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(rt(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let r=this.tree.get(this.focusId);r?.file&&this.cmdOpenInEditor(r)}else this.cmdOpenInEditor();return}if(rt(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(rt(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(rt(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(rt(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(rt(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(rt(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(rt(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(rt(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(rt(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(rt(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(rt(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(rt(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.openSearchInstance=null;this.fmSyncUnsubscribe=null;this.completedState=new Map;this.taskTaggedState=new Map;this.pendingFocusIds=null;this.onFileModify=t=>{!(t instanceof q.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&(this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.authorship.noteModify(t),this.debouncedRender())};this.onFileCreate=t=>{!(t instanceof q.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Ni(this.app),this.log=e.newLog(),this.integrity=new Gi(this.tree,this.log),this.order=new xi(this.app),this.sortStore=new Mi(this.app),this.fmSync=new Ti(this.app,()=>this.tree),this.tree.setOrderProvider(i=>{let s=this.noteFolder,n=this.sortStore.getMode(s,i);return n==="manual"?this.order.getOrder(s,i):yn(this,i,n)}),this.debouncedRender=(0,q.debounce)(()=>this.render(),80),this.authorship=new Pi(this),this.dnd=new Li(this),this.bodyRenderer=new Ji(this,this,this.plugin.renderCacheStore)}getViewType(){return dt}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==U){let i=this.tree.get(this.focusId);if(i){let s=this.titleForNode(i).trim(),n=s.length>40?s.slice(0,40)+"\u2026":s;if(n)return`${e} \u2014 ${n}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let i=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;i&&i.textContent!==t&&i.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",()=>Fi(this)),this.viewRoot.addEventListener("click",()=>Fi(this)),this.viewRoot.addEventListener("mouseup",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),Fi(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new q.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.inListPicker)return this.inListPicker=null,this.pickerEscapeAt=Date.now(),this.repaintSelectionClasses(),!1;if(Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return!1;if(this.selection.size>1){let r=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,r){let c=this.currentChildren.findIndex(l=>l.id===r);this.selection.add(r),this.lastSelected=r,c>=0&&(this.cursorIdx=c)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",r=>{let c=r.relatedTarget;c&&this.viewRoot&&this.viewRoot.contains(c)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",r=>{if(r.extension!=="md")return;let c=this.app.metadataCache.getFileCache(r)?.frontmatter;this.completedState.set(r.path,!!c?.completed),this.taskTaggedState.set(r.path,this.taggedFromFm(c))})),this.registerEvent(this.app.vault.on("rename",(r,c)=>{for(let l of[this.completedState,this.taskTaggedState])l.has(c)&&(l.set(r.path,l.get(c)),l.delete(c))})),this.registerEvent(this.app.vault.on("delete",r=>{this.completedState.delete(r.path),this.taskTaggedState.delete(r.path)})),this.detachSettings=In(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",c=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&c===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&c!==""&&(this.composerDraft=c),!!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(r){let c=r?.message??"";/already exists/i.test(c)||console.warn("[Stashpad] bootstrapFolder failed:",r)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let r=this.plugin.loadLastCursor(this.noteFolder);for(let[c,l]of r)this.lastCursorByFocus.set(c,l);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let n=this.lastCursorByFocus.get(this.focusId),o;n&&this.tree.get(n)?(o={kind:"scroll-to-id",id:n,align:"start"},this.pendingFocusIds=[n]):(this.scrollToBottomOnNextRender=!0,o={kind:"pin-bottom",until:"next-user-input"});let a=this.foldRestoredSelection(n);a&&(this.pendingFocusIds=a),this.render(o),this.scheduleSelectionRestore(),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",r=>{r===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+"/",i=0;for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!(n===t||t!==""&&n.startsWith(e)))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.id;typeof o=="string"&&o&&i++}i!==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(!ft().autofocusComposerAfterSend)return;let t=()=>{if(!this.viewRoot?.isConnected||Date.now()<this.suppressComposerFocusUntil||Date.now()<this.plugin.suppressComposerAutofocusUntil)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(){hn(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.bodyRenderer.dispose(),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();this.authorship.dispose();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 i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"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(),this.lastSelectionByFocus.clear();try{let c=this.plugin.loadLastCursor(this.noteFolder);for(let[l,g]of c)this.lastCursorByFocus.set(l,g);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let o=this.lastCursorByFocus.get(this.focusId),a;o&&this.tree.get(o)?(this.pendingFocusIds=[o],a={kind:"scroll-to-id",id:o,align:"start"}):a={kind:"pin-bottom",until:"next-user-input"};let r=this.foldRestoredSelection(o);r&&(this.pendingFocusIds=r),this.render(a),this.scheduleSelectionRestore()}}focus(){this.viewRoot?.focus({preventScroll:!0})}foldRestoredSelection(t){let e=this.lastSelectionByFocus.get(this.focusId)??null;if(!e||!e.length)return null;let i=e.filter(s=>!!this.tree.get(s));return i.length?t&&i.includes(t)?[t,...i.filter(s=>s!==t)]:i:null}stampSelection(t=!1){let e=[...this.selection],i=()=>{try{this.plugin.saveLastSelection(this.noteFolder,this.focusId,e)}catch{}};if(this.stampSelectionTimer!=null&&(window.clearTimeout(this.stampSelectionTimer),this.stampSelectionTimer=null),t){i();return}this.stampSelectionTimer=window.setTimeout(()=>{this.stampSelectionTimer=null,i()},400)}scheduleSelectionRestore(){let t=this.lastSelectionByFocus.get(this.focusId);if(!t||!t.length)return;let e=()=>{let i=t.filter(a=>this.currentChildren.some(r=>r.id===a));if(!i.length)return;let s=[...this.selection],n=new Set(i);if(s.length<i.length&&s.every(a=>n.has(a))){this.selection.clear();for(let a of i)this.selection.add(a);this.firstSelectedId=i[0],this.lastSelected=i[i.length-1],this.repaintSelectionClasses()}};for(let i of[120,400,900,1600])window.setTimeout(e,i)}loadConfig(){let t=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),i=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"Stashpad";i!==this.noteFolder?(this.noteFolder=i,this.tree.rebuild(this.noteFolder)):this.noteFolder=i}captureNavSnapshot(){return{folder:this.noteFolder,focusId:this.focusId}}recordNavState(t={}){let e=this.captureNavSnapshot(),i=this.navBackStack[this.navBackStack.length-1];i&&i.folder===e.folder&&i.focusId===e.focusId||(this.navBackStack.push(e),t.keepForward||(this.navForwardSnapshots=[]))}async setFolderOverride(t,e={}){let i=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(i&&this.isReservedFolder(i)){new q.Notice(`"${i}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((i||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=i,this.focusId=U,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(s){let n=s?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",s)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let s=this.app.workspace;typeof s.saveLayout=="function"?await s.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 q.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,i)=>e.localeCompare(i))}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(s=>(s??"").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 q.Notice("Nothing to undo.");return}let e=t.peekUndoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.undo().then(()=>this.plugin.notifications.show({message:`Undid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Undo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new q.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Redo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let i=[],s=new Set;for(let r of t)!r.file||s.has(r.file.path)||(s.add(r.file.path),i.push(r.file));let n=await Promise.all(i.map(r=>this.app.vault.read(r))),o=i.map((r,c)=>({path:r.path,content:n[c]})),a=[];if(e){let r=new Set,c=[];for(let g of n)for(let p of this.extractAttachments(this.stripFrontmatter(g))){let d=this.app.metadataCache.getFirstLinkpathDest(p,"");d&&!r.has(d.path)&&(r.add(d.path),c.push(d))}let l=await Promise.all(c.map(g=>this.app.vault.readBinary(g)));for(let g=0;g<c.length;g++)a.push({path:c[g].path,data:l[g]})}return{notes:o,attachments:a}}async restoreSnapshots(t,e){for(let s of t.attachments)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.createBinary(s.path,s.data)}catch{}for(let s of t.notes)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.create(s.path,s.content)}catch{}let i=()=>{e&&e.some(n=>this.tree.get(n))&&(this.pendingFocusIds=e.slice())};i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"}),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},100),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},400),setTimeout(()=>{for(let s of t.notes){let n=this.tree.idForPath(s.path);n&&this.fmSync.schedule(n)}},500)}async trashNotesAndAttachments(t){let e=new Set;for(let i of t.notes){let s=this.tree.idForPath(i.path);if(!s)continue;let n=this.tree.get(s);n?.parent&&e.add(n.parent)}for(let i of t.notes){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}for(let i of t.attachments){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}this.tree.rebuild(this.noteFolder),this.render();for(let i of e)this.fmSync.scheduleParentOfDeleted(i)}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 s={...this.plugin.settings.drafts??{}};t.length===0?delete s[e]:s[e]=t,this.plugin.settings.drafts=s,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,q.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 i=this.tree.get(e);if(i&&(!this.isCompleted(i)||this.hasIncompleteDescendant(i)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof q.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof q.TFolder){s.push(o);continue}if(!(o instanceof q.TFile)||o.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let r of a.attachments){if(typeof r!="string")continue;let c=ae(r),l=this.app.metadataCache.getFirstLinkpathDest(c,o.path);l?t.add(l.path):t.add(c)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof q.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],r=[i];for(;r.length;){let c=r.pop();for(let l of c.children){if(l instanceof q.TFolder){let g=l.name;if(c===i&&o.has(g)||c===i&&g==="_attachments"&&!s)continue;r.push(l);continue}l instanceof q.TFile&&l.extension!=="md"&&(l.name===".stashpad-order.json"||l.name===".stashpad-sort.json"||!s&&n.has(l.path)||a.push(l))}}return a}populateListBody(t,e){this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),e.file&&q.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let s=this.currentViewMode()==="everything"?this.collectFileItems(e.id):[];if(this.currentChildren.length===0&&s.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(s.length===0)for(let n=0;n<this.currentChildren.length;n++)this.renderNote(t,this.currentChildren[n],n);else{let o=[...this.currentChildren.map((a,r)=>({kind:"note",ts:Number.isFinite(Date.parse(a.created))?Date.parse(a.created):0,idx:r})),...s.map(a=>({kind:"file",ts:a.stat.ctime,file:a}))];o.sort((a,r)=>a.ts-r.ts);for(let a of o)a.kind==="note"?this.renderNote(t,this.currentChildren[a.idx],a.idx):this.renderFileRow(t,a.file)}e.file&&q.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,i=this.listEl.scrollTop;this.listEl.empty(),this.populateListBody(this.listEl,t),e?this.listEl.scrollTop=this.listEl.scrollHeight:this.listEl.scrollTop=i}renderFileRow(t,e){let i=t.createDiv({cls:"stashpad-file-row"});i.dataset.path=e.path,i.createDiv({cls:"stashpad-file-meta"}).createSpan({cls:"stashpad-file-time",text:this.formatTime(new Date(e.stat.ctime).toISOString())});let n=i.createDiv({cls:"stashpad-file-body"});n.createSpan({cls:"stashpad-file-name",text:e.name}),n.createSpan({cls:"stashpad-file-ext",text:e.extension.toUpperCase()}),i.title=`${e.path} \u2014 click to open`,i.onclick=o=>{o.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(),i=this.currentHideChildless(),s=this.tree.getChildren(t),n=i?s.filter(r=>r.children.length>0):s;if(e==="nested")return n;let o=[],a=r=>{o.push(r);for(let c of this.tree.getChildren(r.id))a(c)};for(let r of n)a(r);return o}filterChildren(t){let e=this.timeFilterCutoff(),i=this.tagFilter?.toLowerCase(),s=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),o=this.currentAttachmentsOnly(),a=this.importedOnly,r=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!a&&!r?t:t.filter(c=>{if(a&&(!c.file||this.app.metadataCache.getFileCache(c.file)?.frontmatter?.imported!==!0))return!1;if(r){if(!c.file)return!1;let l=Xt(this.app.metadataCache.getFileCache(c.file)?.frontmatter?.author);if(!l||l.id!==r)return!1}if(e&&c.created){let l=Date.parse(c.created);if(!Number.isNaN(l)&&l<e)return!1}return!(i&&(!c.file||!this.nodeHasTag(c,i))||s&&(this.colorForNode(c)?.toLowerCase()??null)!==s||n&&this.isCompleted(c)&&!this.hasIncompleteDescendant(c)||o&&!this.hasAttachmentInSubtree(c))})}nodeHasTag(t,e){if(!t.file)return!1;let i=this.app.metadataCache.getFileCache(t.file);if(!i)return!1;if(i.tags){for(let n of i.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let s=i.frontmatter?.tags;if(s){let n=Array.isArray(s)?s:[s];for(let o of n)if(typeof o=="string"&&o.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){if(!s.file)continue;let n=this.app.metadataCache.getFileCache(s.file);if(n?.tags)for(let a of n.tags){let r=(a.tag||"").replace(/^#/,"");r&&t.set(r,(t.get(r)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let r of a){if(typeof r!="string")continue;let c=r.replace(/^#/,"");c&&t.set(c,(t.get(c)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}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 s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}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){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{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,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){St.enabled&&(this._renderT0=performance.now()),this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,i=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",q.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let r=this.containerEl.closest(".workspace-leaf");r&&(r.classList.toggle("stashpad-is-tiny",this.tinyMode),r.classList.toggle("stashpad-is-compact",this.compactMode));let c=this.containerEl.closest(".workspace-tabs");c&&c.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let l=this.tree.get(this.focusId)??this.tree.getRoot();l.file&&!q.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,l),this.currentChildren=this.filterChildren(this.collectViewItems(l.id));let g=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let I=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(I.id),this.lastSelected=I.id,this.autoSelectNewest=!1,g=!0}else if(this.pendingFocusIds){let I=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let u=-1;for(let f of I){let C=this.currentChildren.findIndex(m=>m.id===f);C>=0&&(this.selection.add(f),u<0&&(u=C))}this.cursorIdx=u,u>=0&&(this.lastSelected=I.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let p=e.createDiv({cls:"stashpad-list"});if(this.listEl=p,this.dnd.attachListDnD(p),this.populateListBody(p,l),this.renderComposer(e),q.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(St.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),g&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let I=this.pendingComposerCaret;this.pendingComposerCaret=null;let u=this.composerInputEl;if(u&&u.isConnected){if(u.focus({preventScroll:!0}),I!=null){let f=Math.min(I,u.value.length);try{u.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),I!=null)){let C=Math.min(I,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let d=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,d&&this.listEl){let I=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,d.kind){case"preserve":I?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=d.scrollTop,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let m=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(u,m),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let u=d.id,f=d.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let E=C.querySelector(`[data-id="${u}"]`);E&&E.scrollIntoView({block:f,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&a?this.scrollListToBottom():this.listEl&&i>0&&(this.listEl.scrollTop=i);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let I=this.listEl,u=I.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){I.scrollTop=I.scrollHeight,u=I.scrollTop;return}let m=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop<u&&u<=m?I.scrollTop=u:u=I.scrollTop});f.observe(I),this.listResizeObserver=f,I.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;I.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),I.addEventListener("touchmove",m=>{let E=m.touches[0]?.clientY??C;E>C&&(this.stickToListBottom=!1),C=E},{passive:!0}),I.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),I.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),i=e.createEl("button",{cls:"stashpad-folder-btn"}),s=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,q.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[A.path],actions:h.actionsForFile(A.path)}),console.error(t)}}function Ea(h){let A=new Set,t=e=>{if(A.add(e),!!h.tree.get(e))for(let s of h.tree.getChildren(e))t(s.id)};return t(U),A}var wa=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),Ki={nested:"Nested",flat:"Flat",everything:"Everything"},Yi=[{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"}],zi=class extends q.ItemView{constructor(t,e){super(t);this.focusId=U;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=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.pickerEscapeAt=0;this.composerExitAt=0;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.lastSelectionByFocus=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.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||Fn(t.target))return;let e=ft().bindings;if(rt(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(rt(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(rt(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(rt(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(rt(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(rt(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(rt(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(rt(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(rt(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let i=t.target,s=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!s){let r=this.composerInputEl;if(r){t.preventDefault(),t.stopPropagation(),r.focus();let l=r.value.length;r.setSelectionRange(l,l);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let r=this.listEl,l=!!r&&r.scrollTop+r.clientHeight>=r.scrollHeight-2,c=r?.scrollTop??0;if(this.render(),r){let g=l?r.scrollHeight:c;r.scrollTop=g,requestAnimationFrame(()=>{r.scrollTop=l?r.scrollHeight:c}),setTimeout(()=>{r.scrollTop=l?r.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}if(rt(t,ft().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(rt(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(rt(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(rt(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(rt(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(rt(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(rt(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(rt(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(rt(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(rt(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(rt(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(rt(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(rt(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let r=this.composerInputEl;if(r){r.focus();let l=r.value.length;r.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 r=this.currentChildren[this.cursorIdx];r&&(t.preventDefault(),this.navigateTo(r.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return;let r=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,r){let l=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,l>=0&&(this.cursorIdx=l)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=ft().bindings;if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(rt(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(rt(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(rt(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(rt(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(rt(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(rt(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(rt(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(rt(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let r=this.tree.get(this.focusId);r?.file&&this.cmdOpenInEditor(r)}else this.cmdOpenInEditor();return}if(rt(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(rt(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(rt(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(rt(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(rt(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(rt(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(rt(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(rt(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(rt(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(rt(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(rt(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(rt(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.openSearchInstance=null;this.fmSyncUnsubscribe=null;this.completedState=new Map;this.taskTaggedState=new Map;this.pendingFocusIds=null;this.onFileModify=t=>{!(t instanceof q.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&(this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.authorship.noteModify(t),this.debouncedRender())};this.onFileCreate=t=>{!(t instanceof q.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Ni(this.app),this.log=e.newLog(),this.integrity=new Gi(this.tree,this.log),this.order=new xi(this.app),this.sortStore=new Mi(this.app),this.fmSync=new Ti(this.app,()=>this.tree),this.tree.setOrderProvider(i=>{let s=this.noteFolder,n=this.sortStore.getMode(s,i);return n==="manual"?this.order.getOrder(s,i):yn(this,i,n)}),this.debouncedRender=(0,q.debounce)(()=>this.render(),80),this.authorship=new Pi(this),this.dnd=new Li(this),this.bodyRenderer=new Ji(this,this,this.plugin.renderCacheStore)}getViewType(){return dt}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==U){let i=this.tree.get(this.focusId);if(i){let s=this.titleForNode(i).trim(),n=s.length>40?s.slice(0,40)+"\u2026":s;if(n)return`${e} \u2014 ${n}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let i=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;i&&i.textContent!==t&&i.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",()=>Fi(this)),this.viewRoot.addEventListener("click",()=>Fi(this)),this.viewRoot.addEventListener("mouseup",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),Fi(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new q.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.inListPicker)return this.inListPicker=null,this.pickerEscapeAt=Date.now(),this.repaintSelectionClasses(),!1;if(Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return!1;if(this.selection.size>1){let r=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,r){let l=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,l>=0&&(this.cursorIdx=l)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",r=>{let l=r.relatedTarget;l&&this.viewRoot&&this.viewRoot.contains(l)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",r=>{if(r.extension!=="md")return;let l=this.app.metadataCache.getFileCache(r)?.frontmatter;this.completedState.set(r.path,!!l?.completed),this.taskTaggedState.set(r.path,this.taggedFromFm(l))})),this.registerEvent(this.app.vault.on("rename",(r,l)=>{for(let c of[this.completedState,this.taskTaggedState])c.has(l)&&(c.set(r.path,c.get(l)),c.delete(l))})),this.registerEvent(this.app.vault.on("delete",r=>{this.completedState.delete(r.path),this.taskTaggedState.delete(r.path)})),this.detachSettings=In(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",l=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&l===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&l!==""&&(this.composerDraft=l),!!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(r){let l=r?.message??"";/already exists/i.test(l)||console.warn("[Stashpad] bootstrapFolder failed:",r)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let r=this.plugin.loadLastCursor(this.noteFolder);for(let[l,c]of r)this.lastCursorByFocus.set(l,c);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let n=this.lastCursorByFocus.get(this.focusId),o;n&&this.tree.get(n)?(o={kind:"scroll-to-id",id:n,align:"start"},this.pendingFocusIds=[n]):(this.scrollToBottomOnNextRender=!0,o={kind:"pin-bottom",until:"next-user-input"});let a=this.foldRestoredSelection(n);a&&(this.pendingFocusIds=a),this.render(o),this.scheduleSelectionRestore(),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",r=>{r===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+"/",i=0;for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!(n===t||t!==""&&n.startsWith(e)))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.id;typeof o=="string"&&o&&i++}i!==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(!ft().autofocusComposerAfterSend)return;let t=()=>{if(!this.viewRoot?.isConnected||Date.now()<this.suppressComposerFocusUntil||Date.now()<this.plugin.suppressComposerAutofocusUntil)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(){hn(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.bodyRenderer.dispose(),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();this.authorship.dispose();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 i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"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(),this.lastSelectionByFocus.clear();try{let l=this.plugin.loadLastCursor(this.noteFolder);for(let[c,g]of l)this.lastCursorByFocus.set(c,g);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let o=this.lastCursorByFocus.get(this.focusId),a;o&&this.tree.get(o)?(this.pendingFocusIds=[o],a={kind:"scroll-to-id",id:o,align:"start"}):a={kind:"pin-bottom",until:"next-user-input"};let r=this.foldRestoredSelection(o);r&&(this.pendingFocusIds=r),this.render(a),this.scheduleSelectionRestore()}}focus(){this.viewRoot?.focus({preventScroll:!0})}foldRestoredSelection(t){let e=this.lastSelectionByFocus.get(this.focusId)??null;if(!e||!e.length)return null;let i=e.filter(s=>!!this.tree.get(s));return i.length?t&&i.includes(t)?[t,...i.filter(s=>s!==t)]:i:null}stampSelection(t=!1){let e=[...this.selection],i=()=>{try{this.plugin.saveLastSelection(this.noteFolder,this.focusId,e)}catch{}};if(this.stampSelectionTimer!=null&&(window.clearTimeout(this.stampSelectionTimer),this.stampSelectionTimer=null),t){i();return}this.stampSelectionTimer=window.setTimeout(()=>{this.stampSelectionTimer=null,i()},400)}scheduleSelectionRestore(){let t=this.lastSelectionByFocus.get(this.focusId);if(!t||!t.length)return;let e=()=>{let i=t.filter(a=>this.currentChildren.some(r=>r.id===a));if(!i.length)return;let s=[...this.selection],n=new Set(i);if(s.length<i.length&&s.every(a=>n.has(a))){this.selection.clear();for(let a of i)this.selection.add(a);this.firstSelectedId=i[0],this.lastSelected=i[i.length-1],this.repaintSelectionClasses()}};for(let i of[120,400,900,1600])window.setTimeout(e,i)}loadConfig(){let t=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),i=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"Stashpad";i!==this.noteFolder?(this.noteFolder=i,this.tree.rebuild(this.noteFolder)):this.noteFolder=i}captureNavSnapshot(){return{folder:this.noteFolder,focusId:this.focusId}}recordNavState(t={}){let e=this.captureNavSnapshot(),i=this.navBackStack[this.navBackStack.length-1];i&&i.folder===e.folder&&i.focusId===e.focusId||(this.navBackStack.push(e),t.keepForward||(this.navForwardSnapshots=[]))}async setFolderOverride(t,e={}){let i=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(i&&this.isReservedFolder(i)){new q.Notice(`"${i}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((i||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=i,this.focusId=U,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(s){let n=s?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",s)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let s=this.app.workspace;typeof s.saveLayout=="function"?await s.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 q.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,i)=>e.localeCompare(i))}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(s=>(s??"").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 q.Notice("Nothing to undo.");return}let e=t.peekUndoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.undo().then(()=>this.plugin.notifications.show({message:`Undid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Undo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new q.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Redo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let i=[],s=new Set;for(let r of t)!r.file||s.has(r.file.path)||(s.add(r.file.path),i.push(r.file));let n=await Promise.all(i.map(r=>this.app.vault.read(r))),o=i.map((r,l)=>({path:r.path,content:n[l]})),a=[];if(e){let r=new Set,l=[];for(let g of n)for(let p of this.extractAttachments(this.stripFrontmatter(g))){let d=this.app.metadataCache.getFirstLinkpathDest(p,"");d&&!r.has(d.path)&&(r.add(d.path),l.push(d))}let c=await Promise.all(l.map(g=>this.app.vault.readBinary(g)));for(let g=0;g<l.length;g++)a.push({path:l[g].path,data:c[g]})}return{notes:o,attachments:a}}async restoreSnapshots(t,e){for(let s of t.attachments)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.createBinary(s.path,s.data)}catch{}for(let s of t.notes)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.create(s.path,s.content)}catch{}let i=()=>{e&&e.some(n=>this.tree.get(n))&&(this.pendingFocusIds=e.slice())};i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"}),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},100),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},400),setTimeout(()=>{for(let s of t.notes){let n=this.tree.idForPath(s.path);n&&this.fmSync.schedule(n)}},500)}async trashNotesAndAttachments(t){let e=new Set;for(let i of t.notes){let s=this.tree.idForPath(i.path);if(!s)continue;let n=this.tree.get(s);n?.parent&&e.add(n.parent)}for(let i of t.notes){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}for(let i of t.attachments){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}this.tree.rebuild(this.noteFolder),this.render();for(let i of e)this.fmSync.scheduleParentOfDeleted(i)}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 s={...this.plugin.settings.drafts??{}};t.length===0?delete s[e]:s[e]=t,this.plugin.settings.drafts=s,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,q.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 i=this.tree.get(e);if(i&&(!this.isCompleted(i)||this.hasIncompleteDescendant(i)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof q.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof q.TFolder){s.push(o);continue}if(!(o instanceof q.TFile)||o.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let r of a.attachments){if(typeof r!="string")continue;let l=ae(r),c=this.app.metadataCache.getFirstLinkpathDest(l,o.path);c?t.add(c.path):t.add(l)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof q.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],r=[i];for(;r.length;){let l=r.pop();for(let c of l.children){if(c instanceof q.TFolder){let g=c.name;if(l===i&&o.has(g)||l===i&&g==="_attachments"&&!s)continue;r.push(c);continue}c instanceof q.TFile&&c.extension!=="md"&&(c.name===".stashpad-order.json"||c.name===".stashpad-sort.json"||!s&&n.has(c.path)||a.push(c))}}return a}populateListBody(t,e){this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),e.file&&q.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let s=this.currentViewMode()==="everything"?this.collectFileItems(e.id):[];if(this.currentChildren.length===0&&s.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(s.length===0)for(let n=0;n<this.currentChildren.length;n++)this.renderNote(t,this.currentChildren[n],n);else{let o=[...this.currentChildren.map((a,r)=>({kind:"note",ts:Number.isFinite(Date.parse(a.created))?Date.parse(a.created):0,idx:r})),...s.map(a=>({kind:"file",ts:a.stat.ctime,file:a}))];o.sort((a,r)=>a.ts-r.ts);for(let a of o)a.kind==="note"?this.renderNote(t,this.currentChildren[a.idx],a.idx):this.renderFileRow(t,a.file)}e.file&&q.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,i=this.listEl.scrollTop;this.listEl.empty(),this.populateListBody(this.listEl,t),e?this.listEl.scrollTop=this.listEl.scrollHeight:this.listEl.scrollTop=i}renderFileRow(t,e){let i=t.createDiv({cls:"stashpad-file-row"});i.dataset.path=e.path,i.createDiv({cls:"stashpad-file-meta"}).createSpan({cls:"stashpad-file-time",text:this.formatTime(new Date(e.stat.ctime).toISOString())});let n=i.createDiv({cls:"stashpad-file-body"});n.createSpan({cls:"stashpad-file-name",text:e.name}),n.createSpan({cls:"stashpad-file-ext",text:e.extension.toUpperCase()}),i.title=`${e.path} \u2014 click to open`,i.onclick=o=>{o.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(),i=this.currentHideChildless(),s=this.tree.getChildren(t),n=i?s.filter(r=>r.children.length>0):s;if(e==="nested")return n;let o=[],a=r=>{o.push(r);for(let l of this.tree.getChildren(r.id))a(l)};for(let r of n)a(r);return o}filterChildren(t){let e=this.timeFilterCutoff(),i=this.tagFilter?.toLowerCase(),s=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),o=this.currentAttachmentsOnly(),a=this.importedOnly,r=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!a&&!r?t:t.filter(l=>{if(a&&(!l.file||this.app.metadataCache.getFileCache(l.file)?.frontmatter?.imported!==!0))return!1;if(r){if(!l.file)return!1;let c=Xt(this.app.metadataCache.getFileCache(l.file)?.frontmatter?.author);if(!c||c.id!==r)return!1}if(e&&l.created){let c=Date.parse(l.created);if(!Number.isNaN(c)&&c<e)return!1}return!(i&&(!l.file||!this.nodeHasTag(l,i))||s&&(this.colorForNode(l)?.toLowerCase()??null)!==s||n&&this.isCompleted(l)&&!this.hasIncompleteDescendant(l)||o&&!this.hasAttachmentInSubtree(l))})}nodeHasTag(t,e){if(!t.file)return!1;let i=this.app.metadataCache.getFileCache(t.file);if(!i)return!1;if(i.tags){for(let n of i.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let s=i.frontmatter?.tags;if(s){let n=Array.isArray(s)?s:[s];for(let o of n)if(typeof o=="string"&&o.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){if(!s.file)continue;let n=this.app.metadataCache.getFileCache(s.file);if(n?.tags)for(let a of n.tags){let r=(a.tag||"").replace(/^#/,"");r&&t.set(r,(t.get(r)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let r of a){if(typeof r!="string")continue;let l=r.replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}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 s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}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){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{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,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){St.enabled&&(this._renderT0=performance.now()),this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,i=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",q.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let r=this.containerEl.closest(".workspace-leaf");r&&(r.classList.toggle("stashpad-is-tiny",this.tinyMode),r.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&&!q.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,c),this.currentChildren=this.filterChildren(this.collectViewItems(c.id));let g=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let I=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(I.id),this.lastSelected=I.id,this.autoSelectNewest=!1,g=!0}else if(this.pendingFocusIds){let I=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let u=-1;for(let f of I){let C=this.currentChildren.findIndex(m=>m.id===f);C>=0&&(this.selection.add(f),u<0&&(u=C))}this.cursorIdx=u,u>=0&&(this.lastSelected=I.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let p=e.createDiv({cls:"stashpad-list"});if(this.listEl=p,this.dnd.attachListDnD(p),this.populateListBody(p,c),this.renderComposer(e),q.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(St.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),g&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let I=this.pendingComposerCaret;this.pendingComposerCaret=null;let u=this.composerInputEl;if(u&&u.isConnected){if(u.focus({preventScroll:!0}),I!=null){let f=Math.min(I,u.value.length);try{u.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),I!=null)){let C=Math.min(I,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let d=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,d&&this.listEl){let I=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,d.kind){case"preserve":I?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=d.scrollTop,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let m=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(u,m),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let u=d.id,f=d.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let E=C.querySelector(`[data-id="${u}"]`);E&&E.scrollIntoView({block:f,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&a?this.scrollListToBottom():this.listEl&&i>0&&(this.listEl.scrollTop=i);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let I=this.listEl,u=I.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){I.scrollTop=I.scrollHeight,u=I.scrollTop;return}let m=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop<u&&u<=m?I.scrollTop=u:u=I.scrollTop});f.observe(I),this.listResizeObserver=f,I.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;I.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),I.addEventListener("touchmove",m=>{let E=m.touches[0]?.clientY??C;E>C&&(this.stickToListBottom=!1),C=E},{passive:!0}),I.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),I.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),i=e.createEl("button",{cls:"stashpad-folder-btn"}),s=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,q.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=d=>{d.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});jt(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=d=>{d.preventDefault(),this.openSearchModal()},q.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"}),r=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,q.setIcon)(r,this.timeFilterCalendar?"calendar":"history"),r.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&&r.addClass("is-active"),r.onclick=d=>{d.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let d of Yi){let I=this.timeFilterCalendar?d.calShort:d.rollShort,u=this.timeFilterCalendar?d.calLong:d.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:I});f.title=u,this.timeFilter===d.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(d.key)}}let c=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let d of Yi){let I=this.timeFilterCalendar?d.calLong:d.rollLong,u=c.createEl("option",{text:I});u.value=d.key,this.timeFilter===d.key&&(u.selected=!0)}c.onchange=()=>this.setTimeFilter(c.value);let l=e.createDiv({cls:"stashpad-view-mode-btns"});if(!q.Platform.isMobile){let d=l.createEl("button",{cls:"stashpad-view-mode-btn"});(0,q.setIcon)(d,"minimize-2"),d.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",d.onclick=I=>{I.preventDefault(),this.plugin.openTinyWindow()}}let g=l.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,q.setIcon)(g,this.compactMode?"panel-top":"rows-2"),g.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&&g.addClass("is-active"),g.onclick=d=>{d.preventDefault(),this.toggleCompactMode()},q.Platform.isMobile)return;let p=l.createEl("button",{cls:"stashpad-view-mode-btn"});(0,q.setIcon)(p,"external-link"),p.title=ft().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.)",p.onclick=d=>{d.preventDefault();let I=ft().popoutDuplicates;try{let u=this.app.workspace;if(I){let f=this.leaf.getViewState(),C=u.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new q.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else u.moveLeafToPopout?.(this.leaf)}catch(u){new q.Notice(`Stashpad: open-in-new-window failed (${u.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),i=e.createEl("button",{cls:"stashpad-mobile-action-btn"});jt(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==U;i.title=this.navBackStack.length>0?"Back":this.focusId!==U?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=l=>{l.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});jt(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=l=>{l.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),r=this.mobileSelectMode;jt(a,r?"check-square":"square",r?"\u2611":"\u2610"),a.title=r?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",r&&a.addClass("is-active"),a.onclick=l=>{if(l.preventDefault(),this.mobileSelectMode){let g=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),g){let p=this.currentChildren.findIndex(d=>d.id===g);this.selection.add(g),this.lastSelected=g,p>=0&&(this.cursorIdx=p)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let g=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),g&&(this.selection.add(g.id),this.lastSelected=g.id,this.firstSelectedId=g.id),this.render(),new q.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let c=e.createEl("button",{cls:"stashpad-mobile-action-btn"});jt(c,"zap","\u26A1"),c.title="Actions (move, delete, undo, \u2026)",c.onclick=l=>{l.preventDefault(),this.openMobileActionsMenu(c)}}openMobileActionsMenu(t){let e=new q.Menu,i=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],s=this.selection.size<=1;e.addItem(o=>o.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(o=>o.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(o=>o.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addSeparator(),e.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!i).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(o=>o.setTitle("Open in editor").setIcon("pencil").setDisabled(!i).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(o=>o.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!i).onClick(()=>this.cmdMovePicker())),e.addItem(o=>o.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!i).onClick(()=>this.cmdInListPicker())),e.addItem(o=>o.setTitle("Outdent").setIcon("outdent").setDisabled(!i).onClick(()=>void this.cmdOutdent())),e.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").setDisabled(!i).onClick(()=>this.cmdSetColor())),e.addItem(o=>o.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!i).onClick(()=>void this.cmdToggleComplete())),e.addItem(o=>o.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!i).onClick(()=>void this.cmdToggleTask())),e.addItem(o=>o.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!i).onClick(()=>this.cmdSetDue())),e.addItem(o=>o.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!i).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(o=>o.setTitle("Copy").setIcon("copy").setDisabled(!i).onClick(()=>void this.cmdCopy())),e.addItem(o=>o.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!i).onClick(()=>void this.cmdCopyTree())),e.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!i).onClick(()=>void this.cmdClone())),e.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(o=>o.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(o=>o.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!i||!s).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(o=>o.setTitle("Delete").setIcon("trash-2").setDisabled(!i).onClick(()=>void this.cmdDelete())),e.addSeparator(),e.addItem(o=>o.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}openCommandPalette(){this.app.commands?.executeCommandById?.("command-palette:open")}openStashpadCommandPalette(){new Ri(this.app).open()}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),i=e.createEl("option",{text:"All tags"});i.value="",this.tagFilter||(i.selected=!0);let s=this.collectFolderTags();if(s.length===0)e.disabled=!0,i.text="No tags";else for(let n of s){let o=e.createEl("option",{text:`${n.label} (${n.count})`});o.value=n.raw,this.tagFilter&&this.tagFilter.toLowerCase()===n.raw.toLowerCase()&&(o.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),i=t.createDiv({cls:"stashpad-color-filter-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0"),(()=>{i.empty();let o=i.createSpan({cls:"stashpad-color-filter-swatch"}),a=i.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let r=this.colorFilter.toLowerCase();o.style.background=r;let c=this.plugin.getColorAlias(this.noteFolder,r);a.setText(c??r)}else e.length===0?(o.addClass("is-empty"),a.setText("No colors"),i.addClass("is-disabled")):(o.addClass("is-empty"),a.setText("All colors"))})();let n=o=>{o.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(i,e)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openColorFilterMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-color-filter-popover").forEach(c=>c.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.style.left=`${Math.max(8,n.left)}px`,s.style.top=`${n.bottom+4}px`,s.style.minWidth=`${n.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let o=new q.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=c=>{!s.contains(c.target)&&c.target!==t&&!t.contains(c.target)&&a()};o.register([],"Escape",c=>(c.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",r,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,i=this.focusId,s=this.sortStore.getMode(e,i),n=this.currentViewMode(),o=n!=="nested",a=t.createDiv({cls:"stashpad-sort-btn"});a.setAttribute("role","button"),a.setAttribute("tabindex",o?"-1":"0"),o&&a.addClass("is-disabled");let r=a.createSpan({cls:"stashpad-sort-icon"});(0,q.setIcon)(r,"arrow-up-down");let c=a.createSpan({cls:"stashpad-sort-label"});o?(c.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${Ki[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(c.setText(ti[s]),s!=="manual"&&a.addClass("is-active"),a.title=s==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${ti[s]}. Drag-reorder will revert this parent to Manual.`);let l=g=>{o||(g.preventDefault(),this.openSortMenu(a))};a.onclick=l,a.onkeydown=g=>{o||(g.key==="Enter"||g.key===" ")&&l(g)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-sort-popover"}),s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateSortMenuBody(i,n);let a=new q.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let i=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,q.setIcon)(i,"sliders-horizontal"),e.title="Filters / view options";let s=!!this.tagFilter,n=!!this.colorFilter,o=this.timeFilter!=="all",a=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",r=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||a||r)&&e.addClass("is-active");let c=l=>{l.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=c,e.onkeydown=l=>{(l.key==="Enter"||l.key===" ")&&c(l)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(p=>p.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.style.right=`${Math.max(8,n.innerWidth-s.right)}px`,i.style.left="auto",i.style.top=`${s.bottom+4}px`,i.style.maxWidth="min(360px, calc(100vw - 16px))",i.style.width="max-content",i.style.minWidth="260px";let o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(g)}catch{}},a=p=>{!i.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&o()},r=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let p=Yi.find(d=>d.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":ti[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:p=>{if(this.currentViewMode()!=="nested"){p.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(p,o)}},{key:"view",title:"View",summary:()=>Ki[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,o)}],c="",l=()=>{i.empty();for(let p of r){let d=i.createDiv({cls:"stashpad-mobile-filters-section"}),I=d.createDiv({cls:"stashpad-mobile-filters-header"}),u=I.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,q.setIcon)(u,c===p.key?"chevron-down":"chevron-right"),I.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),I.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),I.onclick=f=>{f.preventDefault(),f.stopPropagation(),c=c===p.key?"":p.key,l()},c===p.key){let f=d.createDiv({cls:"stashpad-mobile-filters-body"});p.populate(f)}}};l();let g=new q.Scope(this.app.scope);g.register([],"Escape",p=>(p.preventDefault(),o(),!1)),this.app.keymap?.pushScope(g),setTimeout(()=>{e.addEventListener("mousedown",a,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),i=t.createDiv({cls:"stashpad-view-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-view-icon"});(0,q.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(Ki[e]),e!=="nested"&&i.addClass("is-active"),i.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 o=a=>{a.preventDefault(),this.openViewMenu(i)};i.onclick=o,i.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&o(a)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-view-popover"});q.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(320px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateViewMenuBody(i,n);let a=new q.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(y,F)=>{let D=t.createDiv({cls:"stashpad-view-popover-row"});y===i&&D.addClass("is-active"),D.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:Ki[y]}),D.createDiv({cls:"stashpad-view-popover-desc",text:F}),D.onclick=async S=>{S.preventDefault(),S.stopPropagation(),e(),y!==i&&(await this.setViewMode(y),this.render())}};s("nested","Tree of immediate children (default)."),s("flat","All descendants of the current focus, flat by sort."),s("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"}),o=n.createEl("input",{type:"checkbox"});o.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:i==="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 y=>{y.target!==o&&(y.preventDefault(),o.checked=!o.checked),await this.setHideChildless(o.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),r=a.createEl("input",{type:"checkbox"});r.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 y=>{y.target!==r&&(y.preventDefault(),r.checked=!r.checked),await this.setHideCompleted(r.checked),this.refreshList()};let c=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),l=c.createEl("input",{type:"checkbox"});l.checked=this.currentAttachmentsOnly(),c.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),c.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),c.onclick=async y=>{y.target!==l&&(y.preventDefault(),l.checked=!l.checked),await this.setAttachmentsOnly(l.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let g=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&g.addClass("is-disabled");let p=g.createEl("input",{type:"checkbox"});p.checked=this.currentIncludeAttachments(),p.disabled=i!=="everything",g.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),g.createDiv({cls:"stashpad-view-popover-desc",text:i==="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."}),g.onclick=async y=>{i==="everything"&&(y.target!==p&&(y.preventDefault(),p.checked=!p.checked),await this.setIncludeAttachments(p.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let d=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),I=d.createEl("input",{type:"checkbox"});I.checked=this.importedOnly,d.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),d.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),d.onclick=y=>{y.target!==I&&(y.preventDefault(),I.checked=!I.checked),this.importedOnly=I.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let u=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let F=Xt(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);F&&u.set(F.id,F.name)}let C=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),m=C.createDiv({cls:"stashpad-view-popover-main"});m.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let E=m.createEl("select",{cls:"stashpad-view-author-select"}),w=E.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[y,F]of[...u.entries()].sort((D,L)=>D[1].localeCompare(L[1]))){let D=E.createEl("option",{text:F,value:y});this.authorFilter===y&&(D.selected=!0)}E.onclick=y=>y.stopPropagation(),E.onchange=()=>{this.authorFilter=E.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},C.createDiv({cls:"stashpad-view-popover-desc",text:u.size?"Show only notes by the chosen author.":"No authored notes in this folder yet."})}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let i=this.noteFolder,s=this.focusId,n=this.sortStore.getMode(i,s);for(let o of Qs){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:ti[o]}),a.onclick=async r=>{r.preventDefault(),r.stopPropagation(),e(),o!==n&&(this.sortStore.setMode(i,s,o),await this.sortStore.save(i),this.tree.rebuild(i),this.render())}}}populateTimeMenuBody(t,e){let i=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),s=i.createEl("input",{type:"checkbox"});s.checked=this.timeFilterCalendar,i.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),i.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),i.onclick=n=>{n.target!==s&&(n.preventDefault(),s.checked=!s.checked),this.timeFilterCalendar=s.checked,this.persistFocus(),this.refreshList()};for(let n of Yi){let o=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&o.addClass("is-active");let a=this.timeFilterCalendar?n.calLong:n.rollLong;o.createSpan({cls:"stashpad-sort-popover-label",text:a}),o.onclick=r=>{r.preventDefault(),r.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,a)=>{let r=t.createDiv({cls:"stashpad-color-filter-popover-row"}),c=r.createSpan({cls:"stashpad-color-filter-swatch"});o?c.style.background=o:c.addClass("is-empty");let l=r.createSpan({cls:"stashpad-color-filter-popover-label"});l.setText(n),o&&(l.style.color=o),r.onclick=g=>{g.preventDefault(),g.stopPropagation(),a(),i()}};s("All colors",null,()=>this.setColorFilter(null));for(let n of e){let o=this.plugin.getColorAlias(this.noteFolder,n.hex),a=o?`${o} (${n.count})`:`${n.hex} (${n.count})`;s(a,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let i=this.collectFolderTags(),s=(n,o)=>{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??"")===(o??"")&&a.addClass("is-active"),a.onclick=l=>{l.preventDefault(),l.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null);for(let n of i)s(`${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(i=>i.id));for(let i of[...this.selection])e.has(i)||this.selection.delete(i);if(this.firstSelectedId&&!e.has(this.firstSelectedId)&&(this.firstSelectedId=null),this.lastSelected&&!e.has(this.lastSelected)&&(this.lastSelected=null),this.selection.size>0){let i=t.findIndex(s=>this.selection.has(s.id));this.cursorIdx=i>=0?i: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"}),i=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});jt(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==U||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==U?"Back (up to parent)":"No back history",i.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 o=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),r=this.focusId===U?a:`${a} / ${this.titleForNode(o).trim()}`,c=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),l=c.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,q.setIcon)(l,"folder"),c.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:r}),c.title=`${this.noteFolder}${this.focusId!==U?` / ${this.titleForNode(o).trim()}`:""} -Click to switch / create folder.`,c.onclick=u=>{u.preventDefault(),this.plugin.openFolderPicker()};let g=e.createDiv({cls:"stashpad-tiny-sticky"}),p=g.createEl("input",{type:"checkbox"});if(p.checked=this.tinyAlwaysOnTop,g.createSpan({text:"Sticky"}),p.onchange=()=>{this.tinyAlwaysOnTop=p.checked,this.applyTinyAlwaysOnTop()},!q.Platform.isMobile){let u=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,q.setIcon)(u,"contrast"),u.title="Window transparency",this.tinyOpacity<1&&u.addClass("is-active"),u.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(u)}}let d=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,q.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 I=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,q.setIcon)(I,"maximize-2"),I.title="Exit tiny mode",I.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 i=e.createEl("input",{type:"range"});i.min="30",i.max="100",i.step="1",i.value=String(Math.round(this.tinyOpacity*100));let s=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${i.value}%`});i.addEventListener("input",()=>{let l=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=l/100,s.setText(`${l}%`),this.applyTinyOpacity(),t.toggleClass("is-active",this.tinyOpacity<1)}),i.addEventListener("change",()=>{this.app.workspace.requestSaveLayout()}),this.viewRoot.appendChild(e);let n=t.getBoundingClientRect(),o=this.viewRoot.getBoundingClientRect();e.style.top=`${n.bottom-o.top+4}px`,e.style.left=`${Math.max(4,Math.min(n.left-o.left,o.width-180))}px`;let a=l=>{e.contains(l.target)||l.target===t||t.contains(l.target)||c()},r=l=>{l.key==="Escape"&&c()},c=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",r,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",r,!0)},0),this.tinyOpacityPopover=e,i.focus()}getOwnElectronWindow(){try{let t=this.containerEl?.ownerDocument?.defaultView??window,s=((t?.require?.("electron")??window.require?.("electron"))?.remote??t?.electron?.remote??t?.["@electron/remote"])?.getCurrentWindow?.()??t?.electronWindow??null;if(!s)try{let n=window.require?.("electron"),o=n?.remote??n?.["@electron/remote"],r=(o?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];r.length===1?s=r[0]:r.length>1&&(s=o?.getFocusedWindow?.()??null??r[r.length-1])}catch(n){console.debug("[Stashpad] BrowserWindow.getAllWindows fallback failed",n)}return s||console.debug("[Stashpad] couldn't resolve own electron window"),s??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(i){console.debug("[Stashpad] setOpacity failed",i)}}applyTinyWindow(){let t=this.getOwnElectronWindow();if(t)try{if(this.tinyMode){t.setMinimumSize?.(220,260);let s=100,n=100;try{let o=t.getBounds?.();o&&typeof o.x=="number"&&(s=o.x,n=o.y)}catch{}try{t.setBounds?.({x:s,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),q.Platform.isMacOS??!1){let i=this.containerEl?.ownerDocument?.defaultView?.require?.("electron")??window.require?.("electron"),n=(i?.remote?.screen??i?.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 i=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(q.Platform.isMobile?((0,q.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(U),this.focusId===U){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 g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,q.setIcon)(g,"panel-top"),g.title="Exit compact mode",g.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(l=>{let g=this.titleForNode(l),p=g.length>s?g.slice(0,s-1)+"\u2026":g;return{id:l.id,label:p}}),r=l=>l.reduce((g,p)=>g+p.label.length+3,0);if(r(a)>n&&a.length>2){let l=!1;for(;r(a)>n&&a.length>2;)a.splice(1,1),l||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),l=!0)}for(let l of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),l.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:l.label}).title=o.map(g=>this.titleForNode(g)).join(" / ");else{let g=l.id,p=e.createSpan({cls:"stashpad-crumb",text:l.label});p.title=l.label,p.onclick=()=>this.navigateTo(g),p.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,g)},q.Platform.isMobile&&this.attachLongPress(p,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",l=>{l.preventDefault(),this.openCrumbMenu(l,U)}),q.Platform.isMobile){let l=e.querySelector(".stashpad-crumb-home");l&&this.attachLongPress(l,()=>this.openCrumbMenu(null,U))}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 l=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,q.setIcon)(l,"panel-top"),l.title="Exit compact mode",l.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",a=>{let r=a.touches[0];s=r?.clientX??0,n=r?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let r=a.touches[0];r&&(Math.abs(r.clientX-s)>10||Math.abs(r.clientY-n)>10)&&o()},{passive:!0}),t.addEventListener("touchend",o),t.addEventListener("touchcancel",o)}openCrumbMenu(t,e){let i=this.tree.get(e);if(!i)return;let s=new q.Menu;if(s.addItem(n=>n.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),s.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(i))),i.file&&s.addItem(n=>n.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(i))),t&&(t.clientX>0||t.clientY>0))s.showAtMouseEvent(t);else{let o=(t?.target??null)?.getBoundingClientRect();s.showAtPosition({x:o?.left??8,y:(o?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused-mini"});s.dataset.id=e.id,s.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let o=s.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,q.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(i)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),i=t.querySelector(".stashpad-focused-mini");!e||!i||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(s=>{for(let n of s)i.toggleClass("is-visible",!n.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused"}),o=s.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});o.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),o.createDiv({cls:"stashpad-focused-grip-spacer"});let a=s.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",g=>this.handleRenderedClick(g,e));let r=s.createDiv({cls:"stashpad-focused-actions"}),c=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,q.setIcon)(c,"pencil"),c.title="Edit in new tab",c.onclick=()=>void this.openFileAtEnd(i);let l=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,q.setIcon)(l,"copy"),l.title="Open this Stashpad in a new tab (clone)",l.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:q.Platform.isMobile,toggleHost:r,toggleAnchor:c})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(a=>a.id===this.focusId),n=i.slice(s+1,i.length-1);if(n.length===0)return;let o=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,r)=>{let c=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});c.title=`Focus into "${this.titleForNode(a)}"`,c.onclick=l=>{l.stopPropagation(),this.navigateTo(a.id)},r<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return yi(this.app,t,q.Platform.isMobile)}bulkActionMessage(t){let e=t.nodes.map(a=>`"${this.titleForNode(a).trim()||"(untitled)"}"`),i=t.suffix?` ${t.suffix}`:"",s=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${i}${s}`;if(e.length===1)return`${t.verb} ${e[0]}${i}${s}`;let n=t.bulletMax??10,o=e.length<=n?e.map(a=>`\u2022 ${a}`).join(` +Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=d=>{d.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});jt(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=d=>{d.preventDefault(),this.openSearchModal()},q.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"}),r=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,q.setIcon)(r,this.timeFilterCalendar?"calendar":"history"),r.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&&r.addClass("is-active"),r.onclick=d=>{d.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let d of Yi){let I=this.timeFilterCalendar?d.calShort:d.rollShort,u=this.timeFilterCalendar?d.calLong:d.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:I});f.title=u,this.timeFilter===d.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(d.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let d of Yi){let I=this.timeFilterCalendar?d.calLong:d.rollLong,u=l.createEl("option",{text:I});u.value=d.key,this.timeFilter===d.key&&(u.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!q.Platform.isMobile){let d=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,q.setIcon)(d,"minimize-2"),d.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",d.onclick=I=>{I.preventDefault(),this.plugin.openTinyWindow()}}let g=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,q.setIcon)(g,this.compactMode?"panel-top":"rows-2"),g.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&&g.addClass("is-active"),g.onclick=d=>{d.preventDefault(),this.toggleCompactMode()},q.Platform.isMobile)return;let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,q.setIcon)(p,"external-link"),p.title=ft().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.)",p.onclick=d=>{d.preventDefault();let I=ft().popoutDuplicates;try{let u=this.app.workspace;if(I){let f=this.leaf.getViewState(),C=u.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new q.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else u.moveLeafToPopout?.(this.leaf)}catch(u){new q.Notice(`Stashpad: open-in-new-window failed (${u.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),i=e.createEl("button",{cls:"stashpad-mobile-action-btn"});jt(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==U;i.title=this.navBackStack.length>0?"Back":this.focusId!==U?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});jt(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=c=>{c.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),r=this.mobileSelectMode;jt(a,r?"check-square":"square",r?"\u2611":"\u2610"),a.title=r?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",r&&a.addClass("is-active"),a.onclick=c=>{if(c.preventDefault(),this.mobileSelectMode){let g=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),g){let p=this.currentChildren.findIndex(d=>d.id===g);this.selection.add(g),this.lastSelected=g,p>=0&&(this.cursorIdx=p)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let g=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),g&&(this.selection.add(g.id),this.lastSelected=g.id,this.firstSelectedId=g.id),this.render(),new q.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 q.Menu,i=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],s=this.selection.size<=1;e.addItem(o=>o.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(o=>o.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(o=>o.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addSeparator(),e.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!i).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(o=>o.setTitle("Open in editor").setIcon("pencil").setDisabled(!i).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(o=>o.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!i).onClick(()=>this.cmdMovePicker())),e.addItem(o=>o.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!i).onClick(()=>this.cmdInListPicker())),e.addItem(o=>o.setTitle("Outdent").setIcon("outdent").setDisabled(!i).onClick(()=>void this.cmdOutdent())),e.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").setDisabled(!i).onClick(()=>this.cmdSetColor())),e.addItem(o=>o.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!i).onClick(()=>void this.cmdToggleComplete())),e.addItem(o=>o.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!i).onClick(()=>void this.cmdToggleTask())),e.addItem(o=>o.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!i).onClick(()=>this.cmdSetDue())),e.addItem(o=>o.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!i).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(o=>o.setTitle("Copy").setIcon("copy").setDisabled(!i).onClick(()=>void this.cmdCopy())),e.addItem(o=>o.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!i).onClick(()=>void this.cmdCopyTree())),e.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!i).onClick(()=>void this.cmdClone())),e.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(o=>o.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(o=>o.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!i||!s).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(o=>o.setTitle("Delete").setIcon("trash-2").setDisabled(!i).onClick(()=>void this.cmdDelete())),e.addSeparator(),e.addItem(o=>o.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}openCommandPalette(){this.app.commands?.executeCommandById?.("command-palette:open")}openStashpadCommandPalette(){new Ri(this.app).open()}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),i=e.createEl("option",{text:"All tags"});i.value="",this.tagFilter||(i.selected=!0);let s=this.collectFolderTags();if(s.length===0)e.disabled=!0,i.text="No tags";else for(let n of s){let o=e.createEl("option",{text:`${n.label} (${n.count})`});o.value=n.raw,this.tagFilter&&this.tagFilter.toLowerCase()===n.raw.toLowerCase()&&(o.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),i=t.createDiv({cls:"stashpad-color-filter-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0"),(()=>{i.empty();let o=i.createSpan({cls:"stashpad-color-filter-swatch"}),a=i.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let r=this.colorFilter.toLowerCase();o.style.background=r;let l=this.plugin.getColorAlias(this.noteFolder,r);a.setText(l??r)}else e.length===0?(o.addClass("is-empty"),a.setText("No colors"),i.addClass("is-disabled")):(o.addClass("is-empty"),a.setText("All colors"))})();let n=o=>{o.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(i,e)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openColorFilterMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.style.left=`${Math.max(8,n.left)}px`,s.style.top=`${n.bottom+4}px`,s.style.minWidth=`${n.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let o=new q.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=l=>{!s.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&a()};o.register([],"Escape",l=>(l.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",r,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,i=this.focusId,s=this.sortStore.getMode(e,i),n=this.currentViewMode(),o=n!=="nested",a=t.createDiv({cls:"stashpad-sort-btn"});a.setAttribute("role","button"),a.setAttribute("tabindex",o?"-1":"0"),o&&a.addClass("is-disabled");let r=a.createSpan({cls:"stashpad-sort-icon"});(0,q.setIcon)(r,"arrow-up-down");let l=a.createSpan({cls:"stashpad-sort-label"});o?(l.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${Ki[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(ti[s]),s!=="manual"&&a.addClass("is-active"),a.title=s==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${ti[s]}. Drag-reorder will revert this parent to Manual.`);let c=g=>{o||(g.preventDefault(),this.openSortMenu(a))};a.onclick=c,a.onkeydown=g=>{o||(g.key==="Enter"||g.key===" ")&&c(g)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-sort-popover"}),s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateSortMenuBody(i,n);let a=new q.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let i=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,q.setIcon)(i,"sliders-horizontal"),e.title="Filters / view options";let s=!!this.tagFilter,n=!!this.colorFilter,o=this.timeFilter!=="all",a=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",r=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||a||r)&&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(p=>p.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.style.right=`${Math.max(8,n.innerWidth-s.right)}px`,i.style.left="auto",i.style.top=`${s.bottom+4}px`,i.style.maxWidth="min(360px, calc(100vw - 16px))",i.style.width="max-content",i.style.minWidth="260px";let o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(g)}catch{}},a=p=>{!i.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&o()},r=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let p=Yi.find(d=>d.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":ti[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:p=>{if(this.currentViewMode()!=="nested"){p.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(p,o)}},{key:"view",title:"View",summary:()=>Ki[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,o)}],l="",c=()=>{i.empty();for(let p of r){let d=i.createDiv({cls:"stashpad-mobile-filters-section"}),I=d.createDiv({cls:"stashpad-mobile-filters-header"}),u=I.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,q.setIcon)(u,l===p.key?"chevron-down":"chevron-right"),I.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),I.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),I.onclick=f=>{f.preventDefault(),f.stopPropagation(),l=l===p.key?"":p.key,c()},l===p.key){let f=d.createDiv({cls:"stashpad-mobile-filters-body"});p.populate(f)}}};c();let g=new q.Scope(this.app.scope);g.register([],"Escape",p=>(p.preventDefault(),o(),!1)),this.app.keymap?.pushScope(g),setTimeout(()=>{e.addEventListener("mousedown",a,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),i=t.createDiv({cls:"stashpad-view-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-view-icon"});(0,q.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(Ki[e]),e!=="nested"&&i.addClass("is-active"),i.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 o=a=>{a.preventDefault(),this.openViewMenu(i)};i.onclick=o,i.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&o(a)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-view-popover"});q.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(320px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateViewMenuBody(i,n);let a=new q.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(y,F)=>{let D=t.createDiv({cls:"stashpad-view-popover-row"});y===i&&D.addClass("is-active"),D.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:Ki[y]}),D.createDiv({cls:"stashpad-view-popover-desc",text:F}),D.onclick=async S=>{S.preventDefault(),S.stopPropagation(),e(),y!==i&&(await this.setViewMode(y),this.render())}};s("nested","Tree of immediate children (default)."),s("flat","All descendants of the current focus, flat by sort."),s("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"}),o=n.createEl("input",{type:"checkbox"});o.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:i==="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 y=>{y.target!==o&&(y.preventDefault(),o.checked=!o.checked),await this.setHideChildless(o.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),r=a.createEl("input",{type:"checkbox"});r.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 y=>{y.target!==r&&(y.preventDefault(),r.checked=!r.checked),await this.setHideCompleted(r.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 y=>{y.target!==c&&(y.preventDefault(),c.checked=!c.checked),await this.setAttachmentsOnly(c.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let g=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&g.addClass("is-disabled");let p=g.createEl("input",{type:"checkbox"});p.checked=this.currentIncludeAttachments(),p.disabled=i!=="everything",g.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),g.createDiv({cls:"stashpad-view-popover-desc",text:i==="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."}),g.onclick=async y=>{i==="everything"&&(y.target!==p&&(y.preventDefault(),p.checked=!p.checked),await this.setIncludeAttachments(p.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let d=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),I=d.createEl("input",{type:"checkbox"});I.checked=this.importedOnly,d.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),d.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),d.onclick=y=>{y.target!==I&&(y.preventDefault(),I.checked=!I.checked),this.importedOnly=I.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let u=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let F=Xt(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);F&&u.set(F.id,F.name)}let C=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),m=C.createDiv({cls:"stashpad-view-popover-main"});m.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let E=m.createEl("select",{cls:"stashpad-view-author-select"}),w=E.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[y,F]of[...u.entries()].sort((D,L)=>D[1].localeCompare(L[1]))){let D=E.createEl("option",{text:F,value:y});this.authorFilter===y&&(D.selected=!0)}E.onclick=y=>y.stopPropagation(),E.onchange=()=>{this.authorFilter=E.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},C.createDiv({cls:"stashpad-view-popover-desc",text:u.size?"Show only notes by the chosen author.":"No authored notes in this folder yet."})}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let i=this.noteFolder,s=this.focusId,n=this.sortStore.getMode(i,s);for(let o of Qs){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:ti[o]}),a.onclick=async r=>{r.preventDefault(),r.stopPropagation(),e(),o!==n&&(this.sortStore.setMode(i,s,o),await this.sortStore.save(i),this.tree.rebuild(i),this.render())}}}populateTimeMenuBody(t,e){let i=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),s=i.createEl("input",{type:"checkbox"});s.checked=this.timeFilterCalendar,i.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),i.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),i.onclick=n=>{n.target!==s&&(n.preventDefault(),s.checked=!s.checked),this.timeFilterCalendar=s.checked,this.persistFocus(),this.refreshList()};for(let n of Yi){let o=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&o.addClass("is-active");let a=this.timeFilterCalendar?n.calLong:n.rollLong;o.createSpan({cls:"stashpad-sort-popover-label",text:a}),o.onclick=r=>{r.preventDefault(),r.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,a)=>{let r=t.createDiv({cls:"stashpad-color-filter-popover-row"}),l=r.createSpan({cls:"stashpad-color-filter-swatch"});o?l.style.background=o:l.addClass("is-empty");let c=r.createSpan({cls:"stashpad-color-filter-popover-label"});c.setText(n),o&&(c.style.color=o),r.onclick=g=>{g.preventDefault(),g.stopPropagation(),a(),i()}};s("All colors",null,()=>this.setColorFilter(null));for(let n of e){let o=this.plugin.getColorAlias(this.noteFolder,n.hex),a=o?`${o} (${n.count})`:`${n.hex} (${n.count})`;s(a,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let i=this.collectFolderTags(),s=(n,o)=>{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??"")===(o??"")&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),c.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null);for(let n of i)s(`${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(i=>i.id));for(let i of[...this.selection])e.has(i)||this.selection.delete(i);if(this.firstSelectedId&&!e.has(this.firstSelectedId)&&(this.firstSelectedId=null),this.lastSelected&&!e.has(this.lastSelected)&&(this.lastSelected=null),this.selection.size>0){let i=t.findIndex(s=>this.selection.has(s.id));this.cursorIdx=i>=0?i: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"}),i=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});jt(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==U||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==U?"Back (up to parent)":"No back history",i.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 o=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),r=this.focusId===U?a:`${a} / ${this.titleForNode(o).trim()}`,l=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=l.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,q.setIcon)(c,"folder"),l.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:r}),l.title=`${this.noteFolder}${this.focusId!==U?` / ${this.titleForNode(o).trim()}`:""} +Click to switch / create folder.`,l.onclick=u=>{u.preventDefault(),this.plugin.openFolderPicker()};let g=e.createDiv({cls:"stashpad-tiny-sticky"}),p=g.createEl("input",{type:"checkbox"});if(p.checked=this.tinyAlwaysOnTop,g.createSpan({text:"Sticky"}),p.onchange=()=>{this.tinyAlwaysOnTop=p.checked,this.applyTinyAlwaysOnTop()},!q.Platform.isMobile){let u=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,q.setIcon)(u,"contrast"),u.title="Window transparency",this.tinyOpacity<1&&u.addClass("is-active"),u.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(u)}}let d=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,q.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 I=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,q.setIcon)(I,"maximize-2"),I.title="Exit tiny mode",I.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 i=e.createEl("input",{type:"range"});i.min="30",i.max="100",i.step="1",i.value=String(Math.round(this.tinyOpacity*100));let s=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${i.value}%`});i.addEventListener("input",()=>{let c=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=c/100,s.setText(`${c}%`),this.applyTinyOpacity(),t.toggleClass("is-active",this.tinyOpacity<1)}),i.addEventListener("change",()=>{this.app.workspace.requestSaveLayout()}),this.viewRoot.appendChild(e);let n=t.getBoundingClientRect(),o=this.viewRoot.getBoundingClientRect();e.style.top=`${n.bottom-o.top+4}px`,e.style.left=`${Math.max(4,Math.min(n.left-o.left,o.width-180))}px`;let a=c=>{e.contains(c.target)||c.target===t||t.contains(c.target)||l()},r=c=>{c.key==="Escape"&&l()},l=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",r,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",r,!0)},0),this.tinyOpacityPopover=e,i.focus()}getOwnElectronWindow(){try{let t=this.containerEl?.ownerDocument?.defaultView??window,s=((t?.require?.("electron")??window.require?.("electron"))?.remote??t?.electron?.remote??t?.["@electron/remote"])?.getCurrentWindow?.()??t?.electronWindow??null;if(!s)try{let n=window.require?.("electron"),o=n?.remote??n?.["@electron/remote"],r=(o?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];r.length===1?s=r[0]:r.length>1&&(s=o?.getFocusedWindow?.()??null??r[r.length-1])}catch(n){console.debug("[Stashpad] BrowserWindow.getAllWindows fallback failed",n)}return s||console.debug("[Stashpad] couldn't resolve own electron window"),s??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(i){console.debug("[Stashpad] setOpacity failed",i)}}applyTinyWindow(){let t=this.getOwnElectronWindow();if(t)try{if(this.tinyMode){t.setMinimumSize?.(220,260);let s=100,n=100;try{let o=t.getBounds?.();o&&typeof o.x=="number"&&(s=o.x,n=o.y)}catch{}try{t.setBounds?.({x:s,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),q.Platform.isMacOS??!1){let i=this.containerEl?.ownerDocument?.defaultView?.require?.("electron")??window.require?.("electron"),n=(i?.remote?.screen??i?.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 i=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(q.Platform.isMobile?((0,q.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(U),this.focusId===U){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 g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,q.setIcon)(g,"panel-top"),g.title="Exit compact mode",g.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(c=>{let g=this.titleForNode(c),p=g.length>s?g.slice(0,s-1)+"\u2026":g;return{id:c.id,label:p}}),r=c=>c.reduce((g,p)=>g+p.label.length+3,0);if(r(a)>n&&a.length>2){let c=!1;for(;r(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=o.map(g=>this.titleForNode(g)).join(" / ");else{let g=c.id,p=e.createSpan({cls:"stashpad-crumb",text:c.label});p.title=c.label,p.onclick=()=>this.navigateTo(g),p.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,g)},q.Platform.isMobile&&this.attachLongPress(p,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,U)}),q.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,U))}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,q.setIcon)(c,"panel-top"),c.title="Exit compact mode",c.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",a=>{let r=a.touches[0];s=r?.clientX??0,n=r?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let r=a.touches[0];r&&(Math.abs(r.clientX-s)>10||Math.abs(r.clientY-n)>10)&&o()},{passive:!0}),t.addEventListener("touchend",o),t.addEventListener("touchcancel",o)}openCrumbMenu(t,e){let i=this.tree.get(e);if(!i)return;let s=new q.Menu;if(s.addItem(n=>n.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),s.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(i))),i.file&&s.addItem(n=>n.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(i))),t&&(t.clientX>0||t.clientY>0))s.showAtMouseEvent(t);else{let o=(t?.target??null)?.getBoundingClientRect();s.showAtPosition({x:o?.left??8,y:(o?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused-mini"});s.dataset.id=e.id,s.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let o=s.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,q.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(i)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),i=t.querySelector(".stashpad-focused-mini");!e||!i||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(s=>{for(let n of s)i.toggleClass("is-visible",!n.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused"}),o=s.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});o.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),o.createDiv({cls:"stashpad-focused-grip-spacer"});let a=s.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",g=>this.handleRenderedClick(g,e));let r=s.createDiv({cls:"stashpad-focused-actions"}),l=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,q.setIcon)(l,"pencil"),l.title="Edit in new tab",l.onclick=()=>void this.openFileAtEnd(i);let c=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,q.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:q.Platform.isMobile,toggleHost:r,toggleAnchor:l})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(a=>a.id===this.focusId),n=i.slice(s+1,i.length-1);if(n.length===0)return;let o=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,r)=>{let l=o.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)},r<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return yi(this.app,t,q.Platform.isMobile)}bulkActionMessage(t){let e=t.nodes.map(a=>`"${this.titleForNode(a).trim()||"(untitled)"}"`),i=t.suffix?` ${t.suffix}`:"",s=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${i}${s}`;if(e.length===1)return`${t.verb} ${e[0]}${i}${s}`;let n=t.bulletMax??10,o=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${i}${s}: -${o}`}titleList(t,e=3){if(!t.length)return"";let i=t.map(n=>this.titleForNode(n).trim()||"(untitled)");return i.length<=e?i.map(n=>`"${n}"`).join(", "):`${i.slice(0,e).map(n=>`"${n}"`).join(", ")}, +${i.length-e} more`}titleForNode(t){if(!t.file)return"Untitled";let i=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return i||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}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,i){if(!e.file)return;let s=e.file,n=this.tree.getChildren(e.id).length,o=this.selection.has(e.id),a=i===this.cursorIdx,r=this.inListPicker?.activeIdx===i,c=t.createDiv({cls:"stashpad-note"});o&&c.addClass("is-selected"),a&&c.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&c.addClass("is-cursor-expanded"),r&&c.addClass("is-pick-target"),this.isCompleted(e)&&c.addClass("is-completed"),c.dataset.idx=String(i),c.dataset.id=e.id;let l=this.currentViewMode()==="nested";c.draggable=l,l&&this.dnd.attachRowDnD(c,e,i),c.addEventListener("click",y=>this.handleRowClick(y,i,e)),c.addEventListener("dblclick",y=>{!this.plugin.settings.doubleClickToFocus||y.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(y.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let g=this.isTask(e)||this.compactMode;g&&(c.addClass("is-task"),q.Platform.isMobile||this.addTaskCheckbox(c,e));let p=c.createDiv({cls:"stashpad-note-meta"}),d=p.createDiv({cls:"stashpad-note-meta-top"});d.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let I=this.colorForNode(e),u=d.createDiv({cls:"stashpad-note-grip"});I&&u.addClass("has-color"),(0,q.setIcon)(u,"grip-vertical"),u.title=I?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=l,l||(u.title=I?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),I&&u.style.setProperty("--stashpad-note-color",I);let f=g&&q.Platform.isMobile;if(n>0||f){let y=p.createDiv({cls:"stashpad-note-meta-bottom"});if(f&&this.addTaskCheckbox(y,e),n>0){let F=y.createSpan({cls:"stashpad-note-enter"});I&&(F.style.color=I),(0,q.setIcon)(F.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),F.createSpan({text:` ${n}`}),F.onclick=D=>{D.stopPropagation(),this.navigateTo(e.id)}}}if(I)c.addClass("has-color"),c.style.setProperty("--stashpad-note-color",I);else{let y=this.inheritedColorForNode(e);y&&y.depth>0&&(c.addClass("has-inherited-color"),c.style.setProperty("--stashpad-inherited-color",y.hex),c.style.setProperty("--stashpad-inherited-depth",String(y.depth)))}let C=c.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(C,e);let m=C.createDiv({cls:"stashpad-note-body-content"}),E=c.createDiv({cls:"stashpad-note-actions"}),w;if(q.Platform.isMobile){let y=E.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,q.setIcon)(y,"ellipsis-vertical"),y.title="Actions",y.onclick=F=>{F.stopPropagation(),this.openNoteMenu(F,e)},w=y}else{let y=E.createEl("button",{cls:"stashpad-pencil"});(0,q.setIcon)(y,"pencil"),y.title="Edit in new tab",y.onclick=D=>{D.stopPropagation(),this.openFileAtEnd(s)};let F=E.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,q.setIcon)(F,"arrow-right"),F.title="Open in Stashpad view",F.onclick=D=>{D.stopPropagation(),this.navigateTo(e.id)},w=y}this.renderNoteBody(m,e,{clamp:!0,toggleHost:E,toggleAnchor:w}),c.oncontextmenu=y=>{y.preventDefault(),this.openNoteMenu(y,e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,q.setIcon)(i,s?"check-square":"square"),i.title=s?"Mark not done":"Mark done",i.addEventListener("mousedown",n=>n.stopPropagation()),i.addEventListener("dblclick",n=>{n.preventDefault(),n.stopPropagation()}),i.onclick=n=>{n.preventDefault(),n.stopPropagation(),this.toggleCompletedForNode(e)}}renderNoteBody(t,e,i={clamp:!0}){if(!e.file)return;if(this.bodyRenderer.hasFreshRenderCache(e.file)||!this.bodyRenderer.isArmed()){this.renderNoteBodyNow(t,e,i);return}t.empty();let s=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});s.textContent=this.titleForNode(e),this.bodyRenderer.defer(t,()=>this.renderNoteBodyNow(t,e,i))}renderNoteBodyNow(t,e,i={clamp:!0}){if(!e.file)return;let s=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.bodyRenderer.getOrComputeRender(s).then(o=>{if(t.__stashpadRenderToken!==n)return;let{text:a,attachments:r,html:c}=o;t.empty();let l=t.createDiv({cls:"stashpad-note-text"}),g=this.expandedNotes.has(e.id);if(i.clamp&&!g&&l.addClass("is-clamped"),this.compactMode||this.tinyMode?(l.addClass("is-plain"),l.textContent=a):l.innerHTML=c,r.length>0&&this.renderAttachmentRail(t,r),this.renderAuthorshipFooter(t,e),!i.clamp)return;let p=this.lastListWidth;if(o.ovW===p&&o.ovV!==void 0&&!g){o.ovV?this.attachExpandToggle(i,t,e,g):l.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let d=l.scrollHeight>l.clientHeight+4;if(o.ovW=p,o.ovV=d,!d&&!g){l.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,g)})})}attachExpandToggle(t,e,i,s){let n=!!t.toggleHost,o=t.toggleHost??e;o.querySelector(".stashpad-expand-toggle")?.remove();let a=o.createEl("button",{cls:"stashpad-expand-toggle"});a.title=s?"Show less":"Show more",n||q.Platform.isMobile?((0,q.setIcon)(a,s?"chevron-up":"chevron-down"),a.addClass("is-icon"),n&&a.addClass("is-inline")):a.setText(s?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(a,t.toggleAnchor),a.onclick=r=>{r.stopPropagation(),this.expandedNotes.has(i.id)?this.expandedNotes.delete(i.id):this.expandedNotes.add(i.id),e.empty(),this.renderNoteBody(e,i,t)}}renderAttachmentRail(t,e){let i=t.createDiv({cls:"stashpad-rail"});for(let s of e){let n=this.app.metadataCache.getFirstLinkpathDest(s,""),o=(s.split(".").pop()??"").toLowerCase(),a=i.createDiv({cls:"stashpad-att"});if(a.title=s,n&&ya.has(o)){let r=a.createEl("img",{cls:"stashpad-att-img"});r.src=this.app.vault.getResourcePath(n),r.alt=s}else{a.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let r=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:r})}a.onclick=r=>{r.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=ft(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=null,o=t.createDiv({cls:"stashpad-composer"}),a=o.createDiv({cls:"stashpad-composer-input-wrap"}),r=a.createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});r.value=this.composerDraft;let c=null,l=()=>{c&&(c.remove(),c=null)};n!==null&&n.length>0&&(c=a.createEl("button",{cls:"stashpad-composer-clear"}),(0,q.setIcon)(c,"x"),c.title="Clear restored draft",c.onmousedown=T=>T.preventDefault(),c.onclick=T=>{T.preventDefault(),r.value="",this.composerDraft="",this.saveDraft(""),l(),r.focus()},requestAnimationFrame(()=>{r.focus(),r.setSelectionRange(0,r.value.length)})),this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,q.debounce)(T=>{this.saveDraft(T)},250)),r.addEventListener("input",()=>{this.composerDraft=r.value,this.debouncedSaveDraft(r.value),l()}),r.addEventListener("blur",()=>{this.saveDraft(r.value)});let g=null,p=()=>{g||(g=new q.Scope(this.app.scope),g.register([],"Escape",()=>(this.composerExitAt=Date.now(),r.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),g.register(["Mod"],"z",()=>!0),g.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(g))},d=()=>{if(g){try{this.app.keymap?.popScope(g)}catch{}g=null}};if(r.addEventListener("focus",p),r.addEventListener("blur",d),document.activeElement===r&&p(),q.Platform.isMobile){let T=()=>{this.keyboardTransitionUntil=Date.now()+600};r.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),T()}),r.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),T(),q.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=r,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new we(this.app,r),this.composerAutocomplete.attach();let I=async T=>{let J="";for(let Z of T){let G=await this.importAttachment(Z);if(!G)continue;let N=r.value+J,_=N&&!N.endsWith(` +${o}`}titleList(t,e=3){if(!t.length)return"";let i=t.map(n=>this.titleForNode(n).trim()||"(untitled)");return i.length<=e?i.map(n=>`"${n}"`).join(", "):`${i.slice(0,e).map(n=>`"${n}"`).join(", ")}, +${i.length-e} more`}titleForNode(t){if(!t.file)return"Untitled";let i=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return i||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}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,i){if(!e.file)return;let s=e.file,n=this.tree.getChildren(e.id).length,o=this.selection.has(e.id),a=i===this.cursorIdx,r=this.inListPicker?.activeIdx===i,l=t.createDiv({cls:"stashpad-note"});o&&l.addClass("is-selected"),a&&l.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&l.addClass("is-cursor-expanded"),r&&l.addClass("is-pick-target"),this.isCompleted(e)&&l.addClass("is-completed"),l.dataset.idx=String(i),l.dataset.id=e.id;let c=this.currentViewMode()==="nested";l.draggable=c,c&&this.dnd.attachRowDnD(l,e,i),l.addEventListener("click",y=>this.handleRowClick(y,i,e)),l.addEventListener("dblclick",y=>{!this.plugin.settings.doubleClickToFocus||y.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(y.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let g=this.isTask(e)||this.compactMode;g&&(l.addClass("is-task"),q.Platform.isMobile||this.addTaskCheckbox(l,e));let p=l.createDiv({cls:"stashpad-note-meta"}),d=p.createDiv({cls:"stashpad-note-meta-top"});d.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let I=this.colorForNode(e),u=d.createDiv({cls:"stashpad-note-grip"});I&&u.addClass("has-color"),(0,q.setIcon)(u,"grip-vertical"),u.title=I?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=c,c||(u.title=I?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),I&&u.style.setProperty("--stashpad-note-color",I);let f=g&&q.Platform.isMobile;if(n>0||f){let y=p.createDiv({cls:"stashpad-note-meta-bottom"});if(f&&this.addTaskCheckbox(y,e),n>0){let F=y.createSpan({cls:"stashpad-note-enter"});I&&(F.style.color=I),(0,q.setIcon)(F.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),F.createSpan({text:` ${n}`}),F.onclick=D=>{D.stopPropagation(),this.navigateTo(e.id)}}}if(I)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",I);else{let y=this.inheritedColorForNode(e);y&&y.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",y.hex),l.style.setProperty("--stashpad-inherited-depth",String(y.depth)))}let C=l.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(C,e);let m=C.createDiv({cls:"stashpad-note-body-content"}),E=l.createDiv({cls:"stashpad-note-actions"}),w;if(q.Platform.isMobile){let y=E.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,q.setIcon)(y,"ellipsis-vertical"),y.title="Actions",y.onclick=F=>{F.stopPropagation(),this.openNoteMenu(F,e)},w=y}else{let y=E.createEl("button",{cls:"stashpad-pencil"});(0,q.setIcon)(y,"pencil"),y.title="Edit in new tab",y.onclick=D=>{D.stopPropagation(),this.openFileAtEnd(s)};let F=E.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,q.setIcon)(F,"arrow-right"),F.title="Open in Stashpad view",F.onclick=D=>{D.stopPropagation(),this.navigateTo(e.id)},w=y}this.renderNoteBody(m,e,{clamp:!0,toggleHost:E,toggleAnchor:w}),l.oncontextmenu=y=>{y.preventDefault(),this.openNoteMenu(y,e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,q.setIcon)(i,s?"check-square":"square"),i.title=s?"Mark not done":"Mark done",i.addEventListener("mousedown",n=>n.stopPropagation()),i.addEventListener("dblclick",n=>{n.preventDefault(),n.stopPropagation()}),i.onclick=n=>{n.preventDefault(),n.stopPropagation(),this.toggleCompletedForNode(e)}}renderNoteBody(t,e,i={clamp:!0}){if(!e.file)return;if(this.bodyRenderer.hasFreshRenderCache(e.file)||!this.bodyRenderer.isArmed()){this.renderNoteBodyNow(t,e,i);return}t.empty();let s=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});s.textContent=this.titleForNode(e),this.bodyRenderer.defer(t,()=>this.renderNoteBodyNow(t,e,i))}renderNoteBodyNow(t,e,i={clamp:!0}){if(!e.file)return;let s=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.bodyRenderer.getOrComputeRender(s).then(o=>{if(t.__stashpadRenderToken!==n)return;let{text:a,attachments:r,html:l}=o;t.empty();let c=t.createDiv({cls:"stashpad-note-text"}),g=this.expandedNotes.has(e.id);if(i.clamp&&!g&&c.addClass("is-clamped"),this.compactMode||this.tinyMode?(c.addClass("is-plain"),c.textContent=a):c.innerHTML=l,r.length>0&&this.renderAttachmentRail(t,r),this.renderAuthorshipFooter(t,e),!i.clamp)return;let p=this.lastListWidth;if(o.ovW===p&&o.ovV!==void 0&&!g){o.ovV?this.attachExpandToggle(i,t,e,g):c.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let d=c.scrollHeight>c.clientHeight+4;if(o.ovW=p,o.ovV=d,!d&&!g){c.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,g)})})}attachExpandToggle(t,e,i,s){let n=!!t.toggleHost,o=t.toggleHost??e;o.querySelector(".stashpad-expand-toggle")?.remove();let a=o.createEl("button",{cls:"stashpad-expand-toggle"});a.title=s?"Show less":"Show more",n||q.Platform.isMobile?((0,q.setIcon)(a,s?"chevron-up":"chevron-down"),a.addClass("is-icon"),n&&a.addClass("is-inline")):a.setText(s?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(a,t.toggleAnchor),a.onclick=r=>{r.stopPropagation(),this.expandedNotes.has(i.id)?this.expandedNotes.delete(i.id):this.expandedNotes.add(i.id),e.empty(),this.renderNoteBody(e,i,t)}}renderAttachmentRail(t,e){let i=t.createDiv({cls:"stashpad-rail"});for(let s of e){let n=this.app.metadataCache.getFirstLinkpathDest(s,""),o=(s.split(".").pop()??"").toLowerCase(),a=i.createDiv({cls:"stashpad-att"});if(a.title=s,n&&wa.has(o)){let r=a.createEl("img",{cls:"stashpad-att-img"});r.src=this.app.vault.getResourcePath(n),r.alt=s}else{a.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let r=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:r})}a.onclick=r=>{r.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=ft(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=null,o=t.createDiv({cls:"stashpad-composer"}),a=o.createDiv({cls:"stashpad-composer-input-wrap"}),r=a.createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});r.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,q.setIcon)(l,"x"),l.title="Clear restored draft",l.onmousedown=T=>T.preventDefault(),l.onclick=T=>{T.preventDefault(),r.value="",this.composerDraft="",this.saveDraft(""),c(),r.focus()},requestAnimationFrame(()=>{r.focus(),r.setSelectionRange(0,r.value.length)})),this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,q.debounce)(T=>{this.saveDraft(T)},250)),r.addEventListener("input",()=>{this.composerDraft=r.value,this.debouncedSaveDraft(r.value),c()}),r.addEventListener("blur",()=>{this.saveDraft(r.value)});let g=null,p=()=>{g||(g=new q.Scope(this.app.scope),g.register([],"Escape",()=>(this.composerExitAt=Date.now(),r.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),g.register(["Mod"],"z",()=>!0),g.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(g))},d=()=>{if(g){try{this.app.keymap?.popScope(g)}catch{}g=null}};if(r.addEventListener("focus",p),r.addEventListener("blur",d),document.activeElement===r&&p(),q.Platform.isMobile){let T=()=>{this.keyboardTransitionUntil=Date.now()+600};r.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),T()}),r.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),T(),q.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=r,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new we(this.app,r),this.composerAutocomplete.attach();let I=async T=>{let J="";for(let Z of T){let G=await this.importAttachment(Z);if(!G)continue;let N=r.value+J,_=N&&!N.endsWith(` `)?` `:"";J+=`${_}${G} `}J&&(r.value=r.value+J,this.composerDraft=r.value,this.saveDraft(r.value),r.focus(),r.setSelectionRange(r.value.length,r.value.length))};r.addEventListener("dragover",T=>{if(!(!T.dataTransfer||!Array.from(T.dataTransfer.types).includes("Files"))){T.preventDefault(),T.stopPropagation();try{T.dataTransfer.dropEffect="copy"}catch{}}}),r.addEventListener("drop",T=>{let J=Array.from(T.dataTransfer?.files??[]);J.length!==0&&(T.preventDefault(),T.stopPropagation(),I(J))}),r.addEventListener("paste",T=>{let J=[],Z=T.clipboardData;if(Z){for(let G of Array.from(Z.files??[]))J.push(G);if(J.length===0){for(let G of Array.from(Z.items??[]))if(G.kind==="file"){let N=G.getAsFile();N&&J.push(N)}}J.length!==0&&(T.preventDefault(),T.stopPropagation(),I(J))}});let u=o.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});u.style.display="none";let f=o.createDiv({cls:"stashpad-composer-btn-rail"}),C=f.createDiv({cls:"stashpad-composer-btn-group"}),m=C.createEl("button",{cls:"stashpad-composer-btn"});(0,q.setIcon)(m,"list-end"),m.title=s?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",s&&m.addClass("is-active"),m.onmousedown=T=>T.preventDefault(),m.onclick=T=>{T.preventDefault(),this.toggleSplit()};let E=C.createEl("button",{cls:"stashpad-composer-btn"});(0,q.setIcon)(E,"map-pin"),this.nextDestination&&E.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),E.title="Set destination (Mod+D)",this.nextDestination&&E.addClass("is-active"),E.onmousedown=T=>T.preventDefault(),E.onclick=T=>{T.preventDefault();let J=document.activeElement===r;this.openDestinationPicker(J)};let w=C.createEl("button",{cls:"stashpad-composer-btn"});(0,q.setIcon)(w,i?"corner-down-left":"arrow-big-down-dash"),w.title=i?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",w.onmousedown=T=>T.preventDefault(),w.onclick=T=>{T.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let y=T=>{let J=r.value&&!r.value.endsWith(` `)?` `:"";r.value+=`${J}${T} -`,this.composerDraft=r.value},F=C.createEl("button",{cls:"stashpad-composer-btn"});(0,q.setIcon)(F,"paperclip"),F.title="Attach files",F.onmousedown=T=>T.preventDefault(),F.onclick=T=>{T.preventDefault();let J=document.activeElement===r;if(u.click(),J){let Z=()=>{r.focus()};setTimeout(Z,100),setTimeout(Z,500)}},u.addEventListener("change",async()=>{let T=Array.from(u.files??[]);u.value="";for(let J of T){let Z=await this.importAttachment(J);Z&&y(Z)}r.focus()});let D=f.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,q.setIcon)(D,"chevron-left"),D.title="Show more composer options",f.insertBefore(D,C);let L=T=>{f.toggleClass("is-expanded",T),D.title=T?"Hide options":"Show more composer options",(0,q.setIcon)(D,T?"chevron-right":"chevron-left")};D.onmousedown=T=>T.preventDefault(),D.onclick=T=>{T.preventDefault(),L(!f.hasClass("is-expanded"))},L(!1);let S=()=>o.clientWidth<700,b=()=>{let T=S();o.toggleClass("is-narrow",T),L(!T)};b(),requestAnimationFrame(b);let Q=new ResizeObserver(b);Q.observe(o),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=Q;let H=f.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});H.title="Send (Enter)",(0,q.setIcon)(H,"arrow-up");let $=async()=>{let T=r.value.trim();if(!T)return;r.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(T)}catch{}let J=this.modeSplit??ft().splitOnLines,Z=this.nextDestination,G=this.nextDestinationFolder,N=!!G&&G!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!N,this.scrollToBottomOnNextRender=!N;let _=N?{targetFolder:G}:void 0;if(J)for(let K of T.split(/\r?\n/)){let z=K.trim();z&&await this.createNoteUnder(z,Z,_)}else await this.createNoteUnder(T,Z,_);ft().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,N&&this.composerInputEl?.focus())};H.onclick=()=>void $(),r.addEventListener("keydown",T=>{let J=this.modeEnterSubmits;if(T.key==="Escape"){T.preventDefault(),T.stopPropagation(),r.blur(),this.viewRoot.focus({preventScroll:!0});return}if(T.key==="ArrowUp"&&r.selectionStart===0&&r.selectionEnd===0){if(T.preventDefault(),r.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let Z=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,G=Z?this.currentChildren.findIndex(N=>N.id===Z):-1;this.cursorIdx=G>=0?G:this.currentChildren.length-1,this.selectCursor(!1)}return}T.key==="Enter"&&!T.isComposing&&(J?!T.shiftKey:T.shiftKey)&&(T.preventDefault(),T.stopPropagation(),T.stopImmediatePropagation(),$())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return q.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 i=t?"Enter":"Shift+Enter",s=t?"Shift+Enter":"Enter",n=ft().bindings,o=g=>{let p=n[g];return p.primary&&p.secondary?p.preferRight?p.secondary:p.primary:p.primary||p.secondary},a=ei(o("toggleSplit")),r=ei(o("pickDestination")),c=ei(o("search")),l=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${r} destination \xB7 ${c} search${l}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===U)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(U),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let a=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(a){let r=this.app.internalPlugins?.plugins?.["global-search"],c=r?.instance?.openGlobalSearch?.bind(r.instance);c&&c(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=t.target,n=s?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let c=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(c){let l=this.app.internalPlugins?.plugins?.["global-search"],g=l?.instance?.openGlobalSearch?.bind(l.instance);g&&g(`tag:#${c}`)}return}let o=s?.closest?.(".internal-link");if(o){t.preventDefault(),t.stopPropagation();let r=o.getAttribute("data-href")||o.getAttribute("href");if(r){let c=i.file?.path||"";this.app.workspace.openLinkText(r,c,!0)}return}if(s?.tagName==="A"&&s.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 r=this.currentChildren.findIndex(c=>c.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),r!==-1){let[c,l]=r<e?[r,e]:[e,r];for(let g=c;g<=l;g++)this.selection.add(this.currentChildren[g].id)}else this.selection.add(i.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(i.id))if(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null),this.lastSelected===i.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let r=this.lastSelected??[...this.selection][this.selection.size-1],c=r?this.currentChildren.findIndex(l=>l.id===r):-1;c>=0&&(this.cursorIdx=c)}else this.cursorIdx=e,a&&(this.firstSelectedId=i.id),this.selection.add(i.id);else this.mobileSelectMode?(this.cursorIdx=e,this.selection.has(i.id)?(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null)):this.selection.add(i.id)):(this.cursorIdx=e,this.selection.clear(),this.selection.add(i.id),this.firstSelectedId=i.id,this.lastSelected=i.id);this.selection.size===0&&(this.firstSelectedId=null),this.selection.has(i.id)&&(this.lastSelected=i.id),this.viewRoot.focus({preventScroll:!0}),this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}revealCursorRow(){let t=()=>{if(this.cursorIdx<0)return;let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let i=this.listEl,s=i.getBoundingClientRect(),n=e.getBoundingClientRect(),o=4,a=s.top+o,r=s.bottom-o;if(q.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let c=this.viewRoot?.querySelector(".stashpad-composer");c&&(r=Math.min(r,c.getBoundingClientRect().top-o))}n.top<a?i.scrollTop+=n.top-a:n.bottom>r&&(i.scrollTop+=n.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 i=this.firstSelectedId??e.id,s=this.currentChildren.findIndex(n=>n.id===i);if(s===-1)this.selection.add(e.id),this.firstSelectedId=e.id;else{let[n,o]=s<this.cursorIdx?[s,this.cursorIdx]:[this.cursorIdx,s];this.selection.clear();for(let a=n;a<=o;a++)this.selection.add(this.currentChildren[a].id);this.firstSelectedId=i}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(s=>{let n=Number(s.dataset.idx),o=s.dataset.id??"",a=n===this.cursorIdx;s.classList.toggle("is-cursor",a),s.classList.toggle("is-selected",this.selection.has(o)),s.classList.toggle("is-cursor-expanded",t&&a),s.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 i=e.getBoundingClientRect(),s=this.listEl.getBoundingClientRect();(i.top<s.top||i.bottom>s.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??ft().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Ot(this.app,this.tree,i=>this.titleForNode(i),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async i=>{if(e=!0,i.crossFolder){let s=i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===U?"Home":(i.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${n} \u25B8 ${o}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=i.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async i=>{e=!0;let s=await this.createNoteUnder(i,this.focusId);s&&(this.nextDestination=s,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,onClose:()=>{t&&!e&&this.composerInputEl?.focus()}}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===U&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:U,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=s=>{if(s===t)return!0;let n=new Set,o=this.tree.get(s);for(;o&&o.id!==U&&!n.has(o.id);){if(n.add(o.id),o.parent===t||o.id===t)return!0;if(!o.parent)return!1;o=this.tree.get(o.parent)}return t===U},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Ot(this.app,i,s=>this.titleForNode(s),{mode:"search",placeholder:`Search in "${this.titleForNode(this.tree.get(t)??this.tree.getRoot()).trim()}"\u2026`,allowCreate:!1,onPick:s=>{s.node&&e(s.node.id)?this.navigateTo(s.node.id):s.node&&this.navigateTo(s.node.id)}}).open()}openSearchModal(){if(this.openSearchInstance){let i=this.openSearchInstance.inputEl;i&&(i.focus(),i.select());return}let t=new Ot(this.app,this.tree,i=>this.titleForNode(i),{mode:"search",placeholder:"Search Stashpad notes\u2026",allowCreate:!0,onCreate:async i=>{let s=i.trim();s&&new Ot(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",placeholder:`Create "${s}" under which note?`,allowCreate:!1,crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(n=>n!==this.noteFolder),localFolder:this.noteFolder,onPick:async n=>{let o=n.crossFolder?n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!o)return;let r=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",c=this.app.workspace,l=c.getLeaf("tab");await l.setViewState({type:dt,active:!0,state:{focusId:o,folderOverride:a===r?null:a}}),c.revealLeaf(l);let g=l.view;if(g&&typeof g.createNoteUnder=="function"){let p=await g.createNoteUnder(s,o);p&&typeof g.navigateTo=="function"&&g.navigateTo(p)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.id.replace(/^cross:/,"");s?this.openNoteInNewTab(i.crossFolder,n):this.switchToFolderAndFocus(i.crossFolder,n);return}i.node&&(s?this.openNoteInNewTab(this.noteFolder,i.node.id):this.navigateTo(i.node.id))},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(i=>i!==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()}excludedSearchFolders(){let t=new Set(this.plugin.searchableFolders(this.noteFolder));return this.plugin.discoverStashpadFolders().filter(e=>e!==this.noteFolder&&!t.has(e))}collectExcludedFolderNotes(){let t=this.excludedSearchFolders();if(!t.length)return[];let e=this.collectCrossFolderNotes(t),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!t.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===U&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:U,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let r=n.get(a);r||(r=[],n.set(a,r)),r.push(o)}for(let o of i){let a=n.get(o)??[],r=new Map;for(let c of a){let l=this.app.metadataCache.getFileCache(c)?.frontmatter;typeof l?.id=="string"&&r.set(l.id,c)}for(let c of a){let l=this.app.metadataCache.getFileCache(c)?.frontmatter,g=typeof l?.id=="string"?l.id:"";if(!g||g===U)continue;let p=c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),d,I=l?.parent??null;if(I&&I!==U){let u=r.get(I);u&&(d=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:c,folder:o,id:g,title:p,body:"",parentBlurb:d,parentId:I??null})}}return e}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=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===U){i.push(s.id);continue}let o=n.parent??U;await this.changeParent(s,o),e.push(s)}if(e.length===0){new q.Notice(i.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),i.length){let s=e.map(n=>this.tree.get(n)).filter(n=>!!n);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:s,suffix:i.length?`(${i.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e,folder:this.noteFolder})}if(this.plugin.settings.autoNavOnMoveOut&&e.length>0){let s=e[0].parent;s!=null&&e.every(o=>o.parent===s)&&s!==this.focusId&&this.navigateTo(s)}}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(n=>this.colorForNode(n)??"")),i=e.size===1&&Array.from(e)[0]||null,s=this.plugin.settings.customPalette??[];new le(this.app,i,s,async(n,o)=>{let a=[];for(let g of t)if(g.file){a.push({id:g.id,path:g.file.path,was:this.colorForNode(g)??null});try{await this.app.fileManager.processFrontMatter(g.file,p=>{n?p.color=n:delete p.color})}catch(p){new q.Notice(`Couldn't set color for ${g.id}: ${p.message}`)}}if(o.addToPalette&&typeof n=="string"){let g=[...this.plugin.settings.customPalette??[]],p=n.toLowerCase();g.some(d=>d.toLowerCase()===p)||(g.push(n),this.plugin.settings.customPalette=g,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:U,payload:{color:n}}))}this.render();let r=this.noteFolder,c=n,l=async g=>{for(let p of g){let d=this.app.vault.getAbstractFileByPath(p.path);if(d)try{await this.app.fileManager.processFrontMatter(d,I=>{p.col?I.color=p.col:delete I.color})}catch{}}this.tree.rebuild(r),this.render()};this.plugin.getUndoStack(r).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>l(a.map(g=>({path:g.path,col:g.was}))),redo:()=>l(a.map(g=>({path:g.path,col:c})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:U,payload:{color:n}}),o}).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 o=e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,o),this.selection.clear(),this.render();return}let i=e.id,s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&i!==this.focusId&&this.navigateTo(i)},onCreate:async e=>{let i=await this.createNoteUnder(e,this.focusId);if(!i)return;let s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&this.navigateTo(i)},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,showFilterChips:!0}).open()}async moveAcrossFolders(t,e,i){if(!t.length)return;let s=(e||"").replace(/\/+$/,"");if(!s){new q.Notice("Target folder is empty");return}let n=[],o=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(p.path);let a=(p,d)=>{if(!p.file)return;let I=p.file,u=`${s}/${I.name}`;if(o.has(u)){let f=I.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:I.basename,m=f?f[2]:"";for(let E=1;E<1e3;E++){let w=`${C}-${E}${m}.md`,y=`${s}/${w}`;if(!o.has(y)){u=y;break}}}o.add(u),n.push({id:p.id,file:I,oldPath:I.path,newPath:u,oldParent:p.parent,isRoot:d});for(let f of this.tree.getChildren(p.id))a(f,!1)};for(let p of t)a(p,!0);if(!n.length)return;await this.ensureFolder(s);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,d=>{d.parent=i}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?i:p.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(d){new q.Notice(`Move failed for ${p.id}: ${d.message}`)}if(ft().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{ve(this.app,p),ve(this.app,s)},350)}let r=this.titleList(t);this.tree.rebuild(this.noteFolder);let c=i===U?"Open home":"Open parent",l=Math.max(0,n.length-t.length),g=t.length===1?`Moved ${r}${l>0?` and its ${l} nested note${l===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${r}${l>0?` (${l} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:g,kind:"success",category:"move",duration:0,affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:c,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.newPath);if(d)try{await this.app.fileManager.renameFile(d,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.oldPath);if(d)try{await this.app.fileManager.renameFile(d,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=i})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}nextPickableIdx(t,e){for(let i=t+e;i>=0&&i<this.currentChildren.length;i+=e){let s=this.currentChildren[i];if(s&&!this.selection.has(s.id))return i}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 n=this.nextPickableIdx(t,-1);t=n!==t?n:this.nextPickableIdx(t,1)}this.inListPicker={activeIdx:t};let e=ft().bindings.move,i=ei(e.primary||e.secondary||"M");new q.Notice(`Arrows to pick parent, Enter confirms, ${i} for the full picker, Esc cancels.`);let s=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let n=this.listEl;n.scrollTop=s,requestAnimationFrame(()=>{n.scrollTop=s}),setTimeout(()=>{n.scrollTop=s},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(a=>a.id!==t.id),i=new Map(e.map(a=>[a.id,this.tree.getChildren(a.id).length])),s=[];for(let a of e)await this.changeParent(a,t.id,{silentSuccess:!0})&&s.push(a);if(this.notifyBatchMove(s,t.id,i),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 n=this.selectionGuardKey,o=()=>{if(this.selectionGuardKey!==n||this.selection.has(t.id))return;let a=this.currentChildren.findIndex(r=>r.id===t.id);a<0||(this.selection.add(t.id),this.cursorIdx=a,this.render({kind:"follow-cursor"}))};setTimeout(o,120),setTimeout(o,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new q.Notice("Select 2+ notes to merge.");return}t.sort((u,f)=>(u.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],a=[];for(let u of t){if(!u.file)continue;let f=await this.app.vault.cachedRead(u.file);a.push(this.stripFrontmatter(f).trim())}let r=a.map(u=>u.trim()).filter(Boolean).join(` -`),c=await this.app.vault.read(e.file),l=c.startsWith("---")?c.indexOf(` ----`,3)+4:0,p=`${c.slice(0,l)} +`,this.composerDraft=r.value},F=C.createEl("button",{cls:"stashpad-composer-btn"});(0,q.setIcon)(F,"paperclip"),F.title="Attach files",F.onmousedown=T=>T.preventDefault(),F.onclick=T=>{T.preventDefault();let J=document.activeElement===r;if(u.click(),J){let Z=()=>{r.focus()};setTimeout(Z,100),setTimeout(Z,500)}},u.addEventListener("change",async()=>{let T=Array.from(u.files??[]);u.value="";for(let J of T){let Z=await this.importAttachment(J);Z&&y(Z)}r.focus()});let D=f.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,q.setIcon)(D,"chevron-left"),D.title="Show more composer options",f.insertBefore(D,C);let L=T=>{f.toggleClass("is-expanded",T),D.title=T?"Hide options":"Show more composer options",(0,q.setIcon)(D,T?"chevron-right":"chevron-left")};D.onmousedown=T=>T.preventDefault(),D.onclick=T=>{T.preventDefault(),L(!f.hasClass("is-expanded"))},L(!1);let S=()=>o.clientWidth<700,b=()=>{let T=S();o.toggleClass("is-narrow",T),L(!T)};b(),requestAnimationFrame(b);let Q=new ResizeObserver(b);Q.observe(o),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=Q;let H=f.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});H.title="Send (Enter)",(0,q.setIcon)(H,"arrow-up");let $=async()=>{let T=r.value.trim();if(!T)return;r.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(T)}catch{}let J=this.modeSplit??ft().splitOnLines,Z=this.nextDestination,G=this.nextDestinationFolder,N=!!G&&G!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!N,this.scrollToBottomOnNextRender=!N;let _=N?{targetFolder:G}:void 0;if(J)for(let K of T.split(/\r?\n/)){let z=K.trim();z&&await this.createNoteUnder(z,Z,_)}else await this.createNoteUnder(T,Z,_);ft().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,N&&this.composerInputEl?.focus())};H.onclick=()=>void $(),r.addEventListener("keydown",T=>{let J=this.modeEnterSubmits;if(T.key==="Escape"){T.preventDefault(),T.stopPropagation(),r.blur(),this.viewRoot.focus({preventScroll:!0});return}if(T.key==="ArrowUp"&&r.selectionStart===0&&r.selectionEnd===0){if(T.preventDefault(),r.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let Z=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,G=Z?this.currentChildren.findIndex(N=>N.id===Z):-1;this.cursorIdx=G>=0?G:this.currentChildren.length-1,this.selectCursor(!1)}return}T.key==="Enter"&&!T.isComposing&&(J?!T.shiftKey:T.shiftKey)&&(T.preventDefault(),T.stopPropagation(),T.stopImmediatePropagation(),$())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return q.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 i=t?"Enter":"Shift+Enter",s=t?"Shift+Enter":"Enter",n=ft().bindings,o=g=>{let p=n[g];return p.primary&&p.secondary?p.preferRight?p.secondary:p.primary:p.primary||p.secondary},a=ei(o("toggleSplit")),r=ei(o("pickDestination")),l=ei(o("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${r} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===U)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(U),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let a=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(a){let r=this.app.internalPlugins?.plugins?.["global-search"],l=r?.instance?.openGlobalSearch?.bind(r.instance);l&&l(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=t.target,n=s?.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"],g=c?.instance?.openGlobalSearch?.bind(c.instance);g&&g(`tag:#${l}`)}return}let o=s?.closest?.(".internal-link");if(o){t.preventDefault(),t.stopPropagation();let r=o.getAttribute("data-href")||o.getAttribute("href");if(r){let l=i.file?.path||"";this.app.workspace.openLinkText(r,l,!0)}return}if(s?.tagName==="A"&&s.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 r=this.currentChildren.findIndex(l=>l.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),r!==-1){let[l,c]=r<e?[r,e]:[e,r];for(let g=l;g<=c;g++)this.selection.add(this.currentChildren[g].id)}else this.selection.add(i.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(i.id))if(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null),this.lastSelected===i.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let r=this.lastSelected??[...this.selection][this.selection.size-1],l=r?this.currentChildren.findIndex(c=>c.id===r):-1;l>=0&&(this.cursorIdx=l)}else this.cursorIdx=e,a&&(this.firstSelectedId=i.id),this.selection.add(i.id);else this.mobileSelectMode?(this.cursorIdx=e,this.selection.has(i.id)?(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null)):this.selection.add(i.id)):(this.cursorIdx=e,this.selection.clear(),this.selection.add(i.id),this.firstSelectedId=i.id,this.lastSelected=i.id);this.selection.size===0&&(this.firstSelectedId=null),this.selection.has(i.id)&&(this.lastSelected=i.id),this.viewRoot.focus({preventScroll:!0}),this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}revealCursorRow(){let t=()=>{if(this.cursorIdx<0)return;let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let i=this.listEl,s=i.getBoundingClientRect(),n=e.getBoundingClientRect(),o=4,a=s.top+o,r=s.bottom-o;if(q.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let l=this.viewRoot?.querySelector(".stashpad-composer");l&&(r=Math.min(r,l.getBoundingClientRect().top-o))}n.top<a?i.scrollTop+=n.top-a:n.bottom>r&&(i.scrollTop+=n.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 i=this.firstSelectedId??e.id,s=this.currentChildren.findIndex(n=>n.id===i);if(s===-1)this.selection.add(e.id),this.firstSelectedId=e.id;else{let[n,o]=s<this.cursorIdx?[s,this.cursorIdx]:[this.cursorIdx,s];this.selection.clear();for(let a=n;a<=o;a++)this.selection.add(this.currentChildren[a].id);this.firstSelectedId=i}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(s=>{let n=Number(s.dataset.idx),o=s.dataset.id??"",a=n===this.cursorIdx;s.classList.toggle("is-cursor",a),s.classList.toggle("is-selected",this.selection.has(o)),s.classList.toggle("is-cursor-expanded",t&&a),s.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 i=e.getBoundingClientRect(),s=this.listEl.getBoundingClientRect();(i.top<s.top||i.bottom>s.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??ft().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Ot(this.app,this.tree,i=>this.titleForNode(i),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async i=>{if(e=!0,i.crossFolder){let s=i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===U?"Home":(i.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${n} \u25B8 ${o}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=i.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async i=>{e=!0;let s=await this.createNoteUnder(i,this.focusId);s&&(this.nextDestination=s,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,onClose:()=>{t&&!e&&this.composerInputEl?.focus()}}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===U&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:U,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=s=>{if(s===t)return!0;let n=new Set,o=this.tree.get(s);for(;o&&o.id!==U&&!n.has(o.id);){if(n.add(o.id),o.parent===t||o.id===t)return!0;if(!o.parent)return!1;o=this.tree.get(o.parent)}return t===U},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Ot(this.app,i,s=>this.titleForNode(s),{mode:"search",placeholder:`Search in "${this.titleForNode(this.tree.get(t)??this.tree.getRoot()).trim()}"\u2026`,allowCreate:!1,onPick:s=>{s.node&&e(s.node.id)?this.navigateTo(s.node.id):s.node&&this.navigateTo(s.node.id)}}).open()}openSearchModal(){if(this.openSearchInstance){let i=this.openSearchInstance.inputEl;i&&(i.focus(),i.select());return}let t=new Ot(this.app,this.tree,i=>this.titleForNode(i),{mode:"search",placeholder:"Search Stashpad notes\u2026",allowCreate:!0,onCreate:async i=>{let s=i.trim();s&&new Ot(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",placeholder:`Create "${s}" under which note?`,allowCreate:!1,crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(n=>n!==this.noteFolder),localFolder:this.noteFolder,onPick:async n=>{let o=n.crossFolder?n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!o)return;let r=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",l=this.app.workspace,c=l.getLeaf("tab");await c.setViewState({type:dt,active:!0,state:{focusId:o,folderOverride:a===r?null:a}}),l.revealLeaf(c);let g=c.view;if(g&&typeof g.createNoteUnder=="function"){let p=await g.createNoteUnder(s,o);p&&typeof g.navigateTo=="function"&&g.navigateTo(p)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.id.replace(/^cross:/,"");s?this.openNoteInNewTab(i.crossFolder,n):this.switchToFolderAndFocus(i.crossFolder,n);return}i.node&&(s?this.openNoteInNewTab(this.noteFolder,i.node.id):this.navigateTo(i.node.id))},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(i=>i!==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()}excludedSearchFolders(){let t=new Set(this.plugin.searchableFolders(this.noteFolder));return this.plugin.discoverStashpadFolders().filter(e=>e!==this.noteFolder&&!t.has(e))}collectExcludedFolderNotes(){let t=this.excludedSearchFolders();if(!t.length)return[];let e=this.collectCrossFolderNotes(t),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!t.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===U&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:U,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let r=n.get(a);r||(r=[],n.set(a,r)),r.push(o)}for(let o of i){let a=n.get(o)??[],r=new Map;for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter;typeof c?.id=="string"&&r.set(c.id,l)}for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id:"";if(!g||g===U)continue;let p=l.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),d,I=c?.parent??null;if(I&&I!==U){let u=r.get(I);u&&(d=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:l,folder:o,id:g,title:p,body:"",parentBlurb:d,parentId:I??null})}}return e}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=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===U){i.push(s.id);continue}let o=n.parent??U;await this.changeParent(s,o),e.push(s)}if(e.length===0){new q.Notice(i.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),i.length){let s=e.map(n=>this.tree.get(n)).filter(n=>!!n);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:s,suffix:i.length?`(${i.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e,folder:this.noteFolder})}if(this.plugin.settings.autoNavOnMoveOut&&e.length>0){let s=e[0].parent;s!=null&&e.every(o=>o.parent===s)&&s!==this.focusId&&this.navigateTo(s)}}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(n=>this.colorForNode(n)??"")),i=e.size===1&&Array.from(e)[0]||null,s=this.plugin.settings.customPalette??[];new ce(this.app,i,s,async(n,o)=>{let a=[];for(let g of t)if(g.file){a.push({id:g.id,path:g.file.path,was:this.colorForNode(g)??null});try{await this.app.fileManager.processFrontMatter(g.file,p=>{n?p.color=n:delete p.color})}catch(p){new q.Notice(`Couldn't set color for ${g.id}: ${p.message}`)}}if(o.addToPalette&&typeof n=="string"){let g=[...this.plugin.settings.customPalette??[]],p=n.toLowerCase();g.some(d=>d.toLowerCase()===p)||(g.push(n),this.plugin.settings.customPalette=g,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:U,payload:{color:n}}))}this.render();let r=this.noteFolder,l=n,c=async g=>{for(let p of g){let d=this.app.vault.getAbstractFileByPath(p.path);if(d)try{await this.app.fileManager.processFrontMatter(d,I=>{p.col?I.color=p.col:delete I.color})}catch{}}this.tree.rebuild(r),this.render()};this.plugin.getUndoStack(r).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>c(a.map(g=>({path:g.path,col:g.was}))),redo:()=>c(a.map(g=>({path:g.path,col:l})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:U,payload:{color:n}}),o}).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 o=e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,o),this.selection.clear(),this.render();return}let i=e.id,s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&i!==this.focusId&&this.navigateTo(i)},onCreate:async e=>{let i=await this.createNoteUnder(e,this.focusId);if(!i)return;let s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&this.navigateTo(i)},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,showFilterChips:!0}).open()}async moveAcrossFolders(t,e,i){if(!t.length)return;let s=(e||"").replace(/\/+$/,"");if(!s){new q.Notice("Target folder is empty");return}let n=[],o=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(p.path);let a=(p,d)=>{if(!p.file)return;let I=p.file,u=`${s}/${I.name}`;if(o.has(u)){let f=I.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:I.basename,m=f?f[2]:"";for(let E=1;E<1e3;E++){let w=`${C}-${E}${m}.md`,y=`${s}/${w}`;if(!o.has(y)){u=y;break}}}o.add(u),n.push({id:p.id,file:I,oldPath:I.path,newPath:u,oldParent:p.parent,isRoot:d});for(let f of this.tree.getChildren(p.id))a(f,!1)};for(let p of t)a(p,!0);if(!n.length)return;await this.ensureFolder(s);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,d=>{d.parent=i}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?i:p.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(d){new q.Notice(`Move failed for ${p.id}: ${d.message}`)}if(ft().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{ve(this.app,p),ve(this.app,s)},350)}let r=this.titleList(t);this.tree.rebuild(this.noteFolder);let l=i===U?"Open home":"Open parent",c=Math.max(0,n.length-t.length),g=t.length===1?`Moved ${r}${c>0?` and its ${c} nested note${c===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${r}${c>0?` (${c} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:g,kind:"success",category:"move",duration:0,affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:l,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.newPath);if(d)try{await this.app.fileManager.renameFile(d,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.oldPath);if(d)try{await this.app.fileManager.renameFile(d,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=i})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}nextPickableIdx(t,e){for(let i=t+e;i>=0&&i<this.currentChildren.length;i+=e){let s=this.currentChildren[i];if(s&&!this.selection.has(s.id))return i}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 n=this.nextPickableIdx(t,-1);t=n!==t?n:this.nextPickableIdx(t,1)}this.inListPicker={activeIdx:t};let e=ft().bindings.move,i=ei(e.primary||e.secondary||"M");new q.Notice(`Arrows to pick parent, Enter confirms, ${i} for the full picker, Esc cancels.`);let s=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let n=this.listEl;n.scrollTop=s,requestAnimationFrame(()=>{n.scrollTop=s}),setTimeout(()=>{n.scrollTop=s},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(a=>a.id!==t.id),i=new Map(e.map(a=>[a.id,this.tree.getChildren(a.id).length])),s=[];for(let a of e)await this.changeParent(a,t.id,{silentSuccess:!0})&&s.push(a);if(this.notifyBatchMove(s,t.id,i),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 n=this.selectionGuardKey,o=()=>{if(this.selectionGuardKey!==n||this.selection.has(t.id))return;let a=this.currentChildren.findIndex(r=>r.id===t.id);a<0||(this.selection.add(t.id),this.cursorIdx=a,this.render({kind:"follow-cursor"}))};setTimeout(o,120),setTimeout(o,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new q.Notice("Select 2+ notes to merge.");return}t.sort((u,f)=>(u.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],a=[];for(let u of t){if(!u.file)continue;let f=await this.app.vault.cachedRead(u.file);a.push(this.stripFrontmatter(f).trim())}let r=a.map(u=>u.trim()).filter(Boolean).join(` +`),l=await this.app.vault.read(e.file),c=l.startsWith("---")?l.indexOf(` +---`,3)+4:0,p=`${l.slice(0,c)} ${r} -`;await this.app.vault.modify(e.file,p);for(let u=1;u<t.length;u++){let f=t[u];if(f.file){for(let C of this.tree.getChildren(f.id))C.file&&o.push({childId:C.id,childPath:C.file.path,oldParent:C.parent}),await this.changeParent(C,e.id,{record:!1});await this.app.fileManager.trashFile(f.file),await this.log.append({type:"delete",id:f.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(u=>u.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let u=e.id,f=this.selectionGuardKey,C=()=>{if(this.selectionGuardKey!==f||this.selection.has(u))return;let m=this.currentChildren.findIndex(E=>E.id===u);m<0||(this.selection.add(u),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let I=this.noteFolder;this.plugin.getUndoStack(I).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(f=>f.id));let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,s);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=f.oldParent})}this.pendingFocusIds=t.map(f=>f.id),this.tree.rebuild(I),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,p);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=e.id})}this.tree.rebuild(I),this.render()}})}cmdCopy(){return Sn(this)}cmdCopyCodeBlock(){return Dn(this)}cmdCopyTree(){return bn(this)}cmdCopyOutline(){return Nn(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.expandedNotes.has(i.id));for(let i of t)e?this.expandedNotes.add(i.id):this.expandedNotes.delete(i.id);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new q.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let s=this.tree.getChildren(t.id).slice(),n=t.file,o=await this.app.vault.read(n),a=this.stripFrontmatter(o),r=this.app.metadataCache.getFileCache(n)?.frontmatter??{},c=yt(),l=Dt(a,this.activeStopwords()),g=bt(l,c),p=`${this.noteFolder}/${g}`,d=new Date().toISOString(),I=this.extractAttachments(a),u=["---",`id: ${c}`,`parent: ${e}`,`created: ${d}`];if(I.length>0){u.push("attachments:");for(let C of I)u.push(` - "${C.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(p,u.join(` -`)),i.push(p);let f=this.app.vault.getAbstractFileByPath(p);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,E]of Object.entries(r))Wt.includes(m)||(C[m]=E)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:c,parent:e,children:[],file:f,created:d})}catch{}this.fmSync.scheduleParentChange(c,null,e)}for(let C of s)await this.cloneSubtree(C,c,i);return c}async cmdClone(){let t=this.getActionTargets();if(!t.length){new q.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let r of t){if(!r.file)continue;let c=r.parent??this.focusId,l=await this.cloneSubtree(r,c,i);l&&s.push(l)}if(!s.length)return;this.tree.rebuild(e),this.pendingFocusIds=s.slice(),this.render();let n=i.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:Be(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),o=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(e).push({label:`Clone ${s.length} note${s.length===1?"":"s"}`,undo:async()=>{for(let r of[...i].reverse()){let c=this.app.vault.getAbstractFileByPath(r);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:a,suffix:`(${i.length} file${i.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:s,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 q.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 i=this.noteFolder,s=[],n=await this.cloneSubtree(e,this.focusId,s);if(!n)return;this.tree.rebuild(i),this.pendingFocusIds=[n],this.render();let o=s.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:Be(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let r of[...s].reverse()){let c=this.app.vault.getAbstractFileByPath(r);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.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 i=this.lastCursorByFocus.get(t),s;i&&this.tree.get(i)?(this.pendingFocusIds=[i],s={kind:"scroll-to-id",id:i,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==U&&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),i;e&&this.tree.get(e)?(this.pendingFocusIds=[e],i={kind:"scroll-to-id",id:e,align:"start"}):i={kind:"preserve"},this.render(i),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(U)}let e=this.focusId;if(this.recordNavState(),this.listEl){let o=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;o&&this.plugin.saveLastCursor(this.noteFolder,e,o)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let i=this.filterChildren(this.tree.getChildren(this.focusId)),s=i.findIndex(n=>n.id===e);this.selection.clear(),s>=0?(this.cursorIdx=s,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=i.length-1,i.length>0&&(this.selection.add(i[i.length-1].id),this.lastSelected=i[i.length-1].id)),s>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),s<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),i=new q.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(o))),s++)}s||i.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),i.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=[U],e=this.tree.getRoot(),i=s=>{for(let n of this.tree.getChildren(s))t.push(n.id),i(n.id)};for(let s of e.children)i(s);for(let s of t)this.fmSync.wouldWrite(s)&&this.fmSync.schedule(s)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata +`;await this.app.vault.modify(e.file,p);for(let u=1;u<t.length;u++){let f=t[u];if(f.file){for(let C of this.tree.getChildren(f.id))C.file&&o.push({childId:C.id,childPath:C.file.path,oldParent:C.parent}),await this.changeParent(C,e.id,{record:!1});await this.app.fileManager.trashFile(f.file),await this.log.append({type:"delete",id:f.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(u=>u.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let u=e.id,f=this.selectionGuardKey,C=()=>{if(this.selectionGuardKey!==f||this.selection.has(u))return;let m=this.currentChildren.findIndex(E=>E.id===u);m<0||(this.selection.add(u),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let I=this.noteFolder;this.plugin.getUndoStack(I).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(f=>f.id));let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,s);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=f.oldParent})}this.pendingFocusIds=t.map(f=>f.id),this.tree.rebuild(I),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,p);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=e.id})}this.tree.rebuild(I),this.render()}})}cmdCopy(){return Sn(this)}cmdCopyCodeBlock(){return Dn(this)}cmdCopyTree(){return bn(this)}cmdCopyOutline(){return Nn(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.expandedNotes.has(i.id));for(let i of t)e?this.expandedNotes.add(i.id):this.expandedNotes.delete(i.id);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new q.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let s=this.tree.getChildren(t.id).slice(),n=t.file,o=await this.app.vault.read(n),a=this.stripFrontmatter(o),r=this.app.metadataCache.getFileCache(n)?.frontmatter??{},l=yt(),c=Dt(a,this.activeStopwords()),g=bt(c,l),p=`${this.noteFolder}/${g}`,d=new Date().toISOString(),I=this.extractAttachments(a),u=["---",`id: ${l}`,`parent: ${e}`,`created: ${d}`];if(I.length>0){u.push("attachments:");for(let C of I)u.push(` - "${C.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(p,u.join(` +`)),i.push(p);let f=this.app.vault.getAbstractFileByPath(p);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,E]of Object.entries(r))Wt.includes(m)||(C[m]=E)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:f,created:d})}catch{}this.fmSync.scheduleParentChange(l,null,e)}for(let C of s)await this.cloneSubtree(C,l,i);return l}async cmdClone(){let t=this.getActionTargets();if(!t.length){new q.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let r of t){if(!r.file)continue;let l=r.parent??this.focusId,c=await this.cloneSubtree(r,l,i);c&&s.push(c)}if(!s.length)return;this.tree.rebuild(e),this.pendingFocusIds=s.slice(),this.render();let n=i.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:Be(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),o=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(e).push({label:`Clone ${s.length} note${s.length===1?"":"s"}`,undo:async()=>{for(let r of[...i].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:a,suffix:`(${i.length} file${i.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:s,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 q.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 i=this.noteFolder,s=[],n=await this.cloneSubtree(e,this.focusId,s);if(!n)return;this.tree.rebuild(i),this.pendingFocusIds=[n],this.render();let o=s.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:Be(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let r of[...s].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.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 i=this.lastCursorByFocus.get(t),s;i&&this.tree.get(i)?(this.pendingFocusIds=[i],s={kind:"scroll-to-id",id:i,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==U&&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),i;e&&this.tree.get(e)?(this.pendingFocusIds=[e],i={kind:"scroll-to-id",id:e,align:"start"}):i={kind:"preserve"},this.render(i),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(U)}let e=this.focusId;if(this.recordNavState(),this.listEl){let o=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;o&&this.plugin.saveLastCursor(this.noteFolder,e,o)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let i=this.filterChildren(this.tree.getChildren(this.focusId)),s=i.findIndex(n=>n.id===e);this.selection.clear(),s>=0?(this.cursorIdx=s,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=i.length-1,i.length>0&&(this.selection.add(i[i.length-1].id),this.lastSelected=i[i.length-1].id)),s>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),s<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),i=new q.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(o))),s++)}s||i.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),i.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=[U],e=this.tree.getRoot(),i=s=>{for(let n of this.tree.getChildren(s))t.push(n.id),i(n.id)};for(let s of e.children)i(s);for(let s of t)this.fmSync.wouldWrite(s)&&this.fmSync.schedule(s)}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)}`,i=this.app.vault.getMarkdownFiles().filter(o=>o.path.startsWith(t+"/"));for(let o of i){if(this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==U)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let c=this.app.vault.getAbstractFileByPath(e);if(c instanceof q.TFile)return c}catch(c){console.warn("[Stashpad] home note rename failed; keeping legacy path",c)}return o}let s=new Date().toISOString(),n=["---",`id: ${U}`,"parent: null",`created: ${s}`,"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(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===U)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=U}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:U,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:dt,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let r=!1;return e.iterateAllLeaves(c=>{c===s&&(r=!0)}),r})())return;e.offref(n),(()=>{let r=!1;return e.iterateAllLeaves(c=>{c===i&&(r=!0)}),r})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))})}async openNoteInNewTab(t,e){let i=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!i||!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",n=this.app.workspace,o=n.getLeaf("tab");await o.setViewState({type:dt,active:!0,state:{focusId:e,folderOverride:i===s?null:i}}),n.setActiveLeaf(o,{focus:!0}),n.revealLeaf(o)}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let i=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",s=this.app.workspace,n=this.leaf,o=s.getLeaf("tab");await o.setViewState({type:dt,active:!0,state:{focusId:U,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let l=!1;return s.iterateAllLeaves(g=>{g===o&&(l=!0)}),l})())return;s.offref(a),(()=>{let l=!1;return s.iterateAllLeaves(g=>{g===n&&(l=!0)}),l})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new q.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.openFile(t,{active:!0}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let l=!1;return e.iterateAllLeaves(g=>{g===s&&(l=!0)}),l})())return;e.offref(n),(()=>{let l=!1;return e.iterateAllLeaves(g=>{g===i&&(l=!0)}),l})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))}),a=s.view?.editor;a&&requestAnimationFrame(()=>{try{let r=a.lastLine(),c=a.getLine(r)?.length??0;a.setCursor({line:r,ch:c}),a.scrollIntoView({from:{line:r,ch:c},to:{line:r,ch:c}},!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 q.Notice("Nothing to pin.");return}let e=t.some(n=>!this.plugin.isPinned({folder:this.noteFolder,id:n.id})),i=0,s=0;for(let n of t){let o={folder:this.noteFolder,id:n.id};e?this.plugin.isPinned(o)||(await this.plugin.pinNote(o),i++):this.plugin.isPinned(o)&&(await this.plugin.unpinNote(o),s++)}i>0?new q.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new q.Notice(`Unpinned ${s} note${s===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 q.Notice("Nothing to toggle.");return}let i=t.some(a=>!this.isCompleted(a)),s=[],n=[];for(let a of t){if(!a.file)continue;let r=this.isCompleted(a);s.push({id:a.id,path:a.file.path,was:r}),r!==i&&(await this.app.fileManager.processFrontMatter(a.file,c=>{i?c.completed=!0:delete c.completed}),this.completedState.set(a.file.path,i),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:i?"Marked complete":"Unmarked",nodes:a}),kind:"success",category:i?"complete":"uncomplete",affectedIds:n,folder:this.noteFolder})}let o=this.noteFolder;this.plugin.getUndoStack(o).push({label:`${i?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let r of s){let c=this.app.vault.getAbstractFileByPath(r.path);c&&(await this.app.fileManager.processFrontMatter(c,l=>{r.was?l.completed=!0:delete l.completed}),n.includes(r.id)&&a.push(r.id))}a.length>0&&await this.log.append({type:i?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(o),this.render()},redo:async()=>{for(let a of s){let r=this.app.vault.getAbstractFileByPath(a.path);r&&await this.app.fileManager.processFrontMatter(r,c=>{i?c.completed=!0:delete c.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),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}taggedFromFm(t){return t?Ie(t,"task")||t.task===!0:!1}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 q.Notice("Nothing to schedule.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=i&&(typeof i.due=="string"||typeof i.due=="number")?String(i.due):null,n=this.plugin.authorRegistry.all().map(a=>({id:a.id,name:a.name})),o=Re(i??{});new Ye(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let c of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,c.id,c.name);let a=i.map(c=>this.plugin.authorRefFor(this.noteFolder,c.id,c.name));for(let c of t){if(!c.file)continue;let l=this.app.metadataCache.getFileCache(c.file)?.frontmatter,g=this.isTaskTagged(c);s.push({id:c.id,path:c.file.path,due:l?.due,task:l?.task,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,wasTagged:g}),await this.app.fileManager.processFrontMatter(c.file,d=>{e===null?delete d.due:(d.due=e,d.task=!0),a.length>0?(d.assignedTo=a,o&&(d.assignedBy=o.link),d.task=!0):(delete d.assignedTo,delete d.assignedBy)});let p=e!==null||a.length>0;this.taskTaggedState.set(c.file.path,p||g),n.push(c.id)}if(this.render(),n.length>0){let c=n.map(l=>this.tree.get(l)).filter(l=>!!l);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${re(Date.parse(e),this.plugin.settings)}`,nodes:c}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let r=this.noteFolder;this.plugin.getUndoStack(r).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let c of s){let l=this.app.vault.getAbstractFileByPath(c.path);l&&(await this.app.fileManager.processFrontMatter(l,g=>{c.due===void 0?delete g.due:g.due=c.due,c.task===void 0?delete g.task:g.task=c.task,c.assignedTo===void 0?delete g.assignedTo:g.assignedTo=c.assignedTo,c.assignedBy===void 0?delete g.assignedBy:g.assignedBy=c.assignedBy}),this.taskTaggedState.set(c.path,c.wasTagged))}this.tree.rebuild(r),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new q.Notice("Nothing to assign.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=this.plugin.authorRegistry.all().map(o=>({id:o.id,name:o.name})),n=Re(i??{});new Ke(this.app,{knownAuthors:s,currentAssignees:n},o=>{this.applyAssignees(t,o)}).open()}async applyAssignees(t,e){let i=this.authorship.currentAuthorLink();for(let r of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,r.id,r.name);let s=e.map(r=>this.plugin.authorRefFor(this.noteFolder,r.id,r.name)),n=[],o=[];for(let r of t){if(!r.file)continue;let c=this.app.metadataCache.getFileCache(r.file)?.frontmatter,l=this.isTaskTagged(r);n.push({path:r.file.path,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy,task:c?.task,wasTagged:l}),await this.app.fileManager.processFrontMatter(r.file,g=>{s.length>0?(g.assignedTo=s,i&&(g.assignedBy=i.link),g.task=!0):(delete g.assignedTo,delete g.assignedBy)}),this.taskTaggedState.set(r.file.path,s.length>0||l),o.push(r.id)}if(this.render(),o.length>0){let r=o.map(l=>this.tree.get(l)).filter(l=>!!l),c=e.map(l=>l.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:s.length>0?`Assigned to ${c}`:"Cleared assignment",nodes:r}),kind:"success",category:"edit",affectedIds:o,folder:this.noteFolder})}let a=this.noteFolder;this.plugin.getUndoStack(a).push({label:s.length>0?`Assign (${t.length})`:`Clear assignment (${t.length})`,undo:async()=>{for(let r of n){let c=this.app.vault.getAbstractFileByPath(r.path);c&&(await this.app.fileManager.processFrontMatter(c,l=>{r.assignedTo===void 0?delete l.assignedTo:l.assignedTo=r.assignedTo,r.assignedBy===void 0?delete l.assignedBy:l.assignedBy=r.assignedBy,r.task===void 0?delete l.task:l.task=r.task}),this.taskTaggedState.set(r.path,r.wasTagged))}this.tree.rebuild(a),this.render()}})}isTask(t){return t.file?this.isTaskTagged(t)?!0:this.app.metadataCache.getFileCache(t.file)?.frontmatter?.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 q.Notice("Nothing to toggle.");return}let e=t.some(a=>!this.isTaskTagged(a)),i=[],s=[];for(let a of t){if(!a.file)continue;let r=this.isTaskTagged(a),c=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:c?.tags,completed:c?.completed,task:c?.task,wasTagged:r}),r===e)continue;let l=!1;await this.app.fileManager.processFrontMatter(a.file,g=>{e?(as(g,"task"),g.completed===void 0&&(g.completed=!1),l=g.completed===!0,delete g.task):(rs(g,"task"),delete g.completed,delete g.task,l=!1)}),this.completedState.set(a.file.path,l),this.taskTaggedState.set(a.file.path,e),s.push(a.id)}if(this.render(),s.length>0){let a=e?"marked as task":"unmarked as task",r;if(s.length===1){let c=this.tree.get(s[0]);r=`"${c&&this.titleForNode(c).trim()||"(untitled)"}" ${a}`}else r=`${s.length} notes ${a}`;this.plugin.notifications.show({message:r,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);r&&(await this.app.fileManager.processFrontMatter(r,c=>{a.tags===void 0?delete c.tags:c.tags=a.tags,a.completed===void 0?delete c.completed:c.completed=a.completed,a.task===void 0?delete c.task:c.task=a.task}),this.completedState.set(a.path,!!a.completed),this.taskTaggedState.set(a.path,a.wasTagged))}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:o,redo:async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);if(!r)continue;let c=!1;await this.app.fileManager.processFrontMatter(r,l=>{e?(as(l,"task"),l.completed===void 0&&(l.completed=!1),c=l.completed===!0,delete l.task):(rs(l,"task"),delete l.completed,delete l.task,c=!1)}),this.completedState.set(a.path,c),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==U&&!s.has(e.id);){s.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:i};e=e.parent?this.tree.get(e.parent):void 0,i+=1}return null}isDescendant(t,e){let i=this.tree.get(t),s=new Set;for(;i&&i.parent&&!s.has(i.id);){if(i.parent===e)return!0;s.add(i.id),i=this.tree.get(i.parent)}return!1}async moveAcrossThenReorder(t,e,i,s){let n=[],o=new Set;for(let D of t){let L=this.tree.get(D);L?.file&&(n.push({id:D,path:L.file.path,oldParent:L.parent}),o.add(L.parent??U))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(D=>this.tree.get(D)).filter(D=>!!D)),r=this.noteFolder,c={};for(let D of o)c[D]=this.order.getOrder(r,D).slice();for(let D of n){let L=this.app.vault.getAbstractFileByPath(D.path);L&&(await this.app.fileManager.processFrontMatter(L,S=>{S.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(r,D.id))}this.tree.rebuild(r);let l=this.tree.getChildren(e).map(D=>D.id),g=new Set(t),p=l.filter(D=>!g.has(D)),d=p.indexOf(i);d<0&&(d=p.length),s==="after"&&(d+=1);let I=[...p.slice(0,d),...t.filter(D=>!!this.tree.get(D)),...p.slice(d)];this.order.setOrder(r,e,I),await this.order.save(r),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}});let u=this.focusId===e,f=u?t[0]:e,C=u?t.slice():[e];u?this.pendingFocusIds=C:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=C),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let m=this.selectionGuardKey,E=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let D=this.currentChildren.findIndex(L=>L.id===f);D<0||(this.selection.add(f),this.cursorIdx=D,this.render({kind:"follow-cursor"}))};setTimeout(E,120),setTimeout(E,400);let w=t.map(D=>this.tree.get(D)).filter(D=>!!D),y=this.tree.get(e),F=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${F}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:r,actions:e===U?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(r).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let D of n){let L=this.app.vault.getAbstractFileByPath(D.path);L&&(await this.app.fileManager.processFrontMatter(L,S=>{D.oldParent===null||D.oldParent===void 0?S.parent=U:S.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,L]of Object.entries(c))if(L.length===0){let S=this.order.cache.get(r)??{};delete S[D],this.order.cache.set(r,S)}else this.order.setOrder(r,D,L);await this.order.save(r),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(r),this.render()},redo:async()=>{for(let D of n){let L=this.app.vault.getAbstractFileByPath(D.path);L&&(await this.app.fileManager.processFrontMatter(L,S=>{S.parent=e}),this.order.removeChild(r,D.id))}this.order.setOrder(r,e,I),await this.order.save(r),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(r),this.render()}})}async reorderToTarget(t,e,i){let s=this.tree.get(e);if(!s)return;let n=t.map(m=>this.tree.get(m)).filter(m=>!!m&&!!m.file);if(n.length===0)return;if(n.some(m=>m.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(i==="into"){for(let m of n)if(this.isDescendant(e,m.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(m)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let o=i==="into"?e:s.parent??U;if(n.some(m=>(m.parent??U)!==o)){let m=ft(),E=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(m.confirmCrossParentDrag){let w=this.titleForNode(s),y=n.length,F=i==="into"?"Nest":"Move",D=i==="into"?"as children of":"under";new vt(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${F} ${y} note${y===1?"":"s"} ${D} "${w}"? Their parent will change.`,F,L=>{L&&E()}).open()}else await E();return}let r=o,c=n.map(m=>m.id),l=this.tree.getChildren(r).map(m=>m.id),g=new Set(c),p=l.filter(m=>!g.has(m)),d=p.indexOf(e);if(d<0)return;i==="after"&&(d+=1);let I=[...p.slice(0,d),...c,...p.slice(d)];if(Fs(I,l))return;let u=this.noteFolder,f=this.order.getOrder(u,r).slice();this.order.setOrder(u,r,I),await this.order.save(u),await this.forceManualMode(r),await this.log.append({type:"reorder",id:r,payload:{dir:"drag",parent:r,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(u),this.render();let C=c.map(m=>this.tree.get(m)).filter(m=>!!m);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:C}),kind:"success",category:"reorder",affectedIds:c,folder:u}),this.plugin.getUndoStack(u).push({label:`Reorder (drag, ${c.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(u)??{};delete m[r],this.order.cache.set(u,m)}else this.order.setOrder(u,r,f);await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"undo",parent:r,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(u),this.render()},redo:async()=>{this.order.setOrder(u,r,I),await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"redo:drag",parent:r,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(u),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 g=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(g.length===0)return;if(new Set(g.map(d=>d.parent)).size>1){new q.Notice("Reorder requires a single-parent selection.");return}e=g}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new q.Notice("Nothing to reorder.");return}let i=e[0].parent??U,s=this.tree.getChildren(i).map(g=>g.id);if(s.length===0)return;let n=new Set(e.map(g=>g.id)),o=s.filter(g=>n.has(g));if(o.length===0)return;let a=kn(s,o,t);if(Fs(a,s))return;let r=this.noteFolder,c=this.order.getOrder(r,i).slice();this.order.setOrder(r,i,a),await this.order.save(r),await this.forceManualMode(i),await this.log.append({type:"reorder",id:i,payload:{dir:t,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let l=o.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:l,destination:t}),kind:"success",category:"reorder",affectedIds:o,folder:r}),this.plugin.getUndoStack(r).push({label:`Reorder (${t})`,undo:async()=>{if(c.length===0){let g=this.order.cache.get(r)??{};delete g[i],this.order.cache.set(r,g)}else this.order.setOrder(r,i,c);await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:"undo",parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()},redo:async()=>{this.order.setOrder(r,i,a),await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:`redo:${t}`,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let I=this.tree.get(this.focusId);I?.file&&(t=[I])}if(t.length===0){new q.Notice("Nothing selected to delete.");return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],i=new Set,s=I=>{if(!i.has(I.id)){i.add(I.id);for(let u of this.tree.getChildren(I.id))s(u);e.push(I)}};for(let I of t)s(I);let n=e.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.read(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(ae(C))}let r=[...new Set(a)],c=e.length-t.length,l=async I=>{let u=await this.snapshotNotes(e,I),f=0;if(I)for(let H of r){let $=this.app.metadataCache.getFirstLinkpathDest(H,"");if($)try{await this.app.fileManager.trashFile($),await this.log.append({type:"attachment_remove",id:U,payload:{path:$.path}}),this.plugin.notifications.show({message:`Deleted attachment "${$.name}"`,kind:"warning",category:"attachment",affectedPaths:[$.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let H of e)H.parent&&C.add(H.parent);let m=this.authorship.collectAuthorIds(e),E=new Set(t.map(H=>H.id)),w=this.currentChildren.map((H,$)=>E.has(H.id)?$:-1).filter(H=>H>=0),y=w.length>0?w[0]:-1,F=null;if(y>=0){for(let H=y+1;H<this.currentChildren.length;H++)if(!E.has(this.currentChildren[H].id)){F=this.currentChildren[H].id;break}if(!F){for(let H=y-1;H>=0;H--)if(!E.has(this.currentChildren[H].id)){F=this.currentChildren[H].id;break}}}for(let H of e)if(H.file){try{await this.app.fileManager.trashFile(H.file)}catch{}await this.log.append({type:"delete",id:H.id,payload:{path:H.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,F&&(this.pendingFocusIds=[F]),this.tree.rebuild(this.noteFolder);for(let H of C)e.some($=>$.id===H)||this.fmSync.scheduleParentOfDeleted(H);this.render({kind:"follow-cursor"});let D=f>0?` with ${f} attachment${f===1?"":"s"}`:"",L=this.noteFolder,S=t.map(H=>H.id),b=!1,Q=async()=>{b||(b=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,S.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(H=>H.id),affectedAuthorIds:m,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void Q()}]}),this.plugin.getUndoStack(L).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await Q()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,b=!1,await this.trashNotesAndAttachments(u)}}),this.focusView()},g=ft(),p=g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await l(!1);return}new Ce(this.app,`${t.length} selected note${t.length===1?"":"s"}`,c,r.length,d,l).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new q.Notice("Pick a note to split.");return}let i=e.file,s=await this.app.vault.read(i),n=this.stripFrontmatter(s).replace(/\s+$/,""),o=n.split(/\r?\n/);if(n.trim().length<2){new q.Notice("Note is too short to split.");return}let a=s,r=i.path,c=async(l,g,p)=>{if(!l.trim()||!g.trim()){new q.Notice("Split would leave one part empty.");return}try{let d=s.startsWith("---")?s.slice(0,s.indexOf(` +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)}`,i=this.app.vault.getMarkdownFiles().filter(o=>o.path.startsWith(t+"/"));for(let o of i){if(this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==U)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let l=this.app.vault.getAbstractFileByPath(e);if(l instanceof q.TFile)return l}catch(l){console.warn("[Stashpad] home note rename failed; keeping legacy path",l)}return o}let s=new Date().toISOString(),n=["---",`id: ${U}`,"parent: null",`created: ${s}`,"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(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===U)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=U}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:U,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:dt,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let r=!1;return e.iterateAllLeaves(l=>{l===s&&(r=!0)}),r})())return;e.offref(n),(()=>{let r=!1;return e.iterateAllLeaves(l=>{l===i&&(r=!0)}),r})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))})}async openNoteInNewTab(t,e){let i=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!i||!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",n=this.app.workspace,o=n.getLeaf("tab");await o.setViewState({type:dt,active:!0,state:{focusId:e,folderOverride:i===s?null:i}}),n.setActiveLeaf(o,{focus:!0}),n.revealLeaf(o)}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let i=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",s=this.app.workspace,n=this.leaf,o=s.getLeaf("tab");await o.setViewState({type:dt,active:!0,state:{focusId:U,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let c=!1;return s.iterateAllLeaves(g=>{g===o&&(c=!0)}),c})())return;s.offref(a),(()=>{let c=!1;return s.iterateAllLeaves(g=>{g===n&&(c=!0)}),c})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new q.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.openFile(t,{active:!0}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let c=!1;return e.iterateAllLeaves(g=>{g===s&&(c=!0)}),c})())return;e.offref(n),(()=>{let c=!1;return e.iterateAllLeaves(g=>{g===i&&(c=!0)}),c})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))}),a=s.view?.editor;a&&requestAnimationFrame(()=>{try{let r=a.lastLine(),l=a.getLine(r)?.length??0;a.setCursor({line:r,ch:l}),a.scrollIntoView({from:{line:r,ch:l},to:{line:r,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 q.Notice("Nothing to pin.");return}let e=t.some(n=>!this.plugin.isPinned({folder:this.noteFolder,id:n.id})),i=0,s=0;for(let n of t){let o={folder:this.noteFolder,id:n.id};e?this.plugin.isPinned(o)||(await this.plugin.pinNote(o),i++):this.plugin.isPinned(o)&&(await this.plugin.unpinNote(o),s++)}i>0?new q.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new q.Notice(`Unpinned ${s} note${s===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 q.Notice("Nothing to toggle.");return}let i=t.some(a=>!this.isCompleted(a)),s=[],n=[];for(let a of t){if(!a.file)continue;let r=this.isCompleted(a);s.push({id:a.id,path:a.file.path,was:r}),r!==i&&(await this.app.fileManager.processFrontMatter(a.file,l=>{i?l.completed=!0:delete l.completed}),this.completedState.set(a.file.path,i),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:i?"Marked complete":"Unmarked",nodes:a}),kind:"success",category:i?"complete":"uncomplete",affectedIds:n,folder:this.noteFolder})}let o=this.noteFolder;this.plugin.getUndoStack(o).push({label:`${i?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let r of s){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.was?c.completed=!0:delete c.completed}),n.includes(r.id)&&a.push(r.id))}a.length>0&&await this.log.append({type:i?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(o),this.render()},redo:async()=>{for(let a of s){let r=this.app.vault.getAbstractFileByPath(a.path);r&&await this.app.fileManager.processFrontMatter(r,l=>{i?l.completed=!0:delete l.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),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}taggedFromFm(t){return t?Ie(t,"task")||t.task===!0:!1}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 q.Notice("Nothing to schedule.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=i&&(typeof i.due=="string"||typeof i.due=="number")?String(i.due):null,n=this.plugin.authorRegistry.all().map(a=>({id:a.id,name:a.name})),o=Re(i??{});new Ye(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let l of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,l.id,l.name);let a=i.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,g=this.isTaskTagged(l);s.push({id:l.id,path:l.file.path,due:c?.due,task:c?.task,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy,wasTagged:g}),await this.app.fileManager.processFrontMatter(l.file,d=>{e===null?delete d.due:(d.due=e,d.task=!0),a.length>0?(d.assignedTo=a,o&&(d.assignedBy=o.link),d.task=!0):(delete d.assignedTo,delete d.assignedBy)});let p=e!==null||a.length>0;this.taskTaggedState.set(l.file.path,p||g),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 ${re(Date.parse(e),this.plugin.settings)}`,nodes:l}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let r=this.noteFolder;this.plugin.getUndoStack(r).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let l of s){let c=this.app.vault.getAbstractFileByPath(l.path);c&&(await this.app.fileManager.processFrontMatter(c,g=>{l.due===void 0?delete g.due:g.due=l.due,l.task===void 0?delete g.task:g.task=l.task,l.assignedTo===void 0?delete g.assignedTo:g.assignedTo=l.assignedTo,l.assignedBy===void 0?delete g.assignedBy:g.assignedBy=l.assignedBy}),this.taskTaggedState.set(l.path,l.wasTagged))}this.tree.rebuild(r),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new q.Notice("Nothing to assign.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=this.plugin.authorRegistry.all().map(o=>({id:o.id,name:o.name})),n=Re(i??{});new Ke(this.app,{knownAuthors:s,currentAssignees:n},o=>{this.applyAssignees(t,o)}).open()}async applyAssignees(t,e){let i=this.authorship.currentAuthorLink();for(let r of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,r.id,r.name);let s=e.map(r=>this.plugin.authorRefFor(this.noteFolder,r.id,r.name)),n=[],o=[];for(let r of t){if(!r.file)continue;let l=this.app.metadataCache.getFileCache(r.file)?.frontmatter,c=this.isTaskTagged(r);n.push({path:r.file.path,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,task:l?.task,wasTagged:c}),await this.app.fileManager.processFrontMatter(r.file,g=>{s.length>0?(g.assignedTo=s,i&&(g.assignedBy=i.link),g.task=!0):(delete g.assignedTo,delete g.assignedBy)}),this.taskTaggedState.set(r.file.path,s.length>0||c),o.push(r.id)}if(this.render(),o.length>0){let r=o.map(c=>this.tree.get(c)).filter(c=>!!c),l=e.map(c=>c.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:s.length>0?`Assigned to ${l}`:"Cleared assignment",nodes:r}),kind:"success",category:"edit",affectedIds:o,folder:this.noteFolder})}let a=this.noteFolder;this.plugin.getUndoStack(a).push({label:s.length>0?`Assign (${t.length})`:`Clear assignment (${t.length})`,undo:async()=>{for(let r of n){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.assignedTo===void 0?delete c.assignedTo:c.assignedTo=r.assignedTo,r.assignedBy===void 0?delete c.assignedBy:c.assignedBy=r.assignedBy,r.task===void 0?delete c.task:c.task=r.task}),this.taskTaggedState.set(r.path,r.wasTagged))}this.tree.rebuild(a),this.render()}})}isTask(t){return t.file?this.isTaskTagged(t)?!0:this.app.metadataCache.getFileCache(t.file)?.frontmatter?.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 q.Notice("Nothing to toggle.");return}let e=t.some(a=>!this.isTaskTagged(a)),i=[],s=[];for(let a of t){if(!a.file)continue;let r=this.isTaskTagged(a),l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:l?.tags,completed:l?.completed,task:l?.task,wasTagged:r}),r===e)continue;let c=!1;await this.app.fileManager.processFrontMatter(a.file,g=>{e?(as(g,"task"),g.completed===void 0&&(g.completed=!1),c=g.completed===!0,delete g.task):(rs(g,"task"),delete g.completed,delete g.task,c=!1)}),this.completedState.set(a.file.path,c),this.taskTaggedState.set(a.file.path,e),s.push(a.id)}if(this.render(),s.length>0){let a=e?"marked as task":"unmarked as task",r;if(s.length===1){let l=this.tree.get(s[0]);r=`"${l&&this.titleForNode(l).trim()||"(untitled)"}" ${a}`}else r=`${s.length} notes ${a}`;this.plugin.notifications.show({message:r,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);r&&(await this.app.fileManager.processFrontMatter(r,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.completedState.set(a.path,!!a.completed),this.taskTaggedState.set(a.path,a.wasTagged))}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:o,redo:async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);if(!r)continue;let l=!1;await this.app.fileManager.processFrontMatter(r,c=>{e?(as(c,"task"),c.completed===void 0&&(c.completed=!1),l=c.completed===!0,delete c.task):(rs(c,"task"),delete c.completed,delete c.task,l=!1)}),this.completedState.set(a.path,l),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==U&&!s.has(e.id);){s.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:i};e=e.parent?this.tree.get(e.parent):void 0,i+=1}return null}isDescendant(t,e){let i=this.tree.get(t),s=new Set;for(;i&&i.parent&&!s.has(i.id);){if(i.parent===e)return!0;s.add(i.id),i=this.tree.get(i.parent)}return!1}async moveAcrossThenReorder(t,e,i,s){let n=[],o=new Set;for(let D of t){let L=this.tree.get(D);L?.file&&(n.push({id:D,path:L.file.path,oldParent:L.parent}),o.add(L.parent??U))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(D=>this.tree.get(D)).filter(D=>!!D)),r=this.noteFolder,l={};for(let D of o)l[D]=this.order.getOrder(r,D).slice();for(let D of n){let L=this.app.vault.getAbstractFileByPath(D.path);L&&(await this.app.fileManager.processFrontMatter(L,S=>{S.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(r,D.id))}this.tree.rebuild(r);let c=this.tree.getChildren(e).map(D=>D.id),g=new Set(t),p=c.filter(D=>!g.has(D)),d=p.indexOf(i);d<0&&(d=p.length),s==="after"&&(d+=1);let I=[...p.slice(0,d),...t.filter(D=>!!this.tree.get(D)),...p.slice(d)];this.order.setOrder(r,e,I),await this.order.save(r),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}});let u=this.focusId===e,f=u?t[0]:e,C=u?t.slice():[e];u?this.pendingFocusIds=C:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=C),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let m=this.selectionGuardKey,E=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let D=this.currentChildren.findIndex(L=>L.id===f);D<0||(this.selection.add(f),this.cursorIdx=D,this.render({kind:"follow-cursor"}))};setTimeout(E,120),setTimeout(E,400);let w=t.map(D=>this.tree.get(D)).filter(D=>!!D),y=this.tree.get(e),F=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${F}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:r,actions:e===U?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(r).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let D of n){let L=this.app.vault.getAbstractFileByPath(D.path);L&&(await this.app.fileManager.processFrontMatter(L,S=>{D.oldParent===null||D.oldParent===void 0?S.parent=U:S.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,L]of Object.entries(l))if(L.length===0){let S=this.order.cache.get(r)??{};delete S[D],this.order.cache.set(r,S)}else this.order.setOrder(r,D,L);await this.order.save(r),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(r),this.render()},redo:async()=>{for(let D of n){let L=this.app.vault.getAbstractFileByPath(D.path);L&&(await this.app.fileManager.processFrontMatter(L,S=>{S.parent=e}),this.order.removeChild(r,D.id))}this.order.setOrder(r,e,I),await this.order.save(r),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(r),this.render()}})}async reorderToTarget(t,e,i){let s=this.tree.get(e);if(!s)return;let n=t.map(m=>this.tree.get(m)).filter(m=>!!m&&!!m.file);if(n.length===0)return;if(n.some(m=>m.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(i==="into"){for(let m of n)if(this.isDescendant(e,m.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(m)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let o=i==="into"?e:s.parent??U;if(n.some(m=>(m.parent??U)!==o)){let m=ft(),E=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(m.confirmCrossParentDrag){let w=this.titleForNode(s),y=n.length,F=i==="into"?"Nest":"Move",D=i==="into"?"as children of":"under";new vt(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${F} ${y} note${y===1?"":"s"} ${D} "${w}"? Their parent will change.`,F,L=>{L&&E()}).open()}else await E();return}let r=o,l=n.map(m=>m.id),c=this.tree.getChildren(r).map(m=>m.id),g=new Set(l),p=c.filter(m=>!g.has(m)),d=p.indexOf(e);if(d<0)return;i==="after"&&(d+=1);let I=[...p.slice(0,d),...l,...p.slice(d)];if(Fs(I,c))return;let u=this.noteFolder,f=this.order.getOrder(u,r).slice();this.order.setOrder(u,r,I),await this.order.save(u),await this.forceManualMode(r),await this.log.append({type:"reorder",id:r,payload:{dir:"drag",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render();let C=l.map(m=>this.tree.get(m)).filter(m=>!!m);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:C}),kind:"success",category:"reorder",affectedIds:l,folder:u}),this.plugin.getUndoStack(u).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(u)??{};delete m[r],this.order.cache.set(u,m)}else this.order.setOrder(u,r,f);await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"undo",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render()},redo:async()=>{this.order.setOrder(u,r,I),await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"redo:drag",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),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 g=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(g.length===0)return;if(new Set(g.map(d=>d.parent)).size>1){new q.Notice("Reorder requires a single-parent selection.");return}e=g}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new q.Notice("Nothing to reorder.");return}let i=e[0].parent??U,s=this.tree.getChildren(i).map(g=>g.id);if(s.length===0)return;let n=new Set(e.map(g=>g.id)),o=s.filter(g=>n.has(g));if(o.length===0)return;let a=kn(s,o,t);if(Fs(a,s))return;let r=this.noteFolder,l=this.order.getOrder(r,i).slice();this.order.setOrder(r,i,a),await this.order.save(r),await this.forceManualMode(i),await this.log.append({type:"reorder",id:i,payload:{dir:t,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let c=o.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:c,destination:t}),kind:"success",category:"reorder",affectedIds:o,folder:r}),this.plugin.getUndoStack(r).push({label:`Reorder (${t})`,undo:async()=>{if(l.length===0){let g=this.order.cache.get(r)??{};delete g[i],this.order.cache.set(r,g)}else this.order.setOrder(r,i,l);await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:"undo",parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()},redo:async()=>{this.order.setOrder(r,i,a),await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:`redo:${t}`,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let I=this.tree.get(this.focusId);I?.file&&(t=[I])}if(t.length===0){new q.Notice("Nothing selected to delete.");return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],i=new Set,s=I=>{if(!i.has(I.id)){i.add(I.id);for(let u of this.tree.getChildren(I.id))s(u);e.push(I)}};for(let I of t)s(I);let n=e.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.read(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(ae(C))}let r=[...new Set(a)],l=e.length-t.length,c=async I=>{let u=await this.snapshotNotes(e,I),f=0;if(I)for(let H of r){let $=this.app.metadataCache.getFirstLinkpathDest(H,"");if($)try{await this.app.fileManager.trashFile($),await this.log.append({type:"attachment_remove",id:U,payload:{path:$.path}}),this.plugin.notifications.show({message:`Deleted attachment "${$.name}"`,kind:"warning",category:"attachment",affectedPaths:[$.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let H of e)H.parent&&C.add(H.parent);let m=this.authorship.collectAuthorIds(e),E=new Set(t.map(H=>H.id)),w=this.currentChildren.map((H,$)=>E.has(H.id)?$:-1).filter(H=>H>=0),y=w.length>0?w[0]:-1,F=null;if(y>=0){for(let H=y+1;H<this.currentChildren.length;H++)if(!E.has(this.currentChildren[H].id)){F=this.currentChildren[H].id;break}if(!F){for(let H=y-1;H>=0;H--)if(!E.has(this.currentChildren[H].id)){F=this.currentChildren[H].id;break}}}for(let H of e)if(H.file){try{await this.app.fileManager.trashFile(H.file)}catch{}await this.log.append({type:"delete",id:H.id,payload:{path:H.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,F&&(this.pendingFocusIds=[F]),this.tree.rebuild(this.noteFolder);for(let H of C)e.some($=>$.id===H)||this.fmSync.scheduleParentOfDeleted(H);this.render({kind:"follow-cursor"});let D=f>0?` with ${f} attachment${f===1?"":"s"}`:"",L=this.noteFolder,S=t.map(H=>H.id),b=!1,Q=async()=>{b||(b=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,S.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(H=>H.id),affectedAuthorIds:m,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void Q()}]}),this.plugin.getUndoStack(L).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await Q()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,b=!1,await this.trashNotesAndAttachments(u)}}),this.focusView()},g=ft(),p=g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await c(!1);return}new Ce(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,r.length,d,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new q.Notice("Pick a note to split.");return}let i=e.file,s=await this.app.vault.read(i),n=this.stripFrontmatter(s).replace(/\s+$/,""),o=n.split(/\r?\n/);if(n.trim().length<2){new q.Notice("Note is too short to split.");return}let a=s,r=i.path,l=async(c,g,p)=>{if(!c.trim()||!g.trim()){new q.Notice("Split would leave one part empty.");return}try{let d=s.startsWith("---")?s.slice(0,s.indexOf(` ---`,3)+4):"",I=d+(d?` -`:"")+l+` -`;await this.app.vault.modify(i,I);let u=e.parent??U,f=Date.parse(e.created||""),C=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),m=await this.createNoteUnder(g,u,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:m,...p}}),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 E=m?this.tree.get(m):void 0,w=E?.file?.path,y=w?await this.app.vault.read(E.file):null,F=this.noteFolder;this.plugin.getUndoStack(F).push({label:"Split note",undo:async()=>{if(w){let L=this.app.vault.getAbstractFileByPath(w);if(L)try{await this.app.fileManager.trashFile(L)}catch{}}let D=this.app.vault.getAbstractFileByPath(r);D&&await this.app.vault.modify(D,a),this.tree.rebuild(F),this.render()},redo:async()=>{let D=this.app.vault.getAbstractFileByPath(r);D&&await this.app.vault.modify(D,I),w&&y&&!await this.app.vault.adapter.exists(w)&&await this.app.vault.create(w,y),this.tree.rebuild(F),this.render()}})}catch(d){new q.Notice(`Stashpad: split failed (${d.message})`),console.error(d)}};new Je(this.app,n,async l=>{let g=o.slice(0,l).join(` -`).replace(/\s+$/,""),p=o.slice(l).join(` -`).replace(/^\s+|\s+$/g,"");await c(g,p,{mode:"line",splitAtLine:l})},async l=>{let g=n.slice(0,l).replace(/\s+$/,""),p=n.slice(l).replace(/^\s+|\s+$/g,"");await c(g,p,{mode:"cursor",splitAtChar:l})}).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}cmdExportStash(t){return no(this,t)}cmdImportStash(){return oo(this)}processStashFile(t){return Ps(this,t)}async createNoteUnder(t,e,i={record:!0}){let s=(i.targetFolder??this.noteFolder).replace(/\/+$/,""),n=s!==this.noteFolder;await this.ensureFolder(s);let o=yt(),a=null;{let f=(this.plugin.settings.noteTemplates??{})[s];if(f){let C=this.app.vault.getAbstractFileByPath(f);if(C&&C.extension==="md")try{let m=await this.app.vault.cachedRead(C),E=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},E.includes("{{body}}")?t=E.replace(/\{\{body\}\}/g,t):t.trim()?E.trim()&&(t=`${t} +`:"")+c+` +`;await this.app.vault.modify(i,I);let u=e.parent??U,f=Date.parse(e.created||""),C=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),m=await this.createNoteUnder(g,u,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:m,...p}}),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 E=m?this.tree.get(m):void 0,w=E?.file?.path,y=w?await this.app.vault.read(E.file):null,F=this.noteFolder;this.plugin.getUndoStack(F).push({label:"Split note",undo:async()=>{if(w){let L=this.app.vault.getAbstractFileByPath(w);if(L)try{await this.app.fileManager.trashFile(L)}catch{}}let D=this.app.vault.getAbstractFileByPath(r);D&&await this.app.vault.modify(D,a),this.tree.rebuild(F),this.render()},redo:async()=>{let D=this.app.vault.getAbstractFileByPath(r);D&&await this.app.vault.modify(D,I),w&&y&&!await this.app.vault.adapter.exists(w)&&await this.app.vault.create(w,y),this.tree.rebuild(F),this.render()}})}catch(d){new q.Notice(`Stashpad: split failed (${d.message})`),console.error(d)}};new Je(this.app,n,async c=>{let g=o.slice(0,c).join(` +`).replace(/\s+$/,""),p=o.slice(c).join(` +`).replace(/^\s+|\s+$/g,"");await l(g,p,{mode:"line",splitAtLine:c})},async c=>{let g=n.slice(0,c).replace(/\s+$/,""),p=n.slice(c).replace(/^\s+|\s+$/g,"");await l(g,p,{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}cmdExportStash(t){return no(this,t)}cmdImportStash(){return oo(this)}processStashFile(t){return Ps(this,t)}async createNoteUnder(t,e,i={record:!0}){let s=(i.targetFolder??this.noteFolder).replace(/\/+$/,""),n=s!==this.noteFolder;await this.ensureFolder(s);let o=yt(),a=null;{let f=(this.plugin.settings.noteTemplates??{})[s];if(f){let C=this.app.vault.getAbstractFileByPath(f);if(C&&C.extension==="md")try{let m=await this.app.vault.cachedRead(C),E=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},E.includes("{{body}}")?t=E.replace(/\{\{body\}\}/g,t):t.trim()?E.trim()&&(t=`${t} -${E}`):t=E}catch(m){console.warn("[Stashpad] template read failed",m)}}}let r=Dt(t,this.activeStopwords()),c=bt(r,o),l=`${s}/${c}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),I=this.authorship.currentAuthorLink();I&&this.authorship.ensureAuthorFile(I);let u=["---",`id: ${o}`,`parent: ${g}`,`created: ${p}`,`modified: ${p}`];if(I&&u.push(`author: "${I.link.replace(/"/g,'\\"')}"`),d.length>0){u.push("attachments:");for(let f of d)u.push(` - "${f.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",t);try{let f=u.join(` -`);this.plugin.importService.suppress(l,6e4),await St.timeAsync("write.createNote.file",()=>this.app.vault.create(l,f));try{let C=this.app.vault.getAbstractFileByPath(l);if(C&&C.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:g,children:[],file:C,created:p}),this.render(),this.fmSync.scheduleParentChange(o,null,g);else{this.render();let m=s.split("/").pop()||s,E=(t.split(` -`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${E}" landed in \`${m}\``,kind:"success",category:"create",duration:0,folder:s,affectedIds:[o],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(s,o)}}]})}if(a)try{await this.app.fileManager.processFrontMatter(C,m=>{for(let[E,w]of Object.entries(a))Wt.includes(E)||m[E]===void 0&&(m[E]=w)})}catch(m){console.warn("[Stashpad] template fm overlay failed",m)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:l,parent:g}}),i.record!==!1){let C=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let m=this.app.vault.getAbstractFileByPath(l);if(m)try{await this.app.fileManager.trashFile(m)}catch{}if(this.composerDraft=C,this.saveDraft(C),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=C;let E=C.length;this.composerInputEl.setSelectionRange(E,E),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(l)||await this.app.vault.create(l,f),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(C),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(f){return new q.Notice(`Stashpad: failed to create note (${f.message})`),null}}extractAttachments(t){let e=[],i=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,s;for(;(s=i.exec(t))!==null;)e.push(s[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 q.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${n}-${s}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:U,payload:{path:o,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[o],folder:this.noteFolder}),`![[${o}]]`}catch(e){return new q.Notice(`Stashpad: attachment failed (${e.message})`),null}}claimSelectedAsAuthor(){this.authorship.claimSelectedAsAuthor()}claimFolderAsAuthor(){this.authorship.claimFolderAsAuthor()}claimSelectedWithContributor(){this.authorship.claimSelectedWithContributor()}claimFolderWithContributor(){this.authorship.claimFolderWithContributor()}renderAuthorshipFooter(t,e){if(!e.file)return;let i=this.plugin.settings;if(!i.showAuthor&&!i.showContributors&&!i.showLastEdit)return;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof s.author=="string"?s.author:"",o=Array.isArray(s.contributors)?s.contributors.filter(I=>typeof I=="string"&&I.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",r=i.showAuthor&&!!n,c=i.showContributors&&o.length>0,l=i.showLastEdit&&!!a;if(!r&&!c&&!l)return;let g=t.createDiv({cls:"stashpad-note-authorship"}),p=(I,u)=>{let f=u.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,E=C>=0?f.slice(C+1):f.split("/").pop()??f,w=I.createEl("a",{cls:"internal-link",text:E});w.setAttribute("data-href",m),w.setAttribute("href",m)},d=[];r&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(I,n)}),c&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&I.createSpan({text:", "}),p(I,u)})}),l&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"edited "}),I.createSpan({text:this.formatTimeInline(a)})}),d.forEach((I,u)=>{u>0&&g.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=g.createSpan({cls:"stashpad-authorship-piece"});I(f)}),g.addEventListener("click",I=>this.handleRenderedClick(I,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Pt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,q.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=Be(t.basename);if(!e||e===U)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Dt(s,this.activeStopwords()),o=bt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let r=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:r,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,q.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(e),s=this.extractAttachments(i),n=this.app.metadataCache.getFileCache(t)?.frontmatter,a=(Array.isArray(n?.attachments)?n.attachments:[]).filter(l=>typeof l=="string").map(l=>ae(l));if(a.length===s.length&&a.every((l,g)=>l===s[g]))return;let c=s.map(l=>Gt(l));await this.app.fileManager.processFrontMatter(t,l=>{l.attachments=c})}stripFrontmatter(t){let e=t.replace(/^/,""),i=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return i?e.slice(i[0].length):e}formatTime(t){if(!t)return"";let e=(0,q.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let s=Si(this.app);if(s)return`${e.format(s.dateFormat)} +${E}`):t=E}catch(m){console.warn("[Stashpad] template read failed",m)}}}let r=Dt(t,this.activeStopwords()),l=bt(r,o),c=`${s}/${l}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),I=this.authorship.currentAuthorLink();I&&this.authorship.ensureAuthorFile(I);let u=["---",`id: ${o}`,`parent: ${g}`,`created: ${p}`,`modified: ${p}`];if(I&&u.push(`author: "${I.link.replace(/"/g,'\\"')}"`),d.length>0){u.push("attachments:");for(let f of d)u.push(` - "${f.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",t);try{let f=u.join(` +`);this.plugin.importService.suppress(c,6e4),await St.timeAsync("write.createNote.file",()=>this.app.vault.create(c,f));try{let C=this.app.vault.getAbstractFileByPath(c);if(C&&C.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:g,children:[],file:C,created:p}),this.render(),this.fmSync.scheduleParentChange(o,null,g);else{this.render();let m=s.split("/").pop()||s,E=(t.split(` +`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${E}" landed in \`${m}\``,kind:"success",category:"create",duration:0,folder:s,affectedIds:[o],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(s,o)}}]})}if(a)try{await this.app.fileManager.processFrontMatter(C,m=>{for(let[E,w]of Object.entries(a))Wt.includes(E)||m[E]===void 0&&(m[E]=w)})}catch(m){console.warn("[Stashpad] template fm overlay failed",m)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:c,parent:g}}),i.record!==!1){let C=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let m=this.app.vault.getAbstractFileByPath(c);if(m)try{await this.app.fileManager.trashFile(m)}catch{}if(this.composerDraft=C,this.saveDraft(C),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=C;let E=C.length;this.composerInputEl.setSelectionRange(E,E),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,f),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(C),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(f){return new q.Notice(`Stashpad: failed to create note (${f.message})`),null}}extractAttachments(t){let e=[],i=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,s;for(;(s=i.exec(t))!==null;)e.push(s[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 q.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${n}-${s}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:U,payload:{path:o,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[o],folder:this.noteFolder}),`![[${o}]]`}catch(e){return new q.Notice(`Stashpad: attachment failed (${e.message})`),null}}claimSelectedAsAuthor(){this.authorship.claimSelectedAsAuthor()}claimFolderAsAuthor(){this.authorship.claimFolderAsAuthor()}claimSelectedWithContributor(){this.authorship.claimSelectedWithContributor()}claimFolderWithContributor(){this.authorship.claimFolderWithContributor()}renderAuthorshipFooter(t,e){if(!e.file)return;let i=this.plugin.settings;if(!i.showAuthor&&!i.showContributors&&!i.showLastEdit)return;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof s.author=="string"?s.author:"",o=Array.isArray(s.contributors)?s.contributors.filter(I=>typeof I=="string"&&I.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",r=i.showAuthor&&!!n,l=i.showContributors&&o.length>0,c=i.showLastEdit&&!!a;if(!r&&!l&&!c)return;let g=t.createDiv({cls:"stashpad-note-authorship"}),p=(I,u)=>{let f=u.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,E=C>=0?f.slice(C+1):f.split("/").pop()??f,w=I.createEl("a",{cls:"internal-link",text:E});w.setAttribute("data-href",m),w.setAttribute("href",m)},d=[];r&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(I,n)}),l&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&I.createSpan({text:", "}),p(I,u)})}),c&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"edited "}),I.createSpan({text:this.formatTimeInline(a)})}),d.forEach((I,u)=>{u>0&&g.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=g.createSpan({cls:"stashpad-authorship-piece"});I(f)}),g.addEventListener("click",I=>this.handleRenderedClick(I,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Pt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,q.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=Be(t.basename);if(!e||e===U)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Dt(s,this.activeStopwords()),o=bt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let r=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:r,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,q.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(e),s=this.extractAttachments(i),n=this.app.metadataCache.getFileCache(t)?.frontmatter,a=(Array.isArray(n?.attachments)?n.attachments:[]).filter(c=>typeof c=="string").map(c=>ae(c));if(a.length===s.length&&a.every((c,g)=>c===s[g]))return;let l=s.map(c=>Gt(c));await this.app.fileManager.processFrontMatter(t,c=>{c.attachments=l})}stripFrontmatter(t){let e=t.replace(/^/,""),i=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return i?e.slice(i[0].length):e}formatTime(t){if(!t)return"";let e=(0,q.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let s=Si(this.app);if(s)return`${e.format(s.dateFormat)} ${e.format(s.timeFormat)}`}return`${e.format("YYYY.MM.DD")} -${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,q.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let s=Si(this.app);if(s){let n=/:ss/.test(s.timeFormat)?s.timeFormat:s.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(s.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,q.Platform.isMobile){let a=0,r=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(r,120))};window.setTimeout(r,60);return}this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},i=new ResizeObserver(e);for(let a of Array.from(t.children))a instanceof HTMLElement&&i.observe(a);this.stickyRowObserver=i;let s=performance.now(),n=t.scrollHeight,o=()=>{if(!this.stickToListBottom)return;let a=t.scrollHeight;a!==n&&(t.scrollTop=a,n=a),performance.now()-s<3e4?requestAnimationFrame(o):(this.stickToListBottom=!1,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null)};requestAnimationFrame(o)}openNoteMenu(t,e){if(!e.file)return;let i=e.file,s=new q.Menu;s.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(r=>r.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()})),s.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(r=>r.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()})),s.addSeparator(),s.addItem(r=>r.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(r=>r.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,U),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==U&&this.navigateTo(U)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(r=>r.setTitle(o?"Unpin from sidebar":"Pin to sidebar").setIcon(o?"pin-off":"pin").onClick(async()=>{o?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),s.addItem(r=>r.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);s.addItem(r=>r.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()})),s.addSeparator(),s.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{await this.deleteNote(e)})),s.addSeparator(),s.addItem(r=>r.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=I=>{for(let u of this.tree.getChildren(I.id))i(u),e.push(u)};i(t);let s=[...e,t],n=s.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.cachedRead(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(ae(C))}let r=[...new Set(a)],c=this.authorship.collectAuthorIds(s),l=async I=>{let u=await this.snapshotNotes(s,I),f=0;if(I)for(let b of r){let Q=this.app.metadataCache.getFirstLinkpathDest(b,"");if(Q)try{await this.app.fileManager.trashFile(Q),await this.log.append({type:"attachment_remove",id:U,payload:{path:Q.path}}),this.plugin.notifications.show({message:`Deleted attachment "${Q.name}"`,kind:"warning",category:"attachment",affectedPaths:[Q.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let b of s)b.parent&&C.add(b.parent);let m=this.currentChildren.findIndex(b=>b.id===t.id),E=null;if(m>=0){for(let b=m+1;b<this.currentChildren.length;b++)if(this.currentChildren[b].id!==t.id){E=this.currentChildren[b].id;break}if(!E){for(let b=m-1;b>=0;b--)if(this.currentChildren[b].id!==t.id){E=this.currentChildren[b].id;break}}}for(let b of s)if(b.file){try{await this.app.fileManager.trashFile(b.file)}catch{}await this.log.append({type:"delete",id:b.id,payload:{path:b.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let b of C)s.some(Q=>Q.id===b)||this.fmSync.scheduleParentOfDeleted(b);let w=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,F=t.id,D=f>0?` with ${f} attachment${f===1?"":"s"}`:"",L=!1,S=async()=>{L||(L=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[F]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${D}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:c,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void S()}]}),this.plugin.getUndoStack(w).push({label:y,undo:async()=>{await S()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,L=!1,await this.trashNotesAndAttachments(u)}})},g=ft(),p=e.length>0&&g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await l(!1),this.focusView();return}new Ce(this.app,this.titleForNode(t),e.length,r.length,d,async I=>{await l(I),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new q.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===U){new q.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new q.Notice("Couldn't find the parent note.");return}let i=e.parent??U,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(r=>r.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new vt(this.app,"Swap notes?",a.join(` +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,q.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let s=Si(this.app);if(s){let n=/:ss/.test(s.timeFormat)?s.timeFormat:s.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(s.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,q.Platform.isMobile){let a=0,r=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(r,120))};window.setTimeout(r,60);return}this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},i=new ResizeObserver(e);for(let a of Array.from(t.children))a instanceof HTMLElement&&i.observe(a);this.stickyRowObserver=i;let s=performance.now(),n=t.scrollHeight,o=()=>{if(!this.stickToListBottom)return;let a=t.scrollHeight;a!==n&&(t.scrollTop=a,n=a),performance.now()-s<3e4?requestAnimationFrame(o):(this.stickToListBottom=!1,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null)};requestAnimationFrame(o)}openNoteMenu(t,e){if(!e.file)return;let i=e.file,s=new q.Menu;s.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(r=>r.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()})),s.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(r=>r.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()})),s.addSeparator(),s.addItem(r=>r.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(r=>r.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,U),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==U&&this.navigateTo(U)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(r=>r.setTitle(o?"Unpin from sidebar":"Pin to sidebar").setIcon(o?"pin-off":"pin").onClick(async()=>{o?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),s.addItem(r=>r.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);s.addItem(r=>r.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()})),s.addSeparator(),s.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{await this.deleteNote(e)})),s.addSeparator(),s.addItem(r=>r.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=I=>{for(let u of this.tree.getChildren(I.id))i(u),e.push(u)};i(t);let s=[...e,t],n=s.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.cachedRead(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(ae(C))}let r=[...new Set(a)],l=this.authorship.collectAuthorIds(s),c=async I=>{let u=await this.snapshotNotes(s,I),f=0;if(I)for(let b of r){let Q=this.app.metadataCache.getFirstLinkpathDest(b,"");if(Q)try{await this.app.fileManager.trashFile(Q),await this.log.append({type:"attachment_remove",id:U,payload:{path:Q.path}}),this.plugin.notifications.show({message:`Deleted attachment "${Q.name}"`,kind:"warning",category:"attachment",affectedPaths:[Q.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let b of s)b.parent&&C.add(b.parent);let m=this.currentChildren.findIndex(b=>b.id===t.id),E=null;if(m>=0){for(let b=m+1;b<this.currentChildren.length;b++)if(this.currentChildren[b].id!==t.id){E=this.currentChildren[b].id;break}if(!E){for(let b=m-1;b>=0;b--)if(this.currentChildren[b].id!==t.id){E=this.currentChildren[b].id;break}}}for(let b of s)if(b.file){try{await this.app.fileManager.trashFile(b.file)}catch{}await this.log.append({type:"delete",id:b.id,payload:{path:b.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let b of C)s.some(Q=>Q.id===b)||this.fmSync.scheduleParentOfDeleted(b);let w=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,F=t.id,D=f>0?` with ${f} attachment${f===1?"":"s"}`:"",L=!1,S=async()=>{L||(L=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[F]))};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 S()}]}),this.plugin.getUndoStack(w).push({label:y,undo:async()=>{await S()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,L=!1,await this.trashNotesAndAttachments(u)}})},g=ft(),p=e.length>0&&g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await c(!1),this.focusView();return}new Ce(this.app,this.titleForNode(t),e.length,r.length,d,async I=>{await c(I),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new q.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===U){new q.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new q.Notice("Couldn't find the parent note.");return}let i=e.parent??U,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(r=>r.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new vt(this.app,"Swap notes?",a.join(` `),"Swap",async r=>{r&&await this.swapParentChild(e,t,i)}).open()}offerSwapForDescendantMove(t,e){let i=this.tree.get(e);if(!i?.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(i.parent!==t.id){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under "${this.titleForNode(i)}" \u2014 it's a deeper descendant. Only direct parent \u2194 child swaps are supported (try moving "${this.titleForNode(i)}" up first, then swap).`,kind:"warning",category:"move",affectedIds:[t.id,i.id],folder:this.noteFolder});return}let s=this.titleForNode(t),n=this.titleForNode(i),o=this.tree.getChildren(t.id).filter(r=>r.id!==i.id).length,a=[`"${s}" becomes a child of "${n}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new vt(this.app,"Confirm Note Swap",a.join(` -`),"Swap",async r=>{if(!r)return;let c=t.parent??U;await this.swapParentChild(t,i,c)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new q.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(d=>d.id!==e.id).filter(d=>!!d.file),a=o.map(d=>({id:d.id,path:d.file.path,was:d.parent})),r=this.order.getOrder(s,i).slice(),c=this.order.getOrder(s,e.id).slice(),l=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,d=>{d.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,d=>{d.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let d of o)await this.app.fileManager.processFrontMatter(d.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(d.id,t.id,e.id);if(r.length>0){let d=r.includes(t.id)?r.map(I=>I===t.id?e.id:I):[...r.filter(I=>I!==e.id),e.id];this.order.setOrder(s,i,d)}let g=o.map(d=>d.id),p=[t.id,...c.filter(d=>d!==t.id&&!g.includes(d)),...g];this.order.setOrder(s,e.id,p),this.order.setOrder(s,t.id,[]),await this.order.save(s),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:i,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let d of a)await this.log.append({type:"parent_change",id:d.id,payload:{from:d.was,to:e.id,reason:"swap"}});this.tree.rebuild(s),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,...g],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let d=this.tree.get(t.id),I=this.tree.get(e.id);d?.file&&await this.app.fileManager.processFrontMatter(d.file,u=>{n==null||n===U?(delete u.parent,u.parent=U):u.parent=n}),I?.file&&await this.app.fileManager.processFrontMatter(I.file,u=>{u.parent=t.id});for(let u of a){let f=this.app.vault.getAbstractFileByPath(u.path);f&&await this.app.fileManager.processFrontMatter(f,C=>{u.was==null?C.parent=U:C.parent=u.was})}this.order.setOrder(s,i,r),this.order.setOrder(s,e.id,c),this.order.setOrder(s,t.id,l),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=r=>r??U;if(o(n)===o(e)){if(!i.quiet){let r=this.titleForNode(t),c=e===U?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${r}" is already under ${c}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==U&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let a=this.authorship.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(s,r=>{r.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),!i.quiet&&!i.silentSuccess){let r=this.tree.get(e),c=r?this.titleForNode(r):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${c}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===U?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let r=this.noteFolder,c=s.path,l=t.id;this.plugin.getUndoStack(r).push({label:"Move note",undo:async()=>{let g=this.app.vault.getAbstractFileByPath(c);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.parent=n}),this.pendingFocusIds=[l],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(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(l))return;let I=this.currentChildren.findIndex(u=>u.id===l);I<0||(this.selection.add(l),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}},redo:async()=>{let g=this.app.vault.getAbstractFileByPath(c);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.parent=e}),this.pendingFocusIds=[l],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(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(l))return;let I=this.currentChildren.findIndex(u=>u.id===l);I<0||(this.selection.add(l),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===U?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=r=>i.get(r.id)??0,a;if(t.length===1){let r=this.titleForNode(t[0]),c=o(t[0]);a=c>0?`Moved "${r}" and its ${c} ${c===1?"child":"children"} \u2192 ${n}`:`Moved "${r}" \u2192 ${n}`}else{let r=t.reduce((c,l)=>c+o(l),0);a=r>0?`Moved ${t.length} notes (${r} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===U?void 0:0,affectedIds:t.map(r=>r.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===U?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};var ht=require("obsidian");wt();Mt();var Vi=class h extends ht.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return ne}getDisplayText(){return"Stashpad folders"}getIcon(){return"folders"}async onOpen(){this.render(),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("layout-change",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("create",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender()))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},100))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-folderpanel-root");let e=this.clampFrac(this.plugin.settings.folderPanelPinnedFraction??.5),i=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-pinned"});i.style.flex=`0 0 ${(e*100).toFixed(2)}%`;let s=i.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"});s.createSpan({cls:"stashpad-folderpanel-heading-title",text:"Pinned"});let n=s.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(n,"list"),n.setAttr("aria-label","Pinned view options"),n.onclick=r=>{r.stopPropagation(),this.openPinnedOptionsMenu(r)},this.renderPinned(i.createDiv({cls:"stashpad-folderpanel-list stashpad-folderpanel-pins"}));let o=t.createDiv({cls:"stashpad-folderpanel-divider"});o.createDiv({cls:"stashpad-folderpanel-divider-grip"}),this.attachDividerDrag(t,i,o);let a=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-folders"});a.style.flex="1 1 0",a.createDiv({cls:"stashpad-folderpanel-heading"}).setText("Folders"),this.renderFolders(a.createDiv({cls:"stashpad-folderpanel-list"}))}clampFrac(t){return Number.isFinite(t)?Math.max(.15,Math.min(.85,t)):.5}attachDividerDrag(t,e,i){let s=null,n=a=>{let r=t.getBoundingClientRect();if(r.height<=0)return;let c=this.clampFrac((a.clientY-r.top)/r.height);s=c,e.style.flex=`0 0 ${(c*100).toFixed(2)}%`},o=a=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(a.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",a=>{a.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(a.pointerId)}catch{}document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)})}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new ht.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinned(t){let e=this.plugin.listPinnedNotes();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No pinned notes yet \u2014 pin a note from its right-click menu."});return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let s=new Map;e.forEach((a,r)=>{let c=s.get(a.folder);c||(c=[],s.set(a.folder,c)),c.push({...a,idx:r})});let n=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,o=Array.from(s.keys());n&&s.has(n)&&(o.splice(o.indexOf(n),1),o.unshift(n));for(let a of o){let r=t.createDiv({cls:"stashpad-pinned-group-header"});a===n&&r.addClass("is-active-folder"),r.createSpan({cls:"stashpad-pinned-group-name",text:a.split("/").pop()||a});for(let c of s.get(a)??[])this.renderPinNote(t,c.folder,c.id,c.file,c.idx)}}else e.forEach((s,n)=>this.renderPinNote(t,s.folder,s.id,s.file,n))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((l,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],c;!a&&!r?c=Date.now():a?r?c=(a.pinnedAt+r.pinnedAt)/2:c=a.pinnedAt+1e3:c=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,l=>{l.pinnedAt=c})}catch(l){console.warn("[Stashpad] pin reorder failed",l)}this.render()}renderPinNote(t,e,i,s,n){let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,r=o.completed===!0,c=this.childrenOf(e,i),l=c.length>0,g=`${e}|${i}`,p=this.pinExpanded.has(g),d=t.createDiv({cls:"stashpad-pinned-row"});a&&(d.addClass("has-color"),d.style.setProperty("--stashpad-note-color",a)),r&&d.addClass("is-completed"),d.draggable=!0,d.dataset.pinIdx=String(n),d.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),d.addClass("is-dragging")}),d.addEventListener("dragend",()=>d.removeClass("is-dragging")),d.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=d.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;d.toggleClass("drop-before",E),d.toggleClass("drop-after",!E)}),d.addEventListener("dragleave",()=>{d.removeClass("drop-before"),d.removeClass("drop-after")}),d.addEventListener("drop",C=>{C.preventDefault(),d.removeClass("drop-before"),d.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let E=d.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?n:n+1)});let I=d.createSpan({cls:"stashpad-pinned-toggle"});l&&(de(I,c.length,p),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let u=d.createSpan({cls:"stashpad-pinned-icon"});(0,ht.setIcon)(u,l?"folder-tree":"file-text"),a&&(u.style.color=a);let f=d.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},d.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),d.oncontextmenu=C=>{C.preventDefault();let m=new ht.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},l&&p){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(C,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let r=typeof o.color=="string"?o.color:null,c=o.completed===!0,l=this.childrenOf(e,a),g=l.length>0,p=`${e}|${a}`,d=this.pinExpanded.has(p),I=t.createDiv({cls:"stashpad-pinned-subrow"});c&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});g&&(de(u,l.length,d),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,ht.setIcon)(f,"file-text"),r&&(f.style.color=r);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},g&&d&&this.renderPinSubtree(t,e,a,s+1)}}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===U&&(a==null||a===U)){if(o.id===U)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",a=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(a))}),i}onNavigateAway(){ht.Platform.isMobile&&(this.plugin.suppressComposerAutofocusUntil=Date.now()+1500,this.app.workspace.leftSplit?.collapse?.())}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}openFolders(){let t=new Set,e=(this.plugin.settings.folder||"Stashpad").replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(dt)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=h.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=h.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(h.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==U||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let c of e)switch(this.folderState(c)){case"pinned":s.push(c);break;case"downranked":o.push(c);break;case"hidden":a.push(c);break;default:n.push(c)}let r=[...s,...n,...o];if(r.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let c of r)this.renderFolderRow(t,c,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(h.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let a=o.createSpan({cls:"stashpad-folderpanel-dot"});if(a.setAttr("aria-label",n?"Open in a tab":"Not open"),n&&a.setAttr("title","Open in a tab"),s==="pinned"){let I=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,ht.setIcon)(I,"pin"),I.setAttr("aria-label","Pinned")}let r=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,ht.setIcon)(r,"folder");let c=this.folderHomeColor(e);c&&(r.style.color=c);let l=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:l});let g=o.createDiv({cls:"stashpad-folderpanel-actions"}),p=g.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(p,"folder-search"),p.setAttr("aria-label","Reveal in file explorer"),p.onclick=I=>{I.stopPropagation(),this.revealFolder(e)};let d=g.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(d,"plus-square"),d.setAttr("aria-label","Open in new tab"),d.onclick=I=>{I.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e)},o.onclick=()=>{this.onNavigateAway(),this.jumpToFolder(e)},o.oncontextmenu=I=>{I.preventDefault(),this.openFolderMenu(I,e)}}renderHiddenSection(t,e){let i=t.createDiv({cls:"stashpad-folderpanel-hidden"}),s=i.createDiv({cls:"stashpad-folderpanel-hidden-header"}),n=s.createSpan({cls:"stashpad-folderpanel-hidden-caret"});(0,ht.setIcon)(n,"chevron-right"),s.createSpan({cls:"stashpad-folderpanel-hidden-title",text:`Hidden (${e.length})`});let o=i.createDiv({cls:"stashpad-folderpanel-hidden-body"});o.style.display="none",s.onclick=()=>{let a=o.style.display!=="none";o.style.display=a?"none":"",(0,ht.setIcon)(n,a?"chevron-right":"chevron-down")};for(let a of e){let r=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),c=a.split("/").pop()||a;r.createSpan({cls:"stashpad-folderpanel-row-label",text:c});let l=r.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(l,"eye"),l.setAttr("aria-label","Unhide"),l.onclick=g=>{g.stopPropagation(),this.setFolderState(a,"normal")}}}jumpToFolder(t){let e=t.replace(/\/+$/,""),i=this.app.workspace.getLeavesOfType(dt).find(s=>(s.view?.noteFolder??"").replace(/\/+$/,"")===e);if(i){this.app.workspace.revealLeaf(i);return}this.plugin.activateViewForFolder(t)}revealFolder(t){let e=this.app.vault.getAbstractFileByPath(t.replace(/\/+$/,""));if(!(e instanceof ht.TFolder)){new ht.Notice("Couldn't find that folder.");return}let i=this.app.workspace.getLeavesOfType("file-explorer")[0];if(!i){new ht.Notice("File explorer isn't available.");return}this.app.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}openFolderMenu(t,e){let i=new ht.Menu;i.addItem(n=>n.setTitle("Open in new tab").setIcon("plus-square").onClick(()=>void this.plugin.activateViewForFolder(e))),i.addItem(n=>n.setTitle("Reveal in file explorer").setIcon("folder-search").onClick(()=>this.revealFolder(e))),i.addSeparator();let s=this.folderState(e);i.addItem(n=>n.setTitle(s==="pinned"?"Unpin":"Pin to top").setIcon("pin").onClick(()=>void this.setFolderState(e,s==="pinned"?"normal":"pinned"))),i.addItem(n=>n.setTitle(s==="downranked"?"Remove downrank":"Downrank").setIcon("arrow-down").onClick(()=>void this.setFolderState(e,s==="downranked"?"normal":"downranked"))),i.addItem(n=>n.setTitle("Hide from list").setIcon("eye-off").onClick(()=>void this.setFolderState(e,"hidden"))),i.addSeparator(),i.addItem(n=>n.setTitle("Rename\u2026").setIcon("pencil").onClick(()=>this.renameFolder(e))),i.addSeparator(),i.addItem(n=>{n.setTitle("Delete folder\u2026").setIcon("trash").onClick(()=>this.deleteFolder(e)),n.setWarning?.(!0)}),i.showAtMouseEvent(t)}renameFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof ht.TFolder)){new ht.Notice("Couldn't find that folder.");return}let s=i.name;new Ls(this.app,s,async n=>{let o=n.trim().replace(/[\\/:]+/g,"").trim();if(!o||o===s)return;let r=`${i.parent?.path&&i.parent.path!=="/"?`${i.parent.path}/`:""}${o}`;if(this.app.vault.getAbstractFileByPath(r)){new ht.Notice(`"${o}" already exists.`);return}try{await this.app.fileManager.renameFile(i,r),(this.plugin.settings.folder||"").replace(/\/+$/,"")===e&&(this.plugin.settings.folder=r,await this.plugin.saveSettings()),new ht.Notice(`Renamed to "${o}".`)}catch(c){console.warn("[Stashpad] folder rename failed",c),new ht.Notice("Rename failed (see console).")}}).open()}deleteFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof ht.TFolder)){new ht.Notice("Couldn't find that folder.");return}let s=this.app.vault.getMarkdownFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e||o.path.startsWith(e+"/")).length,n=i.name;new vt(this.app,`Delete "${n}"?`,`This moves the entire folder \u2014 about ${s} note${s===1?"":"s"} plus its attachments and exports \u2014 to the trash. +`),"Swap",async r=>{if(!r)return;let l=t.parent??U;await this.swapParentChild(t,i,l)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new q.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(d=>d.id!==e.id).filter(d=>!!d.file),a=o.map(d=>({id:d.id,path:d.file.path,was:d.parent})),r=this.order.getOrder(s,i).slice(),l=this.order.getOrder(s,e.id).slice(),c=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,d=>{d.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,d=>{d.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let d of o)await this.app.fileManager.processFrontMatter(d.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(d.id,t.id,e.id);if(r.length>0){let d=r.includes(t.id)?r.map(I=>I===t.id?e.id:I):[...r.filter(I=>I!==e.id),e.id];this.order.setOrder(s,i,d)}let g=o.map(d=>d.id),p=[t.id,...l.filter(d=>d!==t.id&&!g.includes(d)),...g];this.order.setOrder(s,e.id,p),this.order.setOrder(s,t.id,[]),await this.order.save(s),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:i,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let d of a)await this.log.append({type:"parent_change",id:d.id,payload:{from:d.was,to:e.id,reason:"swap"}});this.tree.rebuild(s),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,...g],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let d=this.tree.get(t.id),I=this.tree.get(e.id);d?.file&&await this.app.fileManager.processFrontMatter(d.file,u=>{n==null||n===U?(delete u.parent,u.parent=U):u.parent=n}),I?.file&&await this.app.fileManager.processFrontMatter(I.file,u=>{u.parent=t.id});for(let u of a){let f=this.app.vault.getAbstractFileByPath(u.path);f&&await this.app.fileManager.processFrontMatter(f,C=>{u.was==null?C.parent=U:C.parent=u.was})}this.order.setOrder(s,i,r),this.order.setOrder(s,e.id,l),this.order.setOrder(s,t.id,c),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=r=>r??U;if(o(n)===o(e)){if(!i.quiet){let r=this.titleForNode(t),l=e===U?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${r}" is already under ${l}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==U&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let a=this.authorship.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(s,r=>{r.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),!i.quiet&&!i.silentSuccess){let r=this.tree.get(e),l=r?this.titleForNode(r):"(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===U?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let r=this.noteFolder,l=s.path,c=t.id;this.plugin.getUndoStack(r).push({label:"Move note",undo:async()=>{let g=this.app.vault.getAbstractFileByPath(l);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.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(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(c))return;let I=this.currentChildren.findIndex(u=>u.id===c);I<0||(this.selection.add(c),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}},redo:async()=>{let g=this.app.vault.getAbstractFileByPath(l);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.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(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(c))return;let I=this.currentChildren.findIndex(u=>u.id===c);I<0||(this.selection.add(c),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===U?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=r=>i.get(r.id)??0,a;if(t.length===1){let r=this.titleForNode(t[0]),l=o(t[0]);a=l>0?`Moved "${r}" and its ${l} ${l===1?"child":"children"} \u2192 ${n}`:`Moved "${r}" \u2192 ${n}`}else{let r=t.reduce((l,c)=>l+o(c),0);a=r>0?`Moved ${t.length} notes (${r} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===U?void 0:0,affectedIds:t.map(r=>r.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===U?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};var ht=require("obsidian");wt();Mt();var Vi=class h extends ht.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return ne}getDisplayText(){return"Stashpad folders"}getIcon(){return"folders"}async onOpen(){this.render(),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("layout-change",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("create",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender()))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},100))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-folderpanel-root");let e=this.clampFrac(this.plugin.settings.folderPanelPinnedFraction??.5),i=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-pinned"});i.style.flex=`0 0 ${(e*100).toFixed(2)}%`;let s=i.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"});s.createSpan({cls:"stashpad-folderpanel-heading-title",text:"Pinned"});let n=s.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(n,"list"),n.setAttr("aria-label","Pinned view options"),n.onclick=r=>{r.stopPropagation(),this.openPinnedOptionsMenu(r)},this.renderPinned(i.createDiv({cls:"stashpad-folderpanel-list stashpad-folderpanel-pins"}));let o=t.createDiv({cls:"stashpad-folderpanel-divider"});o.createDiv({cls:"stashpad-folderpanel-divider-grip"}),this.attachDividerDrag(t,i,o);let a=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-folders"});a.style.flex="1 1 0",a.createDiv({cls:"stashpad-folderpanel-heading"}).setText("Folders"),this.renderFolders(a.createDiv({cls:"stashpad-folderpanel-list"}))}clampFrac(t){return Number.isFinite(t)?Math.max(.15,Math.min(.85,t)):.5}attachDividerDrag(t,e,i){let s=null,n=a=>{let r=t.getBoundingClientRect();if(r.height<=0)return;let l=this.clampFrac((a.clientY-r.top)/r.height);s=l,e.style.flex=`0 0 ${(l*100).toFixed(2)}%`},o=a=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(a.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",a=>{a.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(a.pointerId)}catch{}document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)})}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new ht.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinned(t){let e=this.plugin.listPinnedNotes();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No pinned notes yet \u2014 pin a note from its right-click menu."});return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let s=new Map;e.forEach((a,r)=>{let l=s.get(a.folder);l||(l=[],s.set(a.folder,l)),l.push({...a,idx:r})});let n=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,o=Array.from(s.keys());n&&s.has(n)&&(o.splice(o.indexOf(n),1),o.unshift(n));for(let a of o){let r=t.createDiv({cls:"stashpad-pinned-group-header"});a===n&&r.addClass("is-active-folder"),r.createSpan({cls:"stashpad-pinned-group-name",text:a.split("/").pop()||a});for(let l of s.get(a)??[])this.renderPinNote(t,l.folder,l.id,l.file,l.idx)}}else e.forEach((s,n)=>this.renderPinNote(t,s.folder,s.id,s.file,n))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],l;!a&&!r?l=Date.now():a?r?l=(a.pinnedAt+r.pinnedAt)/2:l=a.pinnedAt+1e3:l=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=l})}catch(c){console.warn("[Stashpad] pin reorder failed",c)}this.render()}renderPinNote(t,e,i,s,n){let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,r=o.completed===!0,l=this.childrenOf(e,i),c=l.length>0,g=`${e}|${i}`,p=this.pinExpanded.has(g),d=t.createDiv({cls:"stashpad-pinned-row"});a&&(d.addClass("has-color"),d.style.setProperty("--stashpad-note-color",a)),r&&d.addClass("is-completed"),d.draggable=!0,d.dataset.pinIdx=String(n),d.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),d.addClass("is-dragging")}),d.addEventListener("dragend",()=>d.removeClass("is-dragging")),d.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=d.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;d.toggleClass("drop-before",E),d.toggleClass("drop-after",!E)}),d.addEventListener("dragleave",()=>{d.removeClass("drop-before"),d.removeClass("drop-after")}),d.addEventListener("drop",C=>{C.preventDefault(),d.removeClass("drop-before"),d.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let E=d.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?n:n+1)});let I=d.createSpan({cls:"stashpad-pinned-toggle"});c&&(de(I,l.length,p),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let u=d.createSpan({cls:"stashpad-pinned-icon"});(0,ht.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let f=d.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},d.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),d.oncontextmenu=C=>{C.preventDefault();let m=new ht.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},c&&p){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(C,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let r=typeof o.color=="string"?o.color:null,l=o.completed===!0,c=this.childrenOf(e,a),g=c.length>0,p=`${e}|${a}`,d=this.pinExpanded.has(p),I=t.createDiv({cls:"stashpad-pinned-subrow"});l&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});g&&(de(u,c.length,d),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,ht.setIcon)(f,"file-text"),r&&(f.style.color=r);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},g&&d&&this.renderPinSubtree(t,e,a,s+1)}}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===U&&(a==null||a===U)){if(o.id===U)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",a=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(a))}),i}onNavigateAway(){ht.Platform.isMobile&&(this.plugin.suppressComposerAutofocusUntil=Date.now()+1500,this.app.workspace.leftSplit?.collapse?.())}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}openFolders(){let t=new Set,e=(this.plugin.settings.folder||"Stashpad").replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(dt)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=h.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=h.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(h.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==U||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let l of e)switch(this.folderState(l)){case"pinned":s.push(l);break;case"downranked":o.push(l);break;case"hidden":a.push(l);break;default:n.push(l)}let r=[...s,...n,...o];if(r.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let l of r)this.renderFolderRow(t,l,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(h.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let a=o.createSpan({cls:"stashpad-folderpanel-dot"});if(a.setAttr("aria-label",n?"Open in a tab":"Not open"),n&&a.setAttr("title","Open in a tab"),s==="pinned"){let I=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,ht.setIcon)(I,"pin"),I.setAttr("aria-label","Pinned")}let r=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,ht.setIcon)(r,"folder");let l=this.folderHomeColor(e);l&&(r.style.color=l);let c=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:c});let g=o.createDiv({cls:"stashpad-folderpanel-actions"}),p=g.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(p,"folder-search"),p.setAttr("aria-label","Reveal in file explorer"),p.onclick=I=>{I.stopPropagation(),this.revealFolder(e)};let d=g.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(d,"plus-square"),d.setAttr("aria-label","Open in new tab"),d.onclick=I=>{I.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e)},o.onclick=()=>{this.onNavigateAway(),this.jumpToFolder(e)},o.oncontextmenu=I=>{I.preventDefault(),this.openFolderMenu(I,e)}}renderHiddenSection(t,e){let i=t.createDiv({cls:"stashpad-folderpanel-hidden"}),s=i.createDiv({cls:"stashpad-folderpanel-hidden-header"}),n=s.createSpan({cls:"stashpad-folderpanel-hidden-caret"});(0,ht.setIcon)(n,"chevron-right"),s.createSpan({cls:"stashpad-folderpanel-hidden-title",text:`Hidden (${e.length})`});let o=i.createDiv({cls:"stashpad-folderpanel-hidden-body"});o.style.display="none",s.onclick=()=>{let a=o.style.display!=="none";o.style.display=a?"none":"",(0,ht.setIcon)(n,a?"chevron-right":"chevron-down")};for(let a of e){let r=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),l=a.split("/").pop()||a;r.createSpan({cls:"stashpad-folderpanel-row-label",text:l});let c=r.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,ht.setIcon)(c,"eye"),c.setAttr("aria-label","Unhide"),c.onclick=g=>{g.stopPropagation(),this.setFolderState(a,"normal")}}}jumpToFolder(t){let e=t.replace(/\/+$/,""),i=this.app.workspace.getLeavesOfType(dt).find(s=>(s.view?.noteFolder??"").replace(/\/+$/,"")===e);if(i){this.app.workspace.revealLeaf(i);return}this.plugin.activateViewForFolder(t)}revealFolder(t){let e=this.app.vault.getAbstractFileByPath(t.replace(/\/+$/,""));if(!(e instanceof ht.TFolder)){new ht.Notice("Couldn't find that folder.");return}let i=this.app.workspace.getLeavesOfType("file-explorer")[0];if(!i){new ht.Notice("File explorer isn't available.");return}this.app.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}openFolderMenu(t,e){let i=new ht.Menu;i.addItem(n=>n.setTitle("Open in new tab").setIcon("plus-square").onClick(()=>void this.plugin.activateViewForFolder(e))),i.addItem(n=>n.setTitle("Reveal in file explorer").setIcon("folder-search").onClick(()=>this.revealFolder(e))),i.addSeparator();let s=this.folderState(e);i.addItem(n=>n.setTitle(s==="pinned"?"Unpin":"Pin to top").setIcon("pin").onClick(()=>void this.setFolderState(e,s==="pinned"?"normal":"pinned"))),i.addItem(n=>n.setTitle(s==="downranked"?"Remove downrank":"Downrank").setIcon("arrow-down").onClick(()=>void this.setFolderState(e,s==="downranked"?"normal":"downranked"))),i.addItem(n=>n.setTitle("Hide from list").setIcon("eye-off").onClick(()=>void this.setFolderState(e,"hidden"))),i.addSeparator(),i.addItem(n=>n.setTitle("Rename\u2026").setIcon("pencil").onClick(()=>this.renameFolder(e))),i.addSeparator(),i.addItem(n=>{n.setTitle("Delete folder\u2026").setIcon("trash").onClick(()=>this.deleteFolder(e)),n.setWarning?.(!0)}),i.showAtMouseEvent(t)}renameFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof ht.TFolder)){new ht.Notice("Couldn't find that folder.");return}let s=i.name;new Ls(this.app,s,async n=>{let o=n.trim().replace(/[\\/:]+/g,"").trim();if(!o||o===s)return;let r=`${i.parent?.path&&i.parent.path!=="/"?`${i.parent.path}/`:""}${o}`;if(this.app.vault.getAbstractFileByPath(r)){new ht.Notice(`"${o}" already exists.`);return}try{await this.app.fileManager.renameFile(i,r),(this.plugin.settings.folder||"").replace(/\/+$/,"")===e&&(this.plugin.settings.folder=r,await this.plugin.saveSettings()),new ht.Notice(`Renamed to "${o}".`)}catch(l){console.warn("[Stashpad] folder rename failed",l),new ht.Notice("Rename failed (see console).")}}).open()}deleteFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof ht.TFolder)){new ht.Notice("Couldn't find that folder.");return}let s=this.app.vault.getMarkdownFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e||o.path.startsWith(e+"/")).length,n=i.name;new vt(this.app,`Delete "${n}"?`,`This moves the entire folder \u2014 about ${s} note${s===1?"":"s"} plus its attachments and exports \u2014 to the trash. You can restore it from your system/Obsidian trash.`,"Delete folder",async o=>{o&&await this.plugin.deleteStashpadFolderWithUndo(i)}).open()}},Ls=class extends ht.Modal{constructor(t,e,i){super(t);this.current=e;this.onSubmit=i;this.delivered=!1}onOpen(){this.modalEl.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Rename folder");let t=this.contentEl.createEl("input",{type:"text"});t.addClass("stashpad-folderpanel-rename-input"),t.value=this.current;let e=this.contentEl.createDiv({cls:"stashpad-folderpanel-rename-footer"});e.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let i=e.createEl("button",{cls:"mod-cta",text:"Rename"}),s=()=>{this.delivered=!0;let n=t.value;this.close(),this.onSubmit(n)};i.onclick=s,this.scope.register([],"Enter",n=>{n.preventDefault(),t.value.trim()&&s()}),requestAnimationFrame(()=>{t.focus(),t.select()})}onClose(){this.contentEl.empty()}};async function Wi(h){let A=h.workspace.getLeavesOfType(ne);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new ht.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ne,active:!0}),h.workspace.revealLeaf(t)}me();var Xi=class{constructor(A,t,e){this.app=A;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 A=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let i of t)e=e?`${e}/${i}`:i,await A.exists(e)||await A.mkdir(e);this.dirOk=!0}append(A){let t=A.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...A};t?e.author=t:delete e.author;let i=JSON.stringify(e)+` -`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let s=this.app.vault.adapter;if(typeof s.append=="function")await s.append(this.logPath,i);else{let n=await s.exists(this.logPath)?await s.read(this.logPath):"";await s.write(this.logPath,n+i)}}catch(s){console.warn("Stashpad: log append failed",s)}}),Promise.resolve()}async readState(){let A=this.app.vault.adapter;if(!await A.exists(this.statePath))return{};try{return JSON.parse(await A.read(this.statePath))}catch{return{}}}async writeState(A){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(A,null,2))}};wt();var Zi=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(A){for(this.undoStack.push(A),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let A=this.undoStack.pop();if(!A)return null;try{await A.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(A),A}async redo(){let A=this.redoStack.pop();if(!A)return null;try{await A.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(A),A}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 $i=class{constructor(A,t){this.app=A;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 A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(A){console.warn("[Stashpad] author registry load failed; starting empty",A),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((A,t)=>(t.lastSeen??"").localeCompare(A.lastSeen??""))}get(A){return this.data.authors[A]??null}record(A){let t=(A.id??"").trim();if(!t)return!1;let e=A.at??new Date().toISOString(),i=(A.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:A.role?.trim()||void 0,department:A.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(i&&i!==s.name&&(s.renames.push({from:s.name,to:i,at:e}),s.name=i,n=!0),A.role!==void 0){let o=A.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(A.department!==void 0){let o=A.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(A,t){let e=t??new Date().toISOString(),i={};for(let s of A){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",r=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&r.push({from:o.name,to:a,at:e}),i[n]={id:n,name:a,role:s.role?.trim()||o?.role||void 0,department:s.department?.trim()||o?.department||void 0,firstSeen:o?.firstSeen??e,lastSeen:e,renames:r}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);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(A){console.warn("[Stashpad] author registry save failed",A)}}),this.writeChain}};var It=require("obsidian");wt();Rt();me();gi();Mt();var _i=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),ao="_archive",ro=new Set([te,"edtz"]),Me=class Me{constructor(A){this.plugin=A;this.pending=new Map;this.pendingFolders=new Map;this.suppressed=new Set;this.armed=!1;this.drainTimer=null;this.draining=!1;this.pendingEncryptedStashes=new Set;this.encryptedNotifySnoozeUntil=0}setArmed(A){this.armed=A}isArmed(){return this.armed}get app(){return this.plugin.app}enqueue(A){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(A)&&(this.pending.set(A.path,Date.now()),this.arm())}enqueueFolder(A){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(A.path))return;let t=A.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(_i.has(A.name)||(this.pendingFolders.set(A.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),Me.DEBOUNCE_MS)}suppress(A,t=4e3){this.suppressed.add(A),window.setTimeout(()=>this.suppressed.delete(A),t)}async createNote(A,t){this.suppress(A,6e4),await this.app.vault.create(A,t)}isEligiblePath(A){if(this.suppressed.has(A.path)||ro.has(A.extension))return!1;let t=A.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return _i.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(A){if(!this.isEligiblePath(A))return!1;if(A.extension==="md")try{let{fm:t}=be(await this.app.vault.read(A));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 A=[...this.pending.keys()];this.pending.clear();let t=A.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFile),e=[];for(let g of t)await this.isStillImportable(g)&&e.push(g);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFolder).map(g=>({folder:g,files:this.filesUnder(g.path)})).filter(g=>g.files.length>0),n=s.reduce((g,p)=>g+p.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,r=[],c=e.filter(g=>this.plugin.importLog.findDuplicate(g.name,g.stat?.size??null));if(c.length>0){let g=c.slice(0,5).map(I=>`\u2022 ${I.name}`).join(` -`),p=c.length>5?` -\u2026and ${c.length-5} more`:"",d=await this.dupChoice(`${c.length} of these look like files you've imported before: +`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let s=this.app.vault.adapter;if(typeof s.append=="function")await s.append(this.logPath,i);else{let n=await s.exists(this.logPath)?await s.read(this.logPath):"";await s.write(this.logPath,n+i)}}catch(s){console.warn("Stashpad: log append failed",s)}}),Promise.resolve()}async readState(){let A=this.app.vault.adapter;if(!await A.exists(this.statePath))return{};try{return JSON.parse(await A.read(this.statePath))}catch{return{}}}async writeState(A){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(A,null,2))}};wt();var Zi=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(A){for(this.undoStack.push(A),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let A=this.undoStack.pop();if(!A)return null;try{await A.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(A),A}async redo(){let A=this.redoStack.pop();if(!A)return null;try{await A.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(A),A}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 $i=class{constructor(A,t){this.app=A;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 A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(A){console.warn("[Stashpad] author registry load failed; starting empty",A),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((A,t)=>(t.lastSeen??"").localeCompare(A.lastSeen??""))}get(A){return this.data.authors[A]??null}record(A){let t=(A.id??"").trim();if(!t)return!1;let e=A.at??new Date().toISOString(),i=(A.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:A.role?.trim()||void 0,department:A.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(i&&i!==s.name&&(s.renames.push({from:s.name,to:i,at:e}),s.name=i,n=!0),A.role!==void 0){let o=A.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(A.department!==void 0){let o=A.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(A,t){let e=t??new Date().toISOString(),i={};for(let s of A){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",r=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&r.push({from:o.name,to:a,at:e}),i[n]={id:n,name:a,role:s.role?.trim()||o?.role||void 0,department:s.department?.trim()||o?.department||void 0,firstSeen:o?.firstSeen??e,lastSeen:e,renames:r}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);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(A){console.warn("[Stashpad] author registry save failed",A)}}),this.writeChain}};var It=require("obsidian");wt();Rt();me();gi();Mt();var _i=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),ao="_archive",ro=new Set([te,"edtz"]),Me=class Me{constructor(A){this.plugin=A;this.pending=new Map;this.pendingFolders=new Map;this.suppressed=new Set;this.armed=!1;this.drainTimer=null;this.draining=!1;this.pendingEncryptedStashes=new Set;this.encryptedNotifySnoozeUntil=0}setArmed(A){this.armed=A}isArmed(){return this.armed}get app(){return this.plugin.app}enqueue(A){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(A)&&(this.pending.set(A.path,Date.now()),this.arm())}enqueueFolder(A){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(A.path))return;let t=A.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(_i.has(A.name)||(this.pendingFolders.set(A.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),Me.DEBOUNCE_MS)}suppress(A,t=4e3){this.suppressed.add(A),window.setTimeout(()=>this.suppressed.delete(A),t)}async createNote(A,t){this.suppress(A,6e4),await this.app.vault.create(A,t)}isEligiblePath(A){if(this.suppressed.has(A.path)||ro.has(A.extension))return!1;let t=A.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return _i.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(A){if(!this.isEligiblePath(A))return!1;if(A.extension==="md")try{let{fm:t}=be(await this.app.vault.read(A));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 A=[...this.pending.keys()];this.pending.clear();let t=A.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFile),e=[];for(let g of t)await this.isStillImportable(g)&&e.push(g);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFolder).map(g=>({folder:g,files:this.filesUnder(g.path)})).filter(g=>g.files.length>0),n=s.reduce((g,p)=>g+p.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,r=[],l=e.filter(g=>this.plugin.importLog.findDuplicate(g.name,g.stat?.size??null));if(l.length>0){let g=l.slice(0,5).map(I=>`\u2022 ${I.name}`).join(` +`),p=l.length>5?` +\u2026and ${l.length-5} more`:"",d=await this.dupChoice(`${l.length} of these look like files you've imported before: ${g}${p} -Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(d==="skip"){let I=new Set(c.map(u=>u.path));if(a=e.filter(u=>!I.has(u.path)),a.length===0&&s.length===0){new It.Notice(`Skipped ${c.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(d==="replace")for(let I of c){let u=this.plugin.importLog.findDuplicate(I.name,I.stat?.size??null);for(let f of u?.notePaths??[]){let C=this.app.vault.getAbstractFileByPath(f);if(C instanceof It.TFile)try{r.push({path:f,content:await this.app.vault.read(C)}),await this.app.fileManager.trashFile(C)}catch(m){console.warn("[Stashpad] replace: couldn't remove prior note",f,m)}}}}if(o=a.length+n,o>=Me.BATCH_CONFIRM_AT){let g=s.length?` (incl. ${s.length} folder${s.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${o} files into Stashpad${g}. Proceed? -Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new It.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let l=[];for(let g of a)try{let p=g.stat?.size??null,d=g.extension==="md"?await this.importMarkdown(g):await this.importOtherFile(g);d&&(l.push(d),this.plugin.importLog.append({ts:new Date().toISOString(),folder:d.folder,kind:d.kind,originalName:g.name,size:p,sourcePath:g.path,notePaths:d.kind==="folder"?d.notePaths:[d.notePath]}))}catch(p){console.warn("[Stashpad] import failed",g.path,p)}for(let{folder:g}of s)try{let p=await this.importFolder(g);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:g.path,notePaths:p.notePaths}))}catch(p){console.warn("[Stashpad] folder import failed",g.path,p)}(l.length>0||r.length>0)&&this.announce(l,r)}finally{this.draining=!1}}}async importMarkdown(A){let t=A.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(A),{fm:i,body:s}=be(e),n=`${t}/${ao}`;await this.ensureFolder(n);let o=await this.uniquePath(n,A.name);if(await this.app.fileManager.renameFile(A,o),!(this.app.vault.getAbstractFileByPath(o)instanceof It.TFile))throw new Error(`archive move failed for ${A.path} \u2014 import aborted to avoid data loss`);let a={};for(let[g,p]of Object.entries(i))Wt.includes(g)||(a[g]=p);a.id=yt(),a.parent=U;let r=this.preservedTimes(i,A);a.created=r.created,r.modified&&(a.modified=r.modified),a.attachments=Array.isArray(i.attachments)?i.attachments:[],i.author!==void 0&&(a.author=i.author),i.contributors!==void 0&&(a.contributors=i.contributors),a.imported=!0;let c=Dt(s)||A.basename,l=await this.uniquePath(t,bt(c,a.id));return await this.createNote(l,ee(a,s)),{kind:"md",folder:t,archivePath:o,notePath:l,originalName:A.name}}async importOtherFile(A){let t=A.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,A.name);await this.app.fileManager.renameFile(A,i);let s=A.basename,n=yt(),o={id:n,parent:U,created:new Date().toISOString(),attachments:[Gt(i)],imported:!0},a=`${s} +Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(d==="skip"){let I=new Set(l.map(u=>u.path));if(a=e.filter(u=>!I.has(u.path)),a.length===0&&s.length===0){new It.Notice(`Skipped ${l.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(d==="replace")for(let I of l){let u=this.plugin.importLog.findDuplicate(I.name,I.stat?.size??null);for(let f of u?.notePaths??[]){let C=this.app.vault.getAbstractFileByPath(f);if(C instanceof It.TFile)try{r.push({path:f,content:await this.app.vault.read(C)}),await this.app.fileManager.trashFile(C)}catch(m){console.warn("[Stashpad] replace: couldn't remove prior note",f,m)}}}}if(o=a.length+n,o>=Me.BATCH_CONFIRM_AT){let g=s.length?` (incl. ${s.length} folder${s.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${o} files into Stashpad${g}. Proceed? +Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new It.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let c=[];for(let g of a)try{let p=g.stat?.size??null,d=g.extension==="md"?await this.importMarkdown(g):await this.importOtherFile(g);d&&(c.push(d),this.plugin.importLog.append({ts:new Date().toISOString(),folder:d.folder,kind:d.kind,originalName:g.name,size:p,sourcePath:g.path,notePaths:d.kind==="folder"?d.notePaths:[d.notePath]}))}catch(p){console.warn("[Stashpad] import failed",g.path,p)}for(let{folder:g}of s)try{let p=await this.importFolder(g);p&&p.kind==="folder"&&(c.push(p),this.plugin.importLog.append({ts:new Date().toISOString(),folder:p.folder,kind:"folder",originalName:p.originalName,size:null,sourcePath:g.path,notePaths:p.notePaths}))}catch(p){console.warn("[Stashpad] folder import failed",g.path,p)}(c.length>0||r.length>0)&&this.announce(c,r)}finally{this.draining=!1}}}async importMarkdown(A){let t=A.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(A),{fm:i,body:s}=be(e),n=`${t}/${ao}`;await this.ensureFolder(n);let o=await this.uniquePath(n,A.name);if(await this.app.fileManager.renameFile(A,o),!(this.app.vault.getAbstractFileByPath(o)instanceof It.TFile))throw new Error(`archive move failed for ${A.path} \u2014 import aborted to avoid data loss`);let a={};for(let[g,p]of Object.entries(i))Wt.includes(g)||(a[g]=p);a.id=yt(),a.parent=U;let r=this.preservedTimes(i,A);a.created=r.created,r.modified&&(a.modified=r.modified),a.attachments=Array.isArray(i.attachments)?i.attachments:[],i.author!==void 0&&(a.author=i.author),i.contributors!==void 0&&(a.contributors=i.contributors),a.imported=!0;let l=Dt(s)||A.basename,c=await this.uniquePath(t,bt(l,a.id));return await this.createNote(c,ee(a,s)),{kind:"md",folder:t,archivePath:o,notePath:c,originalName:A.name}}async importOtherFile(A){let t=A.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,A.name);await this.app.fileManager.renameFile(A,i);let s=A.basename,n=yt(),o={id:n,parent:U,created:new Date().toISOString(),attachments:[Gt(i)],imported:!0},a=`${s} ![[${i}]] -`,r=Dt(s)||s,c=await this.uniquePath(t,bt(r,n));return await this.createNote(c,ee(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:c,originalName:A.name}}preservedTimes(A,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(A.created)?A.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(A.modified)?A.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(A){let t=A.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(A){let t=A.parent.path.replace(/\/+$/,""),e=A.name,i=`${t}/${ao}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(A,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let l of this.app.vault.getMarkdownFiles()){if((l.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let g=this.app.metadataCache.getFileCache(l)?.frontmatter?.id;typeof g=="string"&&g&&o.add(g)}let a=[],r=[],c=await this.createFolderNote(t,e,U,r,o);return n instanceof It.TFolder&&await this.buildNotesFromArchive(n,t,c,r,o,a),a.length&&new It.Notice(`Stashpad: ${a.length} attachment name collision(s) renamed on import \u2014 check ![[links]] in the imported notes.`),{kind:"folder",folder:t,archivePath:s,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(A,t,e,i,s){let n=yt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Dt(t)||t,r=await this.uniquePath(A,bt(a,n));return await this.createNote(r,ee(o,`${t} -`)),i.push(r),n}async mergeReservedFolder(A,t,e){await this.ensureFolder(t);for(let i of[...A.children])if(i instanceof It.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof It.TFile){let s=`${t}/${i.name}`;await this.app.vault.adapter.exists(s)&&(s=await this.uniquePath(t,i.name),e.push(`${i.name} \u2192 ${s.split("/").pop()}`)),await this.app.fileManager.renameFile(i,s)}}async buildNotesFromArchive(A,t,e,i,s,n){for(let o of[...A.children])if(o instanceof It.TFolder)if(_i.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let a=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,a,i,s,n)}else if(o instanceof It.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:r,body:c}=be(a),l={};for(let[f,C]of Object.entries(r))Wt.includes(f)||(l[f]=C);let g=typeof r.id=="string"&&r.id?r.id:null,p=g&&!s.has(g)?g:yt();s.add(p),l.id=p,l.parent=e;let d=this.preservedTimes(r,o);l.created=d.created,d.modified&&(l.modified=d.modified),l.attachments=Array.isArray(r.attachments)?r.attachments:[];let I=Dt(c)||o.basename,u=await this.uniquePath(t,bt(I,l.id));await this.createNote(u,ee(l,c)),i.push(u)}else{if(ro.has(o.extension))continue;{let a=yt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[Gt(o.path)]},c=`${o.basename} +`,r=Dt(s)||s,l=await this.uniquePath(t,bt(r,n));return await this.createNote(l,ee(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:l,originalName:A.name}}preservedTimes(A,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(A.created)?A.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(A.modified)?A.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(A){let t=A.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(A){let t=A.parent.path.replace(/\/+$/,""),e=A.name,i=`${t}/${ao}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(A,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let c of this.app.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let g=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof g=="string"&&g&&o.add(g)}let a=[],r=[],l=await this.createFolderNote(t,e,U,r,o);return n instanceof It.TFolder&&await this.buildNotesFromArchive(n,t,l,r,o,a),a.length&&new It.Notice(`Stashpad: ${a.length} attachment name collision(s) renamed on import \u2014 check ![[links]] in the imported notes.`),{kind:"folder",folder:t,archivePath:s,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(A,t,e,i,s){let n=yt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Dt(t)||t,r=await this.uniquePath(A,bt(a,n));return await this.createNote(r,ee(o,`${t} +`)),i.push(r),n}async mergeReservedFolder(A,t,e){await this.ensureFolder(t);for(let i of[...A.children])if(i instanceof It.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof It.TFile){let s=`${t}/${i.name}`;await this.app.vault.adapter.exists(s)&&(s=await this.uniquePath(t,i.name),e.push(`${i.name} \u2192 ${s.split("/").pop()}`)),await this.app.fileManager.renameFile(i,s)}}async buildNotesFromArchive(A,t,e,i,s,n){for(let o of[...A.children])if(o instanceof It.TFolder)if(_i.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let a=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,a,i,s,n)}else if(o instanceof It.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:r,body:l}=be(a),c={};for(let[f,C]of Object.entries(r))Wt.includes(f)||(c[f]=C);let g=typeof r.id=="string"&&r.id?r.id:null,p=g&&!s.has(g)?g:yt();s.add(p),c.id=p,c.parent=e;let d=this.preservedTimes(r,o);c.created=d.created,d.modified&&(c.modified=d.modified),c.attachments=Array.isArray(r.attachments)?r.attachments:[];let I=Dt(l)||o.basename,u=await this.uniquePath(t,bt(I,c.id));await this.createNote(u,ee(c,l)),i.push(u)}else{if(ro.has(o.extension))continue;{let a=yt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[Gt(o.path)]},l=`${o.basename} ![[${o.path}]] -`,l=Dt(o.basename)||o.basename,g=await this.uniquePath(t,bt(l,a));await this.createNote(g,ee(r,c)),i.push(g)}}}recordNotePaths(A){return A.kind==="folder"?A.notePaths:[A.notePath]}announce(A,t=[]){let e=A[0]?.folder??"",i=A.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(A,t))};this.plugin.notifications.show({message:`Imported ${i} file${i===1?"":"s"}${s} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:A.flatMap(a=>this.recordNotePaths(a)),actions:[{label:"Undo import",onClick:()=>void o()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${i} file${i===1?"":"s"}`,undo:async()=>{await o()},redo:async()=>{}})}async undo(A,t=[]){for(let e of A)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else if(e.kind==="file"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else{for(let s of e.notePaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof It.TFolder){let s=await this.uniquePath(e.folder,e.originalName);this.suppress(s),await this.app.fileManager.renameFile(i,s)}}}catch(i){console.warn("[Stashpad] import undo failed",e,i)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(i){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,i)}new It.Notice(`Undid import of ${A.length} file(s).`)}pickFilesInto(A){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 i=[];for(let n of e)try{let o=await n.arrayBuffer(),a=await this.uniquePath(A,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let r=this.app.vault.getAbstractFileByPath(a);r instanceof It.TFile&&i.push(r)}catch(o){console.warn("[Stashpad] file-picker write failed",n.name,o)}if(i.length===0)return;await this.plugin.importLog.load();let s=[];for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),i=[];for(let n of e)await this.isStillImportable(n)&&i.push(n);if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] loose-file import failed",n.path,o)}return s}async importLooseFoldersIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof It.TFolder))return 0;let i=e.children.filter(n=>n instanceof It.TFolder&&!_i.has(n.name));if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i){let o=n.path;try{let a=await this.importFolder(n);a&&a.kind==="folder"&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:null,sourcePath:o,notePaths:a.notePaths}))}catch(a){console.warn("[Stashpad] loose-folder import failed",o,a)}}return s}pendingEncryptedPaths(){for(let A of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(A)instanceof It.TFile||this.pendingEncryptedStashes.delete(A);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(A){this.pendingEncryptedStashes.delete(A)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(A){this.encryptedNotifySnoozeUntil=A===1/0?Number.MAX_SAFE_INTEGER:Date.now()+A}parkEncrypted(A){return this.pendingEncryptedStashes.has(A)?!1:(this.pendingEncryptedStashes.add(A),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let A=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof It.TFile))continue;let s=i.parent?.path?.replace(/\/+$/,"")??"";if(await this.importOneStash(i,s,this.liveRootIds(s),!1,{allowLater:!0,onLater:()=>{t=!0,this.snoozeEncryptedNotify(60*60*1e3)}})&&A++,t)break}return{imported:A,rescheduled:t}}liveRootIds(A){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==A)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(A,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(A));if(i&&Ne(n))return this.pendingEncryptedStashes.add(A.path),!1;let o=await xe(this.app,n,{...s,secretId:Pe(A.basename)});if(!o)return!1;let a=await De(this.app,o,t,e);try{await this.app.fileManager.trashFile(A)}catch{}this.pendingEncryptedStashes.delete(A.path);try{await this.plugin.newLog().append({type:"stash_import",id:U,payload:{from:A.path,into:t,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,loose:!0}})}catch{}return!0}catch(n){return console.warn("[Stashpad] loose .stash import failed",A.path,n),!1}}async importLooseStashesIn(A,t={}){let e=A.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===te);if(i.length===0)return 0;let s=this.liveRootIds(e),n=0;for(let o of i)await this.importOneStash(o,e,s,!!t.auto)&&n++;return n}async importLooseInto(A,t={}){let e=await this.importLooseFilesIn(A),i=await this.importLooseFoldersIn(A),s=await this.importLooseStashesIn(A,t);return{files:e,folders:i,stashes:s}}defaultDestination(){let t=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder;return t&&this.plugin.discoverStashpadFolders().includes(t)?t:this.plugin.discoverStashpadFolders()[0]??null}confirm(A,t,e){return new Promise(i=>{new vt(this.app,A,t,e,i).open()})}dupChoice(A){return new Promise(t=>{new Ve(this.app,A,t).open()})}async ensureFolder(A){let t=this.app.vault.adapter,e=A.split("/").filter(Boolean),i="";for(let s of e){i=i?`${i}/${s}`:s;try{await t.exists(i)||await t.mkdir(i)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(A,t){let e=this.app.vault.adapter,i=t.lastIndexOf("."),s=i>0?t.slice(0,i):t,n=i>0?t.slice(i):"",o=`${A}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${A}/${s}-${a}${n}`;return o}};Me.DEBOUNCE_MS=900,Me.BATCH_CONFIRM_AT=8;var ji=Me;var ts=class{constructor(A,t){this.app=A;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 A=this.app.vault.adapter;if(await A.exists(this.path)){let t=await A.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(A){console.warn("[Stashpad] import log load failed",A)}}}recent(){return[...this.entries].reverse()}findDuplicate(A,t){for(let e=this.entries.length-1;e>=0;e--){let i=this.entries[e];if(i.originalName===A&&(t==null||i.size==null||i.size===t))return i}return null}append(A){this.entries.push(A),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(A)+` -`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}};var is=class is{constructor(A,t){this.app=A;this.map=new Map;this.loaded=!1;this.dirty=!1;this.saveTimer=null;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/render-cache.json`}async load(){if(!this.loaded){this.loaded=!0;try{let A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));if(t?.schema===1&&t.entries){for(let[e,i]of Object.entries(t.entries))this.map.set(e,i);for(let e of[...this.map.keys()])this.app.vault.getAbstractFileByPath(e)||(this.map.delete(e),this.dirty=!0)}}}catch(A){console.warn("[Stashpad] render cache load failed; starting empty",A),this.map.clear()}}}get(A){return this.map.get(A)}has(A){return this.map.has(A)}set(A,t){this.map.set(A,t),this.dirty=!0,this.scheduleSave()}scheduleSave(){this.saveTimer==null&&(this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},is.SAVE_DEBOUNCE_MS))}save(){return this.saveTimer!=null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.dirty?(this.dirty=!1,this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let A={schema:1,entries:Object.fromEntries(this.map)};await this.app.vault.adapter.write(this.path,JSON.stringify(A))}catch(A){console.warn("[Stashpad] render cache save failed",A)}}),this.writeChain):this.writeChain}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}};is.SAVE_DEBOUNCE_MS=8e3;var es=is;var Js="stashpad:unghost-after-reload",ss=class extends tt.Plugin{constructor(){super(...arguments);this.settings={...Zt};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.suppressComposerAutofocusUntil=0;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this._renderCacheStore=null;this.knownStashpadFolders=new Set;this.suppressedFolderDeletes=new Set;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.reHomePending=new Set;this.autoSweepInProgress=!1;this.notifPersistenceWired=!1;this.notifSaveTimer=null;this.LAST_CURSOR_LS_KEY="stashpad:last-cursor";this.LAST_SELECTION_LS_KEY="stashpad:last-selection";this.writeChain=Promise.resolve()}get notifications(){return this._notifications||(this._notifications=new Ei(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new $i(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new ji(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new ts(this.app,this.pluginPrivatePath())),this._importLog}get renderCacheStore(){return this._renderCacheStore||(this._renderCacheStore=new es(this.app,this.pluginPrivatePath())),this._renderCacheStore}async onunload(){try{await this._renderCacheStore?.save()}catch{}}pluginPrivatePath(t=""){let i=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${i}/${t.replace(/^\/+/,"")}`:i}newLog(){return new Xi(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),i=async()=>{let a=e.split("/").filter(Boolean),r="";for(let c of a)r=r?`${r}/${c}`:c,await t.exists(r)||await t.mkdir(r)},s=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(s)&&!await t.exists(n))try{await i();let a=await t.read(s);await t.write(n,a),console.debug("[Stashpad] migrated data.json \u2192",n)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let o=".stashpad";if(await t.exists(o))try{await i();let a=await t.list(o);for(let r of a.files){let c=r.replace(/^.*\//,""),l=this.pluginPrivatePath(c);if(!await t.exists(l))try{let g=await t.read(r);await t.write(l,g),console.debug("[Stashpad] migrated",r,"\u2192",l)}catch(g){console.warn(`Stashpad: failed to migrate ${r}`,g)}}}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(i){return console.warn("Stashpad: data.json parse failed",i),null}}async saveData(t){let e=this.app.vault.adapter,i=this.pluginPrivatePath();if(!await e.exists(i)){let s=i.split("/").filter(Boolean),n="";for(let o of s)n=n?`${n}/${o}`:o,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 i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let c of s)n=n?`${n}/${c}`:c,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let c=this.app.vault.getAbstractFileByPath(o);c&&await this.app.fileManager.processFrontMatter(c,l=>{(typeof l.id!="string"||!l.id)&&(l.id=U),"parent"in l||(l.parent=null),(typeof l.created!="string"||!l.created)&&(l.created=new Date().toISOString())});return}let a=new Date().toISOString(),r=["---",`id: ${U}`,"parent: null",`created: ${a}`,"---","Home"].join(` -`);await this.app.vault.create(o,r);try{await this.seedLocalAuthorStub(e)}catch{}}collectColorsInFolder(t){let e=new Map,i=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==i&&!o.startsWith(i+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=typeof a?.color=="string"?a.color.trim():"";if(!r||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(r))continue;let c=r.toLowerCase();e.set(c,(e.get(c)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let r of this.app.vault.getMarkdownFiles()){let c=r.parent?.path?.replace(/\/+$/,"")??"";if(c!==s&&!c.startsWith(s+"/"))continue;let l=this.app.metadataCache.getFileCache(r)?.frontmatter;if((typeof l?.color=="string"?l.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(r,p=>{i?p.color=i:delete p.color}),o++}catch(p){console.warn(`Stashpad: recolor failed for ${r.path}`,p)}}let a=this.settings.colorAliases?.[s];if(a){let r=a[n];r&&(delete a[n],i&&(a[i.toLowerCase()]=r),Object.keys(a).length===0&&delete this.settings.colorAliases[s],await this.saveSettings())}return o}getColorAlias(t,e){let i=t.replace(/\/+$/,""),s=this.settings.colorAliases?.[i];if(!s)return;let n=s[e.toLowerCase()];return n&&n.trim()?n:void 0}async setColorAlias(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[s]||(this.settings.colorAliases[s]={});let o=this.settings.colorAliases[s],a=i.trim();a?o[n]=a:delete o[n],Object.keys(o).length===0&&delete this.settings.colorAliases[s],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let i=t.trim().replace(/^\/+|\/+$/g,"");if(!i)return;let s=Date.now();for(;Date.now()-s<e;){if(this.discoverStashpadFolders().includes(i))return;await new Promise(n=>setTimeout(n,80))}}discoverStashpadFolders(){let t=new Set;for(let i of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(i)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let n=i.parent?.path?.replace(/\/+$/,"")??"";n&&t.add(n)}let e=[...t].sort();return this.knownStashpadFolders=new Set(e),e}closeStashpadTabsFor(t){let e=0;for(let i of this.app.workspace.getLeavesOfType(dt)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(a=>a!==t&&!a.startsWith(t+"/")),s=(e.folderPanelPinned?.length??0)+(e.folderPanelDownranked?.length??0)+(e.folderPanelHidden?.length??0);e.folderPanelPinned=i(e.folderPanelPinned),e.folderPanelDownranked=i(e.folderPanelDownranked),e.folderPanelHidden=i(e.folderPanelHidden),e.folderPanelPinned.length+e.folderPanelDownranked.length+e.folderPanelHidden.length!==s&&await this.saveSettings()}async deleteStashpadFolderWithUndo(t){let e=t.path.replace(/\/+$/,""),i=t.name,s=this.app.vault.adapter,n=".trash";try{await s.exists(n)||await s.mkdir(n)}catch(c){console.warn("[Stashpad] couldn't ensure .trash",c)}let o=`${n}/${i}`;for(let c=1;await s.exists(o);c++)o=`${n}/${i} (${c})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let a=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(c){console.warn("[Stashpad] folder delete failed",c),this.suppressedFolderDeletes.delete(e),new tt.Notice("Delete failed (see console).");return}let r=a>0?`Deleted \u201C${i}\u201D \u2014 closed ${a} open tab${a===1?"":"s"}.`:`Deleted \u201C${i}\u201D.`;this.notifications.show({message:r,kind:"warning",category:"delete",duration:0,folder:e,actions:[{label:"Undo",onClick:async()=>{try{if(await s.exists(e)){new tt.Notice(`Can't undo \u2014 \u201C${i}\u201D already exists.`);return}this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3),await s.rename(o,e),new tt.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(c){console.warn("[Stashpad] folder undo failed",c),new tt.Notice("Undo failed (see console).")}}}]})}async handleStashpadFolderDeleted(t){let e=t.replace(/\/+$/,"");if(!e||this.suppressedFolderDeletes.has(e))return;let i=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);let s=e.split("/").pop()||e;this.notifications.show({message:i>0?`Stashpad \u201C${s}\u201D was deleted \u2014 closed ${i} open tab${i===1?"":"s"}.`:`Stashpad \u201C${s}\u201D was deleted.`,kind:"warning",category:"delete",folder:e})}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),i=new Set(this.settings.searchExcludedFolders),n=this.discoverStashpadFolders().filter(r=>e.size>0?e.has(r):!i.has(r)),o=(t||"").trim().replace(/\/+$/,""),a=n.filter(r=>r!==o);return o&&a.unshift(o),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 i=this.newLog(),s={},n=this.app.vault.getMarkdownFiles().filter(c=>c.path===t||c.path.startsWith(t+"/"));for(let c of n){let l=this.app.metadataCache.getFileCache(c)?.frontmatter,g=typeof l?.id=="string"?l.id.trim():"";if(!g)continue;let p=l&&"parent"in l?l.parent??null:null;s[g]={parent:p,path:c.path}}let o=await i.readState(),a=c=>c===t||c.startsWith(t+"/");if(!e.silent){for(let[c,l]of Object.entries(s)){let g=o[c];g?g.parent!==l.parent?await i.append({type:"parent_change",id:c,payload:{from:g.parent,to:l.parent}}):g.path!==l.path&&await i.append({type:"rename",id:c,payload:{from:g.path,to:l.path}}):await i.append({type:"create",id:c,payload:{path:l.path,parent:l.parent}})}for(let[c,l]of Object.entries(o))!s[c]&&a(l.path)&&await i.append({type:"missing",id:c,payload:{lastPath:l.path}})}let r={};for(let[c,l]of Object.entries(o))a(l.path)||(r[c]=l);for(let[c,l]of Object.entries(s))r[c]=l;await i.writeState(r)}catch(i){console.warn("Stashpad: integrity sweep failed",i)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new Zi,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),St.enabled=!!this.settings.enablePerfProfiling,this.settingTab=new ki(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),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),window.setTimeout(()=>void this.runAutoImportSweep(),5e3),this.registerInterval(window.setInterval(()=>void this.runAutoImportSweep(),5*60*1e3)),window.setTimeout(()=>void this.migratePinnedNotesToFrontmatter(),3e3),window.setTimeout(()=>void this.unghostStashpadTabsIfFlagged(),1200)}),this.registerView(dt,d=>new zi(d,this)),this.registerView(oe,d=>new Di(d,this)),this.registerView(Vt,d=>new ui(d,this)),this.registerView(ne,d=>new Vi(d,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",d=>{d&&d.view.getViewType()===dt&&(this.lastActiveStashpadLeaf=d,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(oe).length===0&&setTimeout(()=>{bi(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let d=qt(),I=!!d&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===d,u=!!I&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",u),document.body.classList.toggle("stashpad-active",!!I)};this.register(gn(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=d=>{try{let I=Array.from(document.querySelectorAll("style")).filter(u=>(u.textContent??"").includes(".stashpad-"));for(let u of I){let f=u.id||"",C=f?`style[data-stashpad-source="${f}"]`:null;if(C&&d.head.querySelector(C))continue;let m=d.createElement("style");f?m.setAttribute("data-stashpad-source",f):m.setAttribute("data-stashpad-source","anon"),m.textContent=u.textContent??"",d.head.appendChild(m)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",d=>{let I=d?.doc??d?.win?.document??null;I&&e(I)})),this.registerEvent(this.app.workspace.on("file-menu",(d,I)=>{if(!(I instanceof tt.TFolder))return;let u=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(u)&&d.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(u))})})),setTimeout(()=>{try{let d=this.app.workspace;typeof d.iterateAllLeaves=="function"&&d.iterateAllLeaves(I=>{let u=I?.view?.containerEl?.ownerDocument;u&&u!==document&&e(u)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let i=window.visualViewport,s=()=>{let d=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=d&&d.isConnected?d.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${I}px`);let u=0;i&&(u=Math.max(0,window.innerHeight-i.height-i.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${u}px`),document.body.classList.toggle("stashpad-keyboard-open",u>100)};s(),i&&(i.addEventListener("resize",s),i.addEventListener("scroll",s),this.register(()=>{i.removeEventListener("resize",s),i.removeEventListener("scroll",s)})),window.addEventListener("resize",s),this.register(()=>window.removeEventListener("resize",s)),requestAnimationFrame(s),setTimeout(s,250),setTimeout(s,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)",()=>{fi(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Wi(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{bi(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})}),this.addCommand({id:"stashpad-focus-last-tab",name:"Focus last Stashpad tab",callback:()=>void this.focusLastStashpadTab()}),this.addCommand({id:"stashpad-focus-folder-panel",name:"Focus folder panel",callback:()=>void this.focusFolderPanel()});let o=d=>{let I=qt();I&&typeof I[d]=="function"&&I[d]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>o("toggleSplit")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>o("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>o("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>o("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>o("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>o("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>o("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>o("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>o("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>o("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>o("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>o("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>o("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>o("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>o("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>o("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>o("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>o("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>o("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>o("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>o("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>o("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>o("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>o("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>o("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>o("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>o("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>o("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>o("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>o("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>o("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>o("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new tt.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let d=St.report();console.log(d);try{await navigator.clipboard.writeText(d)}catch{}new tt.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{St.reset(),new tt.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>o("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>o("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>o("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(()=>(Mt(),We));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-import-loose-files",name:"Import loose files & folders in this folder (scan for moved-in / unprocessed items)",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderFrontmatterBackfill(I),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>o("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>o("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void fi(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void Wi(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void bi(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:d=>{let I=this.app.workspace.getActiveFile(),u=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return d||u&&I&&this.revealNoteInStashpad(I),u}});let a=Object.keys(Xe);for(let d of a){let I=Xe[d];this.addCommand({id:`stashpad-open-panels-${d}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await fi(this.app),this.app.workspace.getLeavesOfType(Vt)[0]?.view?.setActivePanel?.(d)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>o("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>o("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:()=>o("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>o("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>o("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>o("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>o("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 I=qt(),u=I&&I.noteFolder;return u?(d||(new tt.Notice(`Running integrity check on "${u}"\u2026`),this.runIntegrityCheckOnFolder(u).then(()=>{new tt.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 tt.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 tt.Notice(`Author registry rebuild failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new tt.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 tt.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 tt.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:d,fmChecked:I,fmWritten:u,slugsRenamed:f,authors:C,imported:m,attachmentsLinked:E}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${d.length} folder${d.length===1?"":"s"}`),m>0&&w.push(`imported ${m} loose file${m===1?"":"s"}`),E>0&&w.push(`linked attachments on ${E} note${E===1?"":"s"}`),u>0&&w.push(`updated ${u} note${u===1?"":"s"}' metadata`),f>0&&w.push(`renamed ${f} note${f===1?"":"s"}`),C>0&&w.push(`${C} author${C===1?"":"s"} in registry`),w.push(`(checked ${I} total)`),new tt.Notice(`Stashpad: ${w.join(" \xB7 ")}`)}catch(d){new tt.Notice(`Stashpad: rebootstrap failed (${d.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:d=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(d||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Mt(),We)).then(({NotificationHistoryModal:d,LogModal:I})=>{new d(this.app,this.notifications,async()=>{let u=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await u.exists(f)){new tt.Notice("No log yet \u2014 make some changes first.");return}let C=await u.read(f);new I(this.app,C,f).open()},this.settings.authorId||null,u=>this.lookupNoteAuthorIds(u)).open()})}});let r=[{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 r){let I=`stashpad-toggle-${String(d.key).replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${d.label}`,callback:async()=>{let u=!this.settings[d.key];this.settings[d.key]=u,await this.saveSettings(),new tt.Notice(`${d.label}: ${u?"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(()=>{d?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let d of vi)this.addCommand({id:`stashpad-open-settings-${d.id}`,name:`Open Stashpad settings: ${d.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let c=()=>{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(()=>($e(),mi)),I=await d(this.app,this,this.settings);if(I.error==="no-dest"){new tt.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),c();return}if(I.error==="no-home"){new tt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:u}=await Promise.resolve().then(()=>($e(),mi));u(this.app,I)}catch(d){console.error("[stashpad] preview failed",d),new tt.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:I,JdBuildConfirmModal:u}=await Promise.resolve().then(()=>($e(),mi));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new tt.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),c();return}let C=I(this.app,this,this.settings);new u(this.app,this,this.settings,C.indexed.length,async()=>{try{let E=await d(this.app,this,this.settings);if(E.error==="no-dest"){new tt.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),c();return}if(E.error==="dest-not-stashpad"){new tt.Notice(`"${E.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),c();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new tt.Notice(`Index built: ${E.created} created, ${E.updated} updated, ${E.skipped} skipped \u2192 ${E.destFolder}`,6e3)}catch(E){console.error("[stashpad] build failed",E),new tt.Notice(`Build failed: ${E?.message??E}`,8e3)}}).open()}catch(d){console.error("[stashpad] build failed",d),new tt.Notice(`Build failed: ${d?.message??d}`,8e3)}}});let l=d=>{if(d.extension!==te)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),u=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=d.parent?.path||"",C=f.split("/").pop()??"";if(I&&C===I){if(u&&f.endsWith(`/${u}`))return;let m=f.slice(0,f.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(d,m);return}this.settings.autoImport&&this.importService.isArmed()&&(ue(d.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(d,f))};this.registerEvent(this.app.vault.on("create",d=>{d instanceof tt.TFile&&l(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof tt.TFile&&l(d)}));let g=d=>{if(d.extension!=="md")return;let I=d.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(d)},800)},p=d=>{if(d.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let u=d.parent?.path?.replace(/\/+$/,"")??"";if((u.split("/").pop()??"")!==I)return;let C=u.slice(0,u.length-I.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(d,C)},200)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof tt.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof tt.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("delete",d=>{if(!(d instanceof tt.TFolder))return;let I=d.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof tt.TFile&&this.maybeReHomeOnCrossFolderMove(d,I)})),this.registerEvent(this.app.vault.on("create",d=>{d instanceof tt.TFile?this.importService.enqueue(d):d instanceof tt.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof tt.TFile?this.importService.enqueue(d):d instanceof tt.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof tt.TFile&&this.maybeAdoptAuthorRename(d,I)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(Js,"1")}catch{}try{if(this.app.commands?.executeCommandById?.("app:reload"))return}catch(t){console.warn("[Stashpad] app:reload command failed",t)}try{window.location.reload()}catch{new tt.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(Js)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Js)}catch{}for(let e of this.app.workspace.getLeavesOfType(dt))try{let i=e;i.isDeferred&&typeof i.loadIfDeferred=="function"&&await i.loadIfDeferred()}catch(i){console.warn("[Stashpad] un-ghost leaf failed",i)}}}isSemverGreater(t,e){let i=t.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0),n=Math.max(i.length,s.length);for(let o=0;o<n;o++){let a=i[o]??0,r=s[o]??0;if(a!==r)return a>r}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 i=this.authorNameToSafe(e);for(let s of this.discoverStashpadFolders()){let n=`${s}/_authors`;if(await this.app.vault.adapter.exists(n))for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(n+"/"))continue;let a=this.parseAuthorFilePath(o.path);if(!a||a.id!==t)continue;let r=`${n}/${i}-${t}.md`,c=o;if(o.path!==r)try{this.authorRenameInFlight.add(o.path),this.authorRenameInFlight.add(r),await this.app.fileManager.renameFile(o,r);let l=this.app.vault.getAbstractFileByPath(r);l&&(c=l)}catch(l){console.warn("[Stashpad] author file rename failed",l);continue}try{await this.refreshAuthorStub(c)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,i?a.role=i:delete a.role,s?a.department=s: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 i=this.parseAuthorFilePath(t.path);if(!i)return;let s=(this.settings.authorId??"").trim();if(!s||i.id!==s)return;let n=i.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let i=this.app.vault.adapter,s=t.name,n=s.lastIndexOf("."),o=n>0?s.slice(0,n):s,a=n>0?s.slice(n):"",r=0;for(;await i.exists(`${e}/${s}`);)r+=1,s=`${o}-${r}${a}`;let c=`${e}/${s}`;await this.app.fileManager.renameFile(t,c);let l=this.app.vault.getAbstractFileByPath(c);l instanceof tt.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(l)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[c]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",a=!i,r=!n,c=!o;if(!a&&!r&&!c)return;let{newId:l}=await Promise.resolve().then(()=>(Rt(),pi)),g,p=!1,d=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(g=l(),f.id=g)),r){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=U,p=!0)}c&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),d=!0))}),!g&&!p&&!d)return;let I=this.newLog(),u=g||i;u&&await I.append({type:"parent_change",id:u,payload:{from:null,to:U,reason:"orphan_auto_fix",path:t.path,addedId:!!g,addedParent:p,addedCreated:d}}),new tt.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}maybeReHomeOnCrossFolderMove(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");i!==n&&this.discoverStashpadFolders().includes(i)&&(this.reHomePending.has(t.path)||(this.reHomePending.add(t.path),setTimeout(()=>{this.reHomePending.delete(t.path),this.reHomeDanglingParent(t,i)},900)))}async reHomeDanglingParent(t,e){try{let i=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof i?.id=="string"?i.id.trim():"",n=typeof i?.parent=="string"?i.parent.trim():"";if(!s||!n||n===U||this.app.vault.getMarkdownFiles().some(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(a)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,a=>{let r=typeof a.parent=="string"?a.parent.trim():"";r&&r!==U&&(a.parent=U)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:U,reason:"rehome_cross_folder_move",path:t.path}}),new tt.Notice(`Re-homed ${t.basename} \u2192 Home (its parent isn't in this folder)`)}catch(i){console.warn("[Stashpad] re-home on cross-folder move failed",i)}}async autoImportStash(t,e){try{let i=new Uint8Array(await this.app.vault.readBinary(t));if(Ne(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await xe(this.app,i);if(!s)return;let n=qt(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let c of n.collectExistingIds())o.add(c);else for(let c of this.app.vault.getMarkdownFiles()){if(!c.path.startsWith(e+"/"))continue;let l=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof l=="string"&&o.add(l)}let a=await De(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:U,payload:{from:t.path,into:e,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let r=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&r.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&r.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:r.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed +`,c=Dt(o.basename)||o.basename,g=await this.uniquePath(t,bt(c,a));await this.createNote(g,ee(r,l)),i.push(g)}}}recordNotePaths(A){return A.kind==="folder"?A.notePaths:[A.notePath]}announce(A,t=[]){let e=A[0]?.folder??"",i=A.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(A,t))};this.plugin.notifications.show({message:`Imported ${i} file${i===1?"":"s"}${s} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:A.flatMap(a=>this.recordNotePaths(a)),actions:[{label:"Undo import",onClick:()=>void o()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${i} file${i===1?"":"s"}`,undo:async()=>{await o()},redo:async()=>{}})}async undo(A,t=[]){for(let e of A)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else if(e.kind==="file"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else{for(let s of e.notePaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof It.TFolder){let s=await this.uniquePath(e.folder,e.originalName);this.suppress(s),await this.app.fileManager.renameFile(i,s)}}}catch(i){console.warn("[Stashpad] import undo failed",e,i)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(i){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,i)}new It.Notice(`Undid import of ${A.length} file(s).`)}pickFilesInto(A){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 i=[];for(let n of e)try{let o=await n.arrayBuffer(),a=await this.uniquePath(A,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let r=this.app.vault.getAbstractFileByPath(a);r instanceof It.TFile&&i.push(r)}catch(o){console.warn("[Stashpad] file-picker write failed",n.name,o)}if(i.length===0)return;await this.plugin.importLog.load();let s=[];for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),i=[];for(let n of e)await this.isStillImportable(n)&&i.push(n);if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] loose-file import failed",n.path,o)}return s}async importLooseFoldersIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof It.TFolder))return 0;let i=e.children.filter(n=>n instanceof It.TFolder&&!_i.has(n.name));if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i){let o=n.path;try{let a=await this.importFolder(n);a&&a.kind==="folder"&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:null,sourcePath:o,notePaths:a.notePaths}))}catch(a){console.warn("[Stashpad] loose-folder import failed",o,a)}}return s}pendingEncryptedPaths(){for(let A of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(A)instanceof It.TFile||this.pendingEncryptedStashes.delete(A);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(A){this.pendingEncryptedStashes.delete(A)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(A){this.encryptedNotifySnoozeUntil=A===1/0?Number.MAX_SAFE_INTEGER:Date.now()+A}parkEncrypted(A){return this.pendingEncryptedStashes.has(A)?!1:(this.pendingEncryptedStashes.add(A),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let A=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof It.TFile))continue;let s=i.parent?.path?.replace(/\/+$/,"")??"";if(await this.importOneStash(i,s,this.liveRootIds(s),!1,{allowLater:!0,onLater:()=>{t=!0,this.snoozeEncryptedNotify(60*60*1e3)}})&&A++,t)break}return{imported:A,rescheduled:t}}liveRootIds(A){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==A)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(A,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(A));if(i&&Ne(n))return this.pendingEncryptedStashes.add(A.path),!1;let o=await xe(this.app,n,{...s,secretId:Pe(A.basename)});if(!o)return!1;let a=await De(this.app,o,t,e);try{await this.app.fileManager.trashFile(A)}catch{}this.pendingEncryptedStashes.delete(A.path);try{await this.plugin.newLog().append({type:"stash_import",id:U,payload:{from:A.path,into:t,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,loose:!0}})}catch{}return!0}catch(n){return console.warn("[Stashpad] loose .stash import failed",A.path,n),!1}}async importLooseStashesIn(A,t={}){let e=A.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===te);if(i.length===0)return 0;let s=this.liveRootIds(e),n=0;for(let o of i)await this.importOneStash(o,e,s,!!t.auto)&&n++;return n}async importLooseInto(A,t={}){let e=await this.importLooseFilesIn(A),i=await this.importLooseFoldersIn(A),s=await this.importLooseStashesIn(A,t);return{files:e,folders:i,stashes:s}}defaultDestination(){let t=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder;return t&&this.plugin.discoverStashpadFolders().includes(t)?t:this.plugin.discoverStashpadFolders()[0]??null}confirm(A,t,e){return new Promise(i=>{new vt(this.app,A,t,e,i).open()})}dupChoice(A){return new Promise(t=>{new Ve(this.app,A,t).open()})}async ensureFolder(A){let t=this.app.vault.adapter,e=A.split("/").filter(Boolean),i="";for(let s of e){i=i?`${i}/${s}`:s;try{await t.exists(i)||await t.mkdir(i)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(A,t){let e=this.app.vault.adapter,i=t.lastIndexOf("."),s=i>0?t.slice(0,i):t,n=i>0?t.slice(i):"",o=`${A}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${A}/${s}-${a}${n}`;return o}};Me.DEBOUNCE_MS=900,Me.BATCH_CONFIRM_AT=8;var ji=Me;var ts=class{constructor(A,t){this.app=A;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 A=this.app.vault.adapter;if(await A.exists(this.path)){let t=await A.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(A){console.warn("[Stashpad] import log load failed",A)}}}recent(){return[...this.entries].reverse()}findDuplicate(A,t){for(let e=this.entries.length-1;e>=0;e--){let i=this.entries[e];if(i.originalName===A&&(t==null||i.size==null||i.size===t))return i}return null}append(A){this.entries.push(A),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(A)+` +`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}};var is=class is{constructor(A,t){this.app=A;this.map=new Map;this.loaded=!1;this.dirty=!1;this.saveTimer=null;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/render-cache.json`}async load(){if(!this.loaded){this.loaded=!0;try{let A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));if(t?.schema===1&&t.entries){for(let[e,i]of Object.entries(t.entries))this.map.set(e,i);for(let e of[...this.map.keys()])this.app.vault.getAbstractFileByPath(e)||(this.map.delete(e),this.dirty=!0)}}}catch(A){console.warn("[Stashpad] render cache load failed; starting empty",A),this.map.clear()}}}get(A){return this.map.get(A)}has(A){return this.map.has(A)}set(A,t){this.map.set(A,t),this.dirty=!0,this.scheduleSave()}scheduleSave(){this.saveTimer==null&&(this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},is.SAVE_DEBOUNCE_MS))}save(){return this.saveTimer!=null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.dirty?(this.dirty=!1,this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let A={schema:1,entries:Object.fromEntries(this.map)};await this.app.vault.adapter.write(this.path,JSON.stringify(A))}catch(A){console.warn("[Stashpad] render cache save failed",A)}}),this.writeChain):this.writeChain}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}};is.SAVE_DEBOUNCE_MS=8e3;var es=is;var Js="stashpad:unghost-after-reload",ss=class extends tt.Plugin{constructor(){super(...arguments);this.settings={...Zt};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.suppressComposerAutofocusUntil=0;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this._renderCacheStore=null;this.knownStashpadFolders=new Set;this.suppressedFolderDeletes=new Set;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.reHomePending=new Set;this.autoSweepInProgress=!1;this.notifPersistenceWired=!1;this.notifSaveTimer=null;this.LAST_CURSOR_LS_KEY="stashpad:last-cursor";this.LAST_SELECTION_LS_KEY="stashpad:last-selection";this.writeChain=Promise.resolve()}get notifications(){return this._notifications||(this._notifications=new Ei(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new $i(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new ji(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new ts(this.app,this.pluginPrivatePath())),this._importLog}get renderCacheStore(){return this._renderCacheStore||(this._renderCacheStore=new es(this.app,this.pluginPrivatePath())),this._renderCacheStore}async onunload(){try{await this._renderCacheStore?.save()}catch{}}pluginPrivatePath(t=""){let i=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${i}/${t.replace(/^\/+/,"")}`:i}newLog(){return new Xi(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),i=async()=>{let a=e.split("/").filter(Boolean),r="";for(let l of a)r=r?`${r}/${l}`:l,await t.exists(r)||await t.mkdir(r)},s=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(s)&&!await t.exists(n))try{await i();let a=await t.read(s);await t.write(n,a),console.debug("[Stashpad] migrated data.json \u2192",n)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let o=".stashpad";if(await t.exists(o))try{await i();let a=await t.list(o);for(let r of a.files){let l=r.replace(/^.*\//,""),c=this.pluginPrivatePath(l);if(!await t.exists(c))try{let g=await t.read(r);await t.write(c,g),console.debug("[Stashpad] migrated",r,"\u2192",c)}catch(g){console.warn(`Stashpad: failed to migrate ${r}`,g)}}}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(i){return console.warn("Stashpad: data.json parse failed",i),null}}async saveData(t){let e=this.app.vault.adapter,i=this.pluginPrivatePath();if(!await e.exists(i)){let s=i.split("/").filter(Boolean),n="";for(let o of s)n=n?`${n}/${o}`:o,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 i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let l of s)n=n?`${n}/${l}`:l,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let l=this.app.vault.getAbstractFileByPath(o);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=U),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),r=["---",`id: ${U}`,"parent: null",`created: ${a}`,"---","Home"].join(` +`);await this.app.vault.create(o,r);try{await this.seedLocalAuthorStub(e)}catch{}}collectColorsInFolder(t){let e=new Map,i=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==i&&!o.startsWith(i+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=typeof a?.color=="string"?a.color.trim():"";if(!r||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(r))continue;let l=r.toLowerCase();e.set(l,(e.get(l)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let r of this.app.vault.getMarkdownFiles()){let l=r.parent?.path?.replace(/\/+$/,"")??"";if(l!==s&&!l.startsWith(s+"/"))continue;let c=this.app.metadataCache.getFileCache(r)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(r,p=>{i?p.color=i:delete p.color}),o++}catch(p){console.warn(`Stashpad: recolor failed for ${r.path}`,p)}}let a=this.settings.colorAliases?.[s];if(a){let r=a[n];r&&(delete a[n],i&&(a[i.toLowerCase()]=r),Object.keys(a).length===0&&delete this.settings.colorAliases[s],await this.saveSettings())}return o}getColorAlias(t,e){let i=t.replace(/\/+$/,""),s=this.settings.colorAliases?.[i];if(!s)return;let n=s[e.toLowerCase()];return n&&n.trim()?n:void 0}async setColorAlias(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[s]||(this.settings.colorAliases[s]={});let o=this.settings.colorAliases[s],a=i.trim();a?o[n]=a:delete o[n],Object.keys(o).length===0&&delete this.settings.colorAliases[s],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let i=t.trim().replace(/^\/+|\/+$/g,"");if(!i)return;let s=Date.now();for(;Date.now()-s<e;){if(this.discoverStashpadFolders().includes(i))return;await new Promise(n=>setTimeout(n,80))}}discoverStashpadFolders(){let t=new Set;for(let i of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(i)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let n=i.parent?.path?.replace(/\/+$/,"")??"";n&&t.add(n)}let e=[...t].sort();return this.knownStashpadFolders=new Set(e),e}closeStashpadTabsFor(t){let e=0;for(let i of this.app.workspace.getLeavesOfType(dt)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(a=>a!==t&&!a.startsWith(t+"/")),s=(e.folderPanelPinned?.length??0)+(e.folderPanelDownranked?.length??0)+(e.folderPanelHidden?.length??0);e.folderPanelPinned=i(e.folderPanelPinned),e.folderPanelDownranked=i(e.folderPanelDownranked),e.folderPanelHidden=i(e.folderPanelHidden),e.folderPanelPinned.length+e.folderPanelDownranked.length+e.folderPanelHidden.length!==s&&await this.saveSettings()}async deleteStashpadFolderWithUndo(t){let e=t.path.replace(/\/+$/,""),i=t.name,s=this.app.vault.adapter,n=".trash";try{await s.exists(n)||await s.mkdir(n)}catch(l){console.warn("[Stashpad] couldn't ensure .trash",l)}let o=`${n}/${i}`;for(let l=1;await s.exists(o);l++)o=`${n}/${i} (${l})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let a=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(l){console.warn("[Stashpad] folder delete failed",l),this.suppressedFolderDeletes.delete(e),new tt.Notice("Delete failed (see console).");return}let r=a>0?`Deleted \u201C${i}\u201D \u2014 closed ${a} open tab${a===1?"":"s"}.`:`Deleted \u201C${i}\u201D.`;this.notifications.show({message:r,kind:"warning",category:"delete",duration:0,folder:e,actions:[{label:"Undo",onClick:async()=>{try{if(await s.exists(e)){new tt.Notice(`Can't undo \u2014 \u201C${i}\u201D already exists.`);return}this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3),await s.rename(o,e),new tt.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(l){console.warn("[Stashpad] folder undo failed",l),new tt.Notice("Undo failed (see console).")}}}]})}async handleStashpadFolderDeleted(t){let e=t.replace(/\/+$/,"");if(!e||this.suppressedFolderDeletes.has(e))return;let i=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);let s=e.split("/").pop()||e;this.notifications.show({message:i>0?`Stashpad \u201C${s}\u201D was deleted \u2014 closed ${i} open tab${i===1?"":"s"}.`:`Stashpad \u201C${s}\u201D was deleted.`,kind:"warning",category:"delete",folder:e})}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),i=new Set(this.settings.searchExcludedFolders),n=this.discoverStashpadFolders().filter(r=>e.size>0?e.has(r):!i.has(r)),o=(t||"").trim().replace(/\/+$/,""),a=n.filter(r=>r!==o);return o&&a.unshift(o),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 i=this.newLog(),s={},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,g=typeof c?.id=="string"?c.id.trim():"";if(!g)continue;let p=c&&"parent"in c?c.parent??null:null;s[g]={parent:p,path:l.path}}let o=await i.readState(),a=l=>l===t||l.startsWith(t+"/");if(!e.silent){for(let[l,c]of Object.entries(s)){let g=o[l];g?g.parent!==c.parent?await i.append({type:"parent_change",id:l,payload:{from:g.parent,to:c.parent}}):g.path!==c.path&&await i.append({type:"rename",id:l,payload:{from:g.path,to:c.path}}):await i.append({type:"create",id:l,payload:{path:c.path,parent:c.parent}})}for(let[l,c]of Object.entries(o))!s[l]&&a(c.path)&&await i.append({type:"missing",id:l,payload:{lastPath:c.path}})}let r={};for(let[l,c]of Object.entries(o))a(c.path)||(r[l]=c);for(let[l,c]of Object.entries(s))r[l]=c;await i.writeState(r)}catch(i){console.warn("Stashpad: integrity sweep failed",i)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new Zi,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),St.enabled=!!this.settings.enablePerfProfiling,this.settingTab=new ki(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),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),window.setTimeout(()=>void this.runAutoImportSweep(),5e3),this.registerInterval(window.setInterval(()=>void this.runAutoImportSweep(),5*60*1e3)),window.setTimeout(()=>void this.migratePinnedNotesToFrontmatter(),3e3),window.setTimeout(()=>void this.unghostStashpadTabsIfFlagged(),1200)}),this.registerView(dt,d=>new zi(d,this)),this.registerView(oe,d=>new Di(d,this)),this.registerView(Vt,d=>new ui(d,this)),this.registerView(ne,d=>new Vi(d,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",d=>{d&&d.view.getViewType()===dt&&(this.lastActiveStashpadLeaf=d,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(oe).length===0&&setTimeout(()=>{bi(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let d=qt(),I=!!d&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===d,u=!!I&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",u),document.body.classList.toggle("stashpad-active",!!I)};this.register(gn(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=d=>{try{let I=Array.from(document.querySelectorAll("style")).filter(u=>(u.textContent??"").includes(".stashpad-"));for(let u of I){let f=u.id||"",C=f?`style[data-stashpad-source="${f}"]`:null;if(C&&d.head.querySelector(C))continue;let m=d.createElement("style");f?m.setAttribute("data-stashpad-source",f):m.setAttribute("data-stashpad-source","anon"),m.textContent=u.textContent??"",d.head.appendChild(m)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",d=>{let I=d?.doc??d?.win?.document??null;I&&e(I)})),this.registerEvent(this.app.workspace.on("file-menu",(d,I)=>{if(!(I instanceof tt.TFolder))return;let u=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(u)&&d.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(u))})})),setTimeout(()=>{try{let d=this.app.workspace;typeof d.iterateAllLeaves=="function"&&d.iterateAllLeaves(I=>{let u=I?.view?.containerEl?.ownerDocument;u&&u!==document&&e(u)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let i=window.visualViewport,s=()=>{let d=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=d&&d.isConnected?d.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${I}px`);let u=0;i&&(u=Math.max(0,window.innerHeight-i.height-i.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${u}px`),document.body.classList.toggle("stashpad-keyboard-open",u>100)};s(),i&&(i.addEventListener("resize",s),i.addEventListener("scroll",s),this.register(()=>{i.removeEventListener("resize",s),i.removeEventListener("scroll",s)})),window.addEventListener("resize",s),this.register(()=>window.removeEventListener("resize",s)),requestAnimationFrame(s),setTimeout(s,250),setTimeout(s,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)",()=>{fi(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Wi(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{bi(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})}),this.addCommand({id:"stashpad-focus-last-tab",name:"Focus last Stashpad tab",callback:()=>void this.focusLastStashpadTab()}),this.addCommand({id:"stashpad-focus-folder-panel",name:"Focus folder panel",callback:()=>void this.focusFolderPanel()});let o=d=>{let I=qt();I&&typeof I[d]=="function"&&I[d]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>o("toggleSplit")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>o("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>o("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>o("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>o("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>o("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>o("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>o("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>o("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>o("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>o("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>o("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>o("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>o("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>o("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>o("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>o("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>o("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>o("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>o("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>o("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>o("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>o("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>o("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>o("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>o("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>o("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>o("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>o("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>o("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>o("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>o("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new tt.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let d=St.report();console.log(d);try{await navigator.clipboard.writeText(d)}catch{}new tt.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{St.reset(),new tt.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>o("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>o("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>o("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(()=>(Mt(),We));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-import-loose-files",name:"Import loose files & folders in this folder (scan for moved-in / unprocessed items)",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderFrontmatterBackfill(I),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>o("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>o("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void fi(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void Wi(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void bi(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:d=>{let I=this.app.workspace.getActiveFile(),u=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return d||u&&I&&this.revealNoteInStashpad(I),u}});let a=Object.keys(Xe);for(let d of a){let I=Xe[d];this.addCommand({id:`stashpad-open-panels-${d}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await fi(this.app),this.app.workspace.getLeavesOfType(Vt)[0]?.view?.setActivePanel?.(d)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>o("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>o("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:()=>o("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>o("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>o("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>o("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>o("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 I=qt(),u=I&&I.noteFolder;return u?(d||(new tt.Notice(`Running integrity check on "${u}"\u2026`),this.runIntegrityCheckOnFolder(u).then(()=>{new tt.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 tt.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 tt.Notice(`Author registry rebuild failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new tt.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 tt.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 tt.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:d,fmChecked:I,fmWritten:u,slugsRenamed:f,authors:C,imported:m,attachmentsLinked:E}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${d.length} folder${d.length===1?"":"s"}`),m>0&&w.push(`imported ${m} loose file${m===1?"":"s"}`),E>0&&w.push(`linked attachments on ${E} note${E===1?"":"s"}`),u>0&&w.push(`updated ${u} note${u===1?"":"s"}' metadata`),f>0&&w.push(`renamed ${f} note${f===1?"":"s"}`),C>0&&w.push(`${C} author${C===1?"":"s"} in registry`),w.push(`(checked ${I} total)`),new tt.Notice(`Stashpad: ${w.join(" \xB7 ")}`)}catch(d){new tt.Notice(`Stashpad: rebootstrap failed (${d.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:d=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(d||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Mt(),We)).then(({NotificationHistoryModal:d,LogModal:I})=>{new d(this.app,this.notifications,async()=>{let u=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await u.exists(f)){new tt.Notice("No log yet \u2014 make some changes first.");return}let C=await u.read(f);new I(this.app,C,f).open()},this.settings.authorId||null,u=>this.lookupNoteAuthorIds(u)).open()})}});let r=[{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 r){let I=`stashpad-toggle-${String(d.key).replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${d.label}`,callback:async()=>{let u=!this.settings[d.key];this.settings[d.key]=u,await this.saveSettings(),new tt.Notice(`${d.label}: ${u?"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(()=>{d?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let d of vi)this.addCommand({id:`stashpad-open-settings-${d.id}`,name:`Open Stashpad settings: ${d.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.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(()=>($e(),mi)),I=await d(this.app,this,this.settings);if(I.error==="no-dest"){new tt.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(I.error==="no-home"){new tt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:u}=await Promise.resolve().then(()=>($e(),mi));u(this.app,I)}catch(d){console.error("[stashpad] preview failed",d),new tt.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:I,JdBuildConfirmModal:u}=await Promise.resolve().then(()=>($e(),mi));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new tt.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}let C=I(this.app,this,this.settings);new u(this.app,this,this.settings,C.indexed.length,async()=>{try{let E=await d(this.app,this,this.settings);if(E.error==="no-dest"){new tt.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(E.error==="dest-not-stashpad"){new tt.Notice(`"${E.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 tt.Notice(`Index built: ${E.created} created, ${E.updated} updated, ${E.skipped} skipped \u2192 ${E.destFolder}`,6e3)}catch(E){console.error("[stashpad] build failed",E),new tt.Notice(`Build failed: ${E?.message??E}`,8e3)}}).open()}catch(d){console.error("[stashpad] build failed",d),new tt.Notice(`Build failed: ${d?.message??d}`,8e3)}}});let c=d=>{if(d.extension!==te)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),u=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=d.parent?.path||"",C=f.split("/").pop()??"";if(I&&C===I){if(u&&f.endsWith(`/${u}`))return;let m=f.slice(0,f.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(d,m);return}this.settings.autoImport&&this.importService.isArmed()&&(ue(d.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(d,f))};this.registerEvent(this.app.vault.on("create",d=>{d instanceof tt.TFile&&c(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof tt.TFile&&c(d)}));let g=d=>{if(d.extension!=="md")return;let I=d.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(d)},800)},p=d=>{if(d.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let u=d.parent?.path?.replace(/\/+$/,"")??"";if((u.split("/").pop()??"")!==I)return;let C=u.slice(0,u.length-I.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(d,C)},200)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof tt.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof tt.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("delete",d=>{if(!(d instanceof tt.TFolder))return;let I=d.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof tt.TFile&&this.maybeReHomeOnCrossFolderMove(d,I)})),this.registerEvent(this.app.vault.on("create",d=>{d instanceof tt.TFile?this.importService.enqueue(d):d instanceof tt.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof tt.TFile?this.importService.enqueue(d):d instanceof tt.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof tt.TFile&&this.maybeAdoptAuthorRename(d,I)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(Js,"1")}catch{}try{if(this.app.commands?.executeCommandById?.("app:reload"))return}catch(t){console.warn("[Stashpad] app:reload command failed",t)}try{window.location.reload()}catch{new tt.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(Js)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Js)}catch{}for(let e of this.app.workspace.getLeavesOfType(dt))try{let i=e;i.isDeferred&&typeof i.loadIfDeferred=="function"&&await i.loadIfDeferred()}catch(i){console.warn("[Stashpad] un-ghost leaf failed",i)}}}isSemverGreater(t,e){let i=t.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0),n=Math.max(i.length,s.length);for(let o=0;o<n;o++){let a=i[o]??0,r=s[o]??0;if(a!==r)return a>r}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 i=this.authorNameToSafe(e);for(let s of this.discoverStashpadFolders()){let n=`${s}/_authors`;if(await this.app.vault.adapter.exists(n))for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(n+"/"))continue;let a=this.parseAuthorFilePath(o.path);if(!a||a.id!==t)continue;let r=`${n}/${i}-${t}.md`,l=o;if(o.path!==r)try{this.authorRenameInFlight.add(o.path),this.authorRenameInFlight.add(r),await this.app.fileManager.renameFile(o,r);let c=this.app.vault.getAbstractFileByPath(r);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(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,i?a.role=i:delete a.role,s?a.department=s: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 i=this.parseAuthorFilePath(t.path);if(!i)return;let s=(this.settings.authorId??"").trim();if(!s||i.id!==s)return;let n=i.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let i=this.app.vault.adapter,s=t.name,n=s.lastIndexOf("."),o=n>0?s.slice(0,n):s,a=n>0?s.slice(n):"",r=0;for(;await i.exists(`${e}/${s}`);)r+=1,s=`${o}-${r}${a}`;let l=`${e}/${s}`;await this.app.fileManager.renameFile(t,l);let c=this.app.vault.getAbstractFileByPath(l);c instanceof tt.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(c)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[l]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",a=!i,r=!n,l=!o;if(!a&&!r&&!l)return;let{newId:c}=await Promise.resolve().then(()=>(Rt(),pi)),g,p=!1,d=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(g=c(),f.id=g)),r){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=U,p=!0)}l&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),d=!0))}),!g&&!p&&!d)return;let I=this.newLog(),u=g||i;u&&await I.append({type:"parent_change",id:u,payload:{from:null,to:U,reason:"orphan_auto_fix",path:t.path,addedId:!!g,addedParent:p,addedCreated:d}}),new tt.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}maybeReHomeOnCrossFolderMove(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");i!==n&&this.discoverStashpadFolders().includes(i)&&(this.reHomePending.has(t.path)||(this.reHomePending.add(t.path),setTimeout(()=>{this.reHomePending.delete(t.path),this.reHomeDanglingParent(t,i)},900)))}async reHomeDanglingParent(t,e){try{let i=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof i?.id=="string"?i.id.trim():"",n=typeof i?.parent=="string"?i.parent.trim():"";if(!s||!n||n===U||this.app.vault.getMarkdownFiles().some(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(a)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,a=>{let r=typeof a.parent=="string"?a.parent.trim():"";r&&r!==U&&(a.parent=U)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:U,reason:"rehome_cross_folder_move",path:t.path}}),new tt.Notice(`Re-homed ${t.basename} \u2192 Home (its parent isn't in this folder)`)}catch(i){console.warn("[Stashpad] re-home on cross-folder move failed",i)}}async autoImportStash(t,e){try{let i=new Uint8Array(await this.app.vault.readBinary(t));if(Ne(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await xe(this.app,i);if(!s)return;let n=qt(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let l of n.collectExistingIds())o.add(l);else for(let l of this.app.vault.getMarkdownFiles()){if(!l.path.startsWith(e+"/"))continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter?.id;typeof c=="string"&&o.add(c)}let a=await De(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:U,payload:{from:t.path,into:e,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let r=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&r.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&r.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:r.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed File: \`${t.name}\` Error: ${i.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:yi(this.app,t.path,tt.Platform.isMobile)}),console.error(i)}}lookupNoteAuthorIds(t){let e=new Set,i=s=>{if(typeof s!="string")return null;let n=s.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;if(n?.id!==t)continue;let o=i(n?.author);o&&e.add(o);let a=n?.contributors;if(Array.isArray(a))for(let r of a){let c=i(r);c&&e.add(c)}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 d of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(d)?.frontmatter?.id!==t)continue;let u=d.parent?.path;u&&e.add(u)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async d=>{if(d&&!await this.app.vault.adapter.exists(d))try{await this.app.vault.createFolder(d)}catch(I){let u=I?.message??"";if(!/already exists/i.test(u))throw I}},a=0,r=0,c=0,l=0;for(let d of e)try{if(i&&await o(`${d}/${i}`),s&&await o(`${d}/${s}`),this.settings.autoImport)try{let u=await this.importService.importLooseInto(d);l+=u.files+u.folders+u.stashes}catch(u){console.warn("Stashpad: loose sweep failed",d,u)}let I=await ve(this.app,d);a+=I.checked,r+=I.written,c+=await this.rebootstrapFolderSlugs(d),n.push(d)}catch(I){console.warn(`Stashpad: rebootstrap skipped ${d}`,I)}let g=0;try{g=(await this.rebuildAuthorRegistry()).total}catch(d){console.warn("Stashpad: rebootstrap author-registry rebuild failed",d)}let p=0;try{p=await this.convertAttachmentsToLinks()}catch(d){console.warn("Stashpad: attachment-link conversion failed",d)}return{touched:n,fmChecked:a,fmWritten:r,slugsRenamed:c,authors:g,imported:l,attachmentsLinked:p}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Pt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let r=Be(a.basename);if(!(!r||r===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==r))try{let l=await this.app.vault.cachedRead(a),g=l.startsWith("---")?l.slice(l.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):l,p=Dt(g,s),d=bt(p,r);if(a.name===d)continue;let I=a.parent?`${a.parent.path}/${d}`:d;if(this.app.vault.getAbstractFileByPath(I))continue;await this.app.fileManager.renameFile(a,I),n+=1}catch(l){console.warn(`Stashpad: slug rebootstrap skipped ${a.path}`,l)}}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?.()!==dt)return null;let i=e.noteFolder??"";if(!i)return null;let s=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=s[e.cursorIdx]),!n&&e.selection?.size>0){let o=e.firstSelectedId??[...e.selection][0];n=s.find(a=>a.id===o)}return n?.file?{folder:i,id:n.id,file:n.file}:null}fileForPin(t,e){let i=t.replace(/\/+$/,"");for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===i&&this.app.metadataCache.getFileCache(s)?.frontmatter?.id===e)return s;return null}async pinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned!==!0&&(await this.app.fileManager.processFrontMatter(e,i=>{i.pinned=!0,i.pinnedAt=Date.now()}),this.refreshPanelsView())}async unpinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0&&(await this.app.fileManager.processFrontMatter(e,i=>{delete i.pinned,delete i.pinnedAt}),this.refreshPanelsView())}isPinned(t){let e=this.fileForPin(t.folder,t.id);return e?this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0:!1}listPinnedNotes(){let t=new Set(this.discoverStashpadFolders()),e=[];for(let i of this.app.vault.getMarkdownFiles()){let s=i.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(s))continue;let n=this.app.metadataCache.getFileCache(i)?.frontmatter;if(!n||n.pinned!==!0||typeof n.id!="string"||!n.id)continue;let o=typeof n.pinnedAt=="number"?n.pinnedAt:0;e.push({folder:s,id:n.id,pinnedAt:o,file:i})}return e.sort((i,s)=>i.pinnedAt-s.pinnedAt||i.file.path.localeCompare(s.file.path)),e}async migratePinnedNotesToFrontmatter(){let t=this.settings.pinnedNotes??[];if(t.length===0)return;let e=Date.now()-t.length*1e3;for(let i of t){let s=this.fileForPin(i.folder,i.id);if(!s){e+=1e3;continue}try{if(this.app.metadataCache.getFileCache(s)?.frontmatter?.pinned!==!0){let n=e;await this.app.fileManager.processFrontMatter(s,o=>{o.pinned=!0,o.pinnedAt=n})}}catch(n){console.warn("[Stashpad] pin migration failed for",i,n)}e+=1e3}this.settings.pinnedNotes=[],await this.saveSettings(),this.refreshPanelsView()}refreshPanelsView(){let t=this.app.workspace.getLeavesOfType(Vt);for(let e of t){let i=e.view;i&&typeof i.render=="function"&&i.render()}}openFolderPicker(){let t=I=>{let f=I.getViewState().state?.folderOverride;return typeof f=="string"&&f.trim()?f.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(dt),i=this.discoverStashpadFolders(),s=qt(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let I of this.app.vault.getAllLoadedFiles())if(I.children){let u=I.path;u&&u!=="/"&&!u.startsWith(".")&&o.add(u)}let a=I=>{let u=I.split("/").filter(Boolean).pop()??"";return u?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive"].map(C=>(C??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(u):!1},r=new Set,c=[],l=[],g=new Set;for(let I of e){let u=t(I);if(g.has(u))continue;g.add(u),r.add(u);let f=u.split("/").pop()||u;c.push({kind:"reveal",folder:u,label:`Reveal "${f}" tab`,leaf:I,icon:"layout-grid"}),l.push({kind:"open-anyway",folder:u,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let I of i.filter(u=>!r.has(u))){let u=I.split("/").pop()||I;c.push({kind:"open",folder:I,label:`Open "${u}" in new tab`,icon:"layout-template"})}let p=this,d=new class extends tt.SuggestModal{getSuggestions(I){let u=I.trim().toLowerCase(),f=u?u.split(/\s+/).filter(Boolean):[],C=y=>{if(!f.length)return!0;let F=y.toLowerCase();for(let D of f)if(!F.includes(D))return!1;return!0},m=u?c.filter(y=>{let F="folder"in y?y.folder:"";return C(y.label)||C(F)}):c.slice();if(u&&s&&n)for(let y of i){if(y.toLowerCase()===n.toLowerCase())continue;let F=y.split("/").pop()??y,D=`${y} ${F}`;C(D)&&m.push({kind:"switch-current",folder:y,label:`Switch this tab to "${F}"`,icon:"folder-input"})}let E=I.trim().replace(/^\/+|\/+$/g,"");if(E&&!a(E)){let y=Array.from(o).find(D=>D.toLowerCase()===E.toLowerCase()),F=i.some(D=>D.toLowerCase()===E.toLowerCase());if(y&&!F)m.push({kind:"convert",folder:y,label:`Convert \u201C${ii(y)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!y){let D=ii(E);m.push({kind:"create",folder:E,label:`+ Create new Stashpad \u201C${D}\u201D`,icon:"folder-plus"})}}let w=l.filter(y=>C(y.label)||C(y.folder));return m.push(...w),m}renderSuggestion(I,u){u.addClass("stashpad-suggest-item"),u.addClass("stashpad-ribbon-suggest-item"),I.kind==="create"&&u.addClass("stashpad-suggest-create");let f=u.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,tt.setIcon)(f,I.icon);let C=u.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:I.label}),"folder"in I&&I.folder&&I.label!==I.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:I.folder})}async onChooseSuggestion(I){if(I.kind==="reveal"){p.app.workspace.revealLeaf(I.leaf);return}if(I.kind==="open"||I.kind==="open-anyway"){await p.activateViewForFolder(I.folder);return}if(I.kind==="switch-current"){let u=s;u&&typeof u.setFolderOverride=="function"&&(await u.setFolderOverride(I.folder),p.app.workspace.revealLeaf(u.leaf));return}if(I.kind==="create"){try{let u=ii(I.folder);await p.app.vault.adapter.exists(u)||await p.app.vault.createFolder(u),await p.activateViewForFolder(u)}catch(u){new tt.Notice(`Stashpad: couldn't create folder (${u.message})`)}return}if(I.kind==="convert"){let{ConfirmModal:u}=await Promise.resolve().then(()=>(Mt(),We)),f=I.folder,C=[`\u201C${f}\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 u(p.app,"Convert into a Stashpad?",C.join(` -`),"Convert",async m=>{if(m)try{await p.activateViewForFolder(f)}catch(E){new tt.Notice(`Stashpad: couldn't convert folder (${E.message})`)}}).open();return}}}(this.app);d.setPlaceholder(s?"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=qt(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new tt.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:dt,active:!0,state:{folderOverride:e,focusId:i,tinyMode:!0,tinyAlwaysOnTop:!1,compactMode:s}});try{this.app.workspace.revealLeaf(n)}catch{}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let s=e.getLeavesOfType(dt);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:dt,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(dt),i=this.lastActiveStashpadLeaf&&e.includes(this.lastActiveStashpadLeaf)?this.lastActiveStashpadLeaf:e[0]??null;if(!i){await this.activateView({reveal:!0});return}t.revealLeaf(i),t.setActiveLeaf(i,{focus:!0})}async focusFolderPanel(){await Wi(this.app);let t=this.app.workspace.getLeavesOfType(ne)[0];t&&this.app.workspace.setActiveLeaf(t,{focus:!0})}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=this.app.workspace.getLeaf("tab");await i.setViewState({type:dt,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(i)}async openFolderInStashpad(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=this.app.workspace.getLeavesOfType(dt).find(s=>(s.view?.noteFolder??"")===e);if(i){this.app.workspace.revealLeaf(i);return}await this.activateViewForFolder(e)}isStashpadNoteFile(t){let e=t.parent?.path?.replace(/\/+$/,"")??"";if(!this.discoverStashpadFolders().includes(e))return!1;let i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;return typeof i=="string"&&i.length>0}async revealNoteInStashpad(t){let e=t.parent?.path?.replace(/\/+$/,"")??"",i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;if(!e||typeof i!="string"||!i){new tt.Notice("That note isn't a Stashpad note.");return}let s=this.app.workspace.getLeavesOfType(dt).find(n=>(n.view?.noteFolder??"")===e);if(s){this.app.workspace.revealLeaf(s);let n=s.view;typeof n?.navigateTo=="function"&&n.navigateTo(i);return}await this.activateViewForFolder(e),this.navigateWhenReady(e,i)}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(dt).find(o=>(o.view?.noteFolder??"").replace(/\/+$/,"")===s)?.view??this.lastActiveStashpadLeaf?.view;if(n&&typeof n.navigateTo=="function"&&(!n.tree||typeof n.tree.get!="function"||!!n.tree.get(e))){n.navigateTo(e);return}i>0?window.setTimeout(()=>this.navigateWhenReady(t,e,i-1),90):n&&typeof n.navigateTo=="function"&&n.navigateTo(e)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,i=this.discoverStashpadFolders(),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(I=>typeof I=="string"):[],c=a.includes(e),l=r.some(I=>I.includes(e));if(!c&&!l)continue;let g=n.parent?.path??"",p=i.find(I=>g===I||g.startsWith(I+"/"));if(!p)continue;s.has(p)||s.set(p,{authored:0,contributed:0});let d=s.get(p);c&&d.authored++,l&&d.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return Xt(t)}authorRefFor(t,e,i){let s=i.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${s}-${e}.md`,o=i.replace(/[\[\]|]/g,"").trim()||s;return`[[${n}|${o}]]`}async ensureAuthorStubFor(t,e,i){if(!e||!i)return;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(c=>c.path.startsWith(s+"/")&&this.parseAuthorFilePath(c.path)?.id===e))return;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),r=`${s}/${a}-${e}.md`;try{if(await this.ensureFolderPath(s),await this.app.vault.adapter.exists(r))return;await this.app.vault.create(r,this.buildAuthorStub({id:e,name:i,role:o?.role,department:o?.department},new Date().toISOString()))}catch(c){console.warn("[Stashpad] ensureAuthorStubFor failed",r,c)}}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,i=0;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=[];if(typeof o.author=="string"&&a.push(o.author),Array.isArray(o.contributors))for(let r of o.contributors)typeof r=="string"&&a.push(r);for(let r of a){let c=this.parseAuthorRef(r);if(c)if(!e.has(c.id))e.set(c.id,{id:c.id,name:c.name,fromStub:!1}),i++;else{let l=e.get(c.id);!l.name&&c.name&&(l.name=c.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let c=this.app.metadataCache.getFileCache(a)?.frontmatter,g=((Array.isArray(c?.aliases)?c.aliases.find(u=>typeof u=="string")??"":typeof c?.aliases=="string"?c.aliases:"")||(typeof c?.name=="string"?c.name:"")||r.name).trim(),p=typeof c?.role=="string"?c.role:void 0,d=typeof c?.department=="string"?c.department:void 0,I=e.get(r.id);I||s++,e.set(r.id,{id:r.id,name:g||I?.name,role:p??I?.role,department:d??I?.department,fromStub:!0})}}return await this.authorRegistry.load(),this.authorRegistry.replaceAll([...e.values()]),await this.authorRegistry.save(),{total:e.size,fromStubs:s,fromNotes:i}}buildAuthorStub(t,e){let i=a=>a.replace(/[\r\n]+/g," ").trim(),s=a=>i(a).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=i(t.name),o=["---",`authorId: ${t.id}`,"aliases:",` - "${s(t.name)}"`];return t.role&&o.push(`role: "${s(t.role)}"`),t.department&&o.push(`department: "${s(t.department)}"`),o.push(`created: ${e}`,"---",`# ${n}`),o.join(` -`)}async restoreMissingAuthorStubs(){await this.authorRegistry.load();let t=this.authorRegistry.all().filter(n=>n.id&&n.name),e=this.discoverStashpadFolders(),i=this.app.vault.getMarkdownFiles(),s=0;for(let n of e){let o=`${n}/_authors`,a=new Set;for(let r of i){if(!r.path.startsWith(o+"/"))continue;let c=this.parseAuthorFilePath(r.path)?.id;c&&a.add(c)}for(let r of t){if(a.has(r.id))continue;let c=this.authorNameToSafe(r.name),l=`${o}/${c}-${r.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(l))continue;await this.app.vault.create(l,this.buildAuthorStub(r,r.firstSeen??new Date().toISOString())),s++}catch(g){console.warn("[Stashpad] restore author stub failed",l,g)}}}return{created:s,folders:e.length}}async convertAttachmentsToLinks(){let t=0,e=i=>/^\[\[.*\]\]$/.test(i.trim());for(let i of this.discoverStashpadFolders()){let s=i.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==s&&!o.startsWith(s+"/")||ue(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let r=a.attachments,c=Array.isArray(r),l=typeof r=="string"&&r.trim().length>0;if(!(!c&&!l||!(l?!e(r):r.some(p=>typeof p=="string"&&p.trim()&&!e(p)))))try{await this.app.fileManager.processFrontMatter(n,p=>{Array.isArray(p.attachments)?p.attachments=p.attachments.map(d=>typeof d=="string"&&d.trim()?Gt(d):d):typeof p.attachments=="string"&&p.attachments.trim()&&(p.attachments=[Gt(p.attachments)])}),t++}catch(p){console.warn("[Stashpad] attachment-link conversion failed",n.path,p)}}}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"):[],i=new Set(e),s=!1;for(let n of this.discoverStashpadFolders()){let o=`${n.replace(/\/+$/,"")}/_archive/`;i.has(o)||(i.add(o),s=!0)}s&&t.setConfig("userIgnoreFilters",[...i])}catch(t){console.warn("[Stashpad] couldn't update Obsidian excluded files",t)}}openImportPicker(){let t=this.discoverStashpadFolders();if(t.length===0){new tt.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,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(c){this.notifications.show({message:`Stashpad: import failed in \`${e}\` -Error: ${c.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,c);return}let o=i+s+n,a=this.lastActiveStashpadLeaf?.view;o>0&&a?.noteFolder===t&&a?.tree&&(a.tree.rebuild(t),a.render?.());let r;if(o===0)r=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let c=[];i&&c.push(`${i} loose file${i===1?"":"s"}`),s&&c.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&c.push(`${n} .stash bundle${n===1?"":"s"}`),r=`Imported ${c.join(" + ")} in \`${e}\`.`}this.notifications.show({message:r,kind:o>0?"success":"info",category:"import",folder:t})}refreshViewIfShowing(t){let e=this.lastActiveStashpadLeaf?.view;e?.noteFolder===t&&e?.tree&&(e.tree.rebuild(t),e.render?.())}async runFolderSlugPass(t){let e=t.split("/").pop()||t,i=0;try{i=await this.rebootstrapFolderSlugs(t)}catch(s){this.notifications.show({message:`Stashpad: slug pass failed in \`${e}\` +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:yi(this.app,t.path,tt.Platform.isMobile)}),console.error(i)}}lookupNoteAuthorIds(t){let e=new Set,i=s=>{if(typeof s!="string")return null;let n=s.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;if(n?.id!==t)continue;let o=i(n?.author);o&&e.add(o);let a=n?.contributors;if(Array.isArray(a))for(let r of a){let l=i(r);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 d of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(d)?.frontmatter?.id!==t)continue;let u=d.parent?.path;u&&e.add(u)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async d=>{if(d&&!await this.app.vault.adapter.exists(d))try{await this.app.vault.createFolder(d)}catch(I){let u=I?.message??"";if(!/already exists/i.test(u))throw I}},a=0,r=0,l=0,c=0;for(let d of e)try{if(i&&await o(`${d}/${i}`),s&&await o(`${d}/${s}`),this.settings.autoImport)try{let u=await this.importService.importLooseInto(d);c+=u.files+u.folders+u.stashes}catch(u){console.warn("Stashpad: loose sweep failed",d,u)}let I=await ve(this.app,d);a+=I.checked,r+=I.written,l+=await this.rebootstrapFolderSlugs(d),n.push(d)}catch(I){console.warn(`Stashpad: rebootstrap skipped ${d}`,I)}let g=0;try{g=(await this.rebuildAuthorRegistry()).total}catch(d){console.warn("Stashpad: rebootstrap author-registry rebuild failed",d)}let p=0;try{p=await this.convertAttachmentsToLinks()}catch(d){console.warn("Stashpad: attachment-link conversion failed",d)}return{touched:n,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:g,imported:c,attachmentsLinked:p}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Pt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let r=Be(a.basename);if(!(!r||r===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==r))try{let c=await this.app.vault.cachedRead(a),g=c.startsWith("---")?c.slice(c.indexOf(` +---`,3)+4).replace(/^\r?\n/,""):c,p=Dt(g,s),d=bt(p,r);if(a.name===d)continue;let I=a.parent?`${a.parent.path}/${d}`:d;if(this.app.vault.getAbstractFileByPath(I))continue;await this.app.fileManager.renameFile(a,I),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?.()!==dt)return null;let i=e.noteFolder??"";if(!i)return null;let s=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=s[e.cursorIdx]),!n&&e.selection?.size>0){let o=e.firstSelectedId??[...e.selection][0];n=s.find(a=>a.id===o)}return n?.file?{folder:i,id:n.id,file:n.file}:null}fileForPin(t,e){let i=t.replace(/\/+$/,"");for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===i&&this.app.metadataCache.getFileCache(s)?.frontmatter?.id===e)return s;return null}async pinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned!==!0&&(await this.app.fileManager.processFrontMatter(e,i=>{i.pinned=!0,i.pinnedAt=Date.now()}),this.refreshPanelsView())}async unpinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0&&(await this.app.fileManager.processFrontMatter(e,i=>{delete i.pinned,delete i.pinnedAt}),this.refreshPanelsView())}isPinned(t){let e=this.fileForPin(t.folder,t.id);return e?this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0:!1}listPinnedNotes(){let t=new Set(this.discoverStashpadFolders()),e=[];for(let i of this.app.vault.getMarkdownFiles()){let s=i.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(s))continue;let n=this.app.metadataCache.getFileCache(i)?.frontmatter;if(!n||n.pinned!==!0||typeof n.id!="string"||!n.id)continue;let o=typeof n.pinnedAt=="number"?n.pinnedAt:0;e.push({folder:s,id:n.id,pinnedAt:o,file:i})}return e.sort((i,s)=>i.pinnedAt-s.pinnedAt||i.file.path.localeCompare(s.file.path)),e}async migratePinnedNotesToFrontmatter(){let t=this.settings.pinnedNotes??[];if(t.length===0)return;let e=Date.now()-t.length*1e3;for(let i of t){let s=this.fileForPin(i.folder,i.id);if(!s){e+=1e3;continue}try{if(this.app.metadataCache.getFileCache(s)?.frontmatter?.pinned!==!0){let n=e;await this.app.fileManager.processFrontMatter(s,o=>{o.pinned=!0,o.pinnedAt=n})}}catch(n){console.warn("[Stashpad] pin migration failed for",i,n)}e+=1e3}this.settings.pinnedNotes=[],await this.saveSettings(),this.refreshPanelsView()}refreshPanelsView(){let t=this.app.workspace.getLeavesOfType(Vt);for(let e of t){let i=e.view;i&&typeof i.render=="function"&&i.render()}}openFolderPicker(){let t=I=>{let f=I.getViewState().state?.folderOverride;return typeof f=="string"&&f.trim()?f.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(dt),i=this.discoverStashpadFolders(),s=qt(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let I of this.app.vault.getAllLoadedFiles())if(I.children){let u=I.path;u&&u!=="/"&&!u.startsWith(".")&&o.add(u)}let a=I=>{let u=I.split("/").filter(Boolean).pop()??"";return u?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive"].map(C=>(C??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(u):!1},r=new Set,l=[],c=[],g=new Set;for(let I of e){let u=t(I);if(g.has(u))continue;g.add(u),r.add(u);let f=u.split("/").pop()||u;l.push({kind:"reveal",folder:u,label:`Reveal "${f}" tab`,leaf:I,icon:"layout-grid"}),c.push({kind:"open-anyway",folder:u,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let I of i.filter(u=>!r.has(u))){let u=I.split("/").pop()||I;l.push({kind:"open",folder:I,label:`Open "${u}" in new tab`,icon:"layout-template"})}let p=this,d=new class extends tt.SuggestModal{getSuggestions(I){let u=I.trim().toLowerCase(),f=u?u.split(/\s+/).filter(Boolean):[],C=y=>{if(!f.length)return!0;let F=y.toLowerCase();for(let D of f)if(!F.includes(D))return!1;return!0},m=u?l.filter(y=>{let F="folder"in y?y.folder:"";return C(y.label)||C(F)}):l.slice();if(u&&s&&n)for(let y of i){if(y.toLowerCase()===n.toLowerCase())continue;let F=y.split("/").pop()??y,D=`${y} ${F}`;C(D)&&m.push({kind:"switch-current",folder:y,label:`Switch this tab to "${F}"`,icon:"folder-input"})}let E=I.trim().replace(/^\/+|\/+$/g,"");if(E&&!a(E)){let y=Array.from(o).find(D=>D.toLowerCase()===E.toLowerCase()),F=i.some(D=>D.toLowerCase()===E.toLowerCase());if(y&&!F)m.push({kind:"convert",folder:y,label:`Convert \u201C${ii(y)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!y){let D=ii(E);m.push({kind:"create",folder:E,label:`+ Create new Stashpad \u201C${D}\u201D`,icon:"folder-plus"})}}let w=c.filter(y=>C(y.label)||C(y.folder));return m.push(...w),m}renderSuggestion(I,u){u.addClass("stashpad-suggest-item"),u.addClass("stashpad-ribbon-suggest-item"),I.kind==="create"&&u.addClass("stashpad-suggest-create");let f=u.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,tt.setIcon)(f,I.icon);let C=u.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:I.label}),"folder"in I&&I.folder&&I.label!==I.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:I.folder})}async onChooseSuggestion(I){if(I.kind==="reveal"){p.app.workspace.revealLeaf(I.leaf);return}if(I.kind==="open"||I.kind==="open-anyway"){await p.activateViewForFolder(I.folder);return}if(I.kind==="switch-current"){let u=s;u&&typeof u.setFolderOverride=="function"&&(await u.setFolderOverride(I.folder),p.app.workspace.revealLeaf(u.leaf));return}if(I.kind==="create"){try{let u=ii(I.folder);await p.app.vault.adapter.exists(u)||await p.app.vault.createFolder(u),await p.activateViewForFolder(u)}catch(u){new tt.Notice(`Stashpad: couldn't create folder (${u.message})`)}return}if(I.kind==="convert"){let{ConfirmModal:u}=await Promise.resolve().then(()=>(Mt(),We)),f=I.folder,C=[`\u201C${f}\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 u(p.app,"Convert into a Stashpad?",C.join(` +`),"Convert",async m=>{if(m)try{await p.activateViewForFolder(f)}catch(E){new tt.Notice(`Stashpad: couldn't convert folder (${E.message})`)}}).open();return}}}(this.app);d.setPlaceholder(s?"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=qt(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new tt.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:dt,active:!0,state:{folderOverride:e,focusId:i,tinyMode:!0,tinyAlwaysOnTop:!1,compactMode:s}});try{this.app.workspace.revealLeaf(n)}catch{}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let s=e.getLeavesOfType(dt);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:dt,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(dt),i=this.lastActiveStashpadLeaf&&e.includes(this.lastActiveStashpadLeaf)?this.lastActiveStashpadLeaf:e[0]??null;if(!i){await this.activateView({reveal:!0});return}t.revealLeaf(i),t.setActiveLeaf(i,{focus:!0})}async focusFolderPanel(){await Wi(this.app);let t=this.app.workspace.getLeavesOfType(ne)[0];t&&this.app.workspace.setActiveLeaf(t,{focus:!0})}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=this.app.workspace.getLeaf("tab");await i.setViewState({type:dt,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(i)}async openFolderInStashpad(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=this.app.workspace.getLeavesOfType(dt).find(s=>(s.view?.noteFolder??"")===e);if(i){this.app.workspace.revealLeaf(i);return}await this.activateViewForFolder(e)}isStashpadNoteFile(t){let e=t.parent?.path?.replace(/\/+$/,"")??"";if(!this.discoverStashpadFolders().includes(e))return!1;let i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;return typeof i=="string"&&i.length>0}async revealNoteInStashpad(t){let e=t.parent?.path?.replace(/\/+$/,"")??"",i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;if(!e||typeof i!="string"||!i){new tt.Notice("That note isn't a Stashpad note.");return}let s=this.app.workspace.getLeavesOfType(dt).find(n=>(n.view?.noteFolder??"")===e);if(s){this.app.workspace.revealLeaf(s);let n=s.view;typeof n?.navigateTo=="function"&&n.navigateTo(i);return}await this.activateViewForFolder(e),this.navigateWhenReady(e,i)}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(dt).find(o=>(o.view?.noteFolder??"").replace(/\/+$/,"")===s)?.view??this.lastActiveStashpadLeaf?.view;if(n&&typeof n.navigateTo=="function"&&(!n.tree||typeof n.tree.get!="function"||!!n.tree.get(e))){n.navigateTo(e);return}i>0?window.setTimeout(()=>this.navigateWhenReady(t,e,i-1),90):n&&typeof n.navigateTo=="function"&&n.navigateTo(e)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,i=this.discoverStashpadFolders(),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(I=>typeof I=="string"):[],l=a.includes(e),c=r.some(I=>I.includes(e));if(!l&&!c)continue;let g=n.parent?.path??"",p=i.find(I=>g===I||g.startsWith(I+"/"));if(!p)continue;s.has(p)||s.set(p,{authored:0,contributed:0});let d=s.get(p);l&&d.authored++,c&&d.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return Xt(t)}authorRefFor(t,e,i){let s=i.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${s}-${e}.md`,o=i.replace(/[\[\]|]/g,"").trim()||s;return`[[${n}|${o}]]`}async ensureAuthorStubFor(t,e,i){if(!e||!i)return;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),r=`${s}/${a}-${e}.md`;try{if(await this.ensureFolderPath(s),await this.app.vault.adapter.exists(r))return;await this.app.vault.create(r,this.buildAuthorStub({id:e,name:i,role:o?.role,department:o?.department},new Date().toISOString()))}catch(l){console.warn("[Stashpad] ensureAuthorStubFor failed",r,l)}}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,i=0;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=[];if(typeof o.author=="string"&&a.push(o.author),Array.isArray(o.contributors))for(let r of o.contributors)typeof r=="string"&&a.push(r);for(let r of a){let l=this.parseAuthorRef(r);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),i++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter,g=((Array.isArray(l?.aliases)?l.aliases.find(u=>typeof u=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||r.name).trim(),p=typeof l?.role=="string"?l.role:void 0,d=typeof l?.department=="string"?l.department:void 0,I=e.get(r.id);I||s++,e.set(r.id,{id:r.id,name:g||I?.name,role:p??I?.role,department:d??I?.department,fromStub:!0})}}return await this.authorRegistry.load(),this.authorRegistry.replaceAll([...e.values()]),await this.authorRegistry.save(),{total:e.size,fromStubs:s,fromNotes:i}}buildAuthorStub(t,e){let i=a=>a.replace(/[\r\n]+/g," ").trim(),s=a=>i(a).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=i(t.name),o=["---",`authorId: ${t.id}`,"aliases:",` - "${s(t.name)}"`];return t.role&&o.push(`role: "${s(t.role)}"`),t.department&&o.push(`department: "${s(t.department)}"`),o.push(`created: ${e}`,"---",`# ${n}`),o.join(` +`)}async restoreMissingAuthorStubs(){await this.authorRegistry.load();let t=this.authorRegistry.all().filter(n=>n.id&&n.name),e=this.discoverStashpadFolders(),i=this.app.vault.getMarkdownFiles(),s=0;for(let n of e){let o=`${n}/_authors`,a=new Set;for(let r of i){if(!r.path.startsWith(o+"/"))continue;let l=this.parseAuthorFilePath(r.path)?.id;l&&a.add(l)}for(let r of t){if(a.has(r.id))continue;let l=this.authorNameToSafe(r.name),c=`${o}/${l}-${r.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(c))continue;await this.app.vault.create(c,this.buildAuthorStub(r,r.firstSeen??new Date().toISOString())),s++}catch(g){console.warn("[Stashpad] restore author stub failed",c,g)}}}return{created:s,folders:e.length}}async convertAttachmentsToLinks(){let t=0,e=i=>/^\[\[.*\]\]$/.test(i.trim());for(let i of this.discoverStashpadFolders()){let s=i.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==s&&!o.startsWith(s+"/")||ue(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let r=a.attachments,l=Array.isArray(r),c=typeof r=="string"&&r.trim().length>0;if(!(!l&&!c||!(c?!e(r):r.some(p=>typeof p=="string"&&p.trim()&&!e(p)))))try{await this.app.fileManager.processFrontMatter(n,p=>{Array.isArray(p.attachments)?p.attachments=p.attachments.map(d=>typeof d=="string"&&d.trim()?Gt(d):d):typeof p.attachments=="string"&&p.attachments.trim()&&(p.attachments=[Gt(p.attachments)])}),t++}catch(p){console.warn("[Stashpad] attachment-link conversion failed",n.path,p)}}}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"):[],i=new Set(e),s=!1;for(let n of this.discoverStashpadFolders()){let o=`${n.replace(/\/+$/,"")}/_archive/`;i.has(o)||(i.add(o),s=!0)}s&&t.setConfig("userIgnoreFilters",[...i])}catch(t){console.warn("[Stashpad] couldn't update Obsidian excluded files",t)}}openImportPicker(){let t=this.discoverStashpadFolders();if(t.length===0){new tt.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,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(l){this.notifications.show({message:`Stashpad: import failed in \`${e}\` +Error: ${l.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,l);return}let o=i+s+n,a=this.lastActiveStashpadLeaf?.view;o>0&&a?.noteFolder===t&&a?.tree&&(a.tree.rebuild(t),a.render?.());let r;if(o===0)r=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let l=[];i&&l.push(`${i} loose file${i===1?"":"s"}`),s&&l.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&l.push(`${n} .stash bundle${n===1?"":"s"}`),r=`Imported ${l.join(" + ")} in \`${e}\`.`}this.notifications.show({message:r,kind:o>0?"success":"info",category:"import",folder:t})}refreshViewIfShowing(t){let e=this.lastActiveStashpadLeaf?.view;e?.noteFolder===t&&e?.tree&&(e.tree.rebuild(t),e.render?.())}async runFolderSlugPass(t){let e=t.split("/").pop()||t,i=0;try{i=await this.rebootstrapFolderSlugs(t)}catch(s){this.notifications.show({message:`Stashpad: slug pass failed in \`${e}\` ${s.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderSlugPass failed",t,s);return}this.refreshViewIfShowing(t),this.notifications.show({message:i>0?`Renamed ${i} stale filename${i===1?"":"s"} in \`${e}\`.`:`No stale filenames in \`${e}\` \u2014 all slugs match their notes.`,kind:i>0?"success":"info",category:"system",folder:t})}async runFolderFrontmatterBackfill(t){let e=t.split("/").pop()||t,i=0,s=0;try{let n=await ve(this.app,t);i=n.written,s=n.checked}catch(n){this.notifications.show({message:`Stashpad: frontmatter backfill failed in \`${e}\` -${n.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderFrontmatterBackfill failed",t,n);return}this.notifications.show({message:i>0?`Backfilled recovery links on ${i} note${i===1?"":"s"} in \`${e}\` (${s} checked).`:`Recovery links already up to date in \`${e}\` (${s} checked).`,kind:i>0?"success":"info",category:"system",folder:t})}async runAutoImportSweep(){if(!this.settings.autoImport||!this.importService.isArmed()||this.autoSweepInProgress)return;this.autoSweepInProgress=!0;let t=0,e=0,i=0;try{for(let n of this.discoverStashpadFolders())try{let o=await this.importService.importLooseInto(n,{auto:!0});t+=o.files,e+=o.folders,i+=o.stashes}catch(o){console.warn("[Stashpad] auto-import sweep failed",n,o)}}finally{this.autoSweepInProgress=!1}if(t+e+i>0){let n=this.lastActiveStashpadLeaf?.view;n?.tree&&n?.noteFolder&&(n.tree.rebuild(n.noteFolder),n.render?.());let o=[];t&&o.push(`${t} file${t===1?"":"s"}`),e&&o.push(`${e} folder${e===1?"":"s"}`),i&&o.push(`${i} .stash bundle${i===1?"":"s"}`),this.notifications.show({message:`Auto-imported ${o.join(" + ")} (background sweep).`,kind:"success",category:"import"})}this.notifyPendingEncrypted()}notifyPendingEncrypted(){let t=this.importService.pendingEncryptedPaths();if(t.length===0||!this.importService.shouldNotifyEncrypted())return;this.importService.snoozeEncryptedNotify(60*60*1e3);let e=t.length;this.notifications.show({message:`${e} encrypted .stash bundle${e===1?"":"s"} waiting to import. Import ${e===1?"it":"them"} with the password?`,kind:"info",category:"import",duration:0,actions:[{label:"Import now",onClick:()=>void this.importPendingEncryptedNow()},{label:"Remind me later",onClick:()=>this.importService.snoozeEncryptedNotify(60*60*1e3)},{label:"Not now (until next launch)",onClick:()=>this.importService.snoozeEncryptedNotify(1/0)}]})}async importPendingEncryptedNow(){let{imported:t,rescheduled:e}=await this.importService.importPendingEncrypted();if(t>0){let i=this.lastActiveStashpadLeaf?.view;i?.tree&&i?.noteFolder&&(i.tree.rebuild(i.noteFolder),i.render?.()),this.notifications.show({message:`Imported ${t} encrypted .stash bundle${t===1?"":"s"}.`,kind:"success",category:"import"})}}async seedLocalAuthorStub(t){let e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();if(!e||!i)return!1;let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(r=>r.path.startsWith(s+"/")&&this.parseAuthorFilePath(r.path)?.id===e))return!1;let o=this.authorNameToSafe(i),a=`${s}/${o}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(a)?!1:(await this.app.vault.create(a,this.buildAuthorStub({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment},new Date().toISOString())),this.authorRegistry.record({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment}),!0)}catch(r){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,r),!1}}async seedLocalAuthorStubsEverywhere(){if(!(this.settings.authorName??"").trim())return 0;let e=0;for(let i of this.discoverStashpadFolders())await this.seedLocalAuthorStub(i)&&e++;return e}async ensureFolderPath(t){let e=this.app.vault.adapter,i=t.split("/").filter(Boolean),s="";for(let n of i){s=s?`${s}/${n}`:n;try{await e.exists(s)||await e.mkdir(s)}catch(o){if(!/already exists/i.test(o.message))throw o}}}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:wa(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:Fa(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Pt]},Bs(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 i=await t.read(e),s=JSON.parse(i);Array.isArray(s)&&this.notifications.loadHistory(s)}}catch(i){console.warn("[Stashpad] failed to load notification history",i)}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(),i=e.replace(/\/[^/]+$/,""),s=this.app.vault.adapter;i&&!await s.exists(i)&&await s.mkdir(i),await s.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 i=this.readLastCursorFile()[t]??{};return new Map(Object.entries(i))}saveLastCursor(t,e,i){try{let s=this.readLastCursorFile();s[t]||(s[t]={}),s[t][e]=i,window.localStorage.setItem(this.LAST_CURSOR_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-cursor",s)}}readLastSelectionFile(){try{let t=window.localStorage.getItem(this.LAST_SELECTION_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastSelection(t){let i=this.readLastSelectionFile()[t]??{},s=new Map;for(let[n,o]of Object.entries(i))Array.isArray(o)&&s.set(n,o.filter(a=>typeof a=="string"));return s}saveLastSelection(t,e,i){try{let s=this.readLastSelectionFile();s[t]||(s[t]={}),i.length?s[t][e]=i:delete s[t][e],window.localStorage.setItem(this.LAST_SELECTION_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-selection",s)}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),Bs(this.settings),St.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 tt.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let g of i){let p=this.app.metadataCache.getFileCache(g)?.frontmatter,d=typeof p?.id=="string"?p.id.trim():"";d&&e.add(d)}let{newId:s}=await Promise.resolve().then(()=>(Rt(),pi)),n=()=>{for(let g=0;g<100;g++){let p=s();if(!e.has(p))return e.add(p),p}for(let g=8;g<=16;g+=2){let p=s(g);if(!e.has(p))return e.add(p),p}throw new Error("Could not generate a unique id")},o=[];for(let g of i){let p=g.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(p))continue;let d=this.app.metadataCache.getFileCache(g)?.frontmatter,I=typeof d?.id=="string"?d.id.trim():"",u=d?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof d?.created=="string"&&d.created.trim()!=="",m=!I,E=!f,w=!C;!m&&!E&&!w||o.push({file:g,addId:m,addParent:E,addCreated:w})}if(o.length===0){new tt.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,r=0,c=this.newLog();for(let g of o)try{let p;await this.app.fileManager.processFrontMatter(g.file,u=>{if(g.addId&&(typeof u.id=="string"&&u.id.trim()||(p=n(),u.id=p)),g.addParent){let f=u.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(u.parent=U)}g.addCreated&&(typeof u.created=="string"&&u.created.trim()||(u.created=new Date(g.file.stat.ctime).toISOString()))});let d=this.app.metadataCache.getFileCache(g.file)?.frontmatter,I=p??d?.id??"";I&&await c.append({type:"parent_change",id:I,payload:{from:null,to:U,reason:"orphan_fix",path:g.file.path,addedId:g.addId,addedParent:g.addParent,addedCreated:g.addCreated}}),a++}catch(p){console.warn("Stashpad: orphan fix failed for",g.file.path,p),r++}let l=r?` (${r} failed \u2014 see console)`:"";new tt.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${l}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Rt(),pi)),i=new Set;for(let c of this.app.vault.getMarkdownFiles()){if(c.path===t.path)continue;let l=this.app.metadataCache.getFileCache(c)?.frontmatter,g=typeof l?.id=="string"?l.id.trim():"";g&&i.add(g)}let s=()=>{for(let c=0;c<50;c++){let l=e();if(!i.has(l))return l}for(let c=8;c<=16;c+=2){let l=e(c);if(!i.has(l))return l}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,c=>{let l=typeof c.id=="string"?c.id.trim():"";!l||/\s/.test(l)||i.has(l)?(c.id=s(),n.push("id")):o.push("id"),c.parent!==void 0&&c.parent!==null&&String(c.parent).trim()!==""?o.push("parent"):(c.parent=U,n.push("parent")),typeof c.created=="string"&&c.created.trim()!==""?o.push("created"):(c.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(c){new tt.Notice(`Adopt failed: ${c.message}`);return}let a=!1;try{let c=this.app.metadataCache.getFileCache(t)?.frontmatter,l=typeof c?.id=="string"?c.id.trim():"";if(l&&t.basename&&!t.basename.endsWith(`-${l}`)){let g=`${t.parent?t.parent.path+"/":""}${t.basename}-${l}.md`;await this.app.vault.adapter.exists(g)||(await this.app.fileManager.renameFile(t,g),a=!0)}}catch(c){console.warn("Stashpad: adopt rename failed",c)}if(n.length===0&&!a){new tt.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let r=[];n.length&&r.push(`added: ${n.join(", ")}`),a&&r.push("renamed with id"),new tt.Notice(`Adopted into Stashpad \u2014 ${r.join("; ")}.`);try{let c=this.newLog(),l=this.app.metadataCache.getFileCache(t)?.frontmatter,g=l?.id??"";g&&await c.append({type:"create",id:g,payload:{path:t.path,parent:l?.parent??U,source:"adopt",added:n}})}catch{}}};function wa(h,A,t){let e=Cs();for(let i of ye){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(h&&typeof h=="object")for(let i of ye){let s=h[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of ye){if(!i.defaultSecondary&&!i.defaultUseBoth)continue;let s=e[i.id];s.primary===i.defaultPrimary&&!s.secondary&&!s.useBoth&&(s.secondary=i.defaultSecondary??"",s.useBoth=!!i.defaultUseBoth)}return e}function Fa(h){let A={};if(!h||typeof h!="object")return A;for(let[t,e]of Object.entries(h))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var qs=class extends tt.SuggestModal{constructor(t,e,i,s){super(t);this.def=e;this.folders=i;this.onPick=s;this.setPlaceholder("Choose a Stashpad folder to import into\u2026")}getSuggestions(t){let e=t.toLowerCase();return[this.def,...this.folders.filter(s=>s!==this.def)].filter(s=>s.toLowerCase().includes(e)).map(s=>({label:s,folder:s,current:s===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)}}; +${n.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderFrontmatterBackfill failed",t,n);return}this.notifications.show({message:i>0?`Backfilled recovery links on ${i} note${i===1?"":"s"} in \`${e}\` (${s} checked).`:`Recovery links already up to date in \`${e}\` (${s} checked).`,kind:i>0?"success":"info",category:"system",folder:t})}async runAutoImportSweep(){if(!this.settings.autoImport||!this.importService.isArmed()||this.autoSweepInProgress)return;this.autoSweepInProgress=!0;let t=0,e=0,i=0;try{for(let n of this.discoverStashpadFolders())try{let o=await this.importService.importLooseInto(n,{auto:!0});t+=o.files,e+=o.folders,i+=o.stashes}catch(o){console.warn("[Stashpad] auto-import sweep failed",n,o)}}finally{this.autoSweepInProgress=!1}if(t+e+i>0){let n=this.lastActiveStashpadLeaf?.view;n?.tree&&n?.noteFolder&&(n.tree.rebuild(n.noteFolder),n.render?.());let o=[];t&&o.push(`${t} file${t===1?"":"s"}`),e&&o.push(`${e} folder${e===1?"":"s"}`),i&&o.push(`${i} .stash bundle${i===1?"":"s"}`),this.notifications.show({message:`Auto-imported ${o.join(" + ")} (background sweep).`,kind:"success",category:"import"})}this.notifyPendingEncrypted()}notifyPendingEncrypted(){let t=this.importService.pendingEncryptedPaths();if(t.length===0||!this.importService.shouldNotifyEncrypted())return;this.importService.snoozeEncryptedNotify(60*60*1e3);let e=t.length;this.notifications.show({message:`${e} encrypted .stash bundle${e===1?"":"s"} waiting to import. Import ${e===1?"it":"them"} with the password?`,kind:"info",category:"import",duration:0,actions:[{label:"Import now",onClick:()=>void this.importPendingEncryptedNow()},{label:"Remind me later",onClick:()=>this.importService.snoozeEncryptedNotify(60*60*1e3)},{label:"Not now (until next launch)",onClick:()=>this.importService.snoozeEncryptedNotify(1/0)}]})}async importPendingEncryptedNow(){let{imported:t,rescheduled:e}=await this.importService.importPendingEncrypted();if(t>0){let i=this.lastActiveStashpadLeaf?.view;i?.tree&&i?.noteFolder&&(i.tree.rebuild(i.noteFolder),i.render?.()),this.notifications.show({message:`Imported ${t} encrypted .stash bundle${t===1?"":"s"}.`,kind:"success",category:"import"})}}async seedLocalAuthorStub(t){let e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();if(!e||!i)return!1;let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(r=>r.path.startsWith(s+"/")&&this.parseAuthorFilePath(r.path)?.id===e))return!1;let o=this.authorNameToSafe(i),a=`${s}/${o}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(a)?!1:(await this.app.vault.create(a,this.buildAuthorStub({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment},new Date().toISOString())),this.authorRegistry.record({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment}),!0)}catch(r){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,r),!1}}async seedLocalAuthorStubsEverywhere(){if(!(this.settings.authorName??"").trim())return 0;let e=0;for(let i of this.discoverStashpadFolders())await this.seedLocalAuthorStub(i)&&e++;return e}async ensureFolderPath(t){let e=this.app.vault.adapter,i=t.split("/").filter(Boolean),s="";for(let n of i){s=s?`${s}/${n}`:n;try{await e.exists(s)||await e.mkdir(s)}catch(o){if(!/already exists/i.test(o.message))throw o}}}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:Fa(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:va(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Pt]},Bs(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 i=await t.read(e),s=JSON.parse(i);Array.isArray(s)&&this.notifications.loadHistory(s)}}catch(i){console.warn("[Stashpad] failed to load notification history",i)}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(),i=e.replace(/\/[^/]+$/,""),s=this.app.vault.adapter;i&&!await s.exists(i)&&await s.mkdir(i),await s.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 i=this.readLastCursorFile()[t]??{};return new Map(Object.entries(i))}saveLastCursor(t,e,i){try{let s=this.readLastCursorFile();s[t]||(s[t]={}),s[t][e]=i,window.localStorage.setItem(this.LAST_CURSOR_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-cursor",s)}}readLastSelectionFile(){try{let t=window.localStorage.getItem(this.LAST_SELECTION_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastSelection(t){let i=this.readLastSelectionFile()[t]??{},s=new Map;for(let[n,o]of Object.entries(i))Array.isArray(o)&&s.set(n,o.filter(a=>typeof a=="string"));return s}saveLastSelection(t,e,i){try{let s=this.readLastSelectionFile();s[t]||(s[t]={}),i.length?s[t][e]=i:delete s[t][e],window.localStorage.setItem(this.LAST_SELECTION_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-selection",s)}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),Bs(this.settings),St.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 tt.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let g of i){let p=this.app.metadataCache.getFileCache(g)?.frontmatter,d=typeof p?.id=="string"?p.id.trim():"";d&&e.add(d)}let{newId:s}=await Promise.resolve().then(()=>(Rt(),pi)),n=()=>{for(let g=0;g<100;g++){let p=s();if(!e.has(p))return e.add(p),p}for(let g=8;g<=16;g+=2){let p=s(g);if(!e.has(p))return e.add(p),p}throw new Error("Could not generate a unique id")},o=[];for(let g of i){let p=g.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(p))continue;let d=this.app.metadataCache.getFileCache(g)?.frontmatter,I=typeof d?.id=="string"?d.id.trim():"",u=d?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof d?.created=="string"&&d.created.trim()!=="",m=!I,E=!f,w=!C;!m&&!E&&!w||o.push({file:g,addId:m,addParent:E,addCreated:w})}if(o.length===0){new tt.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,r=0,l=this.newLog();for(let g of o)try{let p;await this.app.fileManager.processFrontMatter(g.file,u=>{if(g.addId&&(typeof u.id=="string"&&u.id.trim()||(p=n(),u.id=p)),g.addParent){let f=u.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(u.parent=U)}g.addCreated&&(typeof u.created=="string"&&u.created.trim()||(u.created=new Date(g.file.stat.ctime).toISOString()))});let d=this.app.metadataCache.getFileCache(g.file)?.frontmatter,I=p??d?.id??"";I&&await l.append({type:"parent_change",id:I,payload:{from:null,to:U,reason:"orphan_fix",path:g.file.path,addedId:g.addId,addedParent:g.addParent,addedCreated:g.addCreated}}),a++}catch(p){console.warn("Stashpad: orphan fix failed for",g.file.path,p),r++}let c=r?` (${r} failed \u2014 see console)`:"";new tt.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Rt(),pi)),i=new Set;for(let l of this.app.vault.getMarkdownFiles()){if(l.path===t.path)continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id.trim():"";g&&i.add(g)}let s=()=>{for(let l=0;l<50;l++){let c=e();if(!i.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!i.has(c))return c}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||i.has(c)?(l.id=s(),n.push("id")):o.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?o.push("parent"):(l.parent=U,n.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?o.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(l){new tt.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 g=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(g)||(await this.app.fileManager.renameFile(t,g),a=!0)}}catch(l){console.warn("Stashpad: adopt rename failed",l)}if(n.length===0&&!a){new tt.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let r=[];n.length&&r.push(`added: ${n.join(", ")}`),a&&r.push("renamed with id"),new tt.Notice(`Adopted into Stashpad \u2014 ${r.join("; ")}.`);try{let l=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,g=c?.id??"";g&&await l.append({type:"create",id:g,payload:{path:t.path,parent:c?.parent??U,source:"adopt",added:n}})}catch{}}};function Fa(h,A,t){let e=Cs();for(let i of ye){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(h&&typeof h=="object")for(let i of ye){let s=h[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of ye){if(!i.defaultSecondary&&!i.defaultUseBoth)continue;let s=e[i.id];s.primary===i.defaultPrimary&&!s.secondary&&!s.useBoth&&(s.secondary=i.defaultSecondary??"",s.useBoth=!!i.defaultUseBoth)}return e}function va(h){let A={};if(!h||typeof h!="object")return A;for(let[t,e]of Object.entries(h))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var qs=class extends tt.SuggestModal{constructor(t,e,i,s){super(t);this.def=e;this.folders=i;this.onPick=s;this.setPlaceholder("Choose a Stashpad folder to import into\u2026")}getSuggestions(t){let e=t.toLowerCase();return[this.def,...this.folders.filter(s=>s!==this.def)].filter(s=>s.toLowerCase().includes(e)).map(s=>({label:s,folder:s,current:s===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 3fec2af..8bb0efd 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.96.2", + "version": "0.96.3", "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 0ec8ff3..cdd333f 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.96.2", + "version": "0.96.3", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.96.3.md b/release-notes/0.96.3.md new file mode 100644 index 0000000..7beec26 --- /dev/null +++ b/release-notes/0.96.3.md @@ -0,0 +1,11 @@ +# 0.96.3 — Fix plugin failing to load on older Obsidian + +Follow-up to 0.96.2. That release lowered the minimum Obsidian version but the +plugin still failed to load on pre-1.13 Obsidian: a settings class extended a +1.13-only API at module load, which threw before the plugin could start. + +- The plugin now loads correctly on **pre-1.13 Obsidian**, with a working + (non-blank) settings tab. On Obsidian 1.13+, settings and native search are + unchanged. + +If 0.96.2 wouldn't load for you on an older Obsidian, this fixes it. diff --git a/src/settings.ts b/src/settings.ts index b839b26..5f26655 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -1,4 +1,4 @@ -import { App, Notice, Platform, PluginSettingTab, Setting, SettingPage, TFile, requireApiVersion, setIcon, type SettingDefinitionItem } from "obsidian"; +import { App, Notice, Platform, PluginSettingTab, Setting, SettingPage, TFile, setIcon, type SettingDefinitionItem } from "obsidian"; /** Platform-correct OS file-manager name for button/notice labels. */ function osFileManagerName(): string { @@ -502,20 +502,35 @@ export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = [ { id: "hotkeys", label: "Hotkeys" }, ]; -/** 0.94.0: a declarative sub-page that renders one of Stashpad's settings - * tabs via the existing imperative `renderTabContent`. Used by - * `getSettingDefinitions()` so the migration to Obsidian's native settings - * (1.13.0+) reuses all existing rendering — Phase 1. Per-setting search - * entries (decomposing each page into `items`) come in follow-up versions. */ -class StashpadSubPage extends SettingPage { - constructor(title: string, private renderFn: (el: HTMLElement) => void) { - super(); - this.title = title; - } - display(): void { - this.containerEl.empty(); - this.renderFn(this.containerEl); +/** 0.94.0: a declarative sub-page that renders one of Stashpad's settings tabs + * via the existing imperative `renderTabContent`. Used by + * `getSettingDefinitions()` so the 1.13.0+ native-settings migration reuses all + * existing rendering. + * + * 0.96.3 — CRITICAL: `SettingPage` is a 1.13-only export. A top-level + * `class ... extends SettingPage` evaluates at MODULE LOAD, so on pre-1.13 + * Obsidian (`SettingPage` === undefined) it threw `extends undefined` and the + * WHOLE PLUGIN failed to load. The subclass is now built LAZILY — only when the + * declarative `page:` callback fires, which only happens on 1.13+ (where + * `SettingPage` exists). On older Obsidian this factory is never called, so the + * module loads clean and the imperative `display()` fallback renders settings. */ +let SubPageCtor: (new (title: string, renderFn: (el: HTMLElement) => void) => any) | null = null; +function makeStashpadSubPage(title: string, renderFn: (el: HTMLElement) => void): any { + if (!SubPageCtor) { + SubPageCtor = class extends (SettingPage as any) { + _renderFn: (el: HTMLElement) => void; + constructor(t: string, fn: (el: HTMLElement) => void) { + super(); + (this as any).title = t; + this._renderFn = fn; + } + display(): void { + (this as any).containerEl.empty(); + this._renderFn((this as any).containerEl); + } + } as any; } + return new (SubPageCtor as any)(title, renderFn); } export class StashpadSettingTab extends PluginSettingTab { @@ -530,16 +545,16 @@ export class StashpadSettingTab extends PluginSettingTab { * by the existing `renderTabContent`, so behavior is unchanged and only the * PAGE names are searchable. Phase 2 (follow-up versions) decomposes each * page into `items` so individual settings become searchable too. */ - /** 0.96.2: backwards compatibility for pre-1.13 Obsidian. Obsidian 1.13+ has - * the declarative settings renderer + native search — let the base class - * render from getSettingDefinitions() (and index it for search) by delegating - * to super.display(). OLDER Obsidian has no declarative API: the base - * display() is a no-op there, so without this override the Stashpad settings - * tab renders BLANK. The fallback below renders the SAME settings imperatively - * (one section per tab) — no native search there, which is fine. This is why - * minAppVersion can sit below 1.13 again. */ + /** 0.96.2/0.96.3: backwards compatibility for pre-1.13 Obsidian. When the + * declarative settings API is present (gated on the `SettingPage` export + * existing — a precise capability check, not a version guess), let the base + * class render from getSettingDefinitions() and index it for native search by + * delegating to super.display(). On OLDER Obsidian there's no declarative API + * (and super.display() is a no-op), so render the SAME settings imperatively + * (one section per tab) — no native search there, which is fine. Without this + * the Stashpad settings tab renders BLANK on older Obsidian. */ display(): void { - if (requireApiVersion("1.13.0")) { super.display(); return; } + if (SettingPage) { super.display(); return; } const { containerEl } = this; containerEl.empty(); for (const t of SETTINGS_TABS) { @@ -570,7 +585,7 @@ export class StashpadSettingTab extends PluginSettingTab { return { type: "page" as const, name: t.label, - page: () => new StashpadSubPage(t.label, (el) => this.renderTabContent(el, t.id)), + page: () => makeStashpadSubPage(t.label, (el) => this.renderTabContent(el, t.id)), }; }); }