diff --git a/main.js b/main.js index fa1d02b..5a84fe6 100644 --- a/main.js +++ b/main.js @@ -1,76 +1,82 @@ -"use strict";var dn=Object.defineProperty;var br=Object.getOwnPropertyDescriptor;var Nr=Object.getOwnPropertyNames;var xr=Object.prototype.hasOwnProperty;var Lt=(c,r)=>()=>(c&&(r=c(c=0)),r);var ri=(c,r)=>{for(var t in r)dn(c,t,{get:r[t],enumerable:!0})},Mr=(c,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Nr(r))!xr.call(c,i)&&i!==t&&dn(c,i,{get:()=>r[i],enumerable:!(e=br(r,i))||e.enumerable});return c};var Tr=c=>Mr(dn({},"__esModule",{value:!0}),c);function gn(c){return Array.isArray(c)?c.filter(r=>typeof r=="string"):typeof c=="string"?c.split(/[,\s]+/).filter(Boolean):[]}function Le(c,r){let t=r.replace(/^#/,"");return gn(c?.tags).some(e=>e.replace(/^#/,"")===t)}function In(c,r){let t=r.replace(/^#/,""),e=gn(c.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),c.tags=e}function un(c,r){let t=r.replace(/^#/,""),e=gn(c.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?c.tags=e:delete c.tags}function qe(c){return c.split("/").some(r=>ci.has(r))}function To(c){return c.split("/").some(r=>r==="_archive"||r===".archive")}function Ot(c){let r=(c??"").trim();return!r||/^\[\[.*\]\]$/.test(r)?r:`[[${r}]]`}function Fe(c){let r=(c??"").trim(),t=r.match(/^\[\[(.*)\]\]$/);return t&&(r=t[1]),r.split("|")[0].split("#")[0].split("^")[0].trim()}function Ho(c){let r=c.match(/\.([^./]+)$/);return!!r&&Ur.has(r[1].toLowerCase())}function Po(c,r){if(!Array.isArray(r))return!1;for(let t of r){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(c))return!0}catch{}else if(c===e||c.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Xi(c,r){let t=c.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=r.toLowerCase();return t.every(i=>e.includes(i))}function Ae(c){if(typeof c!="string")return null;let r=c.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=r.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 ke(c){let r=c?.assignedTo,t=Array.isArray(r)?r:r!=null?[r]:[],e=[];for(let i of t){let s=Ae(i);s&&e.push(s)}return e}var K,le,we,ve,Re,F,Xt,ci,Ur,rt=Lt(()=>{"use strict";K="stashpad-view",le="stashpad-panels",we="stashpad-folder-panel",ve="stashpad-detail",Re="stashpad-trash",F="__root__";Xt=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","listPinned","listPinnedAt","imported","okfParent","okfChildren"],ci=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);Ur=new Set(["edtz"])});function hi(c,r){let t=c.replace(/\r\n/g,` +"use strict";var dn=Object.defineProperty;var Dr=Object.getOwnPropertyDescriptor;var br=Object.getOwnPropertyNames;var Nr=Object.prototype.hasOwnProperty;var Lt=(c,r)=>()=>(c&&(r=c(c=0)),r);var ri=(c,r)=>{for(var t in r)dn(c,t,{get:r[t],enumerable:!0})},xr=(c,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of br(r))!Nr.call(c,i)&&i!==t&&dn(c,i,{get:()=>r[i],enumerable:!(e=Dr(r,i))||e.enumerable});return c};var Mr=c=>xr(dn({},"__esModule",{value:!0}),c);function gn(c){return Array.isArray(c)?c.filter(r=>typeof r=="string"):typeof c=="string"?c.split(/[,\s]+/).filter(Boolean):[]}function Le(c,r){let t=r.replace(/^#/,"");return gn(c?.tags).some(e=>e.replace(/^#/,"")===t)}function In(c,r){let t=r.replace(/^#/,""),e=gn(c.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),c.tags=e}function un(c,r){let t=r.replace(/^#/,""),e=gn(c.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?c.tags=e:delete c.tags}function qe(c){return c.split("/").some(r=>ci.has(r))}function To(c){return c.split("/").some(r=>r==="_archive"||r===".archive")}function Ot(c){let r=(c??"").trim();return!r||/^\[\[.*\]\]$/.test(r)?r:`[[${r}]]`}function ve(c){let r=(c??"").trim(),t=r.match(/^\[\[(.*)\]\]$/);return t&&(r=t[1]),r.split("|")[0].split("#")[0].split("^")[0].trim()}function Ho(c){let r=c.match(/\.([^./]+)$/);return!!r&&Pr.has(r[1].toLowerCase())}function Po(c,r){if(!Array.isArray(r))return!1;for(let t of r){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(c))return!0}catch{}else if(c===e||c.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Zi(c,r){let t=c.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=r.toLowerCase();return t.every(i=>e.includes(i))}function ce(c){if(typeof c!="string")return null;let r=c.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=r.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 Fe(c){let r=c?.assignedTo,t=Array.isArray(r)?r:r!=null?[r]:[],e=[];for(let i of t){let s=ce(i);s&&e.push(s)}return e}var J,Ae,Ee,we,Re,F,Zt,ci,Pr,lt=Lt(()=>{"use strict";J="stashpad-view",Ae="stashpad-panels",Ee="stashpad-folder-panel",we="stashpad-detail",Re="stashpad-trash",F="__root__";Zt=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","listPinned","listPinnedAt","imported","okfParent","okfChildren"],ci=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);Pr=new Set(["edtz"])});function hi(c,r){let t=c.replace(/\r\n/g,` `);if(r==="lines")return t.split(` `).map(n=>n.trim()).filter(Boolean);if(r==="paragraphs")return t.split(/\n[ \t]*\n+/).map(n=>n.trim()).filter(Boolean);let e=[],i=[],s=n=>/^#{1,6}\s/.test(n);for(let n of t.split(` `))s(n)&&i.some(o=>o.trim())&&(e.push(i.join(` `).trim()),i=[]),i.push(n);return i.some(n=>n.trim())&&e.push(i.join(` -`).trim()),e.filter(Boolean)}function Mt(c,r,t){c.empty();try{(0,Lo.setIcon)(c,r)}catch{}let e=c.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(c.empty(),c.createSpan({cls:"stashpad-icon-fallback",text:t}))}function qo(c){if(c instanceof Element&&c.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let r=new Set([document]);c instanceof Element&&c.ownerDocument&&r.add(c.ownerDocument);for(let t of r)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 Jo(c){let r=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(c))!=null;)r.push({lang:e[3].trim(),code:e[4]});return r}function pi(c){return c.split("/").map(r=>r.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function Ko(c,r,t){let e=new Set(r),i=c.filter(n=>!e.has(n)),s=c.findIndex(n=>e.has(n));if(s<0)return c.slice();switch(t){case"top":return[...r,...i];case"bottom":return[...i,...r];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...r),o}case"down":{let n=(()=>{let A=-1;return c.forEach((d,h)=>{e.has(d)&&(A=h)}),A})(),o=0;for(let A=0;A0){let n=e[i-1];return(!/[a-z0-9]/.test(n)?600:500)-Math.min(i,99)}let s=0;for(let n=0;n({t:e,s:Gr(t,e.raw)})).filter(e=>e.s>=0).sort((e,i)=>i.s-e.s||i.t.count-e.t.count||e.t.label.localeCompare(i.t.label)).map(e=>e.t):r}var Lo,di,Se,De,gi=Lt(()=>{"use strict";Lo=require("obsidian"),di={lines:"Each line",paragraphs:"Paragraphs (blank line)",headings:"Headings"};Se="__stashpad:tagged__",De="__stashpad:untagged__"});function Rr(c,r){return c>12?c>=24?0:c:r==="am"?c===12?0:c:c===12?12:c+12}function ji(c,r){c.addClass("stashpad-when-pop-time");let t=r.seedPeriod,e=c.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(r.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(r.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 l=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};l(),o.addEventListener("mousedown",B=>B.preventDefault()),a.addEventListener("mousedown",B=>B.preventDefault()),o.addEventListener("click",B=>{B.preventDefault(),t="am",l()}),a.addEventListener("click",B=>{B.preventDefault(),t="pm",l()});let A=i;i.addEventListener("focus",()=>{A=i,i.select()}),s.addEventListener("focus",()=>{A=s,s.select()});let d=()=>{let y=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",y),a.toggleClass("is-disabled",y),o.disabled=y,a.disabled=y},h=B=>{let y=B.value.replace(/\D/g,"").slice(0,2);if(y===""){B.value="",B===i&&d();return}let Q=parseInt(y,10);B===i?Q>24&&(Q=24):Q>59&&(Q=59),B.value=String(Q),B===i&&d()};for(let B of[i,s])B.addEventListener("input",()=>h(B));d();let g=()=>{let B=parseInt(i.value||"12",10)||12,y=parseInt(s.value||"0",10)||0,Q=B>12;r.onFinalize({hours24:Rr(B,t),minutes:y,raw:{hh:B,mm:y,period:t,is24:Q}}),r.close()};r.setOnEnter?.(g);let I=[i,s,o,a],p=(B,y)=>{let Q=I.indexOf(B);if(Q===-1)return;let E=(Q+y+I.length)%I.length;I[E].focus()},u=B=>{B.addEventListener("keydown",y=>{y.key==="Enter"?(y.preventDefault(),y.stopPropagation(),g()):y.key==="Escape"?(y.preventDefault(),y.stopPropagation(),r.close()):y.key==="Tab"&&(y.preventDefault(),y.stopPropagation(),p(B,y.shiftKey?-1:1))})},f=c.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let B of C){let y=f.createEl("button",{cls:"stashpad-when-time-padbtn"});y.type="button",B==="backspace"?(0,Yo.setIcon)(y,"delete"):B==="insert"?(y.setText("OK"),m=y):y.setText(B),B==="insert"&&y.addClass("is-go"),y.addEventListener("mousedown",Q=>Q.preventDefault()),y.addEventListener("click",Q=>{if(Q.preventDefault(),B==="insert"){g();return}if(B==="backspace"){A.value=A.value.slice(0,-1),h(A),A.focus();return}let E=A.selectionStart===0&&A.selectionEnd===A.value.length&&A.value.length>0,v=2,w=E||A.value.length>=v?B:A.value+B;A.value=w,h(A),A.focus(),A.setSelectionRange(A.value.length,A.value.length),A===i&&A.value.length>=v&&(s.focus(),s.select())})}m&&I.push(m);for(let B of I)u(B);i.focus(),i.select()}function zo(c){let{hh:r,mm:t,period:e,is24:i}=c.raw;return i?`${r}:${String(t).padStart(2,"0")}`:`${r}:${String(t).padStart(2,"0")}${e}`}var Yo,Cn=Lt(()=>{"use strict";Yo=require("obsidian")});function Vo(c){let r=Math.floor(4294967296/c)*c,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=r);return e%c}function mn(c=5){let r=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),Lr.has(c.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 qr(c){let r=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Ii(c){let r="stashpad-",t=qr(c),e=64-r.length-1-t.length,i=c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${r}${i}-${t}`}var $o,Lr,_i=Lt(()=>{"use strict";$o="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).filter((c,r,t)=>t.indexOf(c)===r);Lr=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 ts={};ri(ts,{newId:()=>tt});function tt(c=6){let r="",t=new Uint8Array(c);crypto.getRandomValues(t);for(let e=0;e{"use strict";Wo="abcdefghijkmnpqrstuvwxyz23456789"});var wi={};ri(wi,{ColorPickerModal:()=>xe,ConfirmDeleteModal:()=>Ke,ConfirmModal:()=>pt,CustomColorModal:()=>es,DueDatePickerModal:()=>Oe,EncryptionPasswordModal:()=>vt,ExportStashModal:()=>Ci,ImportDupChoiceModal:()=>yi,ImportLogModal:()=>Qn,LogModal:()=>Je,NotificationHistoryModal:()=>Qi,OkfExportModal:()=>Ei,SplitNoteModal:()=>fi,StashPasswordModal:()=>mi,TypeToConfirmModal:()=>Bi,buildAssigneePicker:()=>Xo});function Xo(c,r){let t=[...r.initial],e=r.knownAuthors,i=c.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.setCssStyles({display:"none"});let l=()=>r.onChange([...t]),A=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let g of t){let I=s.createSpan({cls:"stashpad-assign-chip"});I.createSpan({cls:"stashpad-assign-chip-name",text:g.name});let p=I.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});p.title=`Remove ${g.name}`,p.onclick=()=>{t=t.filter(u=>u.id!==g.id),l(),A()}}},d=g=>{g.name.trim()&&(t.some(I=>I.id===g.id)||t.push(g),o.value="",a.setCssStyles({display:"none"}),l(),A(),o.focus())},h=()=>{let g=o.value.trim();a.empty();let I=new Set(t.map(f=>f.id)),u=e.filter(f=>!I.has(f.id)&&Xi(g,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>d(f)}));if(g&&!e.some(f=>f.name.toLowerCase()===g.toLowerCase())&&u.push({label:`Create \u201C${g}\u201D`,onPick:()=>d({id:tt(6),name:g})}),u.length===0){a.setCssStyles({display:"none"});return}a.setCssStyles({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",h),o.addEventListener("focus",h),o.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let I=a.querySelector(".stashpad-assign-suggest-item");I&&I.dispatchEvent(new MouseEvent("mousedown"))}else g.key==="Escape"&&a.style.display!=="none"&&(g.stopPropagation(),a.setCssStyles({display:"none"}))}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.setCssStyles({display:"none"})},120)}),A()}var q,Jr,be,Je,Ke,fi,Ci,mi,vt,Bi,es,ui,xe,pt,Oe,Ne,Qi,Qn,yi,Ei,Ft=Lt(()=>{"use strict";q=require("obsidian");gi();Cn();rt();_i();Tt();Jr=q.moment,be=class be extends q.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 l of this.text.trim().split(/\r?\n/))if(l)try{this.events.push(JSON.parse(l))}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(be.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(be.PAGE),this.renderFooter()},t>be.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 q.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,q.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 q.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new q.Notice(`Export failed: ${t.message}`),null}}clearLog(){new pt(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 q.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 q.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,q.moment)(t.ts).isValid()?(0,q.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()}};be.PAGE=100;Je=be,Ke=class extends q.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()}},fi=class extends q.Modal{constructor(t,e,i,s,n){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;this.onSplitMany=n;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` +`).trim()),e.filter(Boolean)}function Tt(c,r,t){c.empty();try{(0,Lo.setIcon)(c,r)}catch{}let e=c.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(c.empty(),c.createSpan({cls:"stashpad-icon-fallback",text:t}))}function qo(c){if(c instanceof Element&&c.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let r=new Set([document]);c instanceof Element&&c.ownerDocument&&r.add(c.ownerDocument);for(let t of r)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 Jo(c){let r=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(c))!=null;)r.push({lang:e[3].trim(),code:e[4]});return r}function pi(c){return c.split("/").map(r=>r.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function Ko(c,r,t){let e=new Set(r),i=c.filter(n=>!e.has(n)),s=c.findIndex(n=>e.has(n));if(s<0)return c.slice();switch(t){case"top":return[...r,...i];case"bottom":return[...i,...r];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...r),o}case"down":{let n=(()=>{let A=-1;return c.forEach((d,h)=>{e.has(d)&&(A=h)}),A})(),o=0;for(let A=0;A0){let n=e[i-1];return(!/[a-z0-9]/.test(n)?600:500)-Math.min(i,99)}let s=0;for(let n=0;n({t:e,s:Ur(t,e.raw)})).filter(e=>e.s>=0).sort((e,i)=>i.s-e.s||i.t.count-e.t.count||e.t.label.localeCompare(i.t.label)).map(e=>e.t):r}var Lo,di,ke,Se,gi=Lt(()=>{"use strict";Lo=require("obsidian"),di={lines:"Each line",paragraphs:"Paragraphs (blank line)",headings:"Headings"};ke="__stashpad:tagged__",Se="__stashpad:untagged__"});function Gr(c,r){return c>12?c>=24?0:c:r==="am"?c===12?0:c:c===12?12:c+12}function _i(c,r){c.addClass("stashpad-when-pop-time");let t=r.seedPeriod,e=c.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(r.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(r.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 l=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};l(),o.addEventListener("mousedown",B=>B.preventDefault()),a.addEventListener("mousedown",B=>B.preventDefault()),o.addEventListener("click",B=>{B.preventDefault(),t="am",l()}),a.addEventListener("click",B=>{B.preventDefault(),t="pm",l()});let A=i;i.addEventListener("focus",()=>{A=i,i.select()}),s.addEventListener("focus",()=>{A=s,s.select()});let d=()=>{let y=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",y),a.toggleClass("is-disabled",y),o.disabled=y,a.disabled=y},h=B=>{let y=B.value.replace(/\D/g,"").slice(0,2);if(y===""){B.value="",B===i&&d();return}let Q=parseInt(y,10);B===i?Q>24&&(Q=24):Q>59&&(Q=59),B.value=String(Q),B===i&&d()};for(let B of[i,s])B.addEventListener("input",()=>h(B));d();let g=()=>{let B=parseInt(i.value||"12",10)||12,y=parseInt(s.value||"0",10)||0,Q=B>12;r.onFinalize({hours24:Gr(B,t),minutes:y,raw:{hh:B,mm:y,period:t,is24:Q}}),r.close()};r.setOnEnter?.(g);let I=[i,s,o,a],p=(B,y)=>{let Q=I.indexOf(B);if(Q===-1)return;let E=(Q+y+I.length)%I.length;I[E].focus()},u=B=>{B.addEventListener("keydown",y=>{y.key==="Enter"?(y.preventDefault(),y.stopPropagation(),g()):y.key==="Escape"?(y.preventDefault(),y.stopPropagation(),r.close()):y.key==="Tab"&&(y.preventDefault(),y.stopPropagation(),p(B,y.shiftKey?-1:1))})},f=c.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let B of C){let y=f.createEl("button",{cls:"stashpad-when-time-padbtn"});y.type="button",B==="backspace"?(0,Yo.setIcon)(y,"delete"):B==="insert"?(y.setText("OK"),m=y):y.setText(B),B==="insert"&&y.addClass("is-go"),y.addEventListener("mousedown",Q=>Q.preventDefault()),y.addEventListener("click",Q=>{if(Q.preventDefault(),B==="insert"){g();return}if(B==="backspace"){A.value=A.value.slice(0,-1),h(A),A.focus();return}let E=A.selectionStart===0&&A.selectionEnd===A.value.length&&A.value.length>0,v=2,w=E||A.value.length>=v?B:A.value+B;A.value=w,h(A),A.focus(),A.setSelectionRange(A.value.length,A.value.length),A===i&&A.value.length>=v&&(s.focus(),s.select())})}m&&I.push(m);for(let B of I)u(B);i.focus(),i.select()}function $o(c){let{hh:r,mm:t,period:e,is24:i}=c.raw;return i?`${r}:${String(t).padStart(2,"0")}`:`${r}:${String(t).padStart(2,"0")}${e}`}var Yo,Cn=Lt(()=>{"use strict";Yo=require("obsidian")});function Vo(c){let r=Math.floor(4294967296/c)*c,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=r);return e%c}function mn(c=5){let r=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),Rr.has(c.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 Lr(c){let r=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Ii(c){let r="stashpad-",t=Lr(c),e=64-r.length-1-t.length,i=c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${r}${i}-${t}`}var zo,Rr,ts=Lt(()=>{"use strict";zo="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).filter((c,r,t)=>t.indexOf(c)===r);Rr=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 es={};ri(es,{newId:()=>tt});function tt(c=6){let r="",t=new Uint8Array(c);crypto.getRandomValues(t);for(let e=0;e{"use strict";Wo="abcdefghijkmnpqrstuvwxyz23456789"});var wi={};ri(wi,{ColorPickerModal:()=>Ne,ConfirmDeleteModal:()=>Ke,ConfirmModal:()=>ot,CustomColorModal:()=>is,DueDatePickerModal:()=>Oe,EncryptionPasswordModal:()=>vt,ExportStashModal:()=>Ci,ImportDupChoiceModal:()=>yi,ImportLogModal:()=>Qn,LogModal:()=>Je,NotificationHistoryModal:()=>Qi,OkfExportModal:()=>Ei,SplitNoteModal:()=>fi,StashPasswordModal:()=>mi,TypeToConfirmModal:()=>Bi,buildAssigneePicker:()=>Xo});function Xo(c,r){let t=[...r.initial],e=r.knownAuthors,i=c.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.setCssStyles({display:"none"});let l=()=>r.onChange([...t]),A=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let g of t){let I=s.createSpan({cls:"stashpad-assign-chip"});I.createSpan({cls:"stashpad-assign-chip-name",text:g.name});let p=I.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});p.title=`Remove ${g.name}`,p.onclick=()=>{t=t.filter(u=>u.id!==g.id),l(),A()}}},d=g=>{g.name.trim()&&(t.some(I=>I.id===g.id)||t.push(g),o.value="",a.setCssStyles({display:"none"}),l(),A(),o.focus())},h=()=>{let g=o.value.trim();a.empty();let I=new Set(t.map(f=>f.id)),u=e.filter(f=>!I.has(f.id)&&Zi(g,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>d(f)}));if(g&&!e.some(f=>f.name.toLowerCase()===g.toLowerCase())&&u.push({label:`Create \u201C${g}\u201D`,onPick:()=>d({id:tt(6),name:g})}),u.length===0){a.setCssStyles({display:"none"});return}a.setCssStyles({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",h),o.addEventListener("focus",h),o.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let I=a.querySelector(".stashpad-assign-suggest-item");I&&I.dispatchEvent(new MouseEvent("mousedown"))}else g.key==="Escape"&&a.style.display!=="none"&&(g.stopPropagation(),a.setCssStyles({display:"none"}))}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.setCssStyles({display:"none"})},120)}),A()}var q,qr,De,Je,Ke,fi,Ci,mi,vt,Bi,is,ui,Ne,ot,Oe,be,Qi,Qn,yi,Ei,Ft=Lt(()=>{"use strict";q=require("obsidian");gi();Cn();lt();ts();Ht();qr=q.moment,De=class De extends q.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 l of this.text.trim().split(/\r?\n/))if(l)try{this.events.push(JSON.parse(l))}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(De.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(De.PAGE),this.renderFooter()},t>De.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 q.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,q.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 q.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new q.Notice(`Export failed: ${t.message}`),null}}clearLog(){new ot(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 q.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 q.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,q.moment)(t.ts).isValid()?(0,q.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()}};De.PAGE=100;Je=De,Ke=class extends q.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()}},fi=class extends q.Modal{constructor(t,e,i,s,n){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;this.onSplitMany=n;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 q.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-quick"});t.createSpan({cls:"stashpad-split-quick-label",text:"Split by:"}),["lines","paragraphs","headings"].forEach(o=>{let a=hi(this.body,o),l=t.createEl("button",{cls:"stashpad-split-quick-btn",text:`${di[o]} (${a.length})`});l.disabled=a.length<2,l.onmousedown=A=>A.preventDefault(),l.onclick=()=>{let A=hi(this.body,o);if(A.length<2){new q.Notice("That delimiter wouldn't split this note.");return}this.close(),this.onSplitMany(A)}});let e=this.contentEl.createDiv({cls:"stashpad-split-toggle-bar"});if(this.lines.length>=2){let o=e.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&o.addClass("is-active"),o.onclick=()=>{this.mode="line",this.render()}}let i=e.createEl("button",{text:"Cursor split",cls:"stashpad-split-mode-btn"});this.mode==="cursor"&&i.addClass("is-active"),i.onclick=()=>{this.mode="cursor",this.render()};let s=e.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});s.onmousedown=o=>o.preventDefault(),s.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let n=this.contentEl.createDiv({cls:"stashpad-split-help"});q.Platform.isMobile?n.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):n.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"}),e=null;for(let i=0;i{let n=Math.max(1,Math.min(this.lines.length-1,i+1));n!==this.lineCursorIdx&&(this.lineCursorIdx=n,this.render())}}e&&window.requestAnimationFrame(()=>e.scrollIntoView({block:"center"}))}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=q.Platform.isMobile?3:12,n=2,o=()=>{e.setCssStyles({height:"auto"});let a=Math.min(e.scrollHeight,i*s+16);e.setCssStyles({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()}},Ci=class extends q.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 l=s.createDiv({cls:"stashpad-export-pw-area"});l.setCssStyles({display:"none"});let A=[],d=R=>{let V=l.createDiv({cls:"stashpad-export-pw-row"}),O=V.createEl("input",{type:"password"});O.addClass("stashpad-export-name"),O.placeholder=R;let Y=V.createEl("button",{cls:"stashpad-export-copy"}),it=()=>{let at=O.value.length===0;Y.setText(at?"Paste":"Copy"),Y.toggleClass("is-paste",at),Y.setAttr("aria-label",`${at?"Paste into":"Copy"} ${R.toLowerCase()}`)};return Y.onclick=async at=>{if(at.preventDefault(),O.value.length===0)try{let _=(await navigator.clipboard?.readText())?.trim();if(!_){new q.Notice("Clipboard is empty.");return}O.value=_,O.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(O.value).then(()=>new q.Notice("Passphrase copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},it(),A.push(it),O},h=d("Password"),g=d("Confirm password"),I=l.createDiv({cls:"stashpad-export-strength"}),p=I.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>p.createDiv({cls:"stashpad-strength-seg"})),f=I.createEl("span",{cls:"stashpad-strength-label"}),C=l.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),B=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),y=l.createEl("div",{cls:"stashpad-export-pw-hint"}),Q=l.createEl("div",{cls:"stashpad-export-pw-suite"});Q.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(R=>{Q.toggleClass("is-weak",!R),Q.setText(R?"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(()=>{Q.setText("Encryption: AES-256-GCM with a password-derived key.")}):Q.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let E=this.app.secretStorage,v=l.createDiv({cls:"stashpad-export-remember"}),w=v.createEl("input",{type:"checkbox"});w.id="stashpad-export-remember-cb";let D=v.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});D.htmlFor=w.id;let N=l.createDiv({cls:"stashpad-export-remember-note"});N.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."),N.setCssStyles({display:"none"}),w.onchange=()=>{N.setCssStyles({display:w.checked?"":"none"})},E||v.setCssStyles({display:"none"});let P=()=>{let R=e.value.trim()||this.defaultBaseName;return o.checked?`${R}-encrypted`:R},H=()=>i.setText(`Saves as: ${P()}-.stash`);e.oninput=H;let b=this.contentEl.createDiv({cls:"stashpad-export-footer"}),S=b.createEl("button",{text:"Cancel"});S.onclick=()=>this.close();let T=b.createEl("button",{cls:"mod-cta",text:"Export"}),U=()=>{let R=Bn(h.value);I.style.visibility=h.value?"visible":"hidden",u.forEach((V,O)=>V.toggleClass("is-on",h.value!==""&&O<=R.level)),p.dataset.level=String(R.level),f.setText(R.label)},L=()=>{let R=o.checked;l.setCssStyles({display:R?"":"none"});let V=!0;R&&(h.value?h.value!==g.value?(y.setText("Passwords don't match."),y.addClass("is-error"),V=!1):(y.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),y.removeClass("is-error")):(y.setText("Enter a password to encrypt this export."),y.removeClass("is-error"),V=!1)),U(),A.forEach(O=>O()),T.disabled=!V,T.toggleClass("is-disabled",!V),H()},W=!1,z=R=>{W=R,h.type=g.type=R?"text":"password",B.setText(R?"Hide":"Show")};B.onclick=R=>{R.preventDefault(),z(!W)},m.onclick=R=>{R.preventDefault(),h.value=g.value=mn(),z(!1),new q.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),L()},o.onchange=L,h.oninput=L,g.oninput=L,L();let $=()=>this.commit(P(),o.checked?h.value:null,o.checked&&w.checked);T.onclick=$,this.scope.register([],"Enter",R=>{R.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()}},mi=class extends q.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()}},vt=class extends q.Modal{constructor(t,e){super(t);this.opts=e;this.succeeded=!1}onOpen(){let{mode:t}=this.opts;this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal","stashpad-encryption-modal"),this.titleEl.setText(this.opts.title??(t==="setup"?"Set up encryption password":t==="change"?"Change encryption password":"Unlock encryption")),this.contentEl.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),this.opts.intro?this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:this.opts.intro}):t==="setup"&&this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This single password protects everything you encrypt in this vault. It is stored only on this device. There is NO recovery \u2014 if you lose it, anything you've encrypted is gone for good."});let e=[],i=u=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),C=f.createEl("input",{type:"password"});C.addClass("stashpad-export-name","stashpad-encryption-field"),C.placeholder=u;let m=f.createEl("button",{cls:"stashpad-export-copy"}),B=()=>{let y=C.value.length===0;m.setText(y?"Paste":"Copy"),m.toggleClass("is-paste",y),m.setAttr("aria-label",`${y?"Paste into":"Copy"} ${u.toLowerCase()}`)};return m.onclick=async y=>{if(y.preventDefault(),C.value.length===0)try{let Q=(await navigator.clipboard?.readText())?.trim();if(!Q){new q.Notice("Clipboard is empty.");return}C.value=Q,C.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(C.value).then(()=>new q.Notice("Copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},C.addEventListener("input",B),B(),e.push(B),C},s=null,n=null,o=null;if((t==="unlock"||t==="change")&&(s=i("Current password")),(t==="setup"||t==="change")&&(n=i(t==="change"?"New password":"Password"),o=i("Confirm password")),n){let u=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=u.createDiv({cls:"stashpad-strength-bar"}),C=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),m=u.createEl("span",{cls:"stashpad-strength-label"}),B=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),y=()=>{let w=n.value,D=Bn(w);C.forEach((N,P)=>N.toggleClass("is-on",P0&&w.length<6?" \u2014 use at least 6":""}`),B.toggleClass("is-weak",w.length>0&&w.length<6)};n.addEventListener("input",y),y();let Q=this.contentEl.createDiv({cls:"stashpad-export-genrow"});Q.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=w=>{w.preventDefault();let D=mn(5);n.value=D,o&&(o.value=D),y(),e.forEach(N=>N()),new q.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(D).catch(()=>{})};let E=Q.createEl("button",{cls:"stashpad-export-show",text:"Show"});E.onclick=w=>{w.preventDefault();let D=n.type==="password";n.type=D?"text":"password",o&&(o.type=D?"text":"password"),E.setText(D?"Hide":"Show")};let v=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});v.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(w=>{v.toggleClass("is-weak",!w),v.setText(w?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run here, so this will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>v.setText("Encryption: AES-256-GCM with a password-derived key.")):v.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let a=null,l=this.app.secretStorage;if(this.opts.offerKeychain&&l){let u=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=u.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let f=u.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});f.htmlFor=a.id;let C=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});C.setText("Stored only in this device's keychain \u2014 doesn't sync to your other devices. Anyone with access to this unlocked device + keychain could decrypt."),C.setCssStyles({display:"none"}),a.onchange=()=>{C.setCssStyles({display:a.checked?"":"none"})}}let A=this.contentEl.createEl("div",{cls:"stashpad-export-error"});A.setCssStyles({display:"none"});let d=u=>{A.setText(u),A.setCssStyles({display:""})},h=this.contentEl.createDiv({cls:"stashpad-export-footer"});h.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let g=h.createEl("button",{cls:"mod-cta",text:t==="setup"?"Set up":t==="change"?"Change":"Unlock"}),I=!1,p=async()=>{if(I)return;let u=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!u){d("Enter your current password.");return}if(t==="setup"||t==="change"){if(!f){d("Enter a password.");return}if(f.length<6){d("Use at least 6 characters.");return}if(f!==o?.value){d("Passwords don't match.");return}}I=!0,g.disabled=!0,A.setCssStyles({display:"none"});let C=g.textContent;g.setText("Working\u2026");try{let m=await this.opts.onSubmit({current:u,next:f,remember:!!a?.checked});if(m){d(m),I=!1,g.disabled=!1,g.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(m){d(`Failed: ${m.message}`),I=!1,g.disabled=!1,g.setText(C??"OK")}};g.onclick=()=>void p(),this.scope.register([],"Enter",u=>{u.preventDefault(),p()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},Bi=class extends q.Modal{constructor(t,e){super(t);this.opts=e}onOpen(){this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal","stashpad-encryption-modal"),this.titleEl.setText(this.opts.title),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:this.opts.body});let t=null;this.opts.requirePassword&&(this.contentEl.createEl("p",{cls:"stashpad-export-desc"}).setText("Enter your encryption password:"),t=this.contentEl.createEl("input",{type:"password"}),t.addClass("stashpad-export-name","stashpad-encryption-field"),t.placeholder="Password"),this.contentEl.createEl("p",{cls:"stashpad-export-desc"}).setText(`Type "${this.opts.phrase}" to confirm.`);let e=this.contentEl.createEl("input",{type:"text"});e.addClass("stashpad-export-name","stashpad-encryption-field"),e.placeholder=this.opts.phrase;let i=this.contentEl.createEl("div",{cls:"stashpad-export-error"});i.setCssStyles({display:"none"});let s=this.contentEl.createDiv({cls:"stashpad-export-footer"});s.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let n=s.createEl("button",{cls:"mod-cta mod-warning",text:this.opts.confirmText}),o=()=>e.value.trim().toLowerCase()===this.opts.phrase.trim().toLowerCase(),a=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",a),t?.addEventListener("input",a),a();let l=!1,A=async()=>{if(!(l||!o())){if(this.opts.requirePassword&&(l=!0,n.disabled=!0,i.setCssStyles({display:"none"}),!await this.opts.requirePassword(t.value))){i.setText("Wrong password."),i.setCssStyles({display:""}),l=!1,a();return}this.close(),await this.opts.onConfirm()}};n.onclick=()=>void A(),this.scope.register([],"Enter",d=>{d.preventDefault(),A()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},es=class extends q.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=d=>{let h=d.startsWith("#")?d:"#"+d;/^#[0-9a-f]{6}$/i.test(h)&&(this.value=h,e.style.background=h,i.value=h,s.value!==h&&(s.value=h))};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 l=o.createEl("button",{cls:"mod-cta",text:"Save"});l.title="Apply this color to the selection (without adding to your palette).",l.onclick=()=>this.commit({addToPalette:!1});let A=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});A.title="Apply and save this color so it appears as a tile next time.",A.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",d=>{d.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",d=>{d.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()}},ui=class ui extends q.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=[...ui.DEFAULT_PALETTE,...this.customPalette];for(let a of i){let l=t.createDiv({cls:"stashpad-color-tile"});l.style.background=a,l.title=a;let A=!ui.DEFAULT_PALETTE.some(h=>h.toLowerCase()===a.toLowerCase()),d=this.items.length;if(l.onclick=()=>this.activate(d),A&&this.onDeleteCustom){let h=l.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});h.title="Remove from palette",h.onclick=g=>{g.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:A?"custom":"preset",color:a,el:l})}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 es(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))}};Oe=class extends q.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(this.opts.title??"Set due date");let t=null;if(this.current){let m=Date.parse(this.current);Number.isNaN(m)||(t=new Date(m))}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,q.setIcon)(n,"calendar");let o=s.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=s.createSpan({cls:"stashpad-due-clear",attr:{"aria-label":"Clear date"}});(0,q.setIcon)(a,"x"),a.onclick=()=>{o.value="",o.focus()};let l=i.createDiv({cls:"stashpad-due-field"}),A=l.createSpan({cls:"stashpad-due-field-icon"});(0,q.setIcon)(A,"clock");let d=l.createEl("input",{type:"time",cls:"stashpad-due-time"}),h=l.createSpan({cls:"stashpad-due-clear",attr:{"aria-label":"Clear time"}});(0,q.setIcon)(h,"x"),h.onclick=()=>{d.value="",d.focus()},n.onclick=()=>{try{o.showPicker?.()}catch{}},A.onclick=()=>this.openTimeNumpad(A,d),t&&(o.value=this.toDateValue(t),d.value=this.toTimeValue(t)),this.renderAssignSection(e);let g=e.createDiv({cls:"stashpad-due-grid"}),I=(m,B)=>{let y=g.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:m});y.onclick=()=>{let Q=B();o.value=this.toDateValue(Q),d.value||(d.value=this.toTimeValue(Q))}},p=m=>(m.setHours(9,0,0,0),m);I("Today",()=>p(this.startOfTodayLocal())),I("Tomorrow",()=>{let m=this.startOfTodayLocal();return m.setDate(m.getDate()+1),p(m)}),I("Next week",()=>{let m=this.startOfTodayLocal();return m.setDate(m.getDate()+7),p(m)});let u=g.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});u.onclick=()=>{o.value="",d.value="",o.focus()};let f=g.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});f.onclick=()=>{this.didChoose=!0,this.close()};let C=g.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});C.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[m,B,y]=o.value.split("-").map(w=>parseInt(w,10)),Q=9,E=0;if(d.value){let[w,D]=d.value.split(":").map(N=>parseInt(N,10));Q=w,E=D}let v=new Date(m,B-1,y,Q,E,0,0);this.didChoose=!0,this.close(),this.onPick({iso:v.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){Xo(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[I,p]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(I)&&(i=I),Number.isFinite(p)&&(s=p)}else{let I=new Date;i=I.getHours(),s=I.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.setCssStyles({position:"fixed",zIndex:"9999"});let l=null,A=()=>{a.remove(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",h,!0),this.tinyClosePopover===A&&(this.tinyClosePopover=null)},d=I=>{!a.contains(I.target)&&I.target!==t&&!t.contains(I.target)&&A()},h=I=>{I.key==="Escape"?(I.preventDefault(),I.stopPropagation(),A()):I.key==="Enter"&&l&&(I.preventDefault(),I.stopPropagation(),l())};this.tinyClosePopover=A,ji(a,{seedH:o,seedM:s,seedPeriod:n,close:A,setOnEnter:I=>{l=I},onFinalize:I=>{e.value=`${String(I.hours24).padStart(2,"0")}:${String(I.minutes).padStart(2,"0")}`}});let g=t.getBoundingClientRect();a.setCssStyles({left:`${Math.max(8,Math.min(g.left,window.innerWidth-220))}px`,top:`${g.bottom+4}px`}),setTimeout(()=>{document.addEventListener("mousedown",d,!0),document.addEventListener("keydown",h,!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}`}},Ne=class Ne extends q.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 pt(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(Ne.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let A=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let d of e.actionLabels){let h=A.createSpan({cls:"stashpad-notif-action-chip"});h.setText(d),h.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(Ne.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Ne.PAGE),this.renderFooter()},t>Ne.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Ne.PAGE=100;Qi=Ne,Qn=class extends q.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,q.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()}},yi=class extends q.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()}},Ei=class extends q.Modal{constructor(t,e,i,s){super(t);this.noteCount=i;this.onConfirm=s;this.base=e}onOpen(){this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal"),this.titleEl.setText("Export as OKF"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`Export ${this.noteCount} note${this.noteCount===1?"":"s"} as an Open Knowledge Format bundle. Pick one or more formats.`});let t=this.contentEl.createEl("input",{type:"text"});t.addClass("stashpad-export-name"),t.value=this.base,t.placeholder="Export name";let e=(l,A)=>{let d=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),h=d.createEl("input",{type:"checkbox"});return h.checked=A,d.createEl("label",{text:l}),h},i=e(".zip \u2014 OKF bundle (portable)",!0),s=e(".tar.gz \u2014 OKF bundle (tarball)",!1),n=e(".stash \u2014 Stashpad format (re-importable)",!1),o=this.contentEl.createDiv({cls:"stashpad-export-footer"});o.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let a=o.createEl("button",{cls:"mod-cta",text:"Export"});a.onclick=()=>{if(!i.checked&&!s.checked&&!n.checked){new q.Notice("Pick at least one format.");return}this.close(),this.onConfirm(t.value.trim()||this.base,{zip:i.checked,targz:s.checked,stash:n.checked})},requestAnimationFrame(()=>t.focus())}onClose(){this.contentEl.empty()}}});function Qt(c,r=Yt){let t=r instanceof Set?r:new Set(r.map(o=>o.toLowerCase())),e=(c.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 yt(c,r){return`${c}-${r}.md`}function de(c){let r=c.match(/-([a-z0-9]{4,12})$/);return r?r[1]:null}function ns(c,r){let t=c.lastIndexOf(".");return t>0?`${c.slice(0,t)}-${r}${c.slice(t)}`:`${c}-${r}`}function Zo(c){let r=c.match(/^([0-9a-z]{7,9})-(.+)$/);if(!r)return null;let t=parseInt(r[1],36);return!Number.isFinite(t)||t<142e10||t>Date.now()+864e5?null:{stamp:r[1],rest:r[2]}}var Yt,Ye=Lt(()=>{"use strict";Yt=["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 rs={};ri(rs,{JdBuildConfirmModal:()=>Fi,buildJdIndexNotes:()=>En,buildJdIndexPreview:()=>os,buildJdPreviewNotice:()=>as,scanForJdNotes:()=>ze});function yn(c,r){if(/^\d+-\d+$/.test(c))return null;if(c.includes(".")){let e=c.split(".").slice(0,-1).join(".");return r.has(e)?e:yn(e,r)}if(/^\d+$/.test(c)){let t=parseInt(c,10);for(let e of r){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 ze(c,r,t){let e=c.vault.getMarkdownFiles(),i=Or(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(r.discoverStashpadFolders()),o=I=>s?!1:Array.from(n).some(p=>I===p||I.startsWith(p+"/")),a=[],l=[],A=[];for(let I of i){let p=I.parent?.path?.replace(/\/+$/,"")??"";if(o(p)){A.push(I);continue}let u=I.basename.match(jo);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:I,folder:null}):l.push(I)}let d=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",h=I=>{let p=I.path.replace(/\/+$/,"");if(!(d&&p&&p!==d&&!p.startsWith(d+"/"))){if(p&&!o(p)){let u=I.name.match(jo);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:I})}}for(let u of I.children)u instanceof gt.TFolder&&h(u)};h(c.vault.getRoot());let g=t.jdIndexSort??"natural";return a.sort((I,p)=>Yr(I,p,g)),{indexed:a,nonIndex:l,skippedStashpadNotes:A}}async function os(c,r,t){let e=wn(t.jdIndexStashpadFolder??"");if(!e)return{...ze(c,r,t),previewPath:null,error:"no-dest"};let i=ze(c,r,t),s=Kr(c,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=zr(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await c.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),l=a?`${a[0]}${n}`:n;return await c.vault.modify(s,l),{...i,previewPath:s.path}}function Kr(c,r){let t=c.vault.getAbstractFileByPath(r);if(!(t instanceof gt.TFolder))return null;for(let e of t.children){if(!(e instanceof gt.TFile)||e.extension!=="md")continue;if((c.metadataCache.getFileCache(e)?.frontmatter??{}).id===F)return e}return null}async function En(c,r,t){let e=wn(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(r.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let s=ze(c,r,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{l.push(f);for(let C of a.get(f)??[])A(C)};for(let f of o)A(f);let d=new Map,h=c.vault.getAbstractFileByPath(e);if(h instanceof gt.TFolder)for(let f of h.children){if(!(f instanceof gt.TFile)||f.extension!=="md")continue;let C=c.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&d.set(C.jdPrefix,f)}let g=new Map,I=0,p=0,u=0;for(let f of l){let C=n.get(f)??null,m=yn(f,new Set(n.keys())),B=m?g.get(m)??F:F,y=C?`${f} ${C.title}`:f,Q=C?.file?`[[${C.file.basename}]]`:"",E=Q?`${Q} +`),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 q.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-quick"});t.createSpan({cls:"stashpad-split-quick-label",text:"Split by:"}),["lines","paragraphs","headings"].forEach(o=>{let a=hi(this.body,o),l=t.createEl("button",{cls:"stashpad-split-quick-btn",text:`${di[o]} (${a.length})`});l.disabled=a.length<2,l.onmousedown=A=>A.preventDefault(),l.onclick=()=>{let A=hi(this.body,o);if(A.length<2){new q.Notice("That delimiter wouldn't split this note.");return}this.close(),this.onSplitMany(A)}});let e=this.contentEl.createDiv({cls:"stashpad-split-toggle-bar"});if(this.lines.length>=2){let o=e.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&o.addClass("is-active"),o.onclick=()=>{this.mode="line",this.render()}}let i=e.createEl("button",{text:"Cursor split",cls:"stashpad-split-mode-btn"});this.mode==="cursor"&&i.addClass("is-active"),i.onclick=()=>{this.mode="cursor",this.render()};let s=e.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});s.onmousedown=o=>o.preventDefault(),s.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let n=this.contentEl.createDiv({cls:"stashpad-split-help"});q.Platform.isMobile?n.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):n.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"}),e=null;for(let i=0;i{let n=Math.max(1,Math.min(this.lines.length-1,i+1));n!==this.lineCursorIdx&&(this.lineCursorIdx=n,this.render())}}e&&window.requestAnimationFrame(()=>e.scrollIntoView({block:"center"}))}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=q.Platform.isMobile?3:12,n=2,o=()=>{e.setCssStyles({height:"auto"});let a=Math.min(e.scrollHeight,i*s+16);e.setCssStyles({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()}},Ci=class extends q.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 l=s.createDiv({cls:"stashpad-export-pw-area"});l.setCssStyles({display:"none"});let A=[],d=R=>{let V=l.createDiv({cls:"stashpad-export-pw-row"}),K=V.createEl("input",{type:"password"});K.addClass("stashpad-export-name"),K.placeholder=R;let O=V.createEl("button",{cls:"stashpad-export-copy"}),it=()=>{let rt=K.value.length===0;O.setText(rt?"Paste":"Copy"),O.toggleClass("is-paste",rt),O.setAttr("aria-label",`${rt?"Paste into":"Copy"} ${R.toLowerCase()}`)};return O.onclick=async rt=>{if(rt.preventDefault(),K.value.length===0)try{let _=(await navigator.clipboard?.readText())?.trim();if(!_){new q.Notice("Clipboard is empty.");return}K.value=_,K.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(K.value).then(()=>new q.Notice("Passphrase copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},it(),A.push(it),K},h=d("Password"),g=d("Confirm password"),I=l.createDiv({cls:"stashpad-export-strength"}),p=I.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>p.createDiv({cls:"stashpad-strength-seg"})),f=I.createEl("span",{cls:"stashpad-strength-label"}),C=l.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),B=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),y=l.createEl("div",{cls:"stashpad-export-pw-hint"}),Q=l.createEl("div",{cls:"stashpad-export-pw-suite"});Q.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(R=>{Q.toggleClass("is-weak",!R),Q.setText(R?"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(()=>{Q.setText("Encryption: AES-256-GCM with a password-derived key.")}):Q.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let E=this.app.secretStorage,v=l.createDiv({cls:"stashpad-export-remember"}),w=v.createEl("input",{type:"checkbox"});w.id="stashpad-export-remember-cb";let D=v.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});D.htmlFor=w.id;let N=l.createDiv({cls:"stashpad-export-remember-note"});N.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."),N.setCssStyles({display:"none"}),w.onchange=()=>{N.setCssStyles({display:w.checked?"":"none"})},E||v.setCssStyles({display:"none"});let P=()=>{let R=e.value.trim()||this.defaultBaseName;return o.checked?`${R}-encrypted`:R},H=()=>i.setText(`Saves as: ${P()}-.stash`);e.oninput=H;let b=this.contentEl.createDiv({cls:"stashpad-export-footer"}),S=b.createEl("button",{text:"Cancel"});S.onclick=()=>this.close();let T=b.createEl("button",{cls:"mod-cta",text:"Export"}),U=()=>{let R=Bn(h.value);I.style.visibility=h.value?"visible":"hidden",u.forEach((V,K)=>V.toggleClass("is-on",h.value!==""&&K<=R.level)),p.dataset.level=String(R.level),f.setText(R.label)},L=()=>{let R=o.checked;l.setCssStyles({display:R?"":"none"});let V=!0;R&&(h.value?h.value!==g.value?(y.setText("Passwords don't match."),y.addClass("is-error"),V=!1):(y.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),y.removeClass("is-error")):(y.setText("Enter a password to encrypt this export."),y.removeClass("is-error"),V=!1)),U(),A.forEach(K=>K()),T.disabled=!V,T.toggleClass("is-disabled",!V),H()},W=!1,$=R=>{W=R,h.type=g.type=R?"text":"password",B.setText(R?"Hide":"Show")};B.onclick=R=>{R.preventDefault(),$(!W)},m.onclick=R=>{R.preventDefault(),h.value=g.value=mn(),$(!1),new q.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),L()},o.onchange=L,h.oninput=L,g.oninput=L,L();let z=()=>this.commit(P(),o.checked?h.value:null,o.checked&&w.checked);T.onclick=z,this.scope.register([],"Enter",R=>{R.preventDefault(),T.disabled||z()}),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()}},mi=class extends q.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()}},vt=class extends q.Modal{constructor(t,e){super(t);this.opts=e;this.succeeded=!1}onOpen(){let{mode:t}=this.opts;this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal","stashpad-encryption-modal"),this.titleEl.setText(this.opts.title??(t==="setup"?"Set up encryption password":t==="change"?"Change encryption password":"Unlock encryption")),this.contentEl.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),this.opts.intro?this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:this.opts.intro}):t==="setup"&&this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This single password protects everything you encrypt in this vault. It is stored only on this device. There is NO recovery \u2014 if you lose it, anything you've encrypted is gone for good."});let e=[],i=u=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),C=f.createEl("input",{type:"password"});C.addClass("stashpad-export-name","stashpad-encryption-field"),C.placeholder=u;let m=f.createEl("button",{cls:"stashpad-export-copy"}),B=()=>{let y=C.value.length===0;m.setText(y?"Paste":"Copy"),m.toggleClass("is-paste",y),m.setAttr("aria-label",`${y?"Paste into":"Copy"} ${u.toLowerCase()}`)};return m.onclick=async y=>{if(y.preventDefault(),C.value.length===0)try{let Q=(await navigator.clipboard?.readText())?.trim();if(!Q){new q.Notice("Clipboard is empty.");return}C.value=Q,C.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(C.value).then(()=>new q.Notice("Copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},C.addEventListener("input",B),B(),e.push(B),C},s=null,n=null,o=null;if((t==="unlock"||t==="change")&&(s=i("Current password")),(t==="setup"||t==="change")&&(n=i(t==="change"?"New password":"Password"),o=i("Confirm password")),n){let u=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=u.createDiv({cls:"stashpad-strength-bar"}),C=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),m=u.createEl("span",{cls:"stashpad-strength-label"}),B=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),y=()=>{let w=n.value,D=Bn(w);C.forEach((N,P)=>N.toggleClass("is-on",P0&&w.length<6?" \u2014 use at least 6":""}`),B.toggleClass("is-weak",w.length>0&&w.length<6)};n.addEventListener("input",y),y();let Q=this.contentEl.createDiv({cls:"stashpad-export-genrow"});Q.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=w=>{w.preventDefault();let D=mn(5);n.value=D,o&&(o.value=D),y(),e.forEach(N=>N()),new q.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(D).catch(()=>{})};let E=Q.createEl("button",{cls:"stashpad-export-show",text:"Show"});E.onclick=w=>{w.preventDefault();let D=n.type==="password";n.type=D?"text":"password",o&&(o.type=D?"text":"password"),E.setText(D?"Hide":"Show")};let v=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});v.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(w=>{v.toggleClass("is-weak",!w),v.setText(w?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run here, so this will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>v.setText("Encryption: AES-256-GCM with a password-derived key.")):v.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let a=null,l=this.app.secretStorage;if(this.opts.offerKeychain&&l){let u=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=u.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let f=u.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});f.htmlFor=a.id;let C=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});C.setText("Stored only in this device's keychain \u2014 doesn't sync to your other devices. Anyone with access to this unlocked device + keychain could decrypt."),C.setCssStyles({display:"none"}),a.onchange=()=>{C.setCssStyles({display:a.checked?"":"none"})}}let A=this.contentEl.createEl("div",{cls:"stashpad-export-error"});A.setCssStyles({display:"none"});let d=u=>{A.setText(u),A.setCssStyles({display:""})},h=this.contentEl.createDiv({cls:"stashpad-export-footer"});h.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let g=h.createEl("button",{cls:"mod-cta",text:t==="setup"?"Set up":t==="change"?"Change":"Unlock"}),I=!1,p=async()=>{if(I)return;let u=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!u){d("Enter your current password.");return}if(t==="setup"||t==="change"){if(!f){d("Enter a password.");return}if(f.length<6){d("Use at least 6 characters.");return}if(f!==o?.value){d("Passwords don't match.");return}}I=!0,g.disabled=!0,A.setCssStyles({display:"none"});let C=g.textContent;g.setText("Working\u2026");try{let m=await this.opts.onSubmit({current:u,next:f,remember:!!a?.checked});if(m){d(m),I=!1,g.disabled=!1,g.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(m){d(`Failed: ${m.message}`),I=!1,g.disabled=!1,g.setText(C??"OK")}};g.onclick=()=>void p(),this.scope.register([],"Enter",u=>{u.preventDefault(),p()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},Bi=class extends q.Modal{constructor(t,e){super(t);this.opts=e}onOpen(){this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal","stashpad-encryption-modal"),this.titleEl.setText(this.opts.title),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:this.opts.body});let t=null;this.opts.requirePassword&&(this.contentEl.createEl("p",{cls:"stashpad-export-desc"}).setText("Enter your encryption password:"),t=this.contentEl.createEl("input",{type:"password"}),t.addClass("stashpad-export-name","stashpad-encryption-field"),t.placeholder="Password"),this.contentEl.createEl("p",{cls:"stashpad-export-desc"}).setText(`Type "${this.opts.phrase}" to confirm.`);let e=this.contentEl.createEl("input",{type:"text"});e.addClass("stashpad-export-name","stashpad-encryption-field"),e.placeholder=this.opts.phrase;let i=this.contentEl.createEl("div",{cls:"stashpad-export-error"});i.setCssStyles({display:"none"});let s=this.contentEl.createDiv({cls:"stashpad-export-footer"});s.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let n=s.createEl("button",{cls:"mod-cta mod-warning",text:this.opts.confirmText}),o=()=>e.value.trim().toLowerCase()===this.opts.phrase.trim().toLowerCase(),a=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",a),t?.addEventListener("input",a),a();let l=!1,A=async()=>{if(!(l||!o())){if(this.opts.requirePassword&&(l=!0,n.disabled=!0,i.setCssStyles({display:"none"}),!await this.opts.requirePassword(t.value))){i.setText("Wrong password."),i.setCssStyles({display:""}),l=!1,a();return}this.close(),await this.opts.onConfirm()}};n.onclick=()=>void A(),this.scope.register([],"Enter",d=>{d.preventDefault(),A()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},is=class extends q.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=d=>{let h=d.startsWith("#")?d:"#"+d;/^#[0-9a-f]{6}$/i.test(h)&&(this.value=h,e.style.background=h,i.value=h,s.value!==h&&(s.value=h))};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 l=o.createEl("button",{cls:"mod-cta",text:"Save"});l.title="Apply this color to the selection (without adding to your palette).",l.onclick=()=>this.commit({addToPalette:!1});let A=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});A.title="Apply and save this color so it appears as a tile next time.",A.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",d=>{d.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",d=>{d.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()}},ui=class ui extends q.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=[...ui.DEFAULT_PALETTE,...this.customPalette];for(let a of i){let l=t.createDiv({cls:"stashpad-color-tile"});l.style.background=a,l.title=a;let A=!ui.DEFAULT_PALETTE.some(h=>h.toLowerCase()===a.toLowerCase()),d=this.items.length;if(l.onclick=()=>this.activate(d),A&&this.onDeleteCustom){let h=l.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});h.title="Remove from palette",h.onclick=g=>{g.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:A?"custom":"preset",color:a,el:l})}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 is(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))}};Oe=class extends q.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(this.opts.title??"Set due date");let t=null;if(this.current){let m=Date.parse(this.current);Number.isNaN(m)||(t=new Date(m))}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,q.setIcon)(n,"calendar");let o=s.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=s.createSpan({cls:"stashpad-due-clear",attr:{"aria-label":"Clear date"}});(0,q.setIcon)(a,"x"),a.onclick=()=>{o.value="",o.focus()};let l=i.createDiv({cls:"stashpad-due-field"}),A=l.createSpan({cls:"stashpad-due-field-icon"});(0,q.setIcon)(A,"clock");let d=l.createEl("input",{type:"time",cls:"stashpad-due-time"}),h=l.createSpan({cls:"stashpad-due-clear",attr:{"aria-label":"Clear time"}});(0,q.setIcon)(h,"x"),h.onclick=()=>{d.value="",d.focus()},n.onclick=()=>{try{o.showPicker?.()}catch{}},A.onclick=()=>this.openTimeNumpad(A,d),t&&(o.value=this.toDateValue(t),d.value=this.toTimeValue(t)),this.renderAssignSection(e);let g=e.createDiv({cls:"stashpad-due-grid"}),I=(m,B)=>{let y=g.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:m});y.onclick=()=>{let Q=B();o.value=this.toDateValue(Q),d.value||(d.value=this.toTimeValue(Q))}},p=m=>(m.setHours(9,0,0,0),m);I("Today",()=>p(this.startOfTodayLocal())),I("Tomorrow",()=>{let m=this.startOfTodayLocal();return m.setDate(m.getDate()+1),p(m)}),I("Next week",()=>{let m=this.startOfTodayLocal();return m.setDate(m.getDate()+7),p(m)});let u=g.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});u.onclick=()=>{o.value="",d.value="",o.focus()};let f=g.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});f.onclick=()=>{this.didChoose=!0,this.close()};let C=g.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});C.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[m,B,y]=o.value.split("-").map(w=>parseInt(w,10)),Q=9,E=0;if(d.value){let[w,D]=d.value.split(":").map(N=>parseInt(N,10));Q=w,E=D}let v=new Date(m,B-1,y,Q,E,0,0);this.didChoose=!0,this.close(),this.onPick({iso:v.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){Xo(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[I,p]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(I)&&(i=I),Number.isFinite(p)&&(s=p)}else{let I=new Date;i=I.getHours(),s=I.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.setCssStyles({position:"fixed",zIndex:"9999"});let l=null,A=()=>{a.remove(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",h,!0),this.tinyClosePopover===A&&(this.tinyClosePopover=null)},d=I=>{!a.contains(I.target)&&I.target!==t&&!t.contains(I.target)&&A()},h=I=>{I.key==="Escape"?(I.preventDefault(),I.stopPropagation(),A()):I.key==="Enter"&&l&&(I.preventDefault(),I.stopPropagation(),l())};this.tinyClosePopover=A,_i(a,{seedH:o,seedM:s,seedPeriod:n,close:A,setOnEnter:I=>{l=I},onFinalize:I=>{e.value=`${String(I.hours24).padStart(2,"0")}:${String(I.minutes).padStart(2,"0")}`}});let g=t.getBoundingClientRect();a.setCssStyles({left:`${Math.max(8,Math.min(g.left,window.innerWidth-220))}px`,top:`${g.bottom+4}px`}),setTimeout(()=>{document.addEventListener("mousedown",d,!0),document.addEventListener("keydown",h,!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}`}},be=class be extends q.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 ot(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(be.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let A=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let d of e.actionLabels){let h=A.createSpan({cls:"stashpad-notif-action-chip"});h.setText(d),h.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(be.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(be.PAGE),this.renderFooter()},t>be.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};be.PAGE=100;Qi=be,Qn=class extends q.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,q.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()}},yi=class extends q.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()}},Ei=class extends q.Modal{constructor(t,e,i,s){super(t);this.noteCount=i;this.onConfirm=s;this.base=e}onOpen(){this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal"),this.titleEl.setText("Export as OKF"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`Export ${this.noteCount} note${this.noteCount===1?"":"s"} as an Open Knowledge Format bundle. Pick one or more formats.`});let t=this.contentEl.createEl("input",{type:"text"});t.addClass("stashpad-export-name"),t.value=this.base,t.placeholder="Export name";let e=(l,A)=>{let d=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),h=d.createEl("input",{type:"checkbox"});return h.checked=A,d.createEl("label",{text:l}),h},i=e(".zip \u2014 OKF bundle (portable)",!0),s=e(".tar.gz \u2014 OKF bundle (tarball)",!1),n=e(".stash \u2014 Stashpad format (re-importable)",!1),o=this.contentEl.createDiv({cls:"stashpad-export-footer"});o.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let a=o.createEl("button",{cls:"mod-cta",text:"Export"});a.onclick=()=>{if(!i.checked&&!s.checked&&!n.checked){new q.Notice("Pick at least one format.");return}this.close(),this.onConfirm(t.value.trim()||this.base,{zip:i.checked,targz:s.checked,stash:n.checked})},requestAnimationFrame(()=>t.focus())}onClose(){this.contentEl.empty()}}});function Qt(c,r=Yt){let t=r instanceof Set?r:new Set(r.map(o=>o.toLowerCase())),e=(c.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 yt(c,r){return`${c}-${r}.md`}function he(c){let r=c.match(/-([a-z0-9]{4,12})$/);return r?r[1]:null}function os(c,r){let t=c.lastIndexOf(".");return t>0?`${c.slice(0,t)}-${r}${c.slice(t)}`:`${c}-${r}`}function Zo(c){let r=c.match(/^([0-9a-z]{7,9})-(.+)$/);if(!r)return null;let t=parseInt(r[1],36);return!Number.isFinite(t)||t<142e10||t>Date.now()+864e5?null:{stamp:r[1],rest:r[2]}}var Yt,Ye=Lt(()=>{"use strict";Yt=["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 ls={};ri(ls,{JdBuildConfirmModal:()=>Fi,buildJdIndexNotes:()=>En,buildJdIndexPreview:()=>as,buildJdPreviewNotice:()=>rs,scanForJdNotes:()=>$e});function yn(c,r){if(/^\d+-\d+$/.test(c))return null;if(c.includes(".")){let e=c.split(".").slice(0,-1).join(".");return r.has(e)?e:yn(e,r)}if(/^\d+$/.test(c)){let t=parseInt(c,10);for(let e of r){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 $e(c,r,t){let e=c.vault.getMarkdownFiles(),i=Kr(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(r.discoverStashpadFolders()),o=I=>s?!1:Array.from(n).some(p=>I===p||I.startsWith(p+"/")),a=[],l=[],A=[];for(let I of i){let p=I.parent?.path?.replace(/\/+$/,"")??"";if(o(p)){A.push(I);continue}let u=I.basename.match(jo);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:I,folder:null}):l.push(I)}let d=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",h=I=>{let p=I.path.replace(/\/+$/,"");if(!(d&&p&&p!==d&&!p.startsWith(d+"/"))){if(p&&!o(p)){let u=I.name.match(jo);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:I})}}for(let u of I.children)u instanceof gt.TFolder&&h(u)};h(c.vault.getRoot());let g=t.jdIndexSort??"natural";return a.sort((I,p)=>Or(I,p,g)),{indexed:a,nonIndex:l,skippedStashpadNotes:A}}async function as(c,r,t){let e=wn(t.jdIndexStashpadFolder??"");if(!e)return{...$e(c,r,t),previewPath:null,error:"no-dest"};let i=$e(c,r,t),s=Jr(c,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Yr(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await c.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),l=a?`${a[0]}${n}`:n;return await c.vault.modify(s,l),{...i,previewPath:s.path}}function Jr(c,r){let t=c.vault.getAbstractFileByPath(r);if(!(t instanceof gt.TFolder))return null;for(let e of t.children){if(!(e instanceof gt.TFile)||e.extension!=="md")continue;if((c.metadataCache.getFileCache(e)?.frontmatter??{}).id===F)return e}return null}async function En(c,r,t){let e=wn(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(r.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let s=$e(c,r,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{l.push(f);for(let C of a.get(f)??[])A(C)};for(let f of o)A(f);let d=new Map,h=c.vault.getAbstractFileByPath(e);if(h instanceof gt.TFolder)for(let f of h.children){if(!(f instanceof gt.TFile)||f.extension!=="md")continue;let C=c.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&d.set(C.jdPrefix,f)}let g=new Map,I=0,p=0,u=0;for(let f of l){let C=n.get(f)??null,m=yn(f,new Set(n.keys())),B=m?g.get(m)??F:F,y=C?`${f} ${C.title}`:f,Q=C?.file?`[[${C.file.basename}]]`:"",E=Q?`${Q} `:`${y} `,v=d.get(f);if(v){try{let w=null;await c.fileManager.processFrontMatter(v,H=>{H.jdPrefix=f,B&&(H.parent=B),(!H.id||typeof H.id!="string")&&(H.id=tt()),H.created||(H.created=new Date().toISOString()),H.attachments||(H.attachments=[]),w=H.id});let N=(await c.vault.read(v)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),P=N?`${N[0]}${E}`:E;await c.vault.modify(v,P),w&&g.set(f,w),p++}catch(w){console.error("[stashpad] buildJdIndexNotes: update failed",w),u++}continue}try{let w=tt();g.set(f,w);let D=Qt(y,t.slugStopWords),N=yt(D,w),P=`${e}/${N}`,H=["---",`id: ${w}`,`parent: ${B}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` -`);await c.vault.create(P,H+E),I++}catch(w){console.error("[stashpad] buildJdIndexNotes: create failed for",f,w),u++}}return{created:I,updated:p,skipped:u,destFolder:e}}function wn(c){return(c||"").trim().replace(/^\/+|\/+$/g,"")}function Or(c,r){if((r.jdIndexScope??"vault")==="vault")return c;let t=wn(r.jdIndexScopeFolder??"");return t?c.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):c}function Yr(c,r,t){if(t==="created"){let e=c.file?.stat?.ctime??0,i=r.file?.stat?.ctime??0;if(e!==i)return e-i}return ta(c.segments,r.segments)}function _o(c,r){let t=c.match(/^(\d+)-(\d+)$/),e=r.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:c.split("."),s=e?[e[1]]:r.split(".");return ta(i,s)}function ta(c,r){let t=Math.min(c.length,r.length);for(let e=0;e{s.set(o,a);for(let l of e.get(o)??[])n(l,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function zr(c,r,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),c.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 A of c)s.set(A.prefix,A);for(let A of c)if(A.prefix.includes("."))for(let d=1;d{let d=s.get(A),h=a.get(A)??0,g=" ".repeat(h),I=i(h),p=d?.folder?` ${d.title} _(folder)_`:(d?.file,"");d?.file?e.push(`${g}- ${I} [[${d.file.basename}|${d.prefix} ${d.title}]]`):d?.folder?e.push(`${g}- ${I} ${d.prefix}${p}`):e.push(`${g}- ${I} ${A}`);for(let u of o.get(A)??[])l(u)};for(let A of n)l(A)}if(r.length>0){e.push(""),e.push(`# Non-indexed (${r.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 r)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(` +`);await c.vault.create(P,H+E),I++}catch(w){console.error("[stashpad] buildJdIndexNotes: create failed for",f,w),u++}}return{created:I,updated:p,skipped:u,destFolder:e}}function wn(c){return(c||"").trim().replace(/^\/+|\/+$/g,"")}function Kr(c,r){if((r.jdIndexScope??"vault")==="vault")return c;let t=wn(r.jdIndexScopeFolder??"");return t?c.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):c}function Or(c,r,t){if(t==="created"){let e=c.file?.stat?.ctime??0,i=r.file?.stat?.ctime??0;if(e!==i)return e-i}return ta(c.segments,r.segments)}function _o(c,r){let t=c.match(/^(\d+)-(\d+)$/),e=r.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:c.split("."),s=e?[e[1]]:r.split(".");return ta(i,s)}function ta(c,r){let t=Math.min(c.length,r.length);for(let e=0;e<t;e++){let i=c[e],s=r[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 c.length-r.length}function ea(c){let r=new Set(c.keys()),t=new Map,e=new Map;for(let o of r){let a=yn(o,r);if(t.set(o,a),a!==null){let l=e.get(a)??[];l.push(o),e.set(a,l)}}let i=[];for(let o of r)t.get(o)===null&&i.push(o);i.sort(_o);for(let o of e.values())o.sort(_o);let s=new Map,n=(o,a)=>{s.set(o,a);for(let l of e.get(o)??[])n(l,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function Yr(c,r,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),c.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 A of c)s.set(A.prefix,A);for(let A of c)if(A.prefix.includes("."))for(let d=1;d<A.segments.length;d++){let h=A.segments.slice(0,d).join(".");s.has(h)||s.set(h,null)}let{roots:n,childrenOf:o,depthOf:a}=ea(s),l=A=>{let d=s.get(A),h=a.get(A)??0,g=" ".repeat(h),I=i(h),p=d?.folder?` ${d.title} _(folder)_`:(d?.file,"");d?.file?e.push(`${g}- ${I} [[${d.file.basename}|${d.prefix} ${d.title}]]`):d?.folder?e.push(`${g}- ${I} ${d.prefix}${p}`):e.push(`${g}- ${I} ${A}`);for(let u of o.get(A)??[])l(u)};for(let A of n)l(A)}if(r.length>0){e.push(""),e.push(`# Non-indexed (${r.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 r)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 as(c,r){let t=document.createDocumentFragment();t.createEl("div",{text:"Home note updated"}).setCssStyles({fontWeight:"600",marginBottom:"6px"});let i=t.createEl("ul");i.setCssStyles({margin:"0 0 8px 0",paddingLeft:"18px"}),i.createEl("li",{text:`${r.indexed.length} indexed`}),i.createEl("li",{text:`${r.nonIndex.length+r.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.setCssStyles({padding:"2px 10px",fontSize:"var(--font-ui-smaller)"});let n;return s.onclick=async o=>{if(o.stopPropagation(),r.previewPath){let a=c.vault.getAbstractFileByPath(r.previewPath);a instanceof gt.TFile&&await c.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new gt.Notice(t,0),n}var gt,jo,Fi,ki=Lt(()=>{"use strict";gt=require("obsidian");Tt();Ye();rt();jo=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Fi=class extends gt.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 l=new gt.Setting(t);(i||s)&&l.addButton(A=>{A.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),A.setCta(),A.onClick(async()=>{try{let d=await os(this.app,this.plugin,this.settings);if(d.error==="no-dest"){new gt.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(d.error==="no-home"){new gt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=d.previewPath,as(this.app,d),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(d){new gt.Notice(`Preview failed: ${d?.message??d}`,8e3)}})}),l.addButton(A=>{A.setButtonText(i?"Build anyway":"Build"),!i&&!s&&A.setCta(),A.onClick(async()=>{this.close(),await this.onBuild()})}),l.addButton(A=>{A.setButtonText("Cancel"),A.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});function Ul(c,r){return Pl(c,r||{},0,0)}function Gl(c,r){return Nl(c,{i:2},r&&r.out,r&&r.dictionary)}function Bs(c,r){if(r){for(var t=new lt(c.length),e=0;e<c.length;++e)t[e]=c.charCodeAt(e);return t}if(Fa)return Fa.encode(c);for(var i=c.length,s=new lt(c.length+(c.length>>1)),n=0,o=function(A){s[n++]=A},e=0;e<i;++e){if(n+5>s.length){var a=new lt(n+8+(i-e<<1));a.set(s),s=a}var l=c.charCodeAt(e);l<128||r?o(l):l<2048?(o(192|l>>6),o(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|c.charCodeAt(++e)&1023,o(240|l>>18),o(128|l>>12&63),o(128|l>>6&63),o(128|l&63)):(o(224|l>>12),o(128|l>>6&63),o(128|l&63))}return Gi(s,0,n)}function eo(c,r){if(r){for(var t="",e=0;e<c.length;e+=16384)t+=String.fromCharCode.apply(null,c.subarray(e,e+16384));return t}else{if(Zn)return Zn.decode(c);var i=Ll(c),s=i.s,t=i.r;return t.length&&ft(8),s}}function Pa(c,r){r||(r={});var t={},e=[];Ha(c,"",t,r);var i=0,s=0;for(var n in t){var o=t[n],a=o[0],l=o[1],A=l.level==0?0:8,d=Bs(n),h=d.length,g=l.comment,I=g&&Bs(g),p=I&&I.length,u=jn(l.extra);h>65535&&ft(11);var f=A?Ul(a,l):a,C=f.length,m=Hl();m.p(a),e.push(Ta(l,{size:a.length,crc:m.d(),c:f,f:d,m:I,u:h!=n.length||I&&g.length!=p,o:i,compression:A})),i+=30+h+u+C,s+=76+2*(h+u)+(p||0)+C}for(var B=new lt(s+22),y=i,Q=s-i,E=0;E<e.length;++E){var d=e[E];ka(B,d.o,d,d.f,d.u,d.c.length);var v=30+d.f.length+jn(d.extra);B.set(d.c,d.o+v),ka(B,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+v+(d.m?d.m.length:0)}return Ol(B,i,e.length,Q,y),B}function Ua(c,r){for(var t={},e=c.length-22;Dt(c,e)!=101010256;--e)(!e||c.length-e>65558)&&ft(13);var i=zt(c,e+8);if(!i)return{};var s=Dt(c,e+16),n=Dt(c,e-20)==117853008;if(n){var o=Dt(c,e-12);n=Dt(c,o)==101075792,n&&(i=Dt(c,o+32),s=Dt(c,o+48))}for(var a=r&&r.filter,l=0;l<i;++l){var A=Jl(c,s,n),d=A[0],h=A[1],g=A[2],I=A[3],p=A[4],u=A[5],f=ql(c,u);s=p,(!a||a({name:I,size:h,originalSize:g,compression:d}))&&(d?d==8?t[I]=Gl(c.subarray(f,f+h),{out:new lt(g)}):ft(14,"unknown compression type "+d):t[I]=Gi(c,f,f+h))}return t}var lt,kt,_n,Qs,ys,$n,Sa,Da,ba,Vn,Na,vl,Ea,Wn,se,Z,$t,pe,Z,Z,Z,Z,Ui,Z,Fl,kl,Sl,Dl,Kn,Gt,On,to,Gi,bl,ft,Nl,ne,Hi,Yn,Xn,wa,Pi,xa,va,xl,Ma,Ml,Tl,Hl,Pl,Ta,zt,Dt,zn,It,Ha,Fa,Zn,Rl,Ll,ql,Jl,Kl,jn,ka,Ol,Ga=Lt(()=>{lt=Uint8Array,kt=Uint16Array,_n=Int32Array,Qs=new lt([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,0,0,0]),ys=new lt([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,0,0]),$n=new lt([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Sa=function(c,r){for(var t=new kt(31),e=0;e<31;++e)t[e]=r+=1<<c[e-1];for(var i=new _n(t[30]),e=1;e<30;++e)for(var s=t[e];s<t[e+1];++s)i[s]=s-t[e]<<5|e;return{b:t,r:i}},Da=Sa(Qs,2),ba=Da.b,Vn=Da.r;ba[28]=258,Vn[258]=28;Na=Sa(ys,0),vl=Na.b,Ea=Na.r,Wn=new kt(32768);for(Z=0;Z<32768;++Z)se=(Z&43690)>>1|(Z&21845)<<1,se=(se&52428)>>2|(se&13107)<<2,se=(se&61680)>>4|(se&3855)<<4,Wn[Z]=((se&65280)>>8|(se&255)<<8)>>1;$t=function(c,r,t){for(var e=c.length,i=0,s=new kt(r);i<e;++i)c[i]&&++s[c[i]-1];var n=new kt(r);for(i=1;i<r;++i)n[i]=n[i-1]+s[i-1]<<1;var o;if(t){o=new kt(1<<r);var a=15-r;for(i=0;i<e;++i)if(c[i])for(var l=i<<4|c[i],A=r-c[i],d=n[c[i]-1]++<<A,h=d|(1<<A)-1;d<=h;++d)o[Wn[d]>>a]=l}else for(o=new kt(e),i=0;i<e;++i)c[i]&&(o[i]=Wn[n[c[i]-1]++]>>15-c[i]);return o},pe=new lt(288);for(Z=0;Z<144;++Z)pe[Z]=8;for(Z=144;Z<256;++Z)pe[Z]=9;for(Z=256;Z<280;++Z)pe[Z]=7;for(Z=280;Z<288;++Z)pe[Z]=8;Ui=new lt(32);for(Z=0;Z<32;++Z)Ui[Z]=5;Fl=$t(pe,9,0),kl=$t(pe,9,1),Sl=$t(Ui,5,0),Dl=$t(Ui,5,1),Kn=function(c){for(var r=c[0],t=1;t<c.length;++t)c[t]>r&&(r=c[t]);return r},Gt=function(c,r,t){var e=r/8|0;return(c[e]|c[e+1]<<8)>>(r&7)&t},On=function(c,r){var t=r/8|0;return(c[t]|c[t+1]<<8|c[t+2]<<16)>>(r&7)},to=function(c){return(c+7)/8|0},Gi=function(c,r,t){return(r==null||r<0)&&(r=0),(t==null||t>c.length)&&(t=c.length),new lt(c.subarray(r,t))},bl=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],ft=function(c,r,t){var e=new Error(r||bl[c]);if(e.code=c,Error.captureStackTrace&&Error.captureStackTrace(e,ft),!t)throw e;return e},Nl=function(c,r,t,e){var i=c.length,s=e?e.length:0;if(!i||r.f&&!r.l)return t||new lt(0);var n=!t,o=n||r.i!=2,a=r.i;n&&(t=new lt(i*3));var l=function(ct){var St=t.length;if(ct>St){var st=new lt(Math.max(St*2,ct));st.set(t),t=st}},A=r.f||0,d=r.p||0,h=r.b||0,g=r.l,I=r.d,p=r.m,u=r.n,f=i*8;do{if(!g){A=Gt(c,d,1);var C=Gt(c,d+1,3);if(d+=3,C)if(C==1)g=kl,I=Dl,p=9,u=5;else if(C==2){var Q=Gt(c,d,31)+257,E=Gt(c,d+10,15)+4,v=Q+Gt(c,d+5,31)+1;d+=14;for(var w=new lt(v),D=new lt(19),N=0;N<E;++N)D[$n[N]]=Gt(c,d+N*3,7);d+=E*3;for(var P=Kn(D),H=(1<<P)-1,b=$t(D,P,1),N=0;N<v;){var S=b[Gt(c,d,H)];d+=S&15;var m=S>>4;if(m<16)w[N++]=m;else{var T=0,U=0;for(m==16?(U=3+Gt(c,d,3),d+=2,T=w[N-1]):m==17?(U=3+Gt(c,d,7),d+=3):m==18&&(U=11+Gt(c,d,127),d+=7);U--;)w[N++]=T}}var L=w.subarray(0,Q),W=w.subarray(Q);p=Kn(L),u=Kn(W),g=$t(L,p,1),I=$t(W,u,1)}else ft(1);else{var m=to(d)+4,B=c[m-4]|c[m-3]<<8,y=m+B;if(y>i){a&&ft(0);break}o&&l(h+B),t.set(c.subarray(m,y),h),r.b=h+=B,r.p=d=y*8,r.f=A;continue}if(d>f){a&&ft(0);break}}o&&l(h+131072);for(var z=(1<<p)-1,$=(1<<u)-1,R=d;;R=d){var T=g[On(c,d)&z],V=T>>4;if(d+=T&15,d>f){a&&ft(0);break}if(T||ft(2),V<256)t[h++]=V;else if(V==256){R=d,g=null;break}else{var O=V-254;if(V>264){var N=V-257,Y=Qs[N];O=Gt(c,d,(1<<Y)-1)+ba[N],d+=Y}var it=I[On(c,d)&$],at=it>>4;it||ft(3),d+=it&15;var W=vl[at];if(at>3){var Y=ys[at];W+=On(c,d)&(1<<Y)-1,d+=Y}if(d>f){a&&ft(0);break}o&&l(h+131072);var _=h+O;if(h<W){var X=s-W,mt=Math.min(W,_);for(X+h<0&&ft(3);h<mt;++h)t[h]=e[X+h]}for(;h<_;++h)t[h]=t[h-W]}}r.l=g,r.p=R,r.b=h,r.f=A,g&&(A=1,r.m=p,r.d=I,r.n=u)}while(!A);return h!=t.length&&n?Gi(t,0,h):t.subarray(0,h)},ne=function(c,r,t){t<<=r&7;var e=r/8|0;c[e]|=t,c[e+1]|=t>>8},Hi=function(c,r,t){t<<=r&7;var e=r/8|0;c[e]|=t,c[e+1]|=t>>8,c[e+2]|=t>>16},Yn=function(c,r){for(var t=[],e=0;e<c.length;++e)c[e]&&t.push({s:e,f:c[e]});var i=t.length,s=t.slice();if(!i)return{t:Ma,l:0};if(i==1){var n=new lt(t[0].s+1);return n[t[0].s]=1,{t:n,l:1}}t.sort(function(y,Q){return y.f-Q.f}),t.push({s:-1,f:25001});var o=t[0],a=t[1],l=0,A=1,d=2;for(t[0]={s:-1,f:o.f+a.f,l:o,r:a};A!=i-1;)o=t[t[l].f<t[d].f?l++:d++],a=t[l!=A&&t[l].f<t[d].f?l++:d++],t[A++]={s:-1,f:o.f+a.f,l:o,r:a};for(var h=s[0].s,e=1;e<i;++e)s[e].s>h&&(h=s[e].s);var g=new kt(h+1),I=Xn(t[A-1],g,0);if(I>r){var e=0,p=0,u=I-r,f=1<<u;for(s.sort(function(Q,E){return g[E.s]-g[Q.s]||Q.f-E.f});e<i;++e){var C=s[e].s;if(g[C]>r)p+=f-(1<<I-g[C]),g[C]=r;else break}for(p>>=u;p>0;){var m=s[e].s;g[m]<r?p-=1<<r-g[m]++-1:++e}for(;e>=0&&p;--e){var B=s[e].s;g[B]==r&&(--g[B],++p)}I=r}return{t:new lt(g),l:I}},Xn=function(c,r,t){return c.s==-1?Math.max(Xn(c.l,r,t+1),Xn(c.r,r,t+1)):r[c.s]=t},wa=function(c){for(var r=c.length;r&&!c[--r];);for(var t=new kt(++r),e=0,i=c[0],s=1,n=function(a){t[e++]=a},o=1;o<=r;++o)if(c[o]==i&&o!=r)++s;else{if(!i&&s>2){for(;s>138;s-=138)n(32754);s>2&&(n(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(n(i),--s;s>6;s-=6)n(8304);s>2&&(n(s-3<<5|8208),s=0)}for(;s--;)n(i);s=1,i=c[o]}return{c:t.subarray(0,e),n:r}},Pi=function(c,r){for(var t=0,e=0;e<r.length;++e)t+=c[e]*r[e];return t},xa=function(c,r,t){var e=t.length,i=to(r+2);c[i]=e&255,c[i+1]=e>>8,c[i+2]=c[i]^255,c[i+3]=c[i+1]^255;for(var s=0;s<e;++s)c[i+s+4]=t[s];return(i+4+e)*8},va=function(c,r,t,e,i,s,n,o,a,l,A){ne(r,A++,t),++i[256];for(var d=Yn(i,15),h=d.t,g=d.l,I=Yn(s,15),p=I.t,u=I.l,f=wa(h),C=f.c,m=f.n,B=wa(p),y=B.c,Q=B.n,E=new kt(19),v=0;v<C.length;++v)++E[C[v]&31];for(var v=0;v<y.length;++v)++E[y[v]&31];for(var w=Yn(E,7),D=w.t,N=w.l,P=19;P>4&&!D[$n[P-1]];--P);var H=l+5<<3,b=Pi(i,pe)+Pi(s,Ui)+n,S=Pi(i,h)+Pi(s,p)+n+14+3*P+Pi(E,D)+2*E[16]+3*E[17]+7*E[18];if(a>=0&&H<=b&&H<=S)return xa(r,A,c.subarray(a,a+l));var T,U,L,W;if(ne(r,A,1+(S<b)),A+=2,S<b){T=$t(h,g,0),U=h,L=$t(p,u,0),W=p;var z=$t(D,N,0);ne(r,A,m-257),ne(r,A+5,Q-1),ne(r,A+10,P-4),A+=14;for(var v=0;v<P;++v)ne(r,A+3*v,D[$n[v]]);A+=3*P;for(var $=[C,y],R=0;R<2;++R)for(var V=$[R],v=0;v<V.length;++v){var O=V[v]&31;ne(r,A,z[O]),A+=D[O],O>15&&(ne(r,A,V[v]>>5&127),A+=V[v]>>12)}}else T=Fl,U=pe,L=Sl,W=Ui;for(var v=0;v<o;++v){var Y=e[v];if(Y>255){var O=Y>>18&31;Hi(r,A,T[O+257]),A+=U[O+257],O>7&&(ne(r,A,Y>>23&31),A+=Qs[O]);var it=Y&31;Hi(r,A,L[it]),A+=W[it],it>3&&(Hi(r,A,Y>>5&8191),A+=ys[it])}else Hi(r,A,T[Y]),A+=U[Y]}return Hi(r,A,T[256]),A+U[256]},xl=new _n([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ma=new lt(0),Ml=function(c,r,t,e,i,s){var n=s.z||c.length,o=new lt(e+n+5*(1+Math.ceil(n/7e3))+i),a=o.subarray(e,o.length-i),l=s.l,A=(s.r||0)&7;if(r){A&&(a[0]=s.r>>3);for(var d=xl[r-1],h=d>>13,g=d&8191,I=(1<<t)-1,p=s.p||new kt(32768),u=s.h||new kt(I+1),f=Math.ceil(t/3),C=2*f,m=function(Bt){return(c[Bt]^c[Bt+1]<<f^c[Bt+2]<<C)&I},B=new _n(25e3),y=new kt(288),Q=new kt(32),E=0,v=0,w=s.i||0,D=0,N=s.w||0,P=0;w+2<n;++w){var H=m(w),b=w&32767,S=u[H];if(p[b]=S,u[H]=b,N<=w){var T=n-w;if((E>7e3||D>24576)&&(T>423||!l)){A=va(c,a,0,B,y,Q,v,D,P,w-P,A),D=E=v=0,P=w;for(var U=0;U<286;++U)y[U]=0;for(var U=0;U<30;++U)Q[U]=0}var L=2,W=0,z=g,$=b-S&32767;if(T>2&&H==m(w-$))for(var R=Math.min(h,T)-1,V=Math.min(32767,w),O=Math.min(258,T);$<=V&&--z&&b!=S;){if(c[w+L]==c[w+L-$]){for(var Y=0;Y<O&&c[w+Y]==c[w+Y-$];++Y);if(Y>L){if(L=Y,W=$,Y>R)break;for(var it=Math.min($,Y-2),at=0,U=0;U<it;++U){var _=w-$+U&32767,X=p[_],mt=_-X&32767;mt>at&&(at=mt,S=_)}}}b=S,S=p[b],$+=b-S&32767}if(W){B[D++]=268435456|Vn[L]<<18|Ea[W];var ct=Vn[L]&31,St=Ea[W]&31;v+=Qs[ct]+ys[St],++y[257+ct],++Q[St],N=w+L,++E}else B[D++]=c[w],++y[c[w]]}}for(w=Math.max(w,N);w<n;++w)B[D++]=c[w],++y[c[w]];A=va(c,a,l,B,y,Q,v,D,P,w-P,A),l||(s.r=A&7|a[A/8|0]<<3,A-=7,s.h=u,s.p=p,s.i=w,s.w=N)}else{for(var w=s.w||0;w<n+l;w+=65535){var st=w+65535;st>=n&&(a[A/8|0]=l,st=n),A=xa(a,A+1,c.subarray(w,st))}s.i=n}return Gi(o,0,e+to(A)+i)},Tl=function(){for(var c=new Int32Array(256),r=0;r<256;++r){for(var t=r,e=9;--e;)t=(t&1&&-306674912)^t>>>1;c[r]=t}return c}(),Hl=function(){var c=-1;return{p:function(r){for(var t=c,e=0;e<r.length;++e)t=Tl[t&255^r[e]]^t>>>8;c=t},d:function(){return~c}}},Pl=function(c,r,t,e,i){if(!i&&(i={l:1},r.dictionary)){var s=r.dictionary.subarray(-32768),n=new lt(s.length+c.length);n.set(s),n.set(c,s.length),c=n,i.w=s.length}return Ml(c,r.level==null?6:r.level,r.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(c.length)))*1.5):20:12+r.mem,t,e,i)},Ta=function(c,r){var t={};for(var e in c)t[e]=c[e];for(var e in r)t[e]=r[e];return t},zt=function(c,r){return c[r]|c[r+1]<<8},Dt=function(c,r){return(c[r]|c[r+1]<<8|c[r+2]<<16|c[r+3]<<24)>>>0},zn=function(c,r){return Dt(c,r)+Dt(c,r+4)*4294967296},It=function(c,r,t){for(;t;++r)c[r]=t,t>>>=8};Ha=function(c,r,t,e){for(var i in c){var s=c[i],n=r+i,o=e;Array.isArray(s)&&(o=Ta(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[n]=[s,o]:(t[n+="/"]=[new lt(0),o],Ha(s,n,t,e))}},Fa=typeof TextEncoder<"u"&&new TextEncoder,Zn=typeof TextDecoder<"u"&&new TextDecoder,Rl=0;try{Zn.decode(Ma,{stream:!0}),Rl=1}catch{}Ll=function(c){for(var r="",t=0;;){var e=c[t++],i=(e>127)+(e>223)+(e>239);if(t+i>c.length)return{s:r,r:Gi(c,t-1)};i?i==3?(e=((e&15)<<18|(c[t++]&63)<<12|(c[t++]&63)<<6|c[t++]&63)-65536,r+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?r+=String.fromCharCode((e&31)<<6|c[t++]&63):r+=String.fromCharCode((e&15)<<12|(c[t++]&63)<<6|c[t++]&63):r+=String.fromCharCode(e)}};ql=function(c,r){return r+30+zt(c,r+26)+zt(c,r+28)},Jl=function(c,r,t){var e=zt(c,r+28),i=zt(c,r+30),s=eo(c.subarray(r+46,r+46+e),!(zt(c,r+8)&2048)),n=r+46+e,o=Kl(c,n,i,t,Dt(c,r+20),Dt(c,r+24),Dt(c,r+42)),a=o[0],l=o[1],A=o[2];return[zt(c,r+10),a,l,s,n+i+zt(c,r+32),A]},Kl=function(c,r,t,e,i,s,n){var o=i==4294967295,a=s==4294967295,l=n==4294967295,A=r+t,d=o+a+l;if(e&&d){for(;r+4<A;r+=4+zt(c,r+2))if(zt(c,r)==1)return[o?zn(c,r+4+8*a):i,a?zn(c,r+4):s,l?zn(c,r+4+8*(a+o)):n,1];e<2&&ft(13)}return[i,s,n,0]},jn=function(c){var r=0;if(c)for(var t in c){var e=c[t].length;e>65535&&ft(9),r+=e+4}return r},ka=function(c,r,t,e,i,s,n,o){var a=e.length,l=t.extra,A=o&&o.length,d=jn(l);It(c,r,n!=null?33639248:67324752),r+=4,n!=null&&(c[r++]=20,c[r++]=t.os),c[r]=20,r+=2,c[r++]=t.flag<<1|(s<0&&8),c[r++]=i&&8,c[r++]=t.compression&255,c[r++]=t.compression>>8;var h=new Date(t.mtime==null?Date.now():t.mtime),g=h.getFullYear()-1980;if((g<0||g>119)&&ft(10),It(c,r,g<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),r+=4,s!=-1&&(It(c,r,t.crc),It(c,r+4,s<0?-s-2:s),It(c,r+8,t.size)),It(c,r+12,a),It(c,r+14,d),r+=16,n!=null&&(It(c,r,A),It(c,r+6,t.attrs),It(c,r+10,n),r+=14),c.set(e,r),r+=a,d)for(var I in l){var p=l[I],u=p.length;It(c,r,+I),It(c,r+2,u),c.set(p,r+4),r+=4+u}return A&&(c.set(o,r),r+=A),r},Ol=function(c,r,t,e,i){It(c,r,101010256),It(c,r+8,t),It(c,r+10,t),It(c,r+12,e),It(c,r+16,i)}});var Ra={};ri(Ra,{bytesToStr:()=>Es,unzipFiles:()=>Li,zipFiles:()=>Ri});function Yl(c){return typeof c=="string"?Bs(c):c instanceof Uint8Array?c:new Uint8Array(c)}function Ri(c,r=6){let t={};for(let e of c)t[e.name]=[Yl(e.data),{level:r}];return Promise.resolve(Pa(t,{level:r}))}function Es(c){return eo(c)}function Li(c){let r=c instanceof Uint8Array?c:new Uint8Array(c);return Promise.resolve(Ua(r))}var ws=Lt(()=>{"use strict";Ga()});var kA={};ri(kA,{default:()=>An});module.exports=Tr(kA);var M=require("obsidian");var Pe="sheet-group",qt="sheet-order",Ee="sheet-final",So="sheet-label",Ue="sheet-origin",Ge="forked-from",Jt="fork-siblings",Vi=[Pe,qt,Ee,So,Ue,Ge,Jt];function Kt(c){if(!c)return null;let r=c[Pe];return typeof r=="string"&&r.trim()?r:null}function hn(c){let r=c?.[qt];return typeof r=="number"?r:null}function li(c){return Kt(c)!==null&&hn(c)!==null}function Ai(c){return c?.[Ee]===!0}function Do(c){return c?.[Ue]===!0}function Hr(c){let r=c?.[Ge];return typeof r=="string"&&r.trim()?r:null}function Wi(c){return typeof c!="string"?null:c.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].split("#")[0].trim()||null}function bo(c){return Wi(Hr(c))}function Pr(c){let r=c?.[So];return typeof r=="string"&&r.trim()?r:null}function No(){let c=Date.now().toString(36),r=Math.floor(Math.random()*1e6).toString(36);return`s-${c}-${r}`}function ut(c,r){return r.file?c.metadataCache.getFileCache(r.file)?.frontmatter:null}function pn(c,r){return r.slice().sort((t,e)=>{let i=hn(ut(c,t)),s=hn(ut(c,e));if(i!=null&&s!=null&&i!==s)return i-s;if(i!=null&&s==null)return-1;if(i==null&&s!=null)return 1;let n=t.created??"",o=e.created??"";return n!==o?n<o?-1:1:t.id<e.id?-1:t.id>e.id?1:0})}function xo(c,r){if(r.length===0)return null;let t=pn(c,r);return t.find(e=>Ai(ut(c,e)))??t[0]}function Mo(c,r,t){let e=Pr(ut(c,r));return e||t}rt();var Et=require("obsidian");var ot=require("obsidian");rt();function Zi(c){let r=(c.dateDisplayTimezone||"").trim();return r?{timeZone:r}:{}}function Zt(c,r){try{return new Intl.DateTimeFormat(void 0,r).format(new Date(c))}catch{let{timeZone:t,...e}=r;return new Intl.DateTimeFormat(void 0,e).format(new Date(c))}}function jt(c,r){let t=Zi(r);switch(r.dateDisplayFormat??"locale"){case"iso":return Ro(c,r,!0);case"us":return Zt(c,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Zt(c,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Zt(c,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Zt(c,{...t,dateStyle:"medium",timeStyle:"short"})}}function Uo(c,r){let t=Zi(r);switch(r.dateDisplayFormat??"locale"){case"iso":return Ro(c,r,!1);case"us":return Zt(c,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Zt(c,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Zt(c,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(c).getFullYear()===e.getFullYear();return Zt(c,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Go(c,r){let t=Zi(r),e=r.dateDisplayFormat==="iso"||r.dateDisplayFormat==="eu";return Zt(c,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Ro(c,r,t){let e=Zi(r),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(c)),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 ce(c,r,t){let e=c.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(r>99?"99+":String(r))}var vi={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},is=class extends ot.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 le}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()===K&&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,ot.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,ot.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,ot.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,ot.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 l=t.createDiv({cls:"stashpad-panels-bar"});for(let d of Object.keys(vi)){let h=vi[d],g=l.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,ot.setIcon)(g.createSpan({cls:"stashpad-panels-bar-btn-icon"}),h.icon),g.createSpan({cls:"stashpad-panels-bar-btn-text",text:h.label}),this.activePanel===d&&g.addClass("is-active"),g.onclick=()=>{this.activePanel!==d&&(this.activePanel=d,this.render())}}let A=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(A):this.activePanel==="shared"?this.renderSharedPanel(A):this.activePanel==="tasks"&&this.renderTasksPanel(A)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new ot.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,ot.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,ot.setIcon)(o,"list"),o.setAttr("aria-label","Pinned view options"),o.onclick=g=>{g.stopPropagation(),this.openPinnedOptionsMenu(g)};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((g,I)=>this.renderPinnedRow(e,g,I));return}let A=new Map;a.forEach((g,I)=>{let p=A.get(g.folder);p||(p=[],A.set(g.folder,p)),p.push({pin:g,idx:I})});let d=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,h=Array.from(A.keys());d&&A.has(d)&&(h.splice(h.indexOf(d),1),h.unshift(d));for(let g of h){let I=g.split("/").pop()||g,p=e.createDiv({cls:"stashpad-pinned-group-header"});g===d&&p.addClass("is-active-folder"),p.createSpan({cls:"stashpad-pinned-group-name",text:I});let u=A.get(g)??[];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,l=n.completed===!0,A=this.childrenOf(e.folder,e.id).length,d=A>0,h=this.expanded.has(`${e.folder}|${e.id}`),g=t.createDiv({cls:"stashpad-pinned-row"});a&&g.addClass("has-color"),l&&g.addClass("is-completed"),g.draggable=!0,g.dataset.pinIdx=String(i),g.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),g.addClass("is-dragging")}),g.addEventListener("dragend",()=>g.removeClass("is-dragging")),g.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=g.getBoundingClientRect(),B=C.clientY-m.top<m.height/2;g.toggleClass("drop-before",B),g.toggleClass("drop-after",!B)}),g.addEventListener("dragleave",()=>{g.removeClass("drop-before"),g.removeClass("drop-after")}),g.addEventListener("drop",C=>{C.preventDefault(),g.removeClass("drop-before"),g.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let B=g.getBoundingClientRect(),y=C.clientY-B.top<B.height/2;this.reorderPin(m,y?i:i+1)});let I=g.createSpan({cls:"stashpad-pinned-toggle"});d&&(ce(I,A,h),I.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 p=g.createSpan({cls:"stashpad-pinned-icon"});(0,ot.setIcon)(p,d?"folder-tree":"file-text"),a&&(p.style.color=a);let u=g.createSpan({cls:"stashpad-pinned-label",text:o});u.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(g.createSpan({cls:"stashpad-pinned-folder",text:f}),g.oncontextmenu=C=>{C.preventDefault();let m=new ot.Menu;m.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},d&&h){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((d,h)=>h!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],l=n[o],A;!a&&!l?A=Date.now():a?l?A=(a.pinnedAt+l.pinnedAt)/2:A=a.pinnedAt+1e3:A=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=A})}catch(d){console.warn("[Stashpad] pin reorder failed",d)}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??{},l=typeof a.id=="string"?a.id:null;if(!l)continue;let A=typeof a.color=="string"?a.color:null,d=a.completed===!0,h=this.childrenOf(e,l).length,g=h>0,I=this.expanded.has(`${e}|${l}`),p=t.createDiv({cls:"stashpad-pinned-subrow"});d&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let u=p.createSpan({cls:"stashpad-pinned-toggle"});g&&(ce(u,h,I),u.onclick=m=>{m.stopPropagation();let B=`${e}|${l}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),this.render()});let f=p.createSpan({cls:"stashpad-pinned-icon"});(0,ot.setIcon)(f,"file-text"),A&&(f.style.color=A);let C=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:l}),g&&I&&this.renderPinnedSubtree(t,e,l,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===F&&(a==null||a===F)){if(o.id===F)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,l=o?.created??"",A=a?.created??"";return l.localeCompare(A)}),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 ot.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Ft(),wi));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(F)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===K)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(K);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()===K?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 d of s){let h=d.authorId;h&&!n.has(h)&&n.set(h,d.authorDisplay||h)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(d,h,g)=>{let I=o.createEl("button",{cls:"stashpad-shared-chip",text:d});return h&&I.addClass("is-active"),I.onclick=g,I};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 d=o.createEl("select",{cls:"stashpad-shared-author-select"}),h=d.createEl("option",{text:"Any author"});h.value="__any__";for(let[I,p]of n){let u=d.createEl("option",{text:p});u.value=I}let g=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;d.value=g,d.onchange=()=>{let I=d.value;I==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=I,this.render()}}let l=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&l.addClass("is-active"),l.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let A=s.filter(d=>{if(this.sharedContribOnly&&d.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return d.authorId===i;case"others":return d.authorId!==i;default:return d.authorId===this.sharedAuthorFilter}});if(A.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let d of A){let h=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),g=h.createSpan({cls:"stashpad-pinned-icon"});(0,ot.setIcon)(g,"users"),d.color&&(g.style.color=d.color);let I=h.createSpan({cls:"stashpad-pinned-label",text:d.title});I.onclick=()=>this.openSharedFromPanel(d.folder,d.id);let p=d.folder.split("/").pop()||d.folder;h.createSpan({cls:"stashpad-pinned-folder",text:p}),d.authorDisplay&&h.createSpan({cls:"stashpad-shared-meta"}).setText(d.authorId===i?`you \xB7 ${d.contributorCount} contributor${d.contributorCount===1?"":"s"}`:`by ${d.authorDisplay}${d.contributorCount>0?` \xB7 ${d.contributorCount} contributor${d.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 l=this.app.metadataCache.getFileCache(o)?.frontmatter??{};l.id===F&&s.set(a,this.extractAuthorId(l.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 l=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof l.id!="string"||l.id===F)continue;let A=this.extractAuthorId(l.author),d=Array.isArray(l.contributors)?l.contributors.filter(m=>typeof m=="string"):[],h=s.get(a)??null;if(!(d.length>0||h===t&&(A!==null&&A!==t)))continue;let f=this.titleFromFile(o),C=typeof l.color=="string"?l.color:null;n.push({file:o,folder:a,id:l.id,title:f,color:C,authorId:A,authorDisplay:this.extractAuthorDisplay(l.author)||(A??""),contributorCount:d.length})}return n.sort((o,a)=>{let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},A=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},d=l.modified??l.created??"";return(A.modified??A.created??"").localeCompare(d)}),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.revealNoteByRef(t,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=S=>!!s&&S.assignedTo.some(T=>T.id===s),o=S=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let U=T.slice(7);return S.assignedTo.some(L=>L.id===U)}switch(T){case"mine":return n(S);case"others":return S.assignedTo.length>0&&!n(S);case"byme":return!!s&&S.assignedBy?.id===s;case"unassigned":return S.assignedTo.length===0;default:return!0}},a=new Map;for(let S of i){for(let T of S.assignedTo)T.id!==s&&a.set(T.id,T.name);S.assignedBy&&S.assignedBy.id!==s&&a.set(S.assignedBy.id,S.assignedBy.name)}let l=[...a.entries()].map(([S,T])=>({id:S,name:T})).sort((S,T)=>S.name.localeCompare(T.name)),A=e.createDiv({cls:"stashpad-task-assign-bar"});A.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let d=A.createEl("select",{cls:"stashpad-task-assign-select"}),h=S=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return S.startsWith("person:")?a.get(S.slice(7))??"Person":T[S]??S},g=S=>{let T=d.createEl("option",{text:h(S),value:S});this.taskAssignFilter===S&&(T.selected=!0)};for(let S of["all","mine","others","byme","unassigned"])g(S);if(l.length>0){let S=d.createEl("optgroup");S.setAttr("label","By person");for(let T of l){let U=S.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(U.selected=!0)}}d.onchange=()=>{this.taskAssignFilter=d.value,this.render()};let I=[...new Set(i.map(S=>S.folder))].sort((S,T)=>S.localeCompare(T));this.taskFolderFilter!=="all"&&!I.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let p=e.createDiv({cls:"stashpad-task-assign-bar"});p.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let u=p.createEl("select",{cls:"stashpad-task-assign-select"}),f=u.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let S of I){let T=u.createEl("option",{text:S.split("/").pop()||S,value:S});this.taskFolderFilter===S&&(T.selected=!0)}u.onchange=()=>{this.taskFolderFilter=u.value,this.render()};let C=S=>this.taskFolderFilter==="all"||S.folder===this.taskFolderFilter,m=i.filter(S=>o(S)&&C(S));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let B=new Date;B.setHours(0,0,0,0);let y=B.getTime(),Q=y+24*60*60*1e3,E={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let S of m){if(S.completed){E.completed.push(S);continue}if(S.due==null){E.nodate.push(S);continue}S.due<y?E.overdue.push(S):S.due<Q?E.today.push(S):E.upcoming.push(S)}let v=(S,T)=>S.due==null&&T.due==null?S.title.localeCompare(T.title):S.due==null?1:T.due==null?-1:S.due-T.due,w=[{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"}],D=e.createDiv({cls:"stashpad-task-filters"}),N=m.length,P=(S,T,U)=>{let L=D.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===S&&L.addClass("is-active"),L.createSpan({cls:"stashpad-task-filter-label",text:T}),L.createSpan({cls:"stashpad-task-filter-count",text:String(U)}),L.onclick=()=>{this.taskFilter=S,this.render()}};P("all","All",N),P("overdue","Overdue",E.overdue.length),P("today","Today",E.today.length),P("upcoming","Upcoming",E.upcoming.length),P("nodate","No date",E.nodate.length),P("completed","Done",E.completed.length);let H=this.taskFilter==="all"?w:w.filter(S=>S.key===this.taskFilter),b=!1;for(let S of H){let T=E[S.key];if(T.length!==0){if(b=!0,T.sort(S.key==="completed"?(U,L)=>v(L,U):v),this.taskFilter==="all"){let U=e.createDiv({cls:`stashpad-task-section-header is-${S.key}`});(0,ot.setIcon)(U.createSpan({cls:"stashpad-task-section-icon"}),S.icon),U.createSpan({cls:"stashpad-task-section-name",text:S.label}),U.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let U of T)this.renderTaskRow(e,U,S.key==="today")}}if(!b&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${H[0]?.label??this.taskFilter}".`);return}b||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,ot.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(),l=s.createSpan({cls:"stashpad-task-assignees"});for(let A of e.assignedTo){let d=l.createSpan({cls:"stashpad-task-assignee"});a&&A.id===a&&d.addClass("is-me"),d.setText(this.initials(A.name)),d.title=a&&A.id===a?`${A.name} (you)`:A.name}}s.oncontextmenu=a=>{a.preventDefault();let l=new ot.Menu;l.addItem(A=>A.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),l.showAtMouseEvent(a)}}formatDueShort(t,e){return e?Go(t,this.plugin.settings):Uo(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new ot.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===F)continue;let l=o.completed===!0,A=Le(o,"task")||o.task===!0||o.completed!==void 0,d=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,h=null;if(d){let g=Date.parse(d);Number.isNaN(g)||(h=g)}!A&&!l&&h==null&&!d||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:A,completed:l,due:h,dueRaw:d,color:typeof o.color=="string"?o.color:null,assignedTo:ke(o),assignedBy:Ae(o.assignedBy)})}return i}};async function ss(c){let r=c.workspace.getLeavesOfType(le);if(r.length>0){c.workspace.revealLeaf(r[0]);return}let t=c.workspace.getLeftLeaf(!1);if(!t){new ot.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:le,active:!0}),c.workspace.revealLeaf(t)}var nr=require("obsidian");rt();var x=require("obsidian");ki();var ls=require("obsidian");rt();var $e=class extends ls.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!=="/"&&ci.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof ls.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()}};rt();Ft();var Me=require("obsidian"),vn={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)."},reminder:{label:"Reminder",desc:"Task due-date reminders \u2014 surfaced when a task comes due (fired at launch / periodically)."},system:{label:"System",desc:"Plumbing toasts: backfill progress, integrity warnings, errors not tied to a verb."}},$r={info:4e3,success:4e3,warning:6e3,error:1e4},ia=5e3,As=class{constructor(r){this.app=r;this.history=[];this.nextId=1;this.historyLimit=ia;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(r){this.defaultAuthorId=r||null}show(r){let t=r.kind??"info",e=r.category??"system",i={id:this.nextId++,ts:Date.now(),message:r.message,kind:t,category:e,authorId:r.authorId??this.defaultAuthorId??void 0,affectedIds:r.affectedIds?r.affectedIds.slice():[],affectedPaths:r.affectedPaths?r.affectedPaths.slice():[],affectedAuthorIds:r.affectedAuthorIds?r.affectedAuthorIds.slice():[],folder:r.folder,actionLabels:(r.actions??[]).map(o=>o.label)};if(this.pushHistory(i),this.muted.has(e))return null;let s=this.buildContent(r,t),n=r.duration??$r[t];return new Me.Notice(s,n)}onChange(r){return this.changeListeners.add(r),()=>this.changeListeners.delete(r)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(r,t){t?this.muted.add(r):this.muted.delete(r)}isMuted(r){return this.muted.has(r)}loadMutedFromList(r){this.muted=new Set(r)}mutedList(){return Array.from(this.muted)}loadHistory(r){let t=this.applyLimit(r.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(r){this.historyLimit=Number.isFinite(r)?r:ia,this.history=this.applyLimit(this.history),this.emit()}applyLimit(r){return this.historyLimit<=0||r.length<=this.historyLimit?r:r.slice(r.length-this.historyLimit)}pushHistory(r){this.history.push(r),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let r of this.changeListeners)try{r()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(r,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=r.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),r.actions&&r.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of r.actions){let l=document.createElement("button");l.className="stashpad-notice-action",l.textContent=a.label,l.addEventListener("click",A=>{if(A.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(d=>console.warn("[Stashpad] notification action failed",d)),!a.keepOpen){let d=l.closest(".notice");d&&d.parentElement&&d.parentElement.removeChild(d)}}),o.appendChild(l)}i.appendChild(o)}return e.appendChild(i),e}};function cs(c,r,t){let e=c.vault.getAbstractFileByPath(r);if(!(e instanceof Me.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=c.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;c.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=Me.Platform.isMacOS?"Finder":Me.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=c.vault.adapter?.getFullPath?.(r);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var sa=require("obsidian"),Fn=sa.Platform.isMacOS;function Si(c){if(!c)return"(none)";let r=c.replace(/\bMod\b/g,Fn?"Cmd":"Ctrl");return Fn&&(r=r.replace(/\bAlt\b/g,"Option")),r}function na(c,r,t={allowSingleKey:!0}){let e=c.placeholder,i=c.value;c.placeholder="Press a key\u2026 (Backspace to cancel)",c.value="",c.classList.add("is-recording");let s=!1,n=()=>{c.placeholder=e,c.classList.remove("is-recording"),s||(c.value=i),c.removeEventListener("keydown",o,!0),c.removeEventListener("blur",a)},o=l=>{if(l.key==="Control"||l.key==="Shift"||l.key==="Alt"||l.key==="Meta"||l.key==="OS")return;let A=!!l.code&&(/^Key[A-Z]$/.test(l.code)||/^Digit\d$/.test(l.code));if((l.key==="Dead"||l.key==="Process"||l.key==="Unidentified")&&!A)return;if(l.preventDefault(),l.stopPropagation(),l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.shiftKey){n();return}let d=[];Fn?(l.metaKey&&d.push("Mod"),l.ctrlKey&&d.push("Ctrl")):l.ctrlKey&&d.push("Mod"),l.altKey&&d.push("Alt"),l.shiftKey&&d.push("Shift");let h=Vr(l.key,l.code);if(!h||d.length===0&&!t.allowSingleKey)return;d.push(h);let g=d.join("+");s=!0,n(),r(g)},a=()=>n();return c.addEventListener("keydown",o,!0),c.addEventListener("blur",a),n}function Vr(c,r){if(!c)return"";if(r){let t=/^Key([A-Z])$/.exec(r);if(t)return t[1];let e=/^Digit(\d)$/.exec(r);if(e)return e[1]}return c.length===1?c.toUpperCase():c}Ye();Tt();function Te(c,r,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(A){try{l(e.next(A))}catch(d){n(d)}}function a(A){try{l(e.throw(A))}catch(d){n(d)}}function l(A){A.done?s(A.value):i(A.value).then(o,a)}l((e=e.apply(c,r||[])).next())})}var nt=class{constructor(){this.mutex=Promise.resolve()}lock(){let r=()=>{};return this.mutex=this.mutex.then(()=>new Promise(r)),new Promise(t=>{r=t})}dispatch(r){return Te(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(r())}finally{t()}})}},kn;function Wr(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Nn=Wr(),Sn=(kn=Nn.Buffer)!==null&&kn!==void 0?kn:null,Xr=Nn.TextEncoder?new Nn.TextEncoder:null;function ca(c,r){return(c&15)+(c>>6|c>>3&8)<<4|(r&15)+(r>>6|r>>3&8)}function da(c,r){let t=r.length>>1;for(let e=0;e<t;e++){let i=e<<1;c[e]=ca(r.charCodeAt(i),r.charCodeAt(i+1))}}function Zr(c,r){if(c.length!==r.length*2)return!1;for(let t=0;t<r.length;t++){let e=t<<1;if(r[t]!==ca(c.charCodeAt(e),c.charCodeAt(e+1)))return!1}return!0}var oa=87,aa=48;function xn(c,r,t){let e=0;for(let i=0;i<t;i++){let s=r[i]>>>4;c[e++]=s>9?s+oa:s+aa,s=r[i]&15,c[e++]=s>9?s+oa:s+aa}return String.fromCharCode.apply(null,c)}var te=Sn!==null?c=>{if(typeof c=="string"){let r=Sn.from(c,"utf8");return new Uint8Array(r.buffer,r.byteOffset,r.length)}if(Sn.isBuffer(c))return new Uint8Array(c.buffer,c.byteOffset,c.length);if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer,c.byteOffset,c.byteLength);throw new Error("Invalid data type!")}:c=>{if(typeof c=="string")return Xr.encode(c);if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer,c.byteOffset,c.byteLength);throw new Error("Invalid data type!")},Ht="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bi=new Uint8Array(256);for(let c=0;c<Ht.length;c++)bi[Ht.charCodeAt(c)]=c;function ra(c,r=!0){let t=c.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(c[n]<<16&16711680)+(c[n+1]<<8&65280)+(c[n+2]&255),a=Ht.charAt(o>>18&63)+Ht.charAt(o>>12&63)+Ht.charAt(o>>6&63)+Ht.charAt(o&63);i.push(a)}if(e===1){let n=c[t-1],o=Ht.charAt(n>>2),a=Ht.charAt(n<<4&63);i.push(`${o}${a}`),r&&i.push("==")}else if(e===2){let n=(c[t-2]<<8)+c[t-1],o=Ht.charAt(n>>10),a=Ht.charAt(n>>4&63),l=Ht.charAt(n<<2&63);i.push(`${o}${a}${l}`),r&&i.push("=")}return i.join("")}function jr(c){let r=Math.floor(c.length*.75),t=c.length;return c[t-1]==="="&&(r-=1,c[t-2]==="="&&(r-=1)),r}function _r(c){let r=jr(c),t=c.length,e=new Uint8Array(r),i=0;for(let s=0;s<t;s+=4){let n=bi[c.charCodeAt(s)],o=bi[c.charCodeAt(s+1)],a=bi[c.charCodeAt(s+2)],l=bi[c.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|l&63,i+=1}return e}var ds=16*1024,Di=4,tl=new nt,Dn=new Map;function ha(c,r){return Te(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=(Q,E=0)=>{e.set(Q,E)},n=()=>e,o=()=>t.exports,a=Q=>{t.exports.Hash_SetMemorySize(Q);let E=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,E,Q)},l=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),A=tl.dispatch(()=>Te(this,void 0,void 0,function*(){if(!Dn.has(c.name)){let E=_r(c.data),v=WebAssembly.compile(E);Dn.set(c.name,v)}let Q=yield Dn.get(c.name);t=yield WebAssembly.instantiate(Q,{})})),d=()=>Te(this,void 0,void 0,function*(){t||(yield A);let Q=t.exports.Hash_GetBuffer(),E=t.exports.memory.buffer;e=new Uint8Array(E,Q,ds)}),h=(Q=null)=>{i=!0,t.exports.Hash_Init(Q)},g=Q=>{let E=0;for(;E<Q.length;){let v=Q.subarray(E,E+ds);E+=v.length,e.set(v),t.exports.Hash_Update(v.length)}},I=Q=>{if(!i)throw new Error("update() called before init()");let E=te(Q);g(E)},p=new Uint8Array(r*2),u=(Q,E=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(E),Q==="binary"?e.slice(0,r):xn(p,e,r)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let Q=t.exports.Hash_GetState(),E=l(),v=t.exports.memory.buffer,w=new Uint8Array(v,Q,E),D=new Uint8Array(Di+E);return da(D,c.hash),D.set(w,Di),D},C=Q=>{if(!(Q instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let E=t.exports.Hash_GetState(),v=l(),w=Di+v,D=t.exports.memory.buffer;if(Q.length!==w)throw new Error(`Bad state length (expected ${w} bytes, got ${Q.length})`);if(!Zr(c.hash,Q.subarray(0,Di)))throw new Error("This state was written by an incompatible hash implementation");let N=Q.subarray(Di);new Uint8Array(D,E,v).set(N),i=!0},m=Q=>typeof Q=="string"?Q.length<ds/4:Q.byteLength<ds,B=m;switch(c.name){case"argon2":case"scrypt":B=()=>!0;break;case"blake2b":case"blake2s":B=(Q,E)=>E<=512&&m(Q);break;case"blake3":B=(Q,E)=>E===0&&m(Q);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":B=()=>!1;break}let y=(Q,E=null,v=null)=>{if(!B(Q,E))return h(E),I(Q),u("hex",v);let w=te(Q);return e.set(w),t.exports.Hash_Calculate(w.length,E,v),xn(p,e,r)};return yield d(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:h,update:I,digest:u,save:f,load:C,calculate:y,hashLength:r}})}var sc=new nt;var el="argon2",il="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",sl="e4cdc523",nl={name:el,data:il,hash:sl},ol="blake2b",al="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=",rl="c6f286e6",ll={name:ol,data:al,hash:rl},nc=new nt;function la(c){return!Number.isInteger(c)||c<8||c>512||c%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function Al(c,r){return c|r<<16}function Mn(c=512,r=null){if(la(c))return Promise.reject(la(c));let t=null,e=c;if(r!==null){if(t=te(r),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=Al(c,t.length)}let i=c/8;return ha(ll,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 cl(c,r,t){let e=[`m=${r.memorySize}`,`t=${r.iterations}`,`p=${r.parallelism}`].join(",");return`$argon2${r.hashType}$v=19$${e}$${ra(c,!1)}$${ra(t,!1)}`}var Aa=new DataView(new ArrayBuffer(4));function _t(c){return Aa.setInt32(0,c,!0),new Uint8Array(Aa.buffer)}function bn(c,r,t){return Te(this,void 0,void 0,function*(){if(t<=64){let a=yield Mn(t*8);return a.update(_t(t)),a.update(r),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);c.init(),c.update(_t(t)),c.update(r);let s=c.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)c.init(),c.update(s),s=c.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=c,o.init()):o=yield Mn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function dl(c){switch(c){case"d":return 0;case"i":return 1;default:return 2}}function hl(c){return Te(this,void 0,void 0,function*(){var r;let{parallelism:t,iterations:e,hashLength:i}=c,s=te(c.password),n=te(c.salt),o=19,a=dl(c.hashType),{memorySize:l}=c,A=te((r=c.secret)!==null&&r!==void 0?r:""),[d,h]=yield Promise.all([ha(nl,1024),Mn(512)]);d.setMemorySize(l*1024+1024);let g=new Uint8Array(24),I=new DataView(g.buffer);I.setInt32(0,t,!0),I.setInt32(4,i,!0),I.setInt32(8,l,!0),I.setInt32(12,e,!0),I.setInt32(16,o,!0),I.setInt32(20,a,!0),d.writeMemory(g,l*1024),h.init(),h.update(g),h.update(_t(s.length)),h.update(s),h.update(_t(n.length)),h.update(n),h.update(_t(A.length)),h.update(A),h.update(_t(0));let u=Math.floor(l/(t*4))*4,f=new Uint8Array(72),C=h.digest("binary");f.set(C);for(let y=0;y<t;y++){f.set(_t(0),64),f.set(_t(y),68);let Q=y*u,E=yield bn(h,f,1024);d.writeMemory(E,Q*1024),Q+=1,f.set(_t(1),64),E=yield bn(h,f,1024),d.writeMemory(E,Q*1024)}let m=new Uint8Array(1024);da(m,d.calculate(new Uint8Array([]),l));let B=yield bn(h,m,i);if(c.outputType==="hex"){let y=new Uint8Array(i*2);return xn(y,B,i)}return c.outputType==="encoded"?cl(n,c,B):B})}var pl=c=>{var r;if(!c||typeof c!="object")throw new Error("Invalid options parameter. It requires an object.");if(!c.password)throw new Error("Password must be specified");if(c.password=te(c.password),c.password.length<1)throw new Error("Password must be specified");if(!c.salt)throw new Error("Salt must be specified");if(c.salt=te(c.salt),c.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(c.secret=te((r=c.secret)!==null&&r!==void 0?r:""),!Number.isInteger(c.iterations)||c.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(c.parallelism)||c.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(c.hashLength)||c.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(c.memorySize))throw new Error("Memory size should be specified.");if(c.memorySize<8*c.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(c.outputType===void 0&&(c.outputType="hex"),!["hex","binary","encoded"].includes(c.outputType))throw new Error(`Insupported output type ${c.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Tn(c){return Te(this,void 0,void 0,function*(){return pl(c),hl(Object.assign(Object.assign({},c),{hashType:"id"}))})}var oc=new nt;var ac=new nt;var rc=new nt;var lc=new nt;var Ac=new Uint8Array(8);var cc=new nt;var dc=new nt;var hc=new nt;var pc=new nt;var gc=new nt;var Ic=new nt;var uc=new nt;var fc=new nt;var Cc=new nt;var mc=new nt;var Bc=new nt;var Qc=new Uint8Array(8);var yc=new nt;var Ec=new Uint8Array(8);var wc=new nt;var vc=new Uint8Array(8);var Fc=new nt;var kc=new nt;var Sc=new nt;Ft();var Pt=new Uint8Array([83,84,65,83,72,69,78,67]),Un=2,Gn=1,Rn=2,Ia=3,gl=32,Ve=12,Hn=32,Il=6e5,ul=47104,fl=3,Cl=1,dt=c=>c;function Ut(c){if(c.length<Pt.length+1)return!1;for(let r=0;r<Pt.length;r++)if(c[r]!==Pt[r])return!1;return!0}function pa(c,r,t){c[r]=t>>>24&255,c[r+1]=t>>>16&255,c[r+2]=t>>>8&255,c[r+3]=t&255}function ga(c,r){return c[r]*16777216+(c[r+1]<<16)+(c[r+2]<<8)+c[r+3]}async function Pn(c,r,t){if(t.id===Rn)return await Tn({password:c,salt:r,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Hn,outputType:"binary"});if(t.id===Gn){let e=await crypto.subtle.importKey("raw",dt(new TextEncoder().encode(c)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:dt(r),iterations:t.a,hash:"SHA-256"},e,Hn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function hs(c){return crypto.subtle.importKey("raw",dt(c),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var ua={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function We(c,r){let t=crypto.getRandomValues(new Uint8Array(gl)),e=crypto.getRandomValues(new Uint8Array(Ve)),i,s,n;try{i={id:Rn,a:ul,b:fl,c:Cl},n=await Pn(r,t,i),s="argon2id"}catch(d){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",d),i={id:Gn,a:Il,b:0,c:0},n=await Pn(r,t,i),s="pbkdf2"}let o=fa(i,t,e),a=await hs(n),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:dt(e),additionalData:dt(o)},a,dt(c))),A=new Uint8Array(o.length+l.length);return A.set(o,0),A.set(l,o.length),{data:A,kdf:s}}var Ni=null;async function ps(){if(Ni!==null)return Ni;try{await Tn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Ni=!0}catch{Ni=!1}return Ni}function fa(c,r,t){let e=new Uint8Array(Pt.length+1+1+4+4+1+1+r.length+t.length),i=0;return e.set(Pt,i),i+=Pt.length,e[i++]=Un,e[i++]=c.id,pa(e,i,c.a),i+=4,pa(e,i,c.b),i+=4,e[i++]=c.c,e[i++]=r.length,e.set(r,i),i+=r.length,e.set(t,i),i+=t.length,e}async function ee(c,r){if(!Ut(c))throw new Error("Not an encrypted Stashpad file.");let t=c[Pt.length];if(t===1)return ml(c,r);if(t!==Un)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Pt.length+1,i={id:c[e++],a:0,b:0,c:0};if(i.a=ga(c,e),e+=4,i.b=ga(c,e),e+=4,i.c=c[e++],i.id===Rn){if(i.a>2097152||i.b>64||i.c<1||i.c>8)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).")}else if(i.id===Gn&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=c[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=c.slice(e,e+s);e+=s;let o=c.slice(e,e+Ve);e+=Ve;let a=c.slice(0,e),l=c.slice(e),A=await Pn(r,n,i),d=await hs(A),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:dt(o),additionalData:dt(a)},d,dt(l));return new Uint8Array(h)}async function ml(c,r){let t=Pt.length+1,e=c.slice(t,t+16);t+=16;let i=c.slice(t,t+12);t+=12;let s=c.slice(t),n=await crypto.subtle.importKey("raw",dt(new TextEncoder().encode(r)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:dt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:dt(i)},o,dt(s));return new Uint8Array(a)}async function xi(c,r){if(r.length!==Hn)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Ve)),i=fa({id:Ia,a:0,b:0,c:0},new Uint8Array(0),t),s=await hs(r),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:dt(t),additionalData:dt(i)},s,dt(c))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function he(c,r){if(!Ut(c))throw new Error("Not an encrypted Stashpad file.");let t=c[Pt.length];if(t!==Un)throw new Error(`Unsupported encrypted version (${t}).`);let e=Pt.length+1;if(c[e++]!==Ia)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=c[e++];e+=s;let n=c.slice(e,e+Ve);e+=Ve;let o=c.slice(0,e),a=c.slice(e),l=await hs(r),A=await crypto.subtle.decrypt({name:"AES-GCM",iv:dt(n),additionalData:dt(o)},l,dt(a));return new Uint8Array(A)}async function Xe(c,r,t={}){if(!Ut(r))return r;if(t.secretId){let i=c.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await ee(r,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new mi(c,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await ee(r,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Tt();var gs={name:"ECDH",namedCurve:"P-256"},Bl="stashpad-vault-dek-wrap",Ql=new TextEncoder;function Ln(c){let r="";for(let t=0;t<c.length;t++)r+=String.fromCharCode(c[t]);return btoa(r)}function qn(c){let r=atob(c),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function Ca(){let c=await crypto.subtle.generateKey(gs,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",c.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",c.privateKey))}}function ma(c){return crypto.subtle.importKey("spki",c,gs,!1,[])}function yl(c){return crypto.subtle.importKey("pkcs8",c,gs,!1,["deriveBits"])}async function Ba(c,r){let t=await crypto.subtle.deriveBits({name:"ECDH",public:r},c,256),e=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:Ql.encode(Bl)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Is(c,r,t){let e=await crypto.subtle.generateKey(gs,!0,["deriveBits"]),i=await Ba(e.privateKey,await ma(r)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,c)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:Ln(o),iv:Ln(s),ct:Ln(n)}}async function Qa(c,r){let t=await Ba(await yl(r),await ma(qn(c.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:qn(c.iv)},t,qn(c.ct)))}var ya=".stashpad/keys.json",El=".stashpad",Mi="_keys";function Jn(c){return{v:2,keyId:c,identities:[],slots:[],joinRequests:[]}}var us=class{constructor(r){this.app=r}get a(){return this.app.vault.adapter}validate(r){let t=r;return!!t&&t.v===2&&typeof t.keyId=="string"&&Array.isArray(t.identities)&&Array.isArray(t.slots)&&Array.isArray(t.joinRequests)}async readValid(r){try{if(!await this.a.exists(r))return null;let t=JSON.parse(await this.a.read(r));return this.validate(t)?t:null}catch{return null}}async load(){let r=await this.readValid(ya);if(r)return r;try{let e=((await this.a.list(Mi)).files||[]).filter(i=>/\/keys-\d+\.json$/.test(i)).sort();for(let i of e.reverse()){let s=await this.readValid(i);if(s)return s}}catch{}return null}async exists(){return await this.load()!==null}async ensureDir(r){try{await this.a.exists(r)||await this.a.mkdir(r)}catch{}}async save(r){let t=JSON.stringify(r,null,2);await this.ensureDir(El),await this.a.write(ya,t),await this.ensureDir(Mi);for(let e=4;e>=1;e--){let i=`${Mi}/keys-${e}.json`,s=`${Mi}/keys-${e+1}.json`;try{await this.a.exists(i)&&await this.a.write(s,await this.a.read(i))}catch{}}try{await this.a.write(`${Mi}/keys-1.json`,t)}catch{}}};var fs="stashpad-vault-encryption";function Ti(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function Cs(c){let r="";for(let t=0;t<c.length;t++)r+=String.fromCharCode(c[t]);return btoa(r)}function ie(c){let r=atob(c),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}var wl=32,ms=class{constructor(r,t,e,i=()=>0){this.app=r;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.idleTimer=null;this.kf=null;this.keyfiles=new us(r)}argonProbe(){return ps()}async init(){await this.refresh()}async refresh(){this.kf=await this.keyfiles.load()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}keychainId(){let r=this.app.appId||"default";return`${fs}-${r}`}isRemembered(){try{return!!this.secretStore()?.getSecret(this.keychainId())}catch{return!1}}async remember(r){try{await this.secretStore()?.setSecret(this.keychainId(),r)}catch(t){console.warn("[Stashpad] couldn't save password to keychain",t)}}async forgetKeychain(){let r=this.secretStore();if(r)try{r.removeSecret?await r.removeSecret(this.keychainId()):await r.setSecret(this.keychainId(),"")}catch(t){console.warn("[Stashpad] couldn't clear keychain",t)}}async tryAutoUnlock(){if(!this.isConfigured()||this.isUnlocked())return this.isUnlocked();if(this.accessState()!=="member"&&!this.hasSharedPassword())return!1;let r=this.secretStore(),t=null;try{t=r?.getSecret(this.keychainId())??null}catch{t=null}if(t)return this.unlock(t);let e=null;try{e=r?.getSecret(fs)??null}catch{e=null}if(!e)return!1;let i=await this.unlock(e);if(i){await this.remember(e);try{r?.removeSecret?await r.removeSecret(fs):await r?.setSecret(fs,"")}catch{}}return i}isConfigured(){return!!this.kf||!!this.load().wrappedKey}isUnlocked(){return this.sessionKey!==null}kdf(){return this.load().identityPrivKdf??this.load().kdf}hasIdentity(){return!!this.load().identityPrivWrapped&&!!this.load().identityId}mySlot(){let r=this.load().identityId;return r?this.kf?.slots.find(t=>t.recipientId===r)??null:null}accessState(){let r=this.load();return!this.kf&&r.wrappedKey?"member":this.kf?this.hasIdentity()&&this.mySlot()?"member":r.identityId&&this.kf.joinRequests.some(t=>t.id===r.identityId)?"pending":"outsider":"none"}amIMember(){return this.accessState()==="member"}async setup(r,t=!1,e){if(await this.refresh(),this.isConfigured())throw new Error("Encryption is already set up in this vault.");if(!r)throw new Error("Password required.");let i=crypto.getRandomValues(new Uint8Array(wl)),s=await this.mintIdentity(r,e),n=Jn(tt(8));n.identities.push(this.identityRecord(s)),n.slots.push(await Is(i,ie(s.pub),s.id)),await this.keyfiles.save(n),this.kf=n,this.sessionKey=i,t?await this.remember(r):await this.forgetKeychain(),this.armIdle()}async unlock(r,t=!1){await this.refresh();let e=this.load();if(!this.kf&&e.wrappedKey){let s;try{s=await ee(ie(e.wrappedKey),r)}catch{return!1}let n=await this.mintIdentity(r,e.identityLabel??void 0),o=Jn(tt(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await Is(s,ie(n.pub),n.id)),await this.keyfiles.save(o),this.kf=o,this.sessionKey=s,t&&await this.remember(r),this.armIdle(),!0}let i=this.hasIdentity()?this.mySlot():null;if(i)try{let s=await ee(ie(e.identityPrivWrapped),r);try{let n=await Qa(i,s);return s.fill(0),this.sessionKey=n,t&&await this.remember(r),this.armIdle(),!0}catch{s.fill(0)}}catch{}for(let s of this.kf?.passwordSlots??[])try{let n=await ee(ie(s.wrapped),r);return this.sessionKey=n,t&&await this.remember(r),this.armIdle(),!0}catch{}return!1}hasSharedPassword(){return(this.kf?.passwordSlots?.length??0)>0}async setSharedPassword(r){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(!r)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let t=await We(this.sessionKey,r);this.kf.passwordSlots=[{id:tt(8),label:"Shared password",wrapped:Cs(t.data),kdf:t.kdf,createdAt:new Date().toISOString()}],await this.keyfiles.save(this.kf)}async removeSharedPassword(){await this.refresh(),!(!this.kf||!this.kf.passwordSlots?.length)&&(this.kf.passwordSlots=[],await this.keyfiles.save(this.kf))}async verifyPassword(r){let t=this.load();try{if(t.identityPrivWrapped)return(await ee(ie(t.identityPrivWrapped),r)).fill(0),!0;if(t.wrappedKey)return(await ee(ie(t.wrappedKey),r)).fill(0),!0}catch{}return!1}async changePassword(r,t,e=!1){let i=this.load();if(!t)throw new Error("New password required.");if(!i.identityPrivWrapped&&!await this.unlock(r,!1))return!1;let s=this.load(),n;try{n=await ee(ie(s.identityPrivWrapped),r)}catch{return!1}let o=await We(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:Cs(o.data),identityPrivKdf:o.kdf}),e?await this.remember(t):await this.forgetKeychain(),this.armIdle(),!0}async requestAccess(r,t,e=!1){if(await this.refresh(),!this.kf)throw new Error("This vault has no encryption set up yet.");if(this.amIMember())return;if(!t)throw new Error("Password required.");let i=this.hasIdentity()?{id:this.load().identityId,label:this.load().identityLabel??r,pub:this.load().identityPub}:await this.mintIdentity(t,r);r&&i.label!==r&&(await this.save({...this.load(),identityLabel:r}),i.label=r);let s={id:i.id,label:i.label,pubKey:i.pub,requestedAt:new Date().toISOString()};this.kf.joinRequests=[...this.kf.joinRequests.filter(n=>n.id!==i.id),s],await this.keyfiles.save(this.kf),e?await this.remember(t):await this.forgetKeychain()}pendingJoinRequests(){return this.kf?.joinRequests??[]}members(){return this.kf?.identities??[]}myIdentityId(){return this.load().identityId}async approveJoinRequest(r,t){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(await this.refresh(),!this.kf)return!1;let e=this.kf.joinRequests.find(i=>i.id===r);return e?(this.kf.slots=[...this.kf.slots.filter(i=>i.recipientId!==e.id),await Is(this.sessionKey,ie(e.pubKey),e.id)],this.kf.identities=[...this.kf.identities.filter(i=>i.id!==e.id),{id:e.id,label:t??e.label,pubKey:e.pubKey,addedAt:new Date().toISOString()}],this.kf.joinRequests=this.kf.joinRequests.filter(i=>i.id!==r),await this.keyfiles.save(this.kf),!0):!1}async removeMember(r){await this.refresh(),this.kf&&(this.kf.slots=this.kf.slots.filter(t=>t.recipientId!==r),this.kf.identities=this.kf.identities.filter(t=>t.id!==r),this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==r),await this.keyfiles.save(this.kf))}async denyJoinRequest(r){await this.refresh(),this.kf&&(this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==r),await this.keyfiles.save(this.kf))}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null,this.clearIdle()}async clear(){this.lock(),await this.forgetKeychain();try{let r=this.app.vault.adapter;for(let t of[".stashpad/keys.json"])try{await r.exists(t)&&await r.remove(t)}catch{}try{let t=await r.list("_keys");for(let e of t.files||[])if(/\/keys-\d+\.json$/.test(e))try{await r.remove(e)}catch{}}catch{}}catch{}this.kf=null,await this.save(Ti())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(r,t){let e=await Ca(),i=await We(e.privKeyPkcs8,r);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??tt(8),o=t??s.identityLabel??"This device",a=Cs(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:a,identityPrivWrapped:Cs(i.data),identityPrivKdf:i.kdf}),{id:n,label:o,pub:a}}identityRecord(r){return{id:r.id,label:r.label,pubKey:r.pub,addedAt:new Date().toISOString()}}armIdle(){this.clearIdle();let r=this.idleMinutes();r>0&&(this.idleTimer=window.setTimeout(()=>this.lock(),r*6e4))}clearIdle(){this.idleTimer!=null&&(window.clearTimeout(this.idleTimer),this.idleTimer=null)}dispose(){this.lock()}};var vs=require("obsidian");ws();Tt();rt();var oe="stash",Ja=1;function La(c){let t=(c.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var io=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function ge(c,r){let t=[],e=zl([...r.rootNotes,...r.allDescendants]),i=new Map,s=[];for(let o of e){let a=await c.vault.read(o.file),l=a,A=Ka(a);for(let d of A){let h=c.metadataCache.getFirstLinkpathDest(d,o.file.path);if(!h){s.push(`Missing attachment "${d}" in ${o.file.path}`);continue}let g=h.name;i.has(g)||i.set(g,await c.vault.readBinary(h)),l=$l(l,d,g)}l=Xl(l,c,o.file.path),t.push({name:`notes/${o.file.name}`,data:l})}for(let[o,a]of i)t.push({name:`attachments/${o}`,data:a});let n={stashSchema:Ja,exportedAt:new Date().toISOString(),sourceFolder:r.sourceFolder,noteCount:e.length,rootIds:r.rootNotes.map(o=>o.id)};return t.push({name:"manifest.json",data:JSON.stringify(n,null,2)}),s.length&&t.push({name:"warnings.txt",data:s.join(` -`)}),Ri(t,6)}async function Vt(c,r,t,e,i={}){let s=await Li(r),n=s["manifest.json"];if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(Es(n));if(typeof o.stashSchema!="number"||o.stashSchema>Ja)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await qa(c,t);let a=Object.entries(s).filter(([E])=>E.startsWith("notes/")&&E.endsWith(".md")),l=[];for(let[E,v]of a){let w=Es(v),{fm:D,body:N}=At(w),P=La(E.slice(6))||`${D.id||"imported-"+tt(4)}.md`;l.push({originalName:P,fm:D,body:N})}let A=new Map,d=0;for(let E of l){let v=E.fm.id;v&&(i.forceNewIds?A.set(v,tt(6)):e.has(v)||A.has(v)?(A.set(v,`${v}-${tt(4)}-Imported`),d++):A.set(v,v))}let h=new Date().toISOString(),g=[],I=`${t}/_attachments`,p=0,u=Object.entries(s).filter(([E])=>E.startsWith("attachments/")),f=new Map,C=null;if(i.dedupeExisting){C=new Map;for(let E of c.vault.getFiles())C.has(E.name)||C.set(E.name,E.path)}let m=(E,v)=>{if(E.length!==v.length)return!1;for(let w=0;w<E.length;w++)if(E[w]!==v[w])return!1;return!0},B=!1;for(let[E,v]of u){let w=La(E.slice(12));if(!w)continue;let D=v,N=[],P=C?.get(w);P&&N.push(P);let H=`${I}/${w}`;await c.vault.adapter.exists(H)&&N.push(H);let b=null;for(let T of N)try{if(m(new Uint8Array(await c.vault.adapter.readBinary(T)),D)){b=T;break}}catch{}if(b){f.set(w,b);continue}let S=H;for(let T=1;await c.vault.adapter.exists(S);T++)S=`${I}/${Vl(w,T)}`;f.set(w,S),B||(await qa(c,I),B=!0),await c.vault.createBinary(S,D.buffer),p++}let y=0;for(let E of l){let v=E.fm.id;if(!v){g.push(`Skipped ${E.originalName} \u2014 no id in frontmatter`);continue}let w=A.get(v),D=E.fm.parent??null,N=D;!D||D===F?N=i.reparentRootsTo??D??F:A.has(D)?N=A.get(D):N=e.has(D)?D:i.reparentRootsTo??F;let P=Wl(E.body,f,I),H={...E.fm,id:w,parent:N,import_date:h};Array.isArray(H.attachments)&&(H.attachments=H.attachments.map(U=>{let L=Oa(Fe(U));return Ot(f.get(L)??`${I}/${L}`)}));let b=Ie(H,P),S=w===v?E.originalName:jl(E.originalName,v,w),T=`${t}/${S}`;await c.vault.adapter.exists(T)&&(S=`${S.replace(/\.md$/,"")}-${tt(4)}.md`,T=`${t}/${S}`),await c.vault.create(T,b),y++}let Q;if(o.colorAliases&&typeof o.colorAliases=="object"){let E={};for(let[v,w]of Object.entries(o.colorAliases)){let D=String(v).trim().toLowerCase(),N=String(w??"").trim();/^#([0-9a-f]{6})$/.test(D)&&N&&(E[D]=N.slice(0,60))}Object.keys(E).length&&(Q=E)}return{notesWritten:y,attachmentsWritten:p,collisionsRenamed:d,warnings:g,colorAliases:Q,idRemap:Object.fromEntries(A)}}function zl(c){let r=new Set,t=[];for(let e of c)r.has(e.id)||(r.add(e.id),t.push(e));return t}function Ka(c){let r=new Set,t;for(io.lastIndex=0;(t=io.exec(c))!==null;)r.add(t[1]);return[...r]}async function Fs(c,r){let t=await c.vault.read(r),e=[],i=new Set;for(let s of Ka(t)){let n=c.metadataCache.getFirstLinkpathDest(s,r.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function $l(c,r,t){return c.replace(new RegExp(`!\\[\\[${Zl(r)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function Vl(c,r){let t=c.lastIndexOf(".");return t>0?`${c.slice(0,t)}-${r}${c.slice(t)}`:`${c}-${r}`}function Wl(c,r,t){return c.replace(io,(e,i,s)=>{if(i.includes("/"))return e;let n=r.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Xl(c,r,t){let e=At(c);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return c;let i=e.fm.attachments.map(n=>{let o=r.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:Oa(n)}),s={...e.fm,attachments:i};return Ie(s,e.body)}function Zl(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Oa(c){let r=c.lastIndexOf("/");return r<0?c:c.slice(r+1)}function jl(c,r,t){return c.includes(r)?c.replace(r,t):c.replace(/\.md$/,`-${t}.md`)}function At(c){if(!c.startsWith("---"))return{fm:{},body:c};let r=c.indexOf(` ----`,3);if(r<0)return{fm:{},body:c};let t=c.slice(3,r).replace(/^\n/,""),e=c.slice(r+4),i={};try{i=(0,vs.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` -`)?e.slice(1):e;return{fm:i,body:s}}function Ie(c,r){return`--- -${(0,vs.stringifyYaml)(c).trimEnd()} ---- -${r}`}async function qa(c,r){if(!(!r||await c.vault.adapter.exists(r)))try{await c.vault.createFolder(r)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}ws();var ue="stashenc",_l="stashmeta";function fe(c){return c.replace(/\.stashenc$/,`.${_l}`)}async function Ya(c,r){try{return JSON.parse(await c.vault.adapter.read(fe(r)))}catch{return null}}async function Ce(c,r,t){let e=r.replace(/\/+$/,""),i=[];for(let A of c.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let d;try{d=At(await c.vault.read(A)).fm}catch{continue}typeof d.id=="string"&&i.push({id:d.id,file:A,parent:typeof d.parent=="string"?d.parent:null,created:typeof d.created=="string"?d.created:""})}let s=i.find(A=>A.id===t);if(!s)return null;let n=new Map;for(let A of i){if(!A.parent)continue;let d=n.get(A.parent)??[];d.push(A),n.set(A.parent,d)}let o=[],a=new Set([t]),l=[t];for(;l.length;){let A=[];for(let d of l)for(let h of n.get(d)??[])a.has(h.id)||(a.add(h.id),o.push(h),A.push(h.id));l=A}return{rootNote:s,descendants:o,parentId:s.parent}}function so(c){if(!c)return null;let r=c.replace(/\/+$/,"");return!r||r.startsWith("/")||r.includes("\\")||/^[a-zA-Z]:/.test(r)||r.split("/").some(t=>t===".."||t===".")?null:r}async function no(c,r,t){await c.vault.adapter.writeBinary(r,t);let e;try{e=new Uint8Array(await c.vault.adapter.readBinary(r))}catch(s){throw new Error(`Couldn't read back the encrypted file to verify it (${s.message}). Nothing was deleted.`)}let i=e.length===t.length;if(i){for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}}if(!i){try{await c.vault.adapter.remove(r)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function ks(c){return c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||c.basename}function Ze(c){return(c.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function za(c,r,t){let e=new Set(r.map(a=>a.file.path)),i=new Map;for(let a of r)for(let l of await Fs(c,a.file))i.set(l.path,l);let s=new Set,n=c.metadataCache.resolvedLinks??{};for(let a of Object.keys(n))if(!e.has(a))for(let l of Object.keys(n[a]??{}))i.has(l)&&s.add(l);let o=[];for(let a of r){let l=t?.get(a.file.path);if(l!=null)try{let A=await c.vault.adapter.stat(a.file.path);if(A&&A.mtime!==l){console.warn("[Stashpad] note changed since it was bundled \u2014 keeping plaintext",a.file.path),o.push(a.file.path);continue}}catch{}try{await c.vault.delete(a.file)}catch(A){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,A),o.push(a.file.path)}}for(let[a,l]of i)if(!s.has(a))try{await c.vault.delete(l)}catch(A){console.warn("[Stashpad] couldn't delete exclusive attachment",a,A),o.push(a)}return{unpurged:o}}async function $a(c,r,t,e,i=null,s=!1,n){let o=await Ce(c,r,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:l,parentId:A}=o,d=[a,...l],h=new Map;for(let Q of d)try{let E=await c.vault.adapter.stat(Q.file.path);E&&h.set(Q.file.path,E.mtime)}catch{}let g=await ge(c,{rootNotes:[{id:a.id,file:a.file}],allDescendants:l.map(Q=>({id:Q.id,file:Q.file})),sourceFolder:r}),I=await xi(g,e),p=await he(I,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size mismatch).");for(let Q=0;Q<g.length;Q++)if(p[Q]!==g[Q])throw new Error("Encryption self-check failed (content mismatch).");let u=(n??r).replace(/\/+$/,"");n&&!await c.vault.adapter.exists(u)&&await c.vault.adapter.mkdir(u);let f=Ze(s?t:ks(a.file)),C=`${u}/${f}.${ue}`;for(let Q=1;await c.vault.adapter.exists(C);Q++)C=`${u}/${f} (${Q}).${ue}`;await no(c,C,I);let m=d,B={v:1,parentId:A,title:s?"":ks(a.file),count:m.length,created:a.created,rootId:t,prevSibling:i};try{await c.vault.adapter.write(fe(C),JSON.stringify(B))}catch(Q){console.warn("[Stashpad] couldn't write lock sidecar",Q)}let{unpurged:y}=await za(c,m,h);return{blobPath:C,noteCount:m.length,rootId:t,parentId:A,title:B.title,created:a.created,unpurged:y}}async function Va(c,r,t,e,i){let s=new Uint8Array(await c.vault.adapter.readBinary(r));if(!Ut(s))throw new Error("Not an encrypted bundle.");let n=await he(s,t),o=so(i)??r.replace(/\/[^/]*$/,""),a=await Vt(c,n,o,e,{dedupeExisting:!0});await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(fe(r))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var bt="_deleted";function tA(c){let r="";for(let t=0;t<c.length;t++)r+=String.fromCharCode(c[t]);return btoa(r)}function eA(c){let r=atob(c),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function oo(c,r,t,e){let i=so(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=so(new TextDecoder().decode(await he(eA(t.originalFolderEnc),e)))}catch{i=null}if(i)return await c.vault.adapter.exists(i)||await c.vault.adapter.mkdir(i),i;let s=r.replace(/\/[^/]*$/,"");if(s===bt||s.startsWith(`${bt}/`))throw new Error("This deleted note's origin folder is unknown (missing or tampered sidecar) \u2014 can't restore it safely. The encrypted copy was kept.");return s}async function ao(c){let r=[""];for(;r.length;){let t=r.shift(),e;try{e=await c.vault.adapter.list(t||"/")}catch{continue}if(e.files.some(i=>i.endsWith(`.${ue}`)))return!0;for(let i of e.folders)i===".obsidian"||i.endsWith("/.obsidian")||r.push(i)}return!1}async function Wa(c,r,t,e,i,s=!1){let n=await Ce(c,r,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:a,parentId:l}=n,A=[o,...a],d=new Map;for(let Q of A)try{let E=await c.vault.adapter.stat(Q.file.path);E&&d.set(Q.file.path,E.mtime)}catch{}let h=await ge(c,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(Q=>({id:Q.id,file:Q.file})),sourceFolder:r}),g=await xi(h,e),I=await he(g,e);if(I.length!==h.length)throw new Error("Encryption self-check failed (size).");for(let Q=0;Q<h.length;Q++)if(I[Q]!==h[Q])throw new Error("Encryption self-check failed (content).");await c.vault.adapter.exists(bt)||await c.vault.adapter.mkdir(bt);let p=r.replace(/\/+$/,""),u=p.split("/").pop()||"vault",f=Ze(s?t:`${u} ${ks(o.file)}`),C=`${bt}/${f}.${ue}`;for(let Q=1;await c.vault.adapter.exists(C);Q++)C=`${bt}/${f} (${Q}).${ue}`;await no(c,C,g);let m=A,B={v:1,kind:"deleted",originalFolder:s?"":p,...s?{originalFolderEnc:tA(await xi(new TextEncoder().encode(p),e))}:{},parentId:l,title:s?"":ks(o.file),count:m.length,created:o.created,rootId:t,deletedAt:i};try{await c.vault.adapter.write(fe(C),JSON.stringify(B))}catch(Q){console.warn("[Stashpad] couldn't write deleted sidecar",Q)}let{unpurged:y}=await za(c,m,d);return{blobPath:C,noteCount:m.length,rootId:t,originalFolder:p,title:B.title,unpurged:y}}async function Xa(c,r,t,e){let i=new Uint8Array(await c.vault.adapter.readBinary(r));if(!Ut(i))throw new Error("Not an encrypted bundle.");let s=await Ss(c,r),n=await oo(c,r,s,t),o=await he(i,t),a=await Vt(c,o,n,e,{dedupeExisting:!0});await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(fe(r))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function Ss(c,r){try{return JSON.parse(await c.vault.adapter.read(fe(r)))}catch{return null}}var Rt=".trash";async function iA(c,r){let t=[],e=[r];for(;e.length;){let i=e.shift(),s;try{s=await c.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function sA(c){let r=c.split("/").filter(Boolean);if(r.length===0)return null;for(let t of r)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return r.join("/")}async function Za(c,r,t,e=!1){if(!await c.vault.adapter.exists(Rt))return null;let i=await iA(c,Rt);if(i.length===0)return null;let s=[],n=new Map;for(let I of i){let p=I.slice(Rt.length+1);s.push({name:`files/${p}`,data:await c.vault.adapter.readBinary(I)});try{let u=await c.vault.adapter.stat(I);u&&n.set(I,u.mtime)}catch{}}let o=await Ri(s),a=await xi(o,r),l=await he(a,r);if(l.length!==o.length)throw new Error("Encryption self-check failed (size).");for(let I=0;I<o.length;I++)if(l[I]!==o[I])throw new Error("Encryption self-check failed (content).");await c.vault.adapter.exists(bt)||await c.vault.adapter.mkdir(bt);let A=Ze(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),d=`${bt}/${A}.${ue}`;for(let I=1;await c.vault.adapter.exists(d);I++)d=`${bt}/${A} (${I}).${ue}`;await no(c,d,a);let h={v:1,kind:"rawtrash",originalFolder:Rt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await c.vault.adapter.write(fe(d),JSON.stringify(h))}catch(I){console.warn("[Stashpad] couldn't write backfill sidecar",I)}let g=[];for(let I of i){let p=n.get(I);try{if(p!=null){let u=await c.vault.adapter.stat(I);if(u&&u.mtime!==p){g.push(I);continue}}await c.vault.adapter.remove(I)}catch(u){console.warn("[Stashpad] couldn't delete trash file",I,u),g.push(I)}}return{blobPath:d,fileCount:i.length,unpurged:g}}async function ja(c,r,t){let e=new Uint8Array(await c.vault.adapter.readBinary(r));if(!Ut(e))throw new Error("Not an encrypted bundle.");let i=await he(e,t),s=await Li(i),n=0;for(let[o,a]of Object.entries(s)){if(!o.startsWith("files/"))continue;let l=sA(o.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",o);continue}let A=`${Rt}/${l}`.split("/").slice(0,-1).join("/"),d="";for(let g of A.split("/"))d=d?`${d}/${g}`:g,await c.vault.adapter.exists(d)||await c.vault.adapter.mkdir(d);let h=`${Rt}/${l}`;for(let g=1;await c.vault.adapter.exists(h);g++)h=`${Rt}/${l.replace(/(\.[^./]*)?$/,` (${g})$1`)}`;await c.vault.adapter.writeBinary(h,a.buffer),n++}await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(fe(r))}catch{}return{filesWritten:n}}async function _a(c){if(!await c.vault.adapter.exists(bt))return[];try{return(await c.vault.adapter.list(bt)).files.filter(t=>t.endsWith(`.${ue}`))}catch{return[]}}var qi=null,Ds=new Set;function bs(c){if(qi!==c){qi=c;for(let r of Ds)r()}}function ae(){return qi}function tr(c){if(qi===c){qi=null;for(let r of Ds)r()}}function er(c){return Ds.add(c),()=>Ds.delete(c)}function nA(){return x.Platform.isMacOS?"Finder":x.Platform.isWin?"File Explorer":"file manager"}var je=[{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:"forkNote",label:"Fork into a separate note (under a chosen parent)",desc:'Duplicate the cursor row (with its subtree) as a separate note and pick which parent it nests under. Distinct from "Fork as a version" (a draft within a sheet group). No default chord.',defaultPrimary:""},{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:"expandAll",label:"Expand all (show every note's full body)",desc:"Un-clamp every note in the current list at once.",defaultPrimary:""},{id:"collapseAll",label:"Collapse all (clamp every note's body)",desc:"Re-clamp every note in the current list at once.",defaultPrimary:""},{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:"listPin",label:"Pin / unpin to top of list",desc:"Float the cursor row (or selection) to the TOP of its list \u2014 distinct from the sidebar pin. No default chord.",defaultPrimary:""},{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"},{id:"lockSelection",label:"Encrypt (lock) selection",desc:"Encrypt the selected note(s) + their children into a locked .stashenc bundle in place (prompts to unlock first if needed). No default chord.",defaultPrimary:""},{id:"unlockAll",label:"Decrypt (unlock) locked notes in view",desc:"Decrypt every locked stash shown in the current view back into place, skipping any that can't be read. No default chord.",defaultPrimary:""},{id:"moveToArchive",label:"Move selection to archive (encrypt)",desc:"Move the selected note(s) to the default archive folder, encrypted on arrival. Undoable. No default chord.",defaultPrimary:""},{id:"encryptDelete",label:"Encrypt & delete selection",desc:"Send the selected note(s) to the encrypted trash (recoverable with your password, Ctrl/Cmd+Z undoable). No default chord.",defaultPrimary:""},{id:"copyNotes",label:"Copy notes (note clipboard)",desc:"Copy the selected note(s) as NOTES: paste in the list to duplicate them (new ids), or anywhere else to paste their text. Skipped when text is highlighted (normal copy wins).",defaultPrimary:"Mod+C"},{id:"cutNotes",label:"Cut notes",desc:"Cut the selected note(s): paste in the list to MOVE them, or in the composer to extract their text and delete the originals (undoable).",defaultPrimary:"Mod+X"},{id:"pasteNotes",label:"Paste notes",desc:"Paste previously copied/cut notes at the cursor row (after it, same parent). Does nothing if the note clipboard is empty.",defaultPrimary:"Mod+V"}];function Ao(){let c={};for(let r of je)c[r.id]={primary:r.defaultPrimary,secondary:r.defaultSecondary??"",preferRight:!1,useBoth:!!r.defaultUseBoth};return c}var me={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,debugTrace:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,splitMode:"lines",confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,encryption:Ti(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],lockedSubtrees:[],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,notifiedDueKeys:[],autoNavOnMoveIn:!1,autoNavOnMoveOut:!1,autoExpandCursorRow:!1,expandBodiesByDefault:!1,autoOpenDetailPanel:!1,doubleClickToFocus:!0,enableSheetVersions:!1,dateDisplayFormat:"locale",dateDisplayTimezone:"",jdIndexScope:"vault",jdIndexScopeFolder:"",jdIndexStashpadFolder:"",jdIndexFile:"Index",jdIndexIncludeStashpadFolders:!1,jdIndexSort:"natural",jdIndexHasBuilt:!1,okfEnabled:!1,okfTemplatePath:"",drafts:{},lastSubmitted:{},bindings:Ao()},ir=JSON.parse(JSON.stringify(me)),lo=new Set;function j(){return ir}function co(c){ir=c;for(let r of lo)r()}function sr(c){return lo.add(c),()=>lo.delete(c)}function Ms(c){try{let r=c.internalPlugins?.plugins?.templates;if(!r?.enabled)return null;let t=r.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var Ns=[{id:"foldersStorage",label:"Folders & storage"},{id:"importExport",label:"Import & export"},{id:"noteTitles",label:"Note titles"},{id:"datesTime",label:"Dates & time"},{id:"listDisplay",label:"List & display"},{id:"movingNotes",label:"Moving notes"},{id:"deleting",label:"Deleting"},{id:"composerCopy",label:"Composer & copying"},{id:"windowsTabs",label:"Windows & tabs"},{id:"notifications",label:"Notifications"},{id:"encryption",label:"Encryption"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"okf",label:"Open Knowledge Format (OKF)"},{id:"maintenance",label:"Maintenance"},{id:"diagnostics",label:"Diagnostics"},{id:"misc",label:"Misc"},{id:"hotkeys",label:"Hotkeys"}],ro=null;function oA(c,r){return ro||(ro=class extends x.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new ro(c,r)}var xs=class extends x.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if(x.SettingPage){super.display();return}let{containerEl:t}=this;t.empty();for(let e of Ns){new x.Setting(t).setName(e.label).setHeading();let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new x.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 Ns.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>oA(t.label,i=>this.renderTabContent(i,t.id))}})}itemsForTab(t){switch(t){case"hotkeys":return this.hotkeyItems();case"diagnostics":return this.diagnosticsItems();case"notifications":return this.notificationsItems();case"foldersStorage":return this.buildGeneralCategories().foldersStorage;case"importExport":return this.buildGeneralCategories().importExport;case"noteTitles":return this.buildGeneralCategories().noteTitles;case"datesTime":return this.buildGeneralCategories().datesTime;case"listDisplay":return this.buildGeneralCategories().listDisplay;case"movingNotes":return this.buildGeneralCategories().movingNotes;case"deleting":return this.buildGeneralCategories().deleting;case"composerCopy":return this.buildGeneralCategories().composerCopy;case"windowsTabs":return this.buildGeneralCategories().windowsTabs;case"maintenance":return this.buildGeneralCategories().maintenance;case"misc":return this.buildGeneralCategories().misc;case"encryption":return this.encryptionItems();case"authorship":return this.authorshipItems();case"templates":return this.templatesItems();case"jdindex":return this.jdIndexItems();case"okf":return this.okfItems();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(){return[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.",t=>t.addToggle(e=>e.setValue(this.plugin.settings.enablePerfProfiling).onChange(async i=>{this.plugin.settings.enablePerfProfiling=i,await this.plugin.saveSettings()})),["perf","profiling","timing","slow"]),this.renderDef("Debug trace","Record low-level diagnostic lines (e.g. tap coordinates vs the row they resolve to) to an in-memory buffer while you reproduce a bug, then copy them below to share. Local only \u2014 no network, no file writes; zero overhead when off.",t=>t.addToggle(e=>e.setValue(this.plugin.settings.debugTrace).onChange(async i=>{this.plugin.settings.debugTrace=i,await this.plugin.saveSettings()})),["debug","trace","diagnostics","tap","log"]),this.renderDef("Copy / clear debug trace","Copy the captured debug lines to the clipboard (paste them back to share), or clear the buffer to start a fresh capture.",t=>{t.addButton(e=>e.setButtonText("Copy").onClick(async()=>{let i=this.plugin.getDebugTrace();if(!i){new x.Notice("Debug trace is empty \u2014 enable it and reproduce the issue first.");return}try{await navigator.clipboard.writeText(i),new x.Notice("Debug trace copied.")}catch{new x.Notice("Couldn't access clipboard.")}})),t.addButton(e=>e.setButtonText("Clear").onClick(()=>{this.plugin.clearDebugTrace(),new x.Notice("Debug trace cleared.")}))},["debug","trace","copy","clear"]),this.renderDef("Open log file","Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.",t=>t.addButton(e=>e.setButtonText("Open log").onClick(async()=>{let i=this.app.vault.adapter,s=this.plugin.pluginPrivatePath("log.jsonl");if(!await i.exists(s)){new x.Notice("No log yet \u2014 make some changes first.");return}let n=await i.read(s);new Je(this.app,n,s).open()})),["log","history","diagnostics"])]}notificationsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(vn);return[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=vn[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async a=>{let l=!a;l?t.add(i):t.delete(i),this.plugin.settings.mutedNotificationCategories=Array.from(t),this.plugin.notifications.setMuted(i,l),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 Qi(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 x.Notice("No log yet \u2014 make some changes first.");return}let l=await o.read(a);new Je(this.app,l,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)}}}buildGeneralCategories(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,l)=>this.renderDef(s,n,A=>A.addToggle(d=>d.setValue(o()).onChange(async h=>{a(h),await t()})),l),i={foldersStorage:[],importExport:[],datesTime:[],noteTitles:[],listDisplay:[],movingNotes:[],deleting:[],composerCopy:[],windowsTabs:[],maintenance:[],misc:[]};i.foldersStorage.push(this.renderDef("Stashpad notes folder","Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.",s=>{s.addText(n=>{new $e(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||me.folder,l=a.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(d=>(d??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(l)){new x.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.importExport.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.foldersStorage.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.importExport.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.importExport.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,"")||me.exportFolder,await t()})),["export","stash","subfolder"])),i.maintenance.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, rename any note whose filename slug no longer matches its body's first line, AND migrate legacy attachment filenames to the new name-first format (`photo-<id>.png`). 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:l,slugsRenamed:A,authors:d,imported:h,attachmentsLinked:g,attachmentsRenamed:I,attachmentsSkipped:p}=await this.plugin.rebootstrapAllFolders(),u=[];u.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),h>0&&u.push(`imported ${h} loose file${h===1?"":"s"}`),g>0&&u.push(`linked attachments on ${g} note${g===1?"":"s"}`),I>0&&u.push(`renamed ${I} attachment${I===1?"":"s"}`),l>0?u.push(`updated frontmatter on ${l} of ${a} notes`):a>0&&u.push(`frontmatter already in sync (${a} notes checked)`),A>0&&u.push(`renamed ${A} note${A===1?"":"s"} to match body`),d>0&&u.push(`rebuilt author registry (${d} author${d===1?"":"s"})`),new x.Notice(`Stashpad: ${u.join("; ")}.`),p>0&&new x.Notice(`Stashpad: ${p} attachment${p===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(o){new x.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.maintenance.push(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.",s=>s.addToggle(n=>n.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async o=>{this.plugin.settings.writeRecoveryLinks=o,await t()})),["recovery","parentlink","children","frontmatter"])),i.datesTime.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=Ms(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: ${jt(Date.now(),this.plugin.settings)}`)};i.datesTime.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 l=>{this.plugin.settings.dateDisplayFormat=l,await t(),n()})})},["date","format","display"])),i.datesTime.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 l=>{this.plugin.settings.dateDisplayTimezone=(l||"").trim(),await t(),n()})})},["timezone","tz","date","iana"])),i.datesTime.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.movingNotes.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.movingNotes.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.listDisplay.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.misc.push(e("Sheet versions (alternate drafts)",`Treat notes that share a 'sheet-group' frontmatter id as alternate versions of one item: only the active version shows as a row, and its siblings collapse into a tab bar at the bottom of that row. Use "Fork as version" on a note to start. Off by default \u2014 when off, no note is ever hidden by this feature and the commands do nothing.`,()=>this.plugin.settings.enableSheetVersions,s=>{this.plugin.settings.enableSheetVersions=s},["sheet","version","draft","alternate","fork"])),i.listDisplay.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.listDisplay.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.listDisplay.push(e("Expand note bodies by default","Show every note's full body by default instead of clamping long notes. The per-note 'Show more / show less' toggle and the Expand-all / Collapse-all commands then work in reverse \u2014 they let you collapse individual notes back down. Off = bodies clamp by default (expand is opt-in).",()=>this.plugin.settings.expandBodiesByDefault,s=>{this.plugin.settings.expandBodiesByDefault=s},["expand","collapse","default","body","clamp"])),i.movingNotes.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.deleting.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.deleting.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.noteTitles.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:Yt).join(` +`}function rs(c,r){let t=document.createDocumentFragment();t.createEl("div",{text:"Home note updated"}).setCssStyles({fontWeight:"600",marginBottom:"6px"});let i=t.createEl("ul");i.setCssStyles({margin:"0 0 8px 0",paddingLeft:"18px"}),i.createEl("li",{text:`${r.indexed.length} indexed`}),i.createEl("li",{text:`${r.nonIndex.length+r.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.setCssStyles({padding:"2px 10px",fontSize:"var(--font-ui-smaller)"});let n;return s.onclick=async o=>{if(o.stopPropagation(),r.previewPath){let a=c.vault.getAbstractFileByPath(r.previewPath);a instanceof gt.TFile&&await c.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new gt.Notice(t,0),n}var gt,jo,Fi,ki=Lt(()=>{"use strict";gt=require("obsidian");Ht();Ye();lt();jo=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Fi=class extends gt.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 l=new gt.Setting(t);(i||s)&&l.addButton(A=>{A.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),A.setCta(),A.onClick(async()=>{try{let d=await as(this.app,this.plugin,this.settings);if(d.error==="no-dest"){new gt.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(d.error==="no-home"){new gt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=d.previewPath,rs(this.app,d),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(d){new gt.Notice(`Preview failed: ${d?.message??d}`,8e3)}})}),l.addButton(A=>{A.setButtonText(i?"Build anyway":"Build"),!i&&!s&&A.setCta(),A.onClick(async()=>{this.close(),await this.onBuild()})}),l.addButton(A=>{A.setButtonText("Cancel"),A.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});function Yl(c,r){return Ol(c,r||{},0,0)}function $l(c,r){return Rl(c,{i:2},r&&r.out,r&&r.dictionary)}function Us(c,r){if(r){for(var t=new At(c.length),e=0;e<c.length;++e)t[e]=c.charCodeAt(e);return t}if(qa)return qa.encode(c);for(var i=c.length,s=new At(c.length+(c.length>>1)),n=0,o=function(A){s[n++]=A},e=0;e<i;++e){if(n+5>s.length){var a=new At(n+8+(i-e<<1));a.set(s),s=a}var l=c.charCodeAt(e);l<128||r?o(l):l<2048?(o(192|l>>6),o(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|c.charCodeAt(++e)&1023,o(240|l>>18),o(128|l>>12&63),o(128|l>>6&63),o(128|l&63)):(o(224|l>>12),o(128|l>>6&63),o(128|l&63))}return Ji(s,0,n)}function ho(c,r){if(r){for(var t="",e=0;e<c.length;e+=16384)t+=String.fromCharCode.apply(null,c.subarray(e,e+16384));return t}else{if(ro)return ro.decode(c);var i=Vl(c),s=i.s,t=i.r;return t.length&&Ct(8),s}}function Za(c,r){r||(r={});var t={},e=[];Xa(c,"",t,r);var i=0,s=0;for(var n in t){var o=t[n],a=o[0],l=o[1],A=l.level==0?0:8,d=Us(n),h=d.length,g=l.comment,I=g&&Us(g),p=I&&I.length,u=lo(l.extra);h>65535&&Ct(11);var f=A?Yl(a,l):a,C=f.length,m=Kl();m.p(a),e.push(Wa(l,{size:a.length,crc:m.d(),c:f,f:d,m:I,u:h!=n.length||I&&g.length!=p,o:i,compression:A})),i+=30+h+u+C,s+=76+2*(h+u)+(p||0)+C}for(var B=new At(s+22),y=i,Q=s-i,E=0;E<e.length;++E){var d=e[E];Ja(B,d.o,d,d.f,d.u,d.c.length);var v=30+d.f.length+lo(d.extra);B.set(d.c,d.o+v),Ja(B,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+v+(d.m?d.m.length:0)}return jl(B,i,e.length,Q,y),B}function ja(c,r){for(var t={},e=c.length-22;bt(c,e)!=101010256;--e)(!e||c.length-e>65558)&&Ct(13);var i=zt(c,e+8);if(!i)return{};var s=bt(c,e+16),n=bt(c,e-20)==117853008;if(n){var o=bt(c,e-12);n=bt(c,o)==101075792,n&&(i=bt(c,o+32),s=bt(c,o+48))}for(var a=r&&r.filter,l=0;l<i;++l){var A=Xl(c,s,n),d=A[0],h=A[1],g=A[2],I=A[3],p=A[4],u=A[5],f=Wl(c,u);s=p,(!a||a({name:I,size:h,originalSize:g,compression:d}))&&(d?d==8?t[I]=$l(c.subarray(f,f+h),{out:new At(g)}):Ct(14,"unknown compression type "+d):t[I]=Ji(c,f,f+h))}return t}var At,kt,Ao,Gs,Rs,so,Ka,Oa,Ya,no,$a,Ml,Ga,oo,oe,j,Vt,fe,j,j,j,j,qi,j,Tl,Hl,Pl,Ul,_n,Rt,to,co,Ji,Gl,Ct,Rl,ae,Ri,eo,ao,Ra,Li,za,La,Ll,Va,ql,Jl,Kl,Ol,Wa,zt,bt,io,It,Xa,qa,ro,zl,Vl,Wl,Xl,Zl,lo,Ja,jl,_a=Lt(()=>{At=Uint8Array,kt=Uint16Array,Ao=Int32Array,Gs=new At([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,0,0,0]),Rs=new At([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,0,0]),so=new At([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Ka=function(c,r){for(var t=new kt(31),e=0;e<31;++e)t[e]=r+=1<<c[e-1];for(var i=new Ao(t[30]),e=1;e<30;++e)for(var s=t[e];s<t[e+1];++s)i[s]=s-t[e]<<5|e;return{b:t,r:i}},Oa=Ka(Gs,2),Ya=Oa.b,no=Oa.r;Ya[28]=258,no[258]=28;$a=Ka(Rs,0),Ml=$a.b,Ga=$a.r,oo=new kt(32768);for(j=0;j<32768;++j)oe=(j&43690)>>1|(j&21845)<<1,oe=(oe&52428)>>2|(oe&13107)<<2,oe=(oe&61680)>>4|(oe&3855)<<4,oo[j]=((oe&65280)>>8|(oe&255)<<8)>>1;Vt=function(c,r,t){for(var e=c.length,i=0,s=new kt(r);i<e;++i)c[i]&&++s[c[i]-1];var n=new kt(r);for(i=1;i<r;++i)n[i]=n[i-1]+s[i-1]<<1;var o;if(t){o=new kt(1<<r);var a=15-r;for(i=0;i<e;++i)if(c[i])for(var l=i<<4|c[i],A=r-c[i],d=n[c[i]-1]++<<A,h=d|(1<<A)-1;d<=h;++d)o[oo[d]>>a]=l}else for(o=new kt(e),i=0;i<e;++i)c[i]&&(o[i]=oo[n[c[i]-1]++]>>15-c[i]);return o},fe=new At(288);for(j=0;j<144;++j)fe[j]=8;for(j=144;j<256;++j)fe[j]=9;for(j=256;j<280;++j)fe[j]=7;for(j=280;j<288;++j)fe[j]=8;qi=new At(32);for(j=0;j<32;++j)qi[j]=5;Tl=Vt(fe,9,0),Hl=Vt(fe,9,1),Pl=Vt(qi,5,0),Ul=Vt(qi,5,1),_n=function(c){for(var r=c[0],t=1;t<c.length;++t)c[t]>r&&(r=c[t]);return r},Rt=function(c,r,t){var e=r/8|0;return(c[e]|c[e+1]<<8)>>(r&7)&t},to=function(c,r){var t=r/8|0;return(c[t]|c[t+1]<<8|c[t+2]<<16)>>(r&7)},co=function(c){return(c+7)/8|0},Ji=function(c,r,t){return(r==null||r<0)&&(r=0),(t==null||t>c.length)&&(t=c.length),new At(c.subarray(r,t))},Gl=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],Ct=function(c,r,t){var e=new Error(r||Gl[c]);if(e.code=c,Error.captureStackTrace&&Error.captureStackTrace(e,Ct),!t)throw e;return e},Rl=function(c,r,t,e){var i=c.length,s=e?e.length:0;if(!i||r.f&&!r.l)return t||new At(0);var n=!t,o=n||r.i!=2,a=r.i;n&&(t=new At(i*3));var l=function(dt){var St=t.length;if(dt>St){var st=new At(Math.max(St*2,dt));st.set(t),t=st}},A=r.f||0,d=r.p||0,h=r.b||0,g=r.l,I=r.d,p=r.m,u=r.n,f=i*8;do{if(!g){A=Rt(c,d,1);var C=Rt(c,d+1,3);if(d+=3,C)if(C==1)g=Hl,I=Ul,p=9,u=5;else if(C==2){var Q=Rt(c,d,31)+257,E=Rt(c,d+10,15)+4,v=Q+Rt(c,d+5,31)+1;d+=14;for(var w=new At(v),D=new At(19),N=0;N<E;++N)D[so[N]]=Rt(c,d+N*3,7);d+=E*3;for(var P=_n(D),H=(1<<P)-1,b=Vt(D,P,1),N=0;N<v;){var S=b[Rt(c,d,H)];d+=S&15;var m=S>>4;if(m<16)w[N++]=m;else{var T=0,U=0;for(m==16?(U=3+Rt(c,d,3),d+=2,T=w[N-1]):m==17?(U=3+Rt(c,d,7),d+=3):m==18&&(U=11+Rt(c,d,127),d+=7);U--;)w[N++]=T}}var L=w.subarray(0,Q),W=w.subarray(Q);p=_n(L),u=_n(W),g=Vt(L,p,1),I=Vt(W,u,1)}else Ct(1);else{var m=co(d)+4,B=c[m-4]|c[m-3]<<8,y=m+B;if(y>i){a&&Ct(0);break}o&&l(h+B),t.set(c.subarray(m,y),h),r.b=h+=B,r.p=d=y*8,r.f=A;continue}if(d>f){a&&Ct(0);break}}o&&l(h+131072);for(var $=(1<<p)-1,z=(1<<u)-1,R=d;;R=d){var T=g[to(c,d)&$],V=T>>4;if(d+=T&15,d>f){a&&Ct(0);break}if(T||Ct(2),V<256)t[h++]=V;else if(V==256){R=d,g=null;break}else{var K=V-254;if(V>264){var N=V-257,O=Gs[N];K=Rt(c,d,(1<<O)-1)+Ya[N],d+=O}var it=I[to(c,d)&z],rt=it>>4;it||Ct(3),d+=it&15;var W=Ml[rt];if(rt>3){var O=Rs[rt];W+=to(c,d)&(1<<O)-1,d+=O}if(d>f){a&&Ct(0);break}o&&l(h+131072);var _=h+K;if(h<W){var X=s-W,mt=Math.min(W,_);for(X+h<0&&Ct(3);h<mt;++h)t[h]=e[X+h]}for(;h<_;++h)t[h]=t[h-W]}}r.l=g,r.p=R,r.b=h,r.f=A,g&&(A=1,r.m=p,r.d=I,r.n=u)}while(!A);return h!=t.length&&n?Ji(t,0,h):t.subarray(0,h)},ae=function(c,r,t){t<<=r&7;var e=r/8|0;c[e]|=t,c[e+1]|=t>>8},Ri=function(c,r,t){t<<=r&7;var e=r/8|0;c[e]|=t,c[e+1]|=t>>8,c[e+2]|=t>>16},eo=function(c,r){for(var t=[],e=0;e<c.length;++e)c[e]&&t.push({s:e,f:c[e]});var i=t.length,s=t.slice();if(!i)return{t:Va,l:0};if(i==1){var n=new At(t[0].s+1);return n[t[0].s]=1,{t:n,l:1}}t.sort(function(y,Q){return y.f-Q.f}),t.push({s:-1,f:25001});var o=t[0],a=t[1],l=0,A=1,d=2;for(t[0]={s:-1,f:o.f+a.f,l:o,r:a};A!=i-1;)o=t[t[l].f<t[d].f?l++:d++],a=t[l!=A&&t[l].f<t[d].f?l++:d++],t[A++]={s:-1,f:o.f+a.f,l:o,r:a};for(var h=s[0].s,e=1;e<i;++e)s[e].s>h&&(h=s[e].s);var g=new kt(h+1),I=ao(t[A-1],g,0);if(I>r){var e=0,p=0,u=I-r,f=1<<u;for(s.sort(function(Q,E){return g[E.s]-g[Q.s]||Q.f-E.f});e<i;++e){var C=s[e].s;if(g[C]>r)p+=f-(1<<I-g[C]),g[C]=r;else break}for(p>>=u;p>0;){var m=s[e].s;g[m]<r?p-=1<<r-g[m]++-1:++e}for(;e>=0&&p;--e){var B=s[e].s;g[B]==r&&(--g[B],++p)}I=r}return{t:new At(g),l:I}},ao=function(c,r,t){return c.s==-1?Math.max(ao(c.l,r,t+1),ao(c.r,r,t+1)):r[c.s]=t},Ra=function(c){for(var r=c.length;r&&!c[--r];);for(var t=new kt(++r),e=0,i=c[0],s=1,n=function(a){t[e++]=a},o=1;o<=r;++o)if(c[o]==i&&o!=r)++s;else{if(!i&&s>2){for(;s>138;s-=138)n(32754);s>2&&(n(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(n(i),--s;s>6;s-=6)n(8304);s>2&&(n(s-3<<5|8208),s=0)}for(;s--;)n(i);s=1,i=c[o]}return{c:t.subarray(0,e),n:r}},Li=function(c,r){for(var t=0,e=0;e<r.length;++e)t+=c[e]*r[e];return t},za=function(c,r,t){var e=t.length,i=co(r+2);c[i]=e&255,c[i+1]=e>>8,c[i+2]=c[i]^255,c[i+3]=c[i+1]^255;for(var s=0;s<e;++s)c[i+s+4]=t[s];return(i+4+e)*8},La=function(c,r,t,e,i,s,n,o,a,l,A){ae(r,A++,t),++i[256];for(var d=eo(i,15),h=d.t,g=d.l,I=eo(s,15),p=I.t,u=I.l,f=Ra(h),C=f.c,m=f.n,B=Ra(p),y=B.c,Q=B.n,E=new kt(19),v=0;v<C.length;++v)++E[C[v]&31];for(var v=0;v<y.length;++v)++E[y[v]&31];for(var w=eo(E,7),D=w.t,N=w.l,P=19;P>4&&!D[so[P-1]];--P);var H=l+5<<3,b=Li(i,fe)+Li(s,qi)+n,S=Li(i,h)+Li(s,p)+n+14+3*P+Li(E,D)+2*E[16]+3*E[17]+7*E[18];if(a>=0&&H<=b&&H<=S)return za(r,A,c.subarray(a,a+l));var T,U,L,W;if(ae(r,A,1+(S<b)),A+=2,S<b){T=Vt(h,g,0),U=h,L=Vt(p,u,0),W=p;var $=Vt(D,N,0);ae(r,A,m-257),ae(r,A+5,Q-1),ae(r,A+10,P-4),A+=14;for(var v=0;v<P;++v)ae(r,A+3*v,D[so[v]]);A+=3*P;for(var z=[C,y],R=0;R<2;++R)for(var V=z[R],v=0;v<V.length;++v){var K=V[v]&31;ae(r,A,$[K]),A+=D[K],K>15&&(ae(r,A,V[v]>>5&127),A+=V[v]>>12)}}else T=Tl,U=fe,L=Pl,W=qi;for(var v=0;v<o;++v){var O=e[v];if(O>255){var K=O>>18&31;Ri(r,A,T[K+257]),A+=U[K+257],K>7&&(ae(r,A,O>>23&31),A+=Gs[K]);var it=O&31;Ri(r,A,L[it]),A+=W[it],it>3&&(Ri(r,A,O>>5&8191),A+=Rs[it])}else Ri(r,A,T[O]),A+=U[O]}return Ri(r,A,T[256]),A+U[256]},Ll=new Ao([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Va=new At(0),ql=function(c,r,t,e,i,s){var n=s.z||c.length,o=new At(e+n+5*(1+Math.ceil(n/7e3))+i),a=o.subarray(e,o.length-i),l=s.l,A=(s.r||0)&7;if(r){A&&(a[0]=s.r>>3);for(var d=Ll[r-1],h=d>>13,g=d&8191,I=(1<<t)-1,p=s.p||new kt(32768),u=s.h||new kt(I+1),f=Math.ceil(t/3),C=2*f,m=function(Bt){return(c[Bt]^c[Bt+1]<<f^c[Bt+2]<<C)&I},B=new Ao(25e3),y=new kt(288),Q=new kt(32),E=0,v=0,w=s.i||0,D=0,N=s.w||0,P=0;w+2<n;++w){var H=m(w),b=w&32767,S=u[H];if(p[b]=S,u[H]=b,N<=w){var T=n-w;if((E>7e3||D>24576)&&(T>423||!l)){A=La(c,a,0,B,y,Q,v,D,P,w-P,A),D=E=v=0,P=w;for(var U=0;U<286;++U)y[U]=0;for(var U=0;U<30;++U)Q[U]=0}var L=2,W=0,$=g,z=b-S&32767;if(T>2&&H==m(w-z))for(var R=Math.min(h,T)-1,V=Math.min(32767,w),K=Math.min(258,T);z<=V&&--$&&b!=S;){if(c[w+L]==c[w+L-z]){for(var O=0;O<K&&c[w+O]==c[w+O-z];++O);if(O>L){if(L=O,W=z,O>R)break;for(var it=Math.min(z,O-2),rt=0,U=0;U<it;++U){var _=w-z+U&32767,X=p[_],mt=_-X&32767;mt>rt&&(rt=mt,S=_)}}}b=S,S=p[b],z+=b-S&32767}if(W){B[D++]=268435456|no[L]<<18|Ga[W];var dt=no[L]&31,St=Ga[W]&31;v+=Gs[dt]+Rs[St],++y[257+dt],++Q[St],N=w+L,++E}else B[D++]=c[w],++y[c[w]]}}for(w=Math.max(w,N);w<n;++w)B[D++]=c[w],++y[c[w]];A=La(c,a,l,B,y,Q,v,D,P,w-P,A),l||(s.r=A&7|a[A/8|0]<<3,A-=7,s.h=u,s.p=p,s.i=w,s.w=N)}else{for(var w=s.w||0;w<n+l;w+=65535){var st=w+65535;st>=n&&(a[A/8|0]=l,st=n),A=za(a,A+1,c.subarray(w,st))}s.i=n}return Ji(o,0,e+co(A)+i)},Jl=function(){for(var c=new Int32Array(256),r=0;r<256;++r){for(var t=r,e=9;--e;)t=(t&1&&-306674912)^t>>>1;c[r]=t}return c}(),Kl=function(){var c=-1;return{p:function(r){for(var t=c,e=0;e<r.length;++e)t=Jl[t&255^r[e]]^t>>>8;c=t},d:function(){return~c}}},Ol=function(c,r,t,e,i){if(!i&&(i={l:1},r.dictionary)){var s=r.dictionary.subarray(-32768),n=new At(s.length+c.length);n.set(s),n.set(c,s.length),c=n,i.w=s.length}return ql(c,r.level==null?6:r.level,r.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(c.length)))*1.5):20:12+r.mem,t,e,i)},Wa=function(c,r){var t={};for(var e in c)t[e]=c[e];for(var e in r)t[e]=r[e];return t},zt=function(c,r){return c[r]|c[r+1]<<8},bt=function(c,r){return(c[r]|c[r+1]<<8|c[r+2]<<16|c[r+3]<<24)>>>0},io=function(c,r){return bt(c,r)+bt(c,r+4)*4294967296},It=function(c,r,t){for(;t;++r)c[r]=t,t>>>=8};Xa=function(c,r,t,e){for(var i in c){var s=c[i],n=r+i,o=e;Array.isArray(s)&&(o=Wa(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[n]=[s,o]:(t[n+="/"]=[new At(0),o],Xa(s,n,t,e))}},qa=typeof TextEncoder<"u"&&new TextEncoder,ro=typeof TextDecoder<"u"&&new TextDecoder,zl=0;try{ro.decode(Va,{stream:!0}),zl=1}catch{}Vl=function(c){for(var r="",t=0;;){var e=c[t++],i=(e>127)+(e>223)+(e>239);if(t+i>c.length)return{s:r,r:Ji(c,t-1)};i?i==3?(e=((e&15)<<18|(c[t++]&63)<<12|(c[t++]&63)<<6|c[t++]&63)-65536,r+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?r+=String.fromCharCode((e&31)<<6|c[t++]&63):r+=String.fromCharCode((e&15)<<12|(c[t++]&63)<<6|c[t++]&63):r+=String.fromCharCode(e)}};Wl=function(c,r){return r+30+zt(c,r+26)+zt(c,r+28)},Xl=function(c,r,t){var e=zt(c,r+28),i=zt(c,r+30),s=ho(c.subarray(r+46,r+46+e),!(zt(c,r+8)&2048)),n=r+46+e,o=Zl(c,n,i,t,bt(c,r+20),bt(c,r+24),bt(c,r+42)),a=o[0],l=o[1],A=o[2];return[zt(c,r+10),a,l,s,n+i+zt(c,r+32),A]},Zl=function(c,r,t,e,i,s,n){var o=i==4294967295,a=s==4294967295,l=n==4294967295,A=r+t,d=o+a+l;if(e&&d){for(;r+4<A;r+=4+zt(c,r+2))if(zt(c,r)==1)return[o?io(c,r+4+8*a):i,a?io(c,r+4):s,l?io(c,r+4+8*(a+o)):n,1];e<2&&Ct(13)}return[i,s,n,0]},lo=function(c){var r=0;if(c)for(var t in c){var e=c[t].length;e>65535&&Ct(9),r+=e+4}return r},Ja=function(c,r,t,e,i,s,n,o){var a=e.length,l=t.extra,A=o&&o.length,d=lo(l);It(c,r,n!=null?33639248:67324752),r+=4,n!=null&&(c[r++]=20,c[r++]=t.os),c[r]=20,r+=2,c[r++]=t.flag<<1|(s<0&&8),c[r++]=i&&8,c[r++]=t.compression&255,c[r++]=t.compression>>8;var h=new Date(t.mtime==null?Date.now():t.mtime),g=h.getFullYear()-1980;if((g<0||g>119)&&Ct(10),It(c,r,g<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),r+=4,s!=-1&&(It(c,r,t.crc),It(c,r+4,s<0?-s-2:s),It(c,r+8,t.size)),It(c,r+12,a),It(c,r+14,d),r+=16,n!=null&&(It(c,r,A),It(c,r+6,t.attrs),It(c,r+10,n),r+=14),c.set(e,r),r+=a,d)for(var I in l){var p=l[I],u=p.length;It(c,r,+I),It(c,r+2,u),c.set(p,r+4),r+=4+u}return A&&(c.set(o,r),r+=A),r},jl=function(c,r,t,e,i){It(c,r,101010256),It(c,r+8,t),It(c,r+10,t),It(c,r+12,e),It(c,r+16,i)}});var tr={};ri(tr,{bytesToStr:()=>Ls,unzipFiles:()=>Oi,zipFiles:()=>Ki});function _l(c){return typeof c=="string"?Us(c):c instanceof Uint8Array?c:new Uint8Array(c)}function Ki(c,r=6){let t={};for(let e of c)t[e.name]=[_l(e.data),{level:r}];return Promise.resolve(Za(t,{level:r}))}function Ls(c){return ho(c)}function Oi(c){let r=c instanceof Uint8Array?c:new Uint8Array(c);return Promise.resolve(ja(r))}var qs=Lt(()=>{"use strict";_a()});var FA={};ri(FA,{default:()=>An});module.exports=Mr(FA);var M=require("obsidian");var Pe="sheet-group",qt="sheet-order",ye="sheet-final",So="sheet-label",Ue="sheet-origin",Ge="forked-from",Jt="fork-siblings",Wi=[Pe,qt,ye,So,Ue,Ge,Jt];function Kt(c){if(!c)return null;let r=c[Pe];return typeof r=="string"&&r.trim()?r:null}function hn(c){let r=c?.[qt];return typeof r=="number"?r:null}function li(c){return Kt(c)!==null&&hn(c)!==null}function Ai(c){return c?.[ye]===!0}function Do(c){return c?.[Ue]===!0}function Tr(c){let r=c?.[Ge];return typeof r=="string"&&r.trim()?r:null}function Xi(c){return typeof c!="string"?null:c.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].split("#")[0].trim()||null}function bo(c){return Xi(Tr(c))}function Hr(c){let r=c?.[So];return typeof r=="string"&&r.trim()?r:null}function No(){let c=Date.now().toString(36),r=Math.floor(Math.random()*1e6).toString(36);return`s-${c}-${r}`}function ut(c,r){return r.file?c.metadataCache.getFileCache(r.file)?.frontmatter:null}function pn(c,r){return r.slice().sort((t,e)=>{let i=hn(ut(c,t)),s=hn(ut(c,e));if(i!=null&&s!=null&&i!==s)return i-s;if(i!=null&&s==null)return-1;if(i==null&&s!=null)return 1;let n=t.created??"",o=e.created??"";return n!==o?n<o?-1:1:t.id<e.id?-1:t.id>e.id?1:0})}function xo(c,r){if(r.length===0)return null;let t=pn(c,r);return t.find(e=>Ai(ut(c,e)))??t[0]}function Mo(c,r,t){let e=Hr(ut(c,r));return e||t}lt();var Et=require("obsidian");var at=require("obsidian");lt();function ji(c){let r=(c.dateDisplayTimezone||"").trim();return r?{timeZone:r}:{}}function jt(c,r){try{return new Intl.DateTimeFormat(void 0,r).format(new Date(c))}catch{let{timeZone:t,...e}=r;return new Intl.DateTimeFormat(void 0,e).format(new Date(c))}}function _t(c,r){let t=ji(r);switch(r.dateDisplayFormat??"locale"){case"iso":return Ro(c,r,!0);case"us":return jt(c,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return jt(c,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return jt(c,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return jt(c,{...t,dateStyle:"medium",timeStyle:"short"})}}function Uo(c,r){let t=ji(r);switch(r.dateDisplayFormat??"locale"){case"iso":return Ro(c,r,!1);case"us":return jt(c,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return jt(c,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return jt(c,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(c).getFullYear()===e.getFullYear();return jt(c,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Go(c,r){let t=ji(r),e=r.dateDisplayFormat==="iso"||r.dateDisplayFormat==="eu";return jt(c,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Ro(c,r,t){let e=ji(r),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(c)),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(c,r,t){let e=c.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(r>99?"99+":String(r))}var vi={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},ss=class extends at.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 Ae}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()===J&&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,at.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,at.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,at.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,at.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 l=t.createDiv({cls:"stashpad-panels-bar"});for(let d of Object.keys(vi)){let h=vi[d],g=l.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,at.setIcon)(g.createSpan({cls:"stashpad-panels-bar-btn-icon"}),h.icon),g.createSpan({cls:"stashpad-panels-bar-btn-text",text:h.label}),this.activePanel===d&&g.addClass("is-active"),g.onclick=()=>{this.activePanel!==d&&(this.activePanel=d,this.render())}}let A=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(A):this.activePanel==="shared"?this.renderSharedPanel(A):this.activePanel==="tasks"&&this.renderTasksPanel(A)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new at.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,at.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,at.setIcon)(o,"list"),o.setAttr("aria-label","Pinned view options"),o.onclick=g=>{g.stopPropagation(),this.openPinnedOptionsMenu(g)};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((g,I)=>this.renderPinnedRow(e,g,I));return}let A=new Map;a.forEach((g,I)=>{let p=A.get(g.folder);p||(p=[],A.set(g.folder,p)),p.push({pin:g,idx:I})});let d=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,h=Array.from(A.keys());d&&A.has(d)&&(h.splice(h.indexOf(d),1),h.unshift(d));for(let g of h){let I=g.split("/").pop()||g,p=e.createDiv({cls:"stashpad-pinned-group-header"});g===d&&p.addClass("is-active-folder"),p.createSpan({cls:"stashpad-pinned-group-name",text:I});let u=A.get(g)??[];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,l=n.completed===!0,A=this.childrenOf(e.folder,e.id).length,d=A>0,h=this.expanded.has(`${e.folder}|${e.id}`),g=t.createDiv({cls:"stashpad-pinned-row"});a&&g.addClass("has-color"),l&&g.addClass("is-completed"),g.draggable=!0,g.dataset.pinIdx=String(i),g.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),g.addClass("is-dragging")}),g.addEventListener("dragend",()=>g.removeClass("is-dragging")),g.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=g.getBoundingClientRect(),B=C.clientY-m.top<m.height/2;g.toggleClass("drop-before",B),g.toggleClass("drop-after",!B)}),g.addEventListener("dragleave",()=>{g.removeClass("drop-before"),g.removeClass("drop-after")}),g.addEventListener("drop",C=>{C.preventDefault(),g.removeClass("drop-before"),g.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let B=g.getBoundingClientRect(),y=C.clientY-B.top<B.height/2;this.reorderPin(m,y?i:i+1)});let I=g.createSpan({cls:"stashpad-pinned-toggle"});d&&(de(I,A,h),I.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 p=g.createSpan({cls:"stashpad-pinned-icon"});(0,at.setIcon)(p,d?"folder-tree":"file-text"),a&&(p.style.color=a);let u=g.createSpan({cls:"stashpad-pinned-label",text:o});u.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(g.createSpan({cls:"stashpad-pinned-folder",text:f}),g.oncontextmenu=C=>{C.preventDefault();let m=new at.Menu;m.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},d&&h){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((d,h)=>h!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],l=n[o],A;!a&&!l?A=Date.now():a?l?A=(a.pinnedAt+l.pinnedAt)/2:A=a.pinnedAt+1e3:A=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=A})}catch(d){console.warn("[Stashpad] pin reorder failed",d)}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??{},l=typeof a.id=="string"?a.id:null;if(!l)continue;let A=typeof a.color=="string"?a.color:null,d=a.completed===!0,h=this.childrenOf(e,l).length,g=h>0,I=this.expanded.has(`${e}|${l}`),p=t.createDiv({cls:"stashpad-pinned-subrow"});d&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let u=p.createSpan({cls:"stashpad-pinned-toggle"});g&&(de(u,h,I),u.onclick=m=>{m.stopPropagation();let B=`${e}|${l}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),this.render()});let f=p.createSpan({cls:"stashpad-pinned-icon"});(0,at.setIcon)(f,"file-text"),A&&(f.style.color=A);let C=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:l}),g&&I&&this.renderPinnedSubtree(t,e,l,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===F&&(a==null||a===F)){if(o.id===F)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,l=o?.created??"",A=a?.created??"";return l.localeCompare(A)}),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 at.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Ft(),wi));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(F)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===J)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(J);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()===J?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 d of s){let h=d.authorId;h&&!n.has(h)&&n.set(h,d.authorDisplay||h)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(d,h,g)=>{let I=o.createEl("button",{cls:"stashpad-shared-chip",text:d});return h&&I.addClass("is-active"),I.onclick=g,I};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 d=o.createEl("select",{cls:"stashpad-shared-author-select"}),h=d.createEl("option",{text:"Any author"});h.value="__any__";for(let[I,p]of n){let u=d.createEl("option",{text:p});u.value=I}let g=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;d.value=g,d.onchange=()=>{let I=d.value;I==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=I,this.render()}}let l=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&l.addClass("is-active"),l.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let A=s.filter(d=>{if(this.sharedContribOnly&&d.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return d.authorId===i;case"others":return d.authorId!==i;default:return d.authorId===this.sharedAuthorFilter}});if(A.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let d of A){let h=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),g=h.createSpan({cls:"stashpad-pinned-icon"});(0,at.setIcon)(g,"users"),d.color&&(g.style.color=d.color);let I=h.createSpan({cls:"stashpad-pinned-label",text:d.title});I.onclick=()=>this.openSharedFromPanel(d.folder,d.id);let p=d.folder.split("/").pop()||d.folder;h.createSpan({cls:"stashpad-pinned-folder",text:p}),d.authorDisplay&&h.createSpan({cls:"stashpad-shared-meta"}).setText(d.authorId===i?`you \xB7 ${d.contributorCount} contributor${d.contributorCount===1?"":"s"}`:`by ${d.authorDisplay}${d.contributorCount>0?` \xB7 ${d.contributorCount} contributor${d.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 l=this.app.metadataCache.getFileCache(o)?.frontmatter??{};l.id===F&&s.set(a,this.extractAuthorId(l.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 l=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof l.id!="string"||l.id===F)continue;let A=this.extractAuthorId(l.author),d=Array.isArray(l.contributors)?l.contributors.filter(m=>typeof m=="string"):[],h=s.get(a)??null;if(!(d.length>0||h===t&&(A!==null&&A!==t)))continue;let f=this.titleFromFile(o),C=typeof l.color=="string"?l.color:null;n.push({file:o,folder:a,id:l.id,title:f,color:C,authorId:A,authorDisplay:this.extractAuthorDisplay(l.author)||(A??""),contributorCount:d.length})}return n.sort((o,a)=>{let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},A=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},d=l.modified??l.created??"";return(A.modified??A.created??"").localeCompare(d)}),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.revealNoteByRef(t,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=S=>!!s&&S.assignedTo.some(T=>T.id===s),o=S=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let U=T.slice(7);return S.assignedTo.some(L=>L.id===U)}switch(T){case"mine":return n(S);case"others":return S.assignedTo.length>0&&!n(S);case"byme":return!!s&&S.assignedBy?.id===s;case"unassigned":return S.assignedTo.length===0;default:return!0}},a=new Map;for(let S of i){for(let T of S.assignedTo)T.id!==s&&a.set(T.id,T.name);S.assignedBy&&S.assignedBy.id!==s&&a.set(S.assignedBy.id,S.assignedBy.name)}let l=[...a.entries()].map(([S,T])=>({id:S,name:T})).sort((S,T)=>S.name.localeCompare(T.name)),A=e.createDiv({cls:"stashpad-task-assign-bar"});A.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let d=A.createEl("select",{cls:"stashpad-task-assign-select"}),h=S=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return S.startsWith("person:")?a.get(S.slice(7))??"Person":T[S]??S},g=S=>{let T=d.createEl("option",{text:h(S),value:S});this.taskAssignFilter===S&&(T.selected=!0)};for(let S of["all","mine","others","byme","unassigned"])g(S);if(l.length>0){let S=d.createEl("optgroup");S.setAttr("label","By person");for(let T of l){let U=S.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(U.selected=!0)}}d.onchange=()=>{this.taskAssignFilter=d.value,this.render()};let I=[...new Set(i.map(S=>S.folder))].sort((S,T)=>S.localeCompare(T));this.taskFolderFilter!=="all"&&!I.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let p=e.createDiv({cls:"stashpad-task-assign-bar"});p.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let u=p.createEl("select",{cls:"stashpad-task-assign-select"}),f=u.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let S of I){let T=u.createEl("option",{text:S.split("/").pop()||S,value:S});this.taskFolderFilter===S&&(T.selected=!0)}u.onchange=()=>{this.taskFolderFilter=u.value,this.render()};let C=S=>this.taskFolderFilter==="all"||S.folder===this.taskFolderFilter,m=i.filter(S=>o(S)&&C(S));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let B=new Date;B.setHours(0,0,0,0);let y=B.getTime(),Q=y+24*60*60*1e3,E={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let S of m){if(S.completed){E.completed.push(S);continue}if(S.due==null){E.nodate.push(S);continue}S.due<y?E.overdue.push(S):S.due<Q?E.today.push(S):E.upcoming.push(S)}let v=(S,T)=>S.due==null&&T.due==null?S.title.localeCompare(T.title):S.due==null?1:T.due==null?-1:S.due-T.due,w=[{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"}],D=e.createDiv({cls:"stashpad-task-filters"}),N=m.length,P=(S,T,U)=>{let L=D.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===S&&L.addClass("is-active"),L.createSpan({cls:"stashpad-task-filter-label",text:T}),L.createSpan({cls:"stashpad-task-filter-count",text:String(U)}),L.onclick=()=>{this.taskFilter=S,this.render()}};P("all","All",N),P("overdue","Overdue",E.overdue.length),P("today","Today",E.today.length),P("upcoming","Upcoming",E.upcoming.length),P("nodate","No date",E.nodate.length),P("completed","Done",E.completed.length);let H=this.taskFilter==="all"?w:w.filter(S=>S.key===this.taskFilter),b=!1;for(let S of H){let T=E[S.key];if(T.length!==0){if(b=!0,T.sort(S.key==="completed"?(U,L)=>v(L,U):v),this.taskFilter==="all"){let U=e.createDiv({cls:`stashpad-task-section-header is-${S.key}`});(0,at.setIcon)(U.createSpan({cls:"stashpad-task-section-icon"}),S.icon),U.createSpan({cls:"stashpad-task-section-name",text:S.label}),U.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let U of T)this.renderTaskRow(e,U,S.key==="today")}}if(!b&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${H[0]?.label??this.taskFilter}".`);return}b||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,at.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(),l=s.createSpan({cls:"stashpad-task-assignees"});for(let A of e.assignedTo){let d=l.createSpan({cls:"stashpad-task-assignee"});a&&A.id===a&&d.addClass("is-me"),d.setText(this.initials(A.name)),d.title=a&&A.id===a?`${A.name} (you)`:A.name}}s.oncontextmenu=a=>{a.preventDefault();let l=new at.Menu;l.addItem(A=>A.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),l.showAtMouseEvent(a)}}formatDueShort(t,e){return e?Go(t,this.plugin.settings):Uo(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new at.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===F)continue;let l=o.completed===!0,A=Le(o,"task")||o.task===!0||o.completed!==void 0,d=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,h=null;if(d){let g=Date.parse(d);Number.isNaN(g)||(h=g)}!A&&!l&&h==null&&!d||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:A,completed:l,due:h,dueRaw:d,color:typeof o.color=="string"?o.color:null,assignedTo:Fe(o),assignedBy:ce(o.assignedBy)})}return i}};async function ns(c){let r=c.workspace.getLeavesOfType(Ae);if(r.length>0){c.workspace.revealLeaf(r[0]);return}let t=c.workspace.getLeftLeaf(!1);if(!t){new at.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:Ae,active:!0}),c.workspace.revealLeaf(t)}var ka=require("obsidian");lt();var x=require("obsidian");ki();var As=require("obsidian");lt();var ze=class extends As.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!=="/"&&ci.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof As.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()}};lt();Ft();var xe=require("obsidian"),vn={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)."},reminder:{label:"Reminder",desc:"Task due-date reminders \u2014 surfaced when a task comes due (fired at launch / periodically)."},system:{label:"System",desc:"Plumbing toasts: backfill progress, integrity warnings, errors not tied to a verb."}},$r={info:4e3,success:4e3,warning:6e3,error:1e4},ia=5e3,cs=class{constructor(r){this.app=r;this.history=[];this.nextId=1;this.historyLimit=ia;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(r){this.defaultAuthorId=r||null}show(r){let t=r.kind??"info",e=r.category??"system",i={id:this.nextId++,ts:Date.now(),message:r.message,kind:t,category:e,authorId:r.authorId??this.defaultAuthorId??void 0,affectedIds:r.affectedIds?r.affectedIds.slice():[],affectedPaths:r.affectedPaths?r.affectedPaths.slice():[],affectedAuthorIds:r.affectedAuthorIds?r.affectedAuthorIds.slice():[],folder:r.folder,actionLabels:(r.actions??[]).map(o=>o.label)};if(this.pushHistory(i),this.muted.has(e))return null;let s=this.buildContent(r,t),n=r.duration??$r[t];return new xe.Notice(s,n)}onChange(r){return this.changeListeners.add(r),()=>this.changeListeners.delete(r)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(r,t){t?this.muted.add(r):this.muted.delete(r)}isMuted(r){return this.muted.has(r)}loadMutedFromList(r){this.muted=new Set(r)}mutedList(){return Array.from(this.muted)}loadHistory(r){let t=this.applyLimit(r.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(r){this.historyLimit=Number.isFinite(r)?r:ia,this.history=this.applyLimit(this.history),this.emit()}applyLimit(r){return this.historyLimit<=0||r.length<=this.historyLimit?r:r.slice(r.length-this.historyLimit)}pushHistory(r){this.history.push(r),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let r of this.changeListeners)try{r()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(r,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=r.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),r.actions&&r.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of r.actions){let l=document.createElement("button");l.className="stashpad-notice-action",l.textContent=a.label,l.addEventListener("click",A=>{if(A.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(d=>console.warn("[Stashpad] notification action failed",d)),!a.keepOpen){let d=l.closest(".notice");d&&d.parentElement&&d.parentElement.removeChild(d)}}),o.appendChild(l)}i.appendChild(o)}return e.appendChild(i),e}};function ds(c,r,t){let e=c.vault.getAbstractFileByPath(r);if(!(e instanceof xe.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=c.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;c.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=xe.Platform.isMacOS?"Finder":xe.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=c.vault.adapter?.getFullPath?.(r);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var sa=require("obsidian"),Fn=sa.Platform.isMacOS;function Si(c){if(!c)return"(none)";let r=c.replace(/\bMod\b/g,Fn?"Cmd":"Ctrl");return Fn&&(r=r.replace(/\bAlt\b/g,"Option")),r}function na(c,r,t={allowSingleKey:!0}){let e=c.placeholder,i=c.value;c.placeholder="Press a key\u2026 (Backspace to cancel)",c.value="",c.classList.add("is-recording");let s=!1,n=()=>{c.placeholder=e,c.classList.remove("is-recording"),s||(c.value=i),c.removeEventListener("keydown",o,!0),c.removeEventListener("blur",a)},o=l=>{if(l.key==="Control"||l.key==="Shift"||l.key==="Alt"||l.key==="Meta"||l.key==="OS")return;let A=!!l.code&&(/^Key[A-Z]$/.test(l.code)||/^Digit\d$/.test(l.code));if((l.key==="Dead"||l.key==="Process"||l.key==="Unidentified")&&!A)return;if(l.preventDefault(),l.stopPropagation(),l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.shiftKey){n();return}let d=[];Fn?(l.metaKey&&d.push("Mod"),l.ctrlKey&&d.push("Ctrl")):l.ctrlKey&&d.push("Mod"),l.altKey&&d.push("Alt"),l.shiftKey&&d.push("Shift");let h=zr(l.key,l.code);if(!h||d.length===0&&!t.allowSingleKey)return;d.push(h);let g=d.join("+");s=!0,n(),r(g)},a=()=>n();return c.addEventListener("keydown",o,!0),c.addEventListener("blur",a),n}function zr(c,r){if(!c)return"";if(r){let t=/^Key([A-Z])$/.exec(r);if(t)return t[1];let e=/^Digit(\d)$/.exec(r);if(e)return e[1]}return c.length===1?c.toUpperCase():c}Ye();Ht();function Me(c,r,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(A){try{l(e.next(A))}catch(d){n(d)}}function a(A){try{l(e.throw(A))}catch(d){n(d)}}function l(A){A.done?s(A.value):i(A.value).then(o,a)}l((e=e.apply(c,r||[])).next())})}var nt=class{constructor(){this.mutex=Promise.resolve()}lock(){let r=()=>{};return this.mutex=this.mutex.then(()=>new Promise(r)),new Promise(t=>{r=t})}dispatch(r){return Me(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(r())}finally{t()}})}},kn;function Vr(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Nn=Vr(),Sn=(kn=Nn.Buffer)!==null&&kn!==void 0?kn:null,Wr=Nn.TextEncoder?new Nn.TextEncoder:null;function ca(c,r){return(c&15)+(c>>6|c>>3&8)<<4|(r&15)+(r>>6|r>>3&8)}function da(c,r){let t=r.length>>1;for(let e=0;e<t;e++){let i=e<<1;c[e]=ca(r.charCodeAt(i),r.charCodeAt(i+1))}}function Xr(c,r){if(c.length!==r.length*2)return!1;for(let t=0;t<r.length;t++){let e=t<<1;if(r[t]!==ca(c.charCodeAt(e),c.charCodeAt(e+1)))return!1}return!0}var oa=87,aa=48;function xn(c,r,t){let e=0;for(let i=0;i<t;i++){let s=r[i]>>>4;c[e++]=s>9?s+oa:s+aa,s=r[i]&15,c[e++]=s>9?s+oa:s+aa}return String.fromCharCode.apply(null,c)}var ee=Sn!==null?c=>{if(typeof c=="string"){let r=Sn.from(c,"utf8");return new Uint8Array(r.buffer,r.byteOffset,r.length)}if(Sn.isBuffer(c))return new Uint8Array(c.buffer,c.byteOffset,c.length);if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer,c.byteOffset,c.byteLength);throw new Error("Invalid data type!")}:c=>{if(typeof c=="string")return Wr.encode(c);if(ArrayBuffer.isView(c))return new Uint8Array(c.buffer,c.byteOffset,c.byteLength);throw new Error("Invalid data type!")},Pt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",bi=new Uint8Array(256);for(let c=0;c<Pt.length;c++)bi[Pt.charCodeAt(c)]=c;function ra(c,r=!0){let t=c.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(c[n]<<16&16711680)+(c[n+1]<<8&65280)+(c[n+2]&255),a=Pt.charAt(o>>18&63)+Pt.charAt(o>>12&63)+Pt.charAt(o>>6&63)+Pt.charAt(o&63);i.push(a)}if(e===1){let n=c[t-1],o=Pt.charAt(n>>2),a=Pt.charAt(n<<4&63);i.push(`${o}${a}`),r&&i.push("==")}else if(e===2){let n=(c[t-2]<<8)+c[t-1],o=Pt.charAt(n>>10),a=Pt.charAt(n>>4&63),l=Pt.charAt(n<<2&63);i.push(`${o}${a}${l}`),r&&i.push("=")}return i.join("")}function Zr(c){let r=Math.floor(c.length*.75),t=c.length;return c[t-1]==="="&&(r-=1,c[t-2]==="="&&(r-=1)),r}function jr(c){let r=Zr(c),t=c.length,e=new Uint8Array(r),i=0;for(let s=0;s<t;s+=4){let n=bi[c.charCodeAt(s)],o=bi[c.charCodeAt(s+1)],a=bi[c.charCodeAt(s+2)],l=bi[c.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|l&63,i+=1}return e}var hs=16*1024,Di=4,_r=new nt,Dn=new Map;function ha(c,r){return Me(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=(Q,E=0)=>{e.set(Q,E)},n=()=>e,o=()=>t.exports,a=Q=>{t.exports.Hash_SetMemorySize(Q);let E=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,E,Q)},l=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),A=_r.dispatch(()=>Me(this,void 0,void 0,function*(){if(!Dn.has(c.name)){let E=jr(c.data),v=WebAssembly.compile(E);Dn.set(c.name,v)}let Q=yield Dn.get(c.name);t=yield WebAssembly.instantiate(Q,{})})),d=()=>Me(this,void 0,void 0,function*(){t||(yield A);let Q=t.exports.Hash_GetBuffer(),E=t.exports.memory.buffer;e=new Uint8Array(E,Q,hs)}),h=(Q=null)=>{i=!0,t.exports.Hash_Init(Q)},g=Q=>{let E=0;for(;E<Q.length;){let v=Q.subarray(E,E+hs);E+=v.length,e.set(v),t.exports.Hash_Update(v.length)}},I=Q=>{if(!i)throw new Error("update() called before init()");let E=ee(Q);g(E)},p=new Uint8Array(r*2),u=(Q,E=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(E),Q==="binary"?e.slice(0,r):xn(p,e,r)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let Q=t.exports.Hash_GetState(),E=l(),v=t.exports.memory.buffer,w=new Uint8Array(v,Q,E),D=new Uint8Array(Di+E);return da(D,c.hash),D.set(w,Di),D},C=Q=>{if(!(Q instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let E=t.exports.Hash_GetState(),v=l(),w=Di+v,D=t.exports.memory.buffer;if(Q.length!==w)throw new Error(`Bad state length (expected ${w} bytes, got ${Q.length})`);if(!Xr(c.hash,Q.subarray(0,Di)))throw new Error("This state was written by an incompatible hash implementation");let N=Q.subarray(Di);new Uint8Array(D,E,v).set(N),i=!0},m=Q=>typeof Q=="string"?Q.length<hs/4:Q.byteLength<hs,B=m;switch(c.name){case"argon2":case"scrypt":B=()=>!0;break;case"blake2b":case"blake2s":B=(Q,E)=>E<=512&&m(Q);break;case"blake3":B=(Q,E)=>E===0&&m(Q);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":B=()=>!1;break}let y=(Q,E=null,v=null)=>{if(!B(Q,E))return h(E),I(Q),u("hex",v);let w=ee(Q);return e.set(w),t.exports.Hash_Calculate(w.length,E,v),xn(p,e,r)};return yield d(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:h,update:I,digest:u,save:f,load:C,calculate:y,hashLength:r}})}var ic=new nt;var tl="argon2",el="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",il="e4cdc523",sl={name:tl,data:el,hash:il},nl="blake2b",ol="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=",al="c6f286e6",rl={name:nl,data:ol,hash:al},sc=new nt;function la(c){return!Number.isInteger(c)||c<8||c>512||c%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function ll(c,r){return c|r<<16}function Mn(c=512,r=null){if(la(c))return Promise.reject(la(c));let t=null,e=c;if(r!==null){if(t=ee(r),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=ll(c,t.length)}let i=c/8;return ha(rl,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 Al(c,r,t){let e=[`m=${r.memorySize}`,`t=${r.iterations}`,`p=${r.parallelism}`].join(",");return`$argon2${r.hashType}$v=19$${e}$${ra(c,!1)}$${ra(t,!1)}`}var Aa=new DataView(new ArrayBuffer(4));function te(c){return Aa.setInt32(0,c,!0),new Uint8Array(Aa.buffer)}function bn(c,r,t){return Me(this,void 0,void 0,function*(){if(t<=64){let a=yield Mn(t*8);return a.update(te(t)),a.update(r),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);c.init(),c.update(te(t)),c.update(r);let s=c.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)c.init(),c.update(s),s=c.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=c,o.init()):o=yield Mn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function cl(c){switch(c){case"d":return 0;case"i":return 1;default:return 2}}function dl(c){return Me(this,void 0,void 0,function*(){var r;let{parallelism:t,iterations:e,hashLength:i}=c,s=ee(c.password),n=ee(c.salt),o=19,a=cl(c.hashType),{memorySize:l}=c,A=ee((r=c.secret)!==null&&r!==void 0?r:""),[d,h]=yield Promise.all([ha(sl,1024),Mn(512)]);d.setMemorySize(l*1024+1024);let g=new Uint8Array(24),I=new DataView(g.buffer);I.setInt32(0,t,!0),I.setInt32(4,i,!0),I.setInt32(8,l,!0),I.setInt32(12,e,!0),I.setInt32(16,o,!0),I.setInt32(20,a,!0),d.writeMemory(g,l*1024),h.init(),h.update(g),h.update(te(s.length)),h.update(s),h.update(te(n.length)),h.update(n),h.update(te(A.length)),h.update(A),h.update(te(0));let u=Math.floor(l/(t*4))*4,f=new Uint8Array(72),C=h.digest("binary");f.set(C);for(let y=0;y<t;y++){f.set(te(0),64),f.set(te(y),68);let Q=y*u,E=yield bn(h,f,1024);d.writeMemory(E,Q*1024),Q+=1,f.set(te(1),64),E=yield bn(h,f,1024),d.writeMemory(E,Q*1024)}let m=new Uint8Array(1024);da(m,d.calculate(new Uint8Array([]),l));let B=yield bn(h,m,i);if(c.outputType==="hex"){let y=new Uint8Array(i*2);return xn(y,B,i)}return c.outputType==="encoded"?Al(n,c,B):B})}var hl=c=>{var r;if(!c||typeof c!="object")throw new Error("Invalid options parameter. It requires an object.");if(!c.password)throw new Error("Password must be specified");if(c.password=ee(c.password),c.password.length<1)throw new Error("Password must be specified");if(!c.salt)throw new Error("Salt must be specified");if(c.salt=ee(c.salt),c.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(c.secret=ee((r=c.secret)!==null&&r!==void 0?r:""),!Number.isInteger(c.iterations)||c.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(c.parallelism)||c.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(c.hashLength)||c.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(c.memorySize))throw new Error("Memory size should be specified.");if(c.memorySize<8*c.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(c.outputType===void 0&&(c.outputType="hex"),!["hex","binary","encoded"].includes(c.outputType))throw new Error(`Insupported output type ${c.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Tn(c){return Me(this,void 0,void 0,function*(){return hl(c),dl(Object.assign(Object.assign({},c),{hashType:"id"}))})}var nc=new nt;var oc=new nt;var ac=new nt;var rc=new nt;var lc=new Uint8Array(8);var Ac=new nt;var cc=new nt;var dc=new nt;var hc=new nt;var pc=new nt;var gc=new nt;var Ic=new nt;var uc=new nt;var fc=new nt;var Cc=new nt;var mc=new nt;var Bc=new Uint8Array(8);var Qc=new nt;var yc=new Uint8Array(8);var Ec=new nt;var wc=new Uint8Array(8);var vc=new nt;var Fc=new nt;var kc=new nt;Ft();var Ut=new Uint8Array([83,84,65,83,72,69,78,67]),Un=2,Gn=1,Rn=2,Ia=3,pl=32,Ve=12,Hn=32,gl=6e5,Il=47104,ul=3,fl=1,ht=c=>c;function Gt(c){if(c.length<Ut.length+1)return!1;for(let r=0;r<Ut.length;r++)if(c[r]!==Ut[r])return!1;return!0}function pa(c,r,t){c[r]=t>>>24&255,c[r+1]=t>>>16&255,c[r+2]=t>>>8&255,c[r+3]=t&255}function ga(c,r){return c[r]*16777216+(c[r+1]<<16)+(c[r+2]<<8)+c[r+3]}async function Pn(c,r,t){if(t.id===Rn)return await Tn({password:c,salt:r,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Hn,outputType:"binary"});if(t.id===Gn){let e=await crypto.subtle.importKey("raw",ht(new TextEncoder().encode(c)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:ht(r),iterations:t.a,hash:"SHA-256"},e,Hn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function ps(c){return crypto.subtle.importKey("raw",ht(c),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var ua={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function We(c,r){let t=crypto.getRandomValues(new Uint8Array(pl)),e=crypto.getRandomValues(new Uint8Array(Ve)),i,s,n;try{i={id:Rn,a:Il,b:ul,c:fl},n=await Pn(r,t,i),s="argon2id"}catch(d){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",d),i={id:Gn,a:gl,b:0,c:0},n=await Pn(r,t,i),s="pbkdf2"}let o=fa(i,t,e),a=await ps(n),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:ht(e),additionalData:ht(o)},a,ht(c))),A=new Uint8Array(o.length+l.length);return A.set(o,0),A.set(l,o.length),{data:A,kdf:s}}var Ni=null;async function gs(){if(Ni!==null)return Ni;try{await Tn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Ni=!0}catch{Ni=!1}return Ni}function fa(c,r,t){let e=new Uint8Array(Ut.length+1+1+4+4+1+1+r.length+t.length),i=0;return e.set(Ut,i),i+=Ut.length,e[i++]=Un,e[i++]=c.id,pa(e,i,c.a),i+=4,pa(e,i,c.b),i+=4,e[i++]=c.c,e[i++]=r.length,e.set(r,i),i+=r.length,e.set(t,i),i+=t.length,e}async function ie(c,r){if(!Gt(c))throw new Error("Not an encrypted Stashpad file.");let t=c[Ut.length];if(t===1)return Cl(c,r);if(t!==Un)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Ut.length+1,i={id:c[e++],a:0,b:0,c:0};if(i.a=ga(c,e),e+=4,i.b=ga(c,e),e+=4,i.c=c[e++],i.id===Rn){if(i.a>2097152||i.b>64||i.c<1||i.c>8)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).")}else if(i.id===Gn&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=c[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=c.slice(e,e+s);e+=s;let o=c.slice(e,e+Ve);e+=Ve;let a=c.slice(0,e),l=c.slice(e),A=await Pn(r,n,i),d=await ps(A),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:ht(o),additionalData:ht(a)},d,ht(l));return new Uint8Array(h)}async function Cl(c,r){let t=Ut.length+1,e=c.slice(t,t+16);t+=16;let i=c.slice(t,t+12);t+=12;let s=c.slice(t),n=await crypto.subtle.importKey("raw",ht(new TextEncoder().encode(r)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:ht(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:ht(i)},o,ht(s));return new Uint8Array(a)}async function xi(c,r){if(r.length!==Hn)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Ve)),i=fa({id:Ia,a:0,b:0,c:0},new Uint8Array(0),t),s=await ps(r),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:ht(t),additionalData:ht(i)},s,ht(c))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function pe(c,r){if(!Gt(c))throw new Error("Not an encrypted Stashpad file.");let t=c[Ut.length];if(t!==Un)throw new Error(`Unsupported encrypted version (${t}).`);let e=Ut.length+1;if(c[e++]!==Ia)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=c[e++];e+=s;let n=c.slice(e,e+Ve);e+=Ve;let o=c.slice(0,e),a=c.slice(e),l=await ps(r),A=await crypto.subtle.decrypt({name:"AES-GCM",iv:ht(n),additionalData:ht(o)},l,ht(a));return new Uint8Array(A)}async function Xe(c,r,t={}){if(!Gt(r))return r;if(t.secretId){let i=c.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await ie(r,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new mi(c,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await ie(r,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Ht();var Is={name:"ECDH",namedCurve:"P-256"},ml="stashpad-vault-dek-wrap",Bl=new TextEncoder;function Ln(c){let r="";for(let t=0;t<c.length;t++)r+=String.fromCharCode(c[t]);return btoa(r)}function qn(c){let r=atob(c),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function Ca(){let c=await crypto.subtle.generateKey(Is,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",c.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",c.privateKey))}}function ma(c){return crypto.subtle.importKey("spki",c,Is,!1,[])}function Ql(c){return crypto.subtle.importKey("pkcs8",c,Is,!1,["deriveBits"])}async function Ba(c,r){let t=await crypto.subtle.deriveBits({name:"ECDH",public:r},c,256),e=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:Bl.encode(ml)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function us(c,r,t){let e=await crypto.subtle.generateKey(Is,!0,["deriveBits"]),i=await Ba(e.privateKey,await ma(r)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,c)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:Ln(o),iv:Ln(s),ct:Ln(n)}}async function Qa(c,r){let t=await Ba(await Ql(r),await ma(qn(c.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:qn(c.iv)},t,qn(c.ct)))}var ya=".stashpad/keys.json",yl=".stashpad",Mi="_keys";function Jn(c){return{v:2,keyId:c,identities:[],slots:[],joinRequests:[]}}var fs=class{constructor(r){this.app=r}get a(){return this.app.vault.adapter}validate(r){let t=r;return!!t&&t.v===2&&typeof t.keyId=="string"&&Array.isArray(t.identities)&&Array.isArray(t.slots)&&Array.isArray(t.joinRequests)}async readValid(r){try{if(!await this.a.exists(r))return null;let t=JSON.parse(await this.a.read(r));return this.validate(t)?t:null}catch{return null}}async load(){let r=await this.readValid(ya);if(r)return r;try{let e=((await this.a.list(Mi)).files||[]).filter(i=>/\/keys-\d+\.json$/.test(i)).sort();for(let i of e.reverse()){let s=await this.readValid(i);if(s)return s}}catch{}return null}async exists(){return await this.load()!==null}async ensureDir(r){try{await this.a.exists(r)||await this.a.mkdir(r)}catch{}}async save(r){let t=JSON.stringify(r,null,2);await this.ensureDir(yl),await this.a.write(ya,t),await this.ensureDir(Mi);for(let e=4;e>=1;e--){let i=`${Mi}/keys-${e}.json`,s=`${Mi}/keys-${e+1}.json`;try{await this.a.exists(i)&&await this.a.write(s,await this.a.read(i))}catch{}}try{await this.a.write(`${Mi}/keys-1.json`,t)}catch{}}};var Ti="stashpad-vault-encryption";function Hi(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function Cs(c){let r="";for(let t=0;t<c.length;t++)r+=String.fromCharCode(c[t]);return btoa(r)}function se(c){let r=atob(c),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}var El=32,ms=class{constructor(r,t,e,i=()=>0){this.app=r;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.idleTimer=null;this.kf=null;this.keyfiles=new fs(r)}argonProbe(){return gs()}async init(){await this.refresh()}async refresh(){this.kf=await this.keyfiles.load()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}keychainId(){let r=this.app.appId||"default";return`${Ti}-${r}`}isRemembered(){try{return!!this.secretStore()?.getSecret(this.keychainId())}catch{return!1}}rememberedPassword(){let r=this.secretStore();if(!r)return null;try{let t=r.getSecret(this.keychainId());if(t)return t}catch{}try{return r.getSecret(Ti)||null}catch{return null}}async verifyWithKeychain(){let r=this.rememberedPassword();if(!r)return!1;try{return await this.verifyPassword(r)}catch{return!1}}async remember(r){try{await this.secretStore()?.setSecret(this.keychainId(),r)}catch(t){console.warn("[Stashpad] couldn't save password to keychain",t)}}async forgetKeychain(){let r=this.secretStore();if(r)try{r.removeSecret?await r.removeSecret(this.keychainId()):await r.setSecret(this.keychainId(),"")}catch(t){console.warn("[Stashpad] couldn't clear keychain",t)}}async tryAutoUnlock(){if(!this.isConfigured()||this.isUnlocked())return this.isUnlocked();if(this.accessState()!=="member"&&!this.hasSharedPassword())return!1;let r=this.secretStore(),t=null;try{t=r?.getSecret(this.keychainId())??null}catch{t=null}if(t)return this.unlock(t);let e=null;try{e=r?.getSecret(Ti)??null}catch{e=null}if(!e)return!1;let i=await this.unlock(e);if(i){await this.remember(e);try{r?.removeSecret?await r.removeSecret(Ti):await r?.setSecret(Ti,"")}catch{}}return i}isConfigured(){return!!this.kf||!!this.load().wrappedKey}isUnlocked(){return this.sessionKey!==null}kdf(){return this.load().identityPrivKdf??this.load().kdf}hasIdentity(){return!!this.load().identityPrivWrapped&&!!this.load().identityId}mySlot(){let r=this.load().identityId;return r?this.kf?.slots.find(t=>t.recipientId===r)??null:null}accessState(){let r=this.load();return!this.kf&&r.wrappedKey?"member":this.kf?this.hasIdentity()&&this.mySlot()?"member":r.identityId&&this.kf.joinRequests.some(t=>t.id===r.identityId)?"pending":"outsider":"none"}amIMember(){return this.accessState()==="member"}async setup(r,t=!1,e){if(await this.refresh(),this.isConfigured())throw new Error("Encryption is already set up in this vault.");if(!r)throw new Error("Password required.");let i=crypto.getRandomValues(new Uint8Array(El)),s=await this.mintIdentity(r,e),n=Jn(tt(8));n.identities.push(this.identityRecord(s)),n.slots.push(await us(i,se(s.pub),s.id)),await this.keyfiles.save(n),this.kf=n,this.sessionKey=i,t?await this.remember(r):await this.forgetKeychain(),this.armIdle()}async unlock(r,t=!1){await this.refresh();let e=this.load();if(!this.kf&&e.wrappedKey){let s;try{s=await ie(se(e.wrappedKey),r)}catch{return!1}let n=await this.mintIdentity(r,e.identityLabel??void 0),o=Jn(tt(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await us(s,se(n.pub),n.id)),await this.keyfiles.save(o),this.kf=o,this.sessionKey=s,t&&await this.remember(r),this.armIdle(),!0}let i=this.hasIdentity()?this.mySlot():null;if(i)try{let s=await ie(se(e.identityPrivWrapped),r);try{let n=await Qa(i,s);return s.fill(0),this.sessionKey=n,t&&await this.remember(r),this.armIdle(),!0}catch{s.fill(0)}}catch{}for(let s of this.kf?.passwordSlots??[])try{let n=await ie(se(s.wrapped),r);return this.sessionKey=n,t&&await this.remember(r),this.armIdle(),!0}catch{}return!1}hasSharedPassword(){return(this.kf?.passwordSlots?.length??0)>0}async setSharedPassword(r){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(!r)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let t=await We(this.sessionKey,r);this.kf.passwordSlots=[{id:tt(8),label:"Shared password",wrapped:Cs(t.data),kdf:t.kdf,createdAt:new Date().toISOString()}],await this.keyfiles.save(this.kf)}async removeSharedPassword(){await this.refresh(),!(!this.kf||!this.kf.passwordSlots?.length)&&(this.kf.passwordSlots=[],await this.keyfiles.save(this.kf))}async verifyPassword(r){let t=this.load();try{if(t.identityPrivWrapped)return(await ie(se(t.identityPrivWrapped),r)).fill(0),!0;if(t.wrappedKey)return(await ie(se(t.wrappedKey),r)).fill(0),!0}catch{}return!1}async changePassword(r,t,e=!1){let i=this.load();if(!t)throw new Error("New password required.");if(!i.identityPrivWrapped&&!await this.unlock(r,!1))return!1;let s=this.load(),n;try{n=await ie(se(s.identityPrivWrapped),r)}catch{return!1}let o=await We(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:Cs(o.data),identityPrivKdf:o.kdf}),e?await this.remember(t):await this.forgetKeychain(),this.armIdle(),!0}async requestAccess(r,t,e=!1){if(await this.refresh(),!this.kf)throw new Error("This vault has no encryption set up yet.");if(this.amIMember())return;if(!t)throw new Error("Password required.");let i=this.hasIdentity()?{id:this.load().identityId,label:this.load().identityLabel??r,pub:this.load().identityPub}:await this.mintIdentity(t,r);r&&i.label!==r&&(await this.save({...this.load(),identityLabel:r}),i.label=r);let s={id:i.id,label:i.label,pubKey:i.pub,requestedAt:new Date().toISOString()};this.kf.joinRequests=[...this.kf.joinRequests.filter(n=>n.id!==i.id),s],await this.keyfiles.save(this.kf),e?await this.remember(t):await this.forgetKeychain()}pendingJoinRequests(){return this.kf?.joinRequests??[]}members(){return this.kf?.identities??[]}myIdentityId(){return this.load().identityId}async approveJoinRequest(r,t){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(await this.refresh(),!this.kf)return!1;let e=this.kf.joinRequests.find(i=>i.id===r);return e?(this.kf.slots=[...this.kf.slots.filter(i=>i.recipientId!==e.id),await us(this.sessionKey,se(e.pubKey),e.id)],this.kf.identities=[...this.kf.identities.filter(i=>i.id!==e.id),{id:e.id,label:t??e.label,pubKey:e.pubKey,addedAt:new Date().toISOString()}],this.kf.joinRequests=this.kf.joinRequests.filter(i=>i.id!==r),await this.keyfiles.save(this.kf),!0):!1}async removeMember(r){await this.refresh(),this.kf&&(this.kf.slots=this.kf.slots.filter(t=>t.recipientId!==r),this.kf.identities=this.kf.identities.filter(t=>t.id!==r),this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==r),await this.keyfiles.save(this.kf))}async denyJoinRequest(r){await this.refresh(),this.kf&&(this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==r),await this.keyfiles.save(this.kf))}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null,this.clearIdle()}async clear(){this.lock(),await this.forgetKeychain();try{let r=this.app.vault.adapter;for(let t of[".stashpad/keys.json"])try{await r.exists(t)&&await r.remove(t)}catch{}try{let t=await r.list("_keys");for(let e of t.files||[])if(/\/keys-\d+\.json$/.test(e))try{await r.remove(e)}catch{}}catch{}}catch{}this.kf=null,await this.save(Hi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(r,t){let e=await Ca(),i=await We(e.privKeyPkcs8,r);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??tt(8),o=t??s.identityLabel??"This device",a=Cs(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:a,identityPrivWrapped:Cs(i.data),identityPrivKdf:i.kdf}),{id:n,label:o,pub:a}}identityRecord(r){return{id:r.id,label:r.label,pubKey:r.pub,addedAt:new Date().toISOString()}}armIdle(){this.clearIdle();let r=this.idleMinutes();r>0&&(this.idleTimer=window.setTimeout(()=>this.lock(),r*6e4))}clearIdle(){this.idleTimer!=null&&(window.clearTimeout(this.idleTimer),this.idleTimer=null)}dispose(){this.lock()}};var Pi=null,Bs=new Set;function Qs(c){if(Pi!==c){Pi=c;for(let r of Bs)r()}}function ne(){return Pi}function Ea(c){if(Pi===c){Pi=null;for(let r of Bs)r()}}function wa(c){return Bs.add(c),()=>Bs.delete(c)}function wl(){return x.Platform.isMacOS?"Finder":x.Platform.isWin?"File Explorer":"file manager"}var Ze=[{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:"forkNote",label:"Fork into a separate note (under a chosen parent)",desc:'Duplicate the cursor row (with its subtree) as a separate note and pick which parent it nests under. Distinct from "Fork as a version" (a draft within a sheet group). No default chord.',defaultPrimary:""},{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:"expandAll",label:"Expand all (show every note's full body)",desc:"Un-clamp every note in the current list at once.",defaultPrimary:""},{id:"collapseAll",label:"Collapse all (clamp every note's body)",desc:"Re-clamp every note in the current list at once.",defaultPrimary:""},{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:"listPin",label:"Pin / unpin to top of list",desc:"Float the cursor row (or selection) to the TOP of its list \u2014 distinct from the sidebar pin. No default chord.",defaultPrimary:""},{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"},{id:"lockSelection",label:"Encrypt (lock) selection",desc:"Encrypt the selected note(s) + their children into a locked .stashenc bundle in place (prompts to unlock first if needed). No default chord.",defaultPrimary:""},{id:"unlockAll",label:"Decrypt (unlock) locked notes in view",desc:"Decrypt every locked stash shown in the current view back into place, skipping any that can't be read. No default chord.",defaultPrimary:""},{id:"moveToArchive",label:"Move selection to archive (encrypt)",desc:"Move the selected note(s) to the default archive folder, encrypted on arrival. Undoable. No default chord.",defaultPrimary:""},{id:"encryptDelete",label:"Encrypt & delete selection",desc:"Send the selected note(s) to the encrypted trash (recoverable with your password, Ctrl/Cmd+Z undoable). No default chord.",defaultPrimary:""},{id:"copyNotes",label:"Copy notes (note clipboard)",desc:"Copy the selected note(s) as NOTES: paste in the list to duplicate them (new ids), or anywhere else to paste their text. Skipped when text is highlighted (normal copy wins).",defaultPrimary:"Mod+C"},{id:"cutNotes",label:"Cut notes",desc:"Cut the selected note(s): paste in the list to MOVE them, or in the composer to extract their text and delete the originals (undoable).",defaultPrimary:"Mod+X"},{id:"pasteNotes",label:"Paste notes",desc:"Paste previously copied/cut notes at the cursor row (after it, same parent). Does nothing if the note clipboard is empty.",defaultPrimary:"Mod+V"}];function Yn(){let c={};for(let r of Ze)c[r.id]={primary:r.defaultPrimary,secondary:r.defaultSecondary??"",preferRight:!1,useBoth:!!r.defaultUseBoth};return c}var ge={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,debugTrace:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,splitMode:"lines",confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,encryption:Hi(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],lockedSubtrees:[],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,notifiedDueKeys:[],autoNavOnMoveIn:!1,autoNavOnMoveOut:!1,autoExpandCursorRow:!1,expandBodiesByDefault:!1,autoOpenDetailPanel:!1,doubleClickToFocus:!0,enableSheetVersions:!1,dateDisplayFormat:"locale",dateDisplayTimezone:"",jdIndexScope:"vault",jdIndexScopeFolder:"",jdIndexStashpadFolder:"",jdIndexFile:"Index",jdIndexIncludeStashpadFolders:!1,jdIndexSort:"natural",jdIndexHasBuilt:!1,okfEnabled:!1,okfTemplatePath:"",drafts:{},lastSubmitted:{},bindings:Yn()},va=JSON.parse(JSON.stringify(ge)),On=new Set;function Z(){return va}function $n(c){va=c;for(let r of On)r()}function Fa(c){return On.add(c),()=>On.delete(c)}function ws(c){try{let r=c.internalPlugins?.plugins?.templates;if(!r?.enabled)return null;let t=r.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var ys=[{id:"foldersStorage",label:"Folders & storage"},{id:"importExport",label:"Import & export"},{id:"noteTitles",label:"Note titles"},{id:"datesTime",label:"Dates & time"},{id:"listDisplay",label:"List & display"},{id:"movingNotes",label:"Moving notes"},{id:"deleting",label:"Deleting"},{id:"composerCopy",label:"Composer & copying"},{id:"windowsTabs",label:"Windows & tabs"},{id:"notifications",label:"Notifications"},{id:"encryption",label:"Encryption"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"okf",label:"Open Knowledge Format (OKF)"},{id:"maintenance",label:"Maintenance"},{id:"diagnostics",label:"Diagnostics"},{id:"misc",label:"Misc"},{id:"hotkeys",label:"Hotkeys"}].sort((c,r)=>c.label.localeCompare(r.label)),Kn=null;function vl(c,r){return Kn||(Kn=class extends x.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new Kn(c,r)}var Es=class extends x.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){let{containerEl:t}=this;t.empty();for(let e of ys){new x.Setting(t).setName(e.label).setHeading();let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new x.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 ys.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>vl(t.label,i=>this.renderTabContent(i,t.id))}})}itemsForTab(t){switch(t){case"hotkeys":return this.hotkeyItems();case"diagnostics":return this.diagnosticsItems();case"notifications":return this.notificationsItems();case"foldersStorage":return this.buildGeneralCategories().foldersStorage;case"importExport":return this.buildGeneralCategories().importExport;case"noteTitles":return this.buildGeneralCategories().noteTitles;case"datesTime":return this.buildGeneralCategories().datesTime;case"listDisplay":return this.buildGeneralCategories().listDisplay;case"movingNotes":return this.buildGeneralCategories().movingNotes;case"deleting":return this.buildGeneralCategories().deleting;case"composerCopy":return this.buildGeneralCategories().composerCopy;case"windowsTabs":return this.buildGeneralCategories().windowsTabs;case"maintenance":return this.buildGeneralCategories().maintenance;case"misc":return this.buildGeneralCategories().misc;case"encryption":return this.encryptionItems();case"authorship":return this.authorshipItems();case"templates":return this.templatesItems();case"jdindex":return this.jdIndexItems();case"okf":return this.okfItems();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(){return[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.",t=>t.addToggle(e=>e.setValue(this.plugin.settings.enablePerfProfiling).onChange(async i=>{this.plugin.settings.enablePerfProfiling=i,await this.plugin.saveSettings()})),["perf","profiling","timing","slow"]),this.renderDef("Debug trace","Record low-level diagnostic lines (e.g. tap coordinates vs the row they resolve to) to an in-memory buffer while you reproduce a bug, then copy them below to share. Local only \u2014 no network, no file writes; zero overhead when off.",t=>t.addToggle(e=>e.setValue(this.plugin.settings.debugTrace).onChange(async i=>{this.plugin.settings.debugTrace=i,await this.plugin.saveSettings()})),["debug","trace","diagnostics","tap","log"]),this.renderDef("Copy / clear debug trace","Copy the captured debug lines to the clipboard (paste them back to share), or clear the buffer to start a fresh capture.",t=>{t.addButton(e=>e.setButtonText("Copy").onClick(async()=>{let i=this.plugin.getDebugTrace();if(!i){new x.Notice("Debug trace is empty \u2014 enable it and reproduce the issue first.");return}try{await navigator.clipboard.writeText(i),new x.Notice("Debug trace copied.")}catch{new x.Notice("Couldn't access clipboard.")}})),t.addButton(e=>e.setButtonText("Clear").onClick(()=>{this.plugin.clearDebugTrace(),new x.Notice("Debug trace cleared.")}))},["debug","trace","copy","clear"]),this.renderDef("Open log file","Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.",t=>t.addButton(e=>e.setButtonText("Open log").onClick(async()=>{let i=this.app.vault.adapter,s=this.plugin.pluginPrivatePath("log.jsonl");if(!await i.exists(s)){new x.Notice("No log yet \u2014 make some changes first.");return}let n=await i.read(s);new Je(this.app,n,s).open()})),["log","history","diagnostics"])]}notificationsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(vn);return[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=vn[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async a=>{let l=!a;l?t.add(i):t.delete(i),this.plugin.settings.mutedNotificationCategories=Array.from(t),this.plugin.notifications.setMuted(i,l),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 Qi(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 x.Notice("No log yet \u2014 make some changes first.");return}let l=await o.read(a);new Je(this.app,l,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);try{i(n)}catch(o){console.error(`[Stashpad] settings control "${t}" failed to render:`,o)}}}}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");try{i(o)}catch(a){console.error(`[Stashpad] settings section "${t}" failed to render:`,a)}}}}buildGeneralCategories(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,l)=>this.renderDef(s,n,A=>A.addToggle(d=>d.setValue(o()).onChange(async h=>{a(h),await t()})),l),i={foldersStorage:[],importExport:[],datesTime:[],noteTitles:[],listDisplay:[],movingNotes:[],deleting:[],composerCopy:[],windowsTabs:[],maintenance:[],misc:[]};i.foldersStorage.push(this.renderDef("Stashpad notes folder","Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.",s=>{s.addText(n=>{new ze(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||ge.folder,l=a.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(d=>(d??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(l)){new x.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.importExport.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.foldersStorage.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.importExport.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.importExport.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,"")||ge.exportFolder,await t()})),["export","stash","subfolder"])),i.maintenance.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, rename any note whose filename slug no longer matches its body's first line, AND migrate legacy attachment filenames to the new name-first format (`photo-<id>.png`). 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:l,slugsRenamed:A,authors:d,imported:h,attachmentsLinked:g,attachmentsRenamed:I,attachmentsSkipped:p}=await this.plugin.rebootstrapAllFolders(),u=[];u.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),h>0&&u.push(`imported ${h} loose file${h===1?"":"s"}`),g>0&&u.push(`linked attachments on ${g} note${g===1?"":"s"}`),I>0&&u.push(`renamed ${I} attachment${I===1?"":"s"}`),l>0?u.push(`updated frontmatter on ${l} of ${a} notes`):a>0&&u.push(`frontmatter already in sync (${a} notes checked)`),A>0&&u.push(`renamed ${A} note${A===1?"":"s"} to match body`),d>0&&u.push(`rebuilt author registry (${d} author${d===1?"":"s"})`),new x.Notice(`Stashpad: ${u.join("; ")}.`),p>0&&new x.Notice(`Stashpad: ${p} attachment${p===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(o){new x.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.maintenance.push(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.",s=>s.addToggle(n=>n.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async o=>{this.plugin.settings.writeRecoveryLinks=o,await t()})),["recovery","parentlink","children","frontmatter"])),i.datesTime.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=ws(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: ${_t(Date.now(),this.plugin.settings)}`)};i.datesTime.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 l=>{this.plugin.settings.dateDisplayFormat=l,await t(),n()})})},["date","format","display"])),i.datesTime.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 l=>{this.plugin.settings.dateDisplayTimezone=(l||"").trim(),await t(),n()})})},["timezone","tz","date","iana"])),i.datesTime.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.movingNotes.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.movingNotes.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.listDisplay.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.misc.push(e("Sheet versions (alternate drafts)",`Treat notes that share a 'sheet-group' frontmatter id as alternate versions of one item: only the active version shows as a row, and its siblings collapse into a tab bar at the bottom of that row. Use "Fork as version" on a note to start. Off by default \u2014 when off, no note is ever hidden by this feature and the commands do nothing.`,()=>this.plugin.settings.enableSheetVersions,s=>{this.plugin.settings.enableSheetVersions=s},["sheet","version","draft","alternate","fork"])),i.listDisplay.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.listDisplay.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.listDisplay.push(e("Expand note bodies by default","Show every note's full body by default instead of clamping long notes. The per-note 'Show more / show less' toggle and the Expand-all / Collapse-all commands then work in reverse \u2014 they let you collapse individual notes back down. Off = bodies clamp by default (expand is opt-in).",()=>this.plugin.settings.expandBodiesByDefault,s=>{this.plugin.settings.expandBodiesByDefault=s},["expand","collapse","default","body","clamp"])),i.movingNotes.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.deleting.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.deleting.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.noteTitles.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:Yt).join(` `);s.addTextArea(a=>{a.setValue(o),n=a.inputEl,n.rows=6,n.setCssStyles({fontFamily:"var(--font-monospace)"}),a.onChange(async l=>{this.plugin.settings.slugStopWords=(l||"").split(/\r?\n/).map(A=>A.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(a=>a.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Yt],n&&(n.value=Yt.join(` -`)),await t()}))},["slug","stopwords","filename","title"])),i.foldersStorage.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 x.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 l of n)this.renderFolderScopeRow(a,l)}let o=null;new x.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 l=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new x.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(l),new x.Notice(`Created Stashpad "${l}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(l,2e3),this.update?.()}catch(A){new x.Notice(`Couldn't create: ${A.message}`)}}))},["search","scope","exclude","include","create","new","stashpad","folder"])),i.foldersStorage.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 x.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.composerCopy.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.windowsTabs.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.windowsTabs.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.composerCopy.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}encryptionItems(){let t=this.plugin.encryption,e=[];return e.push(this.sectionDef("Vault encryption","Set one password to encrypt content in this vault. Stored only on this device \u2014 there is no recovery if you lose it.",i=>{i.addClass("stashpad-encryption-section");let s=i.createDiv({cls:"stashpad-beta-row"});s.createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),s.createEl("span",{cls:"stashpad-beta-note",text:"Encryption is in beta \u2014 keep your own backups of anything important."}),i.createEl("div",{cls:"stashpad-ai-disclaimer"}).setText("\u26A0\uFE0F AI-built, NOT human-audited. This encryption was written by an AI assistant \u2014 not designed, reviewed, or security-audited by a human, and not tested by any security professional. It may carry real security, privacy, and DATA-LOSS risks. Treat it as a best-effort nice-to-have that might buy a little time against a casual snoop \u2014 nothing is guaranteed. Do NOT rely on it for anything sensitive, and always keep your own unencrypted backups of anything important."),i.createEl("p",{cls:"setting-item-description"}).setText("\u26A0\uFE0F Encryption protects what you lock in this vault. Each device unlocks with its own password (which never leaves the device); the vault key is shared with collaborators by approving their device \u2014 no shared password. If everyone with access loses their password, anything encrypted is gone for good. While encrypting, avoid a sync/cloud service writing the vault mid-operation \u2014 it can corrupt files.");let n=()=>t.argonProbe(),o=()=>this.plugin.settings.authorName?.trim()||"This device",a=t.accessState();t.refresh().then(()=>{t.accessState()!==a&&this.update?.()});let l=a;if(l==="none"){new x.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(g=>g.setButtonText("Set up password\u2026").setCta().onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:I,remember:p})=>{if(!I)return"Enter a password.";try{await t.setup(I,p,o())}catch(u){return u.message}return new x.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}if(l==="outsider"&&!t.isUnlocked()){t.hasSharedPassword()&&new x.Setting(i).setName("This vault is encrypted").setDesc("Enter the shared password (ask whoever set it up \u2014 they'll send it via a password manager or secure message).").addButton(g=>g.setButtonText("Unlock with shared password\u2026").setCta().onClick(()=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:I,remember:p})=>await t.unlock(I,p)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password (or the keyfile hasn't synced here yet)."}).open()})),new x.Setting(i).setName(t.hasSharedPassword()?"Or request device approval":"This vault is encrypted by a collaborator").setDesc("Request access \u2014 pick a password for THIS device, then ask an existing member to approve it. Once approved (and the keyfile syncs to you), you'll unlock with that password. No shared secret.").addButton(g=>g.setButtonText("Request access\u2026").onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:I,remember:p})=>{if(!I)return"Choose a password for this device.";try{await t.requestAccess(o(),I,p)}catch(u){return u.message}return new x.Notice("Access requested. An existing member can now approve this device."),this.update?.(),null}}).open()}));return}if(l==="pending"){new x.Setting(i).setName("Access requested \u2014 waiting for approval").setDesc("An existing member needs to approve this device. After they do and the keyfile syncs here, reopen this page to unlock with the password you chose.").addButton(g=>g.setButtonText("Try unlock now").setCta().onClick(()=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:I,remember:p})=>await t.unlock(I,p)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Not approved yet (or wrong password). Ask a member to approve this device, then try again."}).open()})).addButton(g=>g.setButtonText("Cancel request").onClick(async()=>{let I=t.myIdentityId();I&&await t.denyJoinRequest(I),new x.Notice("Access request cancelled."),this.update?.()}));return}let A=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",d=t.isRemembered()?" \xB7 remembered on this device":"";if(new x.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${A?` \xB7 ${A}`:""}${d}`),t.isUnlocked()?new x.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(g=>g.setButtonText("Lock now").onClick(()=>{t.lock(),new x.Notice("Encryption locked."),this.update?.()})):new x.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(g=>g.setButtonText("Unlock\u2026").setCta().onClick(()=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:I,remember:p})=>await t.unlock(I,p)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),t.keychainAvailable()&&t.isRemembered()&&new x.Setting(i).setName("Forget password on this device").setDesc("Drops ONLY the copy saved in this device's keychain \u2014 your encryption stays set up and nothing is decrypted or deleted. You'll just re-type the password next session. (To turn encryption off entirely, use \u201CRemove encryption\u201D below.)").addButton(g=>g.setButtonText("Forget on this device").onClick(async()=>{await t.forgetKeychain(),new x.Notice("Removed from this device's keychain \u2014 encryption still set up."),this.update?.()})),t.amIMember()&&new x.Setting(i).setName("Change this device's password").setDesc("Re-wraps THIS device's key under a new password \u2014 doesn't re-encrypt files or affect other people.").addButton(g=>g.setButtonText("Change\u2026").onClick(()=>{new vt(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:I,next:p,remember:u})=>await t.changePassword(I,p,u)?(new x.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),t.amIMember()&&new x.Setting(i).setName("Remove encryption").setDesc("Erases the key from this vault. Refused while any locked notes exist \u2014 decrypt everything first (locked notes have NO plaintext copy; losing the key loses them forever).").addButton(g=>{g.setButtonText("Remove\u2026").onClick(async()=>{if(await ao(this.app)){new x.Notice(`Can't remove encryption: locked/encrypted-deleted notes still exist and would be lost forever. Run "Decrypt (unlock) ALL locked notes in the vault" and empty the encrypted trash first.`,1e4);return}new Bi(this.app,{title:"Remove encryption?",body:"This erases the encryption key for this vault. Nothing is currently encrypted (locked notes are checked), so no content is lost \u2014 but you'll need to set a new password to encrypt later, and anything you had exported encrypted with this key stays locked to its passphrase.",phrase:"REMOVE ENCRYPTION",confirmText:"Remove encryption",requirePassword:I=>t.verifyPassword(I),onConfirm:async()=>{if(await ao(this.app)){new x.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}await t.clear(),new x.Notice("Encryption removed."),this.update?.()}}).open()}),g.setDestructive()}),new x.Setting(i).setName("Sharing").setHeading(),t.isUnlocked()?t.hasSharedPassword()?new x.Setting(i).setName("Shared password").setDesc("ON \u2014 anyone who knows it can unlock this vault (no approval). Share it via a password manager or secure message; don't send it in the clear.").addButton(g=>g.setButtonText("Change\u2026").onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Change shared password",intro:"Everyone who unlocks with the shared password will need the new one. Re-share it securely after changing.",onSubmit:async({next:I})=>{if(!I)return"Enter a password.";try{await t.setSharedPassword(I)}catch(p){return p.message}return new x.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(g=>{g.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new x.Notice("Shared password turned off."),this.update?.()}),g.setDestructive()}):new x.Setting(i).setName("Shared password").setDesc("OFF \u2014 set one passphrase that everyone types to unlock (the simplest way to share). Anyone who knows it can unlock; turning it off later doesn't claw back copies already synced elsewhere.").addButton(g=>g.setButtonText("Set shared password\u2026").onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Set shared password",intro:"One passphrase everyone types to unlock this vault. Anyone who knows it gets in \u2014 share it ONLY through a password manager or secure message, never in the clear. You can turn it off later.",onSubmit:async({next:I})=>{if(!I)return"Enter a password.";try{await t.setSharedPassword(I)}catch(p){return p.message}return new x.Notice("Shared password set \u2014 share it securely with your collaborators."),this.update?.(),null}}).open()})):i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to manage how this vault is shared."),new x.Setting(i).setName("Collaborators (device approval)").setHeading(),i.createEl("p",{cls:"setting-item-description"}).setText("Everyone who can unlock this vault, and devices waiting for access. Approving a request shares the vault key with that device \u2014 it never sees a password. Removing a member revokes future access (existing synced copies they already hold aren't clawed back \u2014 rotate the key for that, a future feature)."),new x.Setting(i).setName("Synced from the vault keyfile").addButton(g=>g.setButtonText("Refresh").onClick(async()=>{await t.refresh(),this.update?.()})),!t.isUnlocked())i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to approve or remove collaborators.");else{let g=t.myIdentityId();for(let p of t.members()){let u=p.id===g,f=new x.Setting(i).setName(`${p.label}${u?" \u2014 this device":""}`).setDesc(u?"You":"Member");u||f.addButton(C=>{C.setButtonText("Remove").onClick(async()=>{await t.removeMember(p.id),new x.Notice(`Removed ${p.label}. (Not full revocation without rotating the key.)`),this.update?.()}),C.setDestructive()})}let I=t.pendingJoinRequests();if(I.length===0)i.createEl("p",{cls:"setting-item-description"}).setText("No pending access requests.");else for(let p of I)new x.Setting(i).setName(p.label).setDesc("Wants access to this vault").addButton(u=>u.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(p.id)}catch(f){new x.Notice(f.message);return}new x.Notice(`Approved ${p.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(u=>u.setButtonText("Deny").onClick(async()=>{await t.denyJoinRequest(p.id),new x.Notice("Request denied."),this.update?.()}))}},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private","collaborator","share","team","member","approve"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{this.plugin.settings.encryptTrash=n,await this.plugin.saveSettings()})),["trash","delete","encrypt"])),e.push(this.renderDef("Encrypt trash filenames","Hide the filename + origin folder of encrypted-trashed items (opaque names on disk; shown under \u201CHidden\u201D in the trash tab). Default OFF so you can still tell what to restore when working outside the app.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFilenames).onChange(async n=>{this.plugin.settings.encryptTrashFilenames=n,await this.plugin.saveSettings()})),["trash","filename","encrypt"])),e.push(this.renderDef("Follow Obsidian's trash setting instead","OFF (recommended): encrypted-deleted notes go to Stashpad's own \u201C_deleted/\u201D store \u2014 the only trash location Stashpad fully controls, so it can encrypt, list, and restore them. ON: deletes follow Obsidian's \u201CDeleted files\u201D setting instead (system/OS trash or permanent). \u26A0\uFE0F Stashpad CANNOT encrypt or recover notes that go to the system trash \u2014 so the encrypted trash + recoverable trash view won't apply. Only turn this on if you specifically want Obsidian's native trash behavior.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFollowObsidian??!1).onChange(async n=>{this.plugin.settings.encryptTrashFollowObsidian=n||void 0,await this.plugin.saveSettings()})),["trash","obsidian","system","delete","encrypt"])),e.push(this.renderDef("Auto-lock after idle minutes","Forget the password from memory after this many idle minutes (0 = never). Re-prompts on the next encryption action.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.encryptionIdleLockMinutes??0)).onChange(async n=>{let o=Math.max(0,Math.floor(Number(n)||0));this.plugin.settings.encryptionIdleLockMinutes=o,await this.plugin.saveSettings()})),["auto-lock","idle","timeout","lock"])),e.push(this.renderDef("Hide titles of locked notes","Show a generic label on \u{1F512} locked placeholders instead of the note's title, so a glance at the vault doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.renderDef("Default archive folder",`Where the "Move selection to archive" command sends notes (they're auto-encrypted on arrival). Leaving this blank is fine \u2014 the command will just show you a list of your archive folders to pick from each time (or use the only one if you have a single archive). Mark a folder as an archive via the folder panel \u2192 right-click \u2192 "Mark as archive".`,i=>{let s=this.plugin.settings.archiveFolders??[];i.addDropdown(n=>{n.addOption("",s.length?"\u2014 pick from list each time \u2014":"\u2014 no archive folders yet \u2014");for(let a of s)n.addOption(a,a);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async a=>{this.plugin.settings.defaultArchiveFolder=a||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e}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=je.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=new x.Setting(t).setName("JD Index Builder").setHeading();e.settingEl.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 x.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(l=>{l.addOption("vault","Entire vault"),l.addOption("folder","Single folder"),l.setValue(this.plugin.settings.jdIndexScope??"vault"),l.onChange(async A=>{this.plugin.settings.jdIndexScope=A==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new x.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(l=>{new $e(this.app,l.inputEl),l.setPlaceholder("Path/To/Folder"),l.setValue(this.plugin.settings.jdIndexScopeFolder??""),l.onChange(async A=>{this.plugin.settings.jdIndexScopeFolder=(A||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new x.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(l=>{l.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),l.onChange(async A=>{this.plugin.settings.jdIndexIncludeStashpadFolders=A,await this.plugin.saveSettings(),this.display()})}),new x.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(l=>{new $e(this.app,l.inputEl),l.setPlaceholder(s[0]??"(pick a Stashpad folder)"),l.setValue(this.plugin.settings.jdIndexStashpadFolder??""),l.onChange(async A=>{this.plugin.settings.jdIndexStashpadFolder=(A||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new x.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(l=>{l.addOption("natural","Natural (numeric \u2192 alphabetical)"),l.addOption("created","By creation time"),l.setValue(this.plugin.settings.jdIndexSort??"natural"),l.onChange(async A=>{this.plugin.settings.jdIndexSort=A==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=ze(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 x.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(l=>{l.setButtonText("Preview"),l.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),l.onClick(async()=>{try{let A=await os(this.app,this.plugin,this.plugin.settings);if(A.error==="no-dest"){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(A.error==="no-home"){new x.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}as(this.app,A),this.display()}catch(A){console.error("[stashpad] preview failed",A),new x.Notice(`Preview failed: ${A?.message??A}`,8e3)}})}).addButton(l=>{l.setButtonText("Build Stashpad notes"),l.setCta(),l.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),l.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Fi(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let h=await En(this.app,this.plugin,this.plugin.settings);if(h.error==="no-dest"){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(h.error==="dest-not-stashpad"){new x.Notice(`"${h.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 x.Notice(`Built: ${h.created} created, ${h.updated} updated, ${h.skipped} skipped \u2192 ${h.destFolder}`,6e3),this.display()}catch(h){console.error("[stashpad] build failed",h),new x.Notice(`Build failed: ${h?.message??h}`,8e3)}}).open()})}).addButton(l=>{l.setButtonText(`Reveal in ${nA()}`),l.setTooltip("Open the designated Stashpad folder in your OS file browser."),l.onClick(async()=>{let A=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!A){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(A)){new x.Notice(`Folder "${A}" doesn't exist yet.`,5e3);return}try{let h=this.app.vault.adapter.basePath;if(h){let{shell:g}=window.require?.("electron")??{},I=`${h}/${A}`;g?.openPath?.(I)}else new x.Notice("Reveal in file system not supported on this platform.",4e3)}catch(h){new x.Notice(`Couldn't open folder: ${h?.message??h}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new x.Setting(t).setName("Color aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=ae()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new x.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(h=>[h.hex,h.count])),l=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},A=new Set([...a.keys(),...Object.keys(l)]);if(A.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 d=[...A].map(h=>({hex:h,count:a.get(h)??0}));d.sort((h,g)=>g.count-h.count||h.hex.localeCompare(g.hex));for(let h of d)this.renderColorAliasRow(s,i,h.hex,h.count,n)};n()}authorshipItems(){let t=[];t.push(this.renderDef("Author name","Your display name. Used in the note footer + as the author/contributor link target. Leave blank to opt out (notes won't be stamped).",i=>i.addText(s=>s.setValue(this.plugin.settings.authorName).onChange(async n=>{this.plugin.settings.authorName=n.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=tt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["author","name","identity","stamp"])),t.push(this.renderDef("Author id (auto-assigned)","Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. To reset it, clear and retype your author name.",i=>i.addText(s=>s.setValue(this.plugin.settings.authorId).setDisabled(!0)),["author","id"])),t.push(this.renderDef("Title / role",'Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorRole).onChange(async n=>{this.plugin.settings.authorRole=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["role","title","job"])),t.push(this.renderDef("Department / team",'Optional. Shown on your author page (e.g. "Engineering", "Growth").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorDepartment).onChange(async n=>{this.plugin.settings.authorDepartment=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["department","team"]));let e=(i,s,n,o)=>this.renderDef(i,"",a=>a.addToggle(l=>l.setValue(s()).onChange(async A=>{n(A),await this.plugin.saveSettings()})),o);return t.push(e("Show author in note footer",()=>this.plugin.settings.showAuthor,i=>{this.plugin.settings.showAuthor=i},["author","footer","show"])),t.push(e("Show contributors in note footer",()=>this.plugin.settings.showContributors,i=>{this.plugin.settings.showContributors=i},["contributors","footer","show"])),t.push(e("Show last edit time in note footer",()=>this.plugin.settings.showLastEdit,i=>{this.plugin.settings.showLastEdit=i},["last edit","modified","footer","time"])),t.push(this.sectionDef("Folders you've worked in","Folders where you've authored or contributed notes. Click one to open it.",i=>this.renderAuthoredFolders(i),["folders","authored","contributed","worked"])),t.push(this.sectionDef("Known authors","Everyone the plugin has seen, with role/department + rename history; rebuild/restore the registry.",i=>this.renderKnownAuthorsSection(i),["authors","registry","rename","known","rebuild"])),t}renderAuthoredFolders(t){let e=this.plugin.collectAuthoredFolders();if(e.length===0){t.createEl("p",{cls:"setting-item-description",text:"No authored or contributed folders yet."});return}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=l=>{l.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(", ")}`})}}templatesItems(){return[this.sectionDef("Color aliases","Give your note colors friendly names, per Stashpad folder.",t=>this.renderColorAliasesSection(t),["color","colour","alias","name","swatch","palette","label"]),this.sectionDef("Note templates","Per-Stashpad note templates \u2014 content stamped into new notes.",t=>this.renderNoteTemplatesSection(t),["template","note","default","boilerplate","snippet"])]}jdIndexItems(){return[this.sectionDef("JD Index (Johnny Decimal)","Build a Johnny-Decimal-style index from dotted-prefix note titles \u2014 set the scope, preview, then build.",t=>this.renderJdIndexSection(t),["jd","johnny","decimal","index","scope","build","preview","hierarchy","folder"])]}okfItems(){return[this.sectionDef("Open Knowledge Format (OKF)","Turn a Stashpad folder into a browsable OKF bundle \u2014 markdown concept files with OKF frontmatter, a generated index.md, and relative-markdown cross-links \u2014 that LLMs/agents can read. Complements (never replaces) Stashpad's own frontmatter and links.",t=>this.renderOkfSection(t),["okf","open knowledge format","knowledge","catalog","index","export","bundle","tarball","agent","google"])]}appendCode(t,e){e.split(/`([^`]+)`/g).forEach((i,s)=>{s%2===1?t.createEl("code",{text:i}):i&&t.appendText(i)})}codeDesc(t){let e=document.createDocumentFragment();return this.appendCode(e,t),e}renderOkfSection(t){if(t.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),new x.Setting(t).setName("Enable OKF").setDesc(this.codeDesc("Master switch. When on, you choose which folders use OKF by assigning the OKF template to them in Settings \u2192 Templates (all / some / none \u2014 your call). Those folders then get OKF frontmatter and a maintained `index.md`. Turning this off leaves existing OKF files in place; it just stops maintaining them.")).addToggle(i=>i.setValue(this.plugin.settings.okfEnabled).onChange(async s=>{if(this.plugin.settings.okfEnabled=s,await this.plugin.saveSettings(),s)try{await this.plugin.ensureOkfTemplate()}catch(n){console.warn("[Stashpad] OKF template create failed",n)}new x.Notice(s?`OKF on. Next: assign the template "${this.plugin.okfTemplatePathOrDefault()}" to a folder \u2014 use \u201CCreate template + open Templates\u201D below. Heads-up: OKF frontmatter + index.md refresh automatically but NOT instantly (a few seconds after changes); hit Rebuild for an immediate pass.`:"OKF disabled.",s?0:4e3),this.update?.()})),this.plugin.settings.okfEnabled){let i=this.plugin.okfTemplatePathOrDefault(),s=this.plugin.okfActiveFolders().length,n=t.createEl("div",{cls:"setting-item-description stashpad-okf-howto"});n.createEl("p",{text:"How to use OKF in a folder:"});let o=n.createEl("ol");if(this.appendCode(o.createEl("li"),`Open Templates and set a folder's template to \`${i}\` (archive folders are skipped).`),this.appendCode(o.createEl("li"),"Hit Rebuild below to write OKF frontmatter (`okfParent`/`okfChildren` + `okfType`/`okfTitle`/`okfTimestamp`) and generate that folder's `index.md`."),this.appendCode(o.createEl("li"),"Right-click a note (or a selection) \u2192 \u201CExport as OKF\u2026\u201D to save a `.zip` / `.tar.gz` bundle (or `.stash`)."),n.createEl("p",{cls:"stashpad-okf-soon",text:"OKF frontmatter + index.md refresh automatically a few seconds after you add, move, or delete notes \u2014 NOT instantly. Use Rebuild for an immediate pass."}),s===0){let a=t.createEl("p",{cls:"stashpad-okf-cta"});this.appendCode(a,"\u{1F449} No folder is using OKF yet. Click \u201CCreate template + open Templates\u201D below, then set a folder's template to `"+i+"`.")}else n.createEl("p",{cls:"stashpad-okf-soon",text:`Currently ${s} folder${s===1?"":"s"} actively using OKF.`});new x.Setting(t).setName("Assign OKF to folders").setDesc(this.codeDesc(`Creates the OKF template if needed (never duplicates it), then opens Templates \u2014 set a folder's template to \`${i}\` there.`)).addButton(a=>{a.setButtonText("Create template + open Templates").setCta(),a.onClick(async()=>{let l;try{l=await this.plugin.ensureOkfTemplate()}catch(A){new x.Notice(`Couldn't create the OKF template: ${A.message}`);return}new x.Notice(`OKF template ready at "${l}" \u2014 set a folder's template to that path.`),this.update?.(),this.openSettingsPage("Templates")})}),new x.Setting(t).setName("Rebuild OKF frontmatter").setDesc(this.codeDesc("Write/refresh OKF fields for every folder using the OKF template \u2014 `okfParent`/`okfChildren` relative links (managed) plus `okfType`/`okfTitle`/`okfTimestamp` defaults (yours to edit after). Heads-up: adding, moving, or deleting notes already auto-refreshes the folder, but NOT instantly \u2014 it waits ~a few seconds after you stop. Use this button for an immediate rebuild (e.g. right after first assigning the template). Complements Stashpad's own links; nothing is removed.")).addButton(a=>a.setButtonText("Rebuild now").onClick(async()=>{let l=await this.plugin.rebuildAllOkf();new x.Notice(l.folders===0?"No folders use the OKF template yet \u2014 assign it in Templates first.":`OKF: updated ${l.written} of ${l.checked} notes across ${l.folders} folder${l.folders===1?"":"s"}.`),this.update?.()}))}let e=new x.Setting(t).setName("Learn about OKF").setDesc("Google's open, vendor-neutral spec for sharing curated knowledge with agents.");e.addButton(i=>i.setButtonText("Spec / repo").onClick(()=>window.open("https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf"))),e.addButton(i=>i.setButtonText("Announcement").onClick(()=>window.open("https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing/")))}openSettingsPage(t){let e=()=>new x.Notice(`Open Settings \u2192 Stashpad \u2192 ${t}.`);try{let i=this.app.setting;if(!i?.openTabById){e();return}i.openTabById("stashpad"),window.setTimeout(()=>{let s=i.modalEl?.querySelector(".vertical-tab-content");if(!s){e();return}let o=Array.from(s.querySelectorAll("*")).find(a=>a.childElementCount===0&&a.textContent?.trim()===t&&!a.closest(".vertical-tab-header"))?.closest("[class*='nav'], .setting-item, button, a");o&&!o.closest(".vertical-tab-header")?o.click():e()},60)}catch{e()}}renderAuthorshipSection(t){new x.Setting(t).setName("Authorship").setHeading(),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 x.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=tt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new x.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 x.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 x.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 x.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 x.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 x.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){new x.Setting(t).setName("Folders you've worked in").setHeading();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=l=>{l.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){new x.Setting(t).setName("Known authors (registry)").setHeading(),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 x.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 x.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new x.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 x.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new x.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 l=n.createDiv({cls:"stashpad-known-author-history"}),A=s.renames.map(d=>`${d.from} \u2192 ${d.to}`).join(", ");l.setText(`Renamed: ${A}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;if(new x.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."),this.plugin.settings.okfEnabled){let n=this.plugin.okfTemplatePathOrDefault();this.appendCode(t.createEl("p",{cls:"setting-item-description"}),`\u{1F4A1} OKF tip: type \`${n}\` into a folder's template field below to turn that folder into an OKF bundle (OKF frontmatter + a maintained \`index.md\`). Assign it to all, some, or none of your folders \u2014 it's per-folder. Manage OKF itself in Settings \u2192 OKF.`)}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 A=a.createDiv({cls:"stashpad-note-template-input-wrap"}),d=A.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});d.value=(this.plugin.settings.noteTemplates??{})[o]??"";let h=A.createDiv({cls:"stashpad-note-template-suggest"});h.setCssStyles({display:"none"});let g=[],I=[],p=-1,u=()=>h.style.display!=="none"&&g.length>0,f=w=>{p=w,I.forEach((D,N)=>D.toggleClass("is-active",N===w)),w>=0&&I[w]&&I[w].scrollIntoView({block:"nearest"})},C=()=>{h.setCssStyles({display:"none"}),p=-1},m=async w=>{d.value=w,await E(),C()},B=a.createDiv({cls:"stashpad-note-template-warn"});B.setCssStyles({display:"none"});let y=()=>this.app.vault.getMarkdownFiles().map(w=>w.path).filter(w=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(w)).sort(),Q=()=>{h.empty(),I=[];let w=d.value.trim().toLowerCase().split(/\s+/).filter(Boolean),D=N=>{let P=N.toLowerCase();return w.every(H=>P.includes(H))};if(g=y().filter(N=>D(N)).slice(0,12),g.length===0){C();return}h.setCssStyles({display:""}),g.forEach((N,P)=>{let H=h.createDiv({cls:"stashpad-note-template-suggest-item",text:N});I.push(H),H.addEventListener("mousemove",()=>f(P)),H.addEventListener("mousedown",async b=>{b.preventDefault(),await m(N)})}),p=p>=0&&p<g.length?p:-1,p>=0&&f(p)},E=async()=>{let w=d.value.trim(),D={...this.plugin.settings.noteTemplates??{}};w?D[o]=w:delete D[o],this.plugin.settings.noteTemplates=D,await this.plugin.saveSettings(),v()},v=()=>{B.empty(),B.setCssStyles({display:"none"});let w=d.value.trim();if(!w)return;let D=this.app.vault.getAbstractFileByPath(w);if(!D||D.extension!=="md"){B.setCssStyles({display:""}),B.setText(`\u26A0 "${w}" is not a markdown file in this vault.`);return}let N=this.app.metadataCache.getFileCache(D)?.frontmatter??{},H=Xt.filter(b=>{let S=N[b];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.length===0)});H.length!==0&&(B.setCssStyles({display:""}),B.setText(`\u26A0 Template defines ${H.join(", ")} \u2014 Stashpad always sets ${H.length===1?"this":"these"} on new notes, so the template value${H.length===1?"":"s"} will be ignored.`))};d.addEventListener("focus",Q),d.addEventListener("input",()=>{p=-1,Q()}),d.addEventListener("blur",()=>{setTimeout(C,150)}),d.addEventListener("change",()=>{E()}),d.addEventListener("keydown",w=>{if(w.key==="ArrowDown")w.preventDefault(),u()?f((p+1)%g.length):(Q(),g.length&&f(0));else if(w.key==="ArrowUp"){if(!u())return;w.preventDefault(),f((p-1+g.length)%g.length)}else if(w.key==="Enter")u()&&p>=0&&(w.preventDefault(),m(g[p]));else if(w.key==="Escape")u()&&(w.preventDefault(),C());else if(w.key==="Tab"&&!w.shiftKey){if(!u())return;let D=g[p>=0?p:0],N=d.value,P;if(D.toLowerCase().startsWith(N.toLowerCase())){let H=D.indexOf("/",N.length);P=H>=0?D.slice(0,H+1):D}else P=D;P&&P!==N&&(w.preventDefault(),d.value=P,p=-1,Q(),g.length===1&&f(0))}}),v()};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.setCssStyles({background:i}),a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let h=this.plugin.settings.customPalette??[];new xe(this.app,i,h,async g=>{if((g??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(g&&g.toLowerCase()===i){n();return}let I=await this.plugin.recolorAllInFolder(e,i,g??null);if(I>0)new x.Notice(`Recolored ${I} note${I===1?"":"s"}.`);else if(s===0){let p=this.plugin.getColorAlias(e,i);p&&(await this.plugin.setColorAlias(e,i,""),g&&await this.plugin.setColorAlias(e,g,p))}n()},async g=>{let I=(this.plugin.settings.customPalette??[]).filter(p=>p.toLowerCase()!==g.toLowerCase());return this.plugin.settings.customPalette=I,await this.plugin.saveSettings(),I}).open()};let l=o.createDiv({cls:"stashpad-color-alias-meta"});l.createSpan({cls:"stashpad-color-alias-hex",text:i}),l.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let A=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});A.value=this.plugin.getColorAlias(e,i)??"",A.onchange=async()=>{await this.plugin.setColorAlias(e,i,A.value),!A.value.trim()&&s===0&&n()};let d=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});A.value||d.setCssStyles({visibility:"hidden"}),d.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(A.value="",d.setCssStyles({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),l=()=>{let d=a();n.toggleClass("is-right",d),n.setAttribute("aria-checked",String(d)),o.setText(d?"X":"\u2713"),s.setText(d?"Excluded":"Included"),s.toggleClass("is-excluded",d),n.title=d?"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."},A=async()=>{let d=new Set(this.plugin.settings.searchExcludedFolders??[]);d.has(e)?d.delete(e):d.add(e),this.plugin.settings.searchExcludedFolders=[...d].sort(),l(),await this.plugin.saveSettings()};n.onclick=()=>void A(),n.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),A())},l()}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 l=t.createDiv({cls:"stashpad-folder-list"});for(let A of a){let d=l.createDiv({cls:"stashpad-folder-row"});d.createSpan({cls:"stashpad-folder-row-label",text:A});let h=d.createEl("button",{text:o.action});h.onclick=()=>void n(A)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=I=>{let p=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=p.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=Si(i()[I]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=I==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{na(u,async Q=>{this.plugin.settings.bindings[e.id][I]=Q,u.value=Si(Q),f(),await this.plugin.saveSettings(),o(),y()})};let m=p.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][I]="",u.value="",f(),await this.plugin.saveSettings(),o(),y()};let B=p.createEl("button",{cls:"stashpad-binding-revert"});(0,x.setIcon)(B,"rotate-ccw");let y=()=>{let E=i()[I]!==C;B.toggleClass("is-hidden",!E),B.title=C?`Revert to default (${Si(C)})`:"Revert to default (no binding)"};return B.onclick=async()=>{this.plugin.settings.bindings[e.id][I]=C,u.value=Si(C),f(),await this.plugin.saveSettings(),o(),y()},y(),u};s=a("primary"),n=a("secondary");let l=t.controlEl.createDiv({cls:"stashpad-binding-pill"});l.setAttribute("role","switch"),l.setAttribute("tabindex","0");let A=l.createDiv({cls:"stashpad-binding-pill-knob"}),d=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),h=d.createEl("input",{type:"checkbox"});h.title="Use both bindings simultaneously (overrides the L/R toggle)",d.createSpan({text:"Use both"}),h.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=h.checked,await this.plugin.saveSettings(),o()},o=()=>{let I=i(),p=!!(I.primary&&I.secondary);h.checked=!!I.useBoth,h.disabled=!p,d.toggleClass("is-disabled",!p);let u=!!I.useBoth&&p;l.toggleClass("is-disabled",!p||u),l.toggleClass("is-right",I.preferRight),l.setAttribute("aria-checked",String(I.preferRight)),l.setAttribute("aria-disabled",String(!p||u)),A.setText(I.preferRight?"R":"L"),l.title=p?u?'Overridden by "Use both"':I.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let g=async()=>{let I=i();!I.primary||!I.secondary||(this.plugin.settings.bindings[e.id].preferRight=!I.preferRight,o(),await this.plugin.saveSettings())};l.onclick=()=>void g(),l.onkeydown=I=>{(I.key===" "||I.key==="Enter")&&(I.preventDefault(),g())},o()}};var _e=class{constructor(r,t){this.app=r;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 r=this.detectTrigger();if(!r){this.close();return}this.openFor(r)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=r=>{r.key==="Escape"&&(!this.state||!this.items.length||(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),this.close()))};this.onKeyDown=r=>{!this.state||!this.items.length||(r.key==="ArrowDown"?(r.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):r.key==="ArrowUp"?(r.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):r.key==="Enter"||r.key==="Tab"?(r.preventDefault(),r.stopPropagation(),this.commit()):r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let r=this.ta.ownerDocument??document;r.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>r.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 r of this.vaultListeners)r();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let r=j().inheritObsidianExclusions,t=r?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!To(i.path)&&!Ho(i.path)&&!(r&&Po(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 r=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=r.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(r){this.buildIndex();let t=r.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 r.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(r){if(this.state=r,this.items=this.buildItems(r),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let r=new nr.Scope(this.app.scope);r.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=r,this.app.keymap?.pushScope(r)}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 r=this.popupEl;r.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],i=r.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 r=this.popupEl.children;for(let e=0;e<r.length;e++)r[e].toggleClass("is-active",e===this.activeIdx);let t=r[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let r=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=r.top-t-4,i=r.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,r.width)}px`}commit(){if(!this.state||!this.items.length)return;let r=this.items[this.activeIdx];if(!r)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),i=r.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()}};rt();var Ts=class extends Et.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 ve}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?.()===K&&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?.()===K&&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 p=t.createDiv({cls:"stashpad-detail-empty"});(0,Et.setIcon)(p.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),p.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"}),l=a.createDiv({cls:"stashpad-detail-header"}),A=l.createDiv({cls:"stashpad-detail-titlerow"});A.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let d=A.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,Et.setIcon)(d,"arrow-up-right"),d.title="Open this note in a new Stashpad tab",d.onclick=()=>{this.openInStashpad(s.folder,s.id)};let h=l.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&h.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let p=h.createSpan({cls:"stashpad-detail-meta-color"});p.style.background=o.color,p.title=o.color}if(o.completed===!0&&h.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let p=Date.parse(String(o.due)),u=Number.isNaN(p)?String(o.due):jt(p,this.plugin.settings);h.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${u}`})}if(Array.isArray(o.tags))for(let p of o.tags.filter(u=>typeof u=="string"))h.createSpan({cls:"stashpad-detail-meta-tag",text:`#${p.replace(/^#/,"")}`});let g=a.createDiv({cls:"stashpad-detail-body"});try{let p=await this.app.vault.cachedRead(n),u=this.stripFrontmatter(p);await Et.MarkdownRenderer.render(this.app,u,g,n.path,this)}catch(p){g.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${p.message}`})}this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s);let I=this.composerInputEl;if(e&&I&&(I.focus(),i!=null)){let p=Math.min(i,I.value.length);try{I.setSelectionRange(p,p)}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,Et.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 _e(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?.()!==K||typeof i.createNoteUnder!="function"){new Et.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new Et.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?.()!==K)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 l=a.createDiv({cls:"stashpad-detail-children-list"});for(let A of o)A.file&&this.renderDetailChildRow(l,s,n,e,A,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},l=typeof a.color=="string"?a.color:null,A=a.completed===!0,d=i.getChildren(n.id),h=d.length>0,g=`${s}|${n.id}`,I=this.expanded.has(g),p=t.createDiv({cls:"stashpad-detail-child-row"});A&&p.addClass("is-completed"),o>0&&(p.style.paddingLeft=`${o*16}px`),p.draggable=!0,p.dataset.id=n.id,p.addEventListener("dragstart",B=>{B.dataTransfer?.setData("text/plain",n.id),B.dataTransfer&&(B.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",B=>{B.preventDefault(),B.dataTransfer&&(B.dataTransfer.dropEffect="move");let y=p.getBoundingClientRect(),Q=B.clientY-y.top<y.height/2;p.toggleClass("drop-before",Q),p.toggleClass("drop-after",!Q)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",B=>{B.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let y=B.dataTransfer?.getData("text/plain");if(!y||y===n.id)return;let Q=p.getBoundingClientRect(),E=B.clientY-Q.top<Q.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([y],n.id,E?"before":"after")}),p.oncontextmenu=B=>{B.preventDefault();let y=i.get(n.id);y&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(B,y)};let u=p.createSpan({cls:"stashpad-detail-child-toggle"});if(h&&(ce(u,d.length,I),u.onclick=B=>{B.stopPropagation(),this.expanded.has(g)?this.expanded.delete(g):this.expanded.add(g),this.render()}),Le(a,"task")||a.task===!0||a.completed!==void 0){let B=p.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Et.setIcon)(B,A?"check-square":"square"),B.title=A?"Mark not done":"Mark done",B.addEventListener("mousedown",y=>y.stopPropagation()),B.addEventListener("dblclick",y=>{y.preventDefault(),y.stopPropagation()}),B.onclick=y=>{y.preventDefault(),y.stopPropagation();let Q=i.get(n.id);Q&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(Q)}}let C=p.createSpan({cls:"stashpad-detail-child-icon"});(0,Et.setIcon)(C,h?"folder-tree":"file-text"),l&&(C.style.color=l);let m=p.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},h&&I)for(let B of d)this.renderDetailChildRow(t,e,i,s,B,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(l=>typeof l=="string").map(l=>this.stripWikiLink(l));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 l=n.createDiv({cls:"stashpad-detail-meta-line"});l.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),l.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)?jt(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==F&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new Et.Notice(`Couldn't open: ${i.message}`)}}};async function Hs(c){let r=c.workspace.getLeavesOfType(ve);if(r.length>0){c.workspace.revealLeaf(r[0]);return}let t=c.workspace.getRightLeaf(!1);if(!t){new Et.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:ve,active:!0}),c.workspace.revealLeaf(t)}var k=require("obsidian");rt();var Be=require("obsidian");rt();function aA(c,r){let t=c.vault.getAbstractFileByPath(r);if(!(t instanceof Be.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof Be.TFile?n.extension==="md"&&e.push(n):n instanceof Be.TFolder&&(ci.has(n.name)||i.push(n))}return e}var Ps=class{constructor(r){this.app=r;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(F,{id:F,parent:null,children:[],file:null,created:""})}setOrderProvider(r){this.orderProvider=r}onChange(r){return this.listeners.add(r),()=>this.listeners.delete(r)}emit(){for(let r of this.listeners)r()}rebuild(r){r!==void 0&&(this.currentFolder=r);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(F,{id:F,parent:null,children:[],file:null,created:""});let s=t?aA(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 A=e.get(n.path),d=A?i.get(A):void 0,h=this.synthetic.get(n.path),g=d??h;g&&(this.nodes.set(g.id,{...g,children:[],file:n}),this.byPath.set(n.path,g.id));continue}if(this.synthetic.delete(n.path),a===F){let A=this.nodes.get(F);A.file=n,A.created=o?.created??"",this.byPath.set(n.path,F);continue}let l=o?.parent??null;l===a&&(l=null),this.nodes.set(a,{id:a,parent:l??F,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===F)continue;let o=n.parent??F;(this.nodes.get(o)??this.nodes.get(F)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let l=this.nodes.get(o),A=this.nodes.get(a);return(l.created||"").localeCompare(A.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((l,A)=>a.set(l,A)),n.children.sort((l,A)=>{let d=a.has(l)?a.get(l):1/0,h=a.has(A)?a.get(A):1/0;return d===h?0:d-h})}}this.emit()}insertSynthetic(r){if(!r.file)return;let t=r.file.path;this.synthetic.set(t,r),this.nodes.set(r.id,r),this.byPath.set(t,r.id);let e=r.parent??F,i=this.nodes.get(e);i&&!i.children.includes(r.id)&&i.children.push(r.id),this.emit()}get(r){return this.nodes.get(r)}getRoot(){return this.nodes.get(F)}getChildren(r){let t=this.nodes.get(r);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let r=0;for(let t of this.nodes.values())t.file&&r++;return r}pathTo(r){let t=[],e=new Set,i=this.nodes.get(r);for(;i&&i.id!==F&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(r){return this.byPath.get(r)}snapshot(){let r={};for(let t of this.nodes.values())t.id===F||!t.file||(r[t.id]={parent:t.parent===F?null:t.parent,path:t.file.path});return r}hookMetadataCache(r){let t=l=>{let A=this.currentFolder;return A?typeof l!="string"?!1:l===A||l.startsWith(A+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),r())},16))},s=l=>{l instanceof Be.TFile&&t(l.path)&&l.extension==="md"&&(this.applyChange(l),i())},n=l=>{l instanceof Be.TFile&&t(l.path)&&l.extension==="md"&&this.applyChange(l)&&i()},o=l=>{let A=l?.path;typeof A=="string"&&t(A)&&this.applyDelete(A)&&i()},a=(l,A)=>{if(!(l instanceof Be.TFile))return;let d=typeof A=="string"?A:null;!t(l.path)&&!t(d)||this.applyRename(l,d??"")&&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(r){if(qe(r.path))return this.byPath.has(r.path)?this.applyDelete(r.path):!1;let t=this.app.metadataCache.getFileCache(r)?.frontmatter,e=t?.id,i=this.byPath.get(r.path);if(!e){if(i){let A=this.nodes.get(i);if(A&&A.file!==r)return A.file=r,!0}return!1}if(this.synthetic.delete(r.path),e===F){let A=this.nodes.get(F),d=t?.created??"",h=!1;return A.file!==r&&(A.file=r,h=!0),A.created!==d&&(A.created=d,h=!0),this.byPath.get(r.path)!==F&&(this.byPath.set(r.path,F),h=!0),h}let s=t?.parent??F,n=t?.created??"";if(!(s===F||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 A={id:e,parent:s,children:[],file:r,created:n};return this.nodes.set(e,A),this.byPath.set(r.path,e),this.attachToParent(A),this.resortChildrenOf(s),!0}let l=!1;if(a.file!==r&&(a.file=r,l=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??F),l=!0),a.parent!==s){let A=a.parent??F;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(A),this.resortChildrenOf(s),l=!0}return l}applyDelete(r){let t=this.byPath.get(r);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(r),this.synthetic.delete(r),!0;this.detachFromParent(e);let i=this.nodes.get(F);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=F,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(F),this.nodes.delete(t),this.byPath.delete(r),this.synthetic.delete(r),!0}applyRename(r,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||r.path===e||r.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(r);if(qe(r.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(r);this.byPath.delete(t),this.byPath.set(r.path,n);let o=this.nodes.get(n);return o&&(o.file=r),!0}detachFromParent(r){let t=this.nodes.get(r.parent??F);if(!t)return;let e=t.children.indexOf(r.id);e>=0&&t.children.splice(e,1)}attachToParent(r){let t=this.nodes.get(r.parent??F);t||(t=this.nodes.get(F)),t.children.includes(r.id)||t.children.push(r.id)}resortChildrenOf(r){let t=this.nodes.get(r);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(r);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 ho=class{constructor(){this.enabled=!1;this.buckets=new Map}record(r,t){if(!this.enabled)return;let e=this.buckets.get(r);e||(e={count:0,total:0,max:0},this.buckets.set(r,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(r,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(r,performance.now()-e)}}async timeAsync(r,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(r,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let r=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(r.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 r)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` -`)}},wt=new ho;var or=".stashpad-order.json",ti=class{constructor(r){this.app=r;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(r){if(this.cache.has(r))return this.cache.get(r);let t=`${r}/${or}`,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(l=>typeof l=="string")&&(i[o]=a)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(r,i),i}async save(r){this.scheduleWrite(r)}async flush(r){let t=this.pendingTimers.get(r);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(r)),await this.writeNow(r)}scheduleWrite(r){let t=this.pendingTimers.get(r);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(r),this.writeNow(r)},150);this.pendingTimers.set(r,e)}async writeNow(r){let e=(this.writeInFlight.get(r)??Promise.resolve()).then(()=>this.doWrite(r));this.writeInFlight.set(r,e);try{await e}finally{this.writeInFlight.get(r)===e&&this.writeInFlight.delete(r)}}async doWrite(r){let t=this.cache.get(r)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(r,e);let i=`${r}/${or}`,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(r,t){return this.cache.get(r)?.[t]?.slice()??[]}setOrder(r,t,e){let i=this.cache.get(r)??{};i[t]=e.slice(),this.cache.set(r,i)}appendChild(r,t,e){let i=this.cache.get(r)??{},s=i[t]??[];s.includes(e)||s.push(e),i[t]=s,this.cache.set(r,i)}removeChild(r,t){let e=this.cache.get(r);if(e)for(let i of Object.values(e)){let s=i.indexOf(t);s>=0&&i.splice(s,1)}}invalidate(r){this.cache.delete(r)}};var Ji={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"},po=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],rA=new Set(po),ar=".stashpad-sort.json",Us=class{constructor(r){this.app=r;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(r){if(this.cache.has(r))return this.cache.get(r);let t=`${r}/${ar}`,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"&&rA.has(o)&&(i[n]=o)}}catch(s){console.warn("Stashpad: sort load failed",s)}return this.cache.set(r,i),i}async save(r){this.scheduleWrite(r)}async flush(r){let t=this.pendingTimers.get(r);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(r)),await this.writeNow(r)}scheduleWrite(r){let t=this.pendingTimers.get(r);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(r),this.writeNow(r)},150);this.pendingTimers.set(r,e)}async writeNow(r){let e=(this.writeInFlight.get(r)??Promise.resolve()).then(()=>this.doWrite(r));this.writeInFlight.set(r,e);try{await e}finally{this.writeInFlight.get(r)===e&&this.writeInFlight.delete(r)}}async doWrite(r){let t=this.cache.get(r)??{},e=`${r}/${ar}`,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(r,t){return this.cache.get(r)?.[t]??"manual"}setMode(r,t,e){let i=this.cache.get(r)??{};e==="manual"?delete i[t]:i[t]=e,this.cache.set(r,i)}removeParent(r,t){let e=this.cache.get(r);e&&delete e[t]}invalidate(r){this.cache.delete(r)}};rt();var Qe="parentLink",ei="children";var Ls=class Ls{constructor(r,t){this.app=r;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(r){return this.activityListeners.add(r),()=>this.activityListeners.delete(r)}emitActivity(){let r=this.pending.size;for(let t of this.activityListeners)try{t(r)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(r){if(!r||!j().writeRecoveryLinks)return;let t=this.pending.size;this.pending.add(r),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(r,t,e){this.schedule(r),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(r){let t=this.getTree(),e=i=>{this.schedule(i);for(let s of t.getChildren(i))e(s.id)};e(r)}scheduleParentOfDeleted(r){r&&this.schedule(r)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let r=this.pending.values().next().value;if(r===void 0)break;this.pending.delete(r),this.emitActivity(),await this.syncOne(r)}}pendingCount(){return this.pending.size}onError(r){return this.errorListeners.add(r),()=>this.errorListeners.delete(r)}emitError(r,t){for(let e of this.errorListeners)try{e(r,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(),Ls.PACING_MS))}async tick(){this.timer=null;let r=this.pending.values().next().value;if(r!==void 0){this.pending.delete(r),this.emitActivity();try{await this.syncOne(r)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(r){let e=this.getTree().get(r);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[Qe]=="string"?n[Qe]:null,a=n?.[ei],l=Array.isArray(a)?a.filter(A=>typeof A=="string"):[];if((o??null)!==(i??null)||l.length!==s.length)return!0;for(let A=0;A<l.length;A++)if(l[A]!==s[A])return!0;return!1}async syncOne(r){let e=this.getTree().get(r);if(!e||!e.file||!this.wouldWrite(r))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await wt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[Qe]=i:delete n[Qe],s.length>0?n[ei]=s:delete n[ei]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(r){if(r.id===F)return null;let t=this.getTree();if(!r.parent||r.parent===F){let i=t.getRoot();return i&&i.id!==r.id&&i.file?Gs(i.file.path):null}let e=t.get(r.parent);return e?.file?Gs(e.file.path):null}computeChildrenLinks(r){return this.getTree().getChildren(r.id).filter(e=>!!e.file).map(e=>Gs(e.file.path))}};Ls.PACING_MS=100;var Rs=Ls;async function ii(c,r){let t=r.endsWith("/")?r:r+"/",e=new Map,i=new Map;for(let A of c.vault.getMarkdownFiles()){if(A.path!==r&&!A.path.startsWith(t))continue;let d=c.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id:null;if(!h)continue;let g=typeof d?.parent=="string"?d.parent:F;e.set(h,{file:A,id:h,parent:g});let I=i.get(g)??[];I.push(h),i.set(g,I)}let s=A=>Gs(A.file.path),n=A=>{if(A.id===F)return null;if(A.parent===F||!A.parent){let h=e.get(F);return h?s(h):null}let d=e.get(A.parent);return d?s(d):null},o=A=>{let d=i.get(A.id)??[],h=[];for(let g of d){let I=e.get(g);I&&h.push(s(I))}return h},a=0,l=0;for(let A of e.values()){a+=1;let d=n(A),h=o(A),g=c.metadataCache.getFileCache(A.file)?.frontmatter,I=g&&typeof g[Qe]=="string"?g[Qe]:null,p=g?.[ei],u=Array.isArray(p)?p.filter(m=>typeof m=="string"):[],f=(I??null)===(d??null),C=u.length===h.length&&u.every((m,B)=>m===h[B]);if(!(f&&C))try{await c.fileManager.processFrontMatter(A.file,m=>{d?m[Qe]=d:delete m[Qe],h.length>0?m[ei]=h:delete m[ei]}),l+=1,await new Promise(m=>setTimeout(m,50))}catch(m){console.warn("[Stashpad] rebootstrap fm sync failed",A.file.path,m)}}return{checked:a,written:l}}function Gs(c){return`[[${c.replace(/\.md$/i,"")}]]`}Tt();Ye();var qs=class{constructor(r,t){this.tree=r;this.log=t}async sweep(r){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!r)return!0;let o=r.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 ht=require("obsidian");rt();Cn();var Ct=ht.moment;function go(c){let r=c.trim().toLowerCase();if(!r)return null;let t=Date.now(),e=p=>Ct(p).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=r,a=i.exec(r);if(a&&(a[3]||a[2])){let p=parseInt(a[1],10),u=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&p<12&&(p+=12),f==="am"&&p===12&&(p=0),p>=0&&p<24&&u>=0&&u<60&&(s=(p*3600+u*60)*1e3,n=!0,o=r.replace(a[0]," ").replace(/\s+/g," ").trim())}let l=p=>n?p+s:p;if(o===""||o==="today")return l(e(t));if(o==="yesterday")return l(e(t)-864e5);if(o==="tomorrow")return l(e(t)+864e5);let A=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=["sun","mon","tue","wed","thu","fri","sat"],h=A.indexOf(o)>=0?A.indexOf(o):d.indexOf(o);if(h>=0){let p=Ct().startOf("day"),f=(p.day()-h+7)%7;return l(p.subtract(f,"days").valueOf())}let g=/^(\d+)\s*([dwmy])$/.exec(o);if(g){let p=parseInt(g[1],10),u={d:"days",w:"weeks",m:"months",y:"years"}[g[2]];return l(Ct().subtract(p,u).startOf("day").valueOf())}let I=Ct(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return I.isValid()?l(I.startOf("day").valueOf()):null}function rr(c){let r={text:[],filters:{}},t=(c||"").trim();if(!t)return r;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")r.filters.in=o.toLowerCase();else if(n==="before"){let a=go(o);a!=null&&(r.filters.before=a)}else if(n==="after"){let a=go(o);a!=null&&(r.filters.after=a)}else if(n==="on"){let a=go(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))r.filters.on={start:a-6e4,end:a+6e4};else{let A=Ct(a).startOf("day").valueOf();r.filters.on={start:A,end:A+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&r.text.push(n.toLowerCase());return r}var Wt=class c extends ht.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!==F?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===F&&this.notes.push({node:a,title:i,body:""});for(let l of this.tree.getChildren(n))s(l.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(F))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=rr(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=Q=>C.every(E=>Q.toLowerCase().includes(E)),B=Q=>{if(!o.has(Q)){o.add(Q);for(let E of this.tree.getChildren(Q))B(E.id)}};for(let Q of this.notes)!Q.node||Q.cross||m(Q.title)&&B(Q.node.id);let y=new Map;for(let Q of this.notes){if(!Q.cross)continue;let E=y.get(Q.cross.folder)??[];E.push(Q),y.set(Q.cross.folder,E)}for(let[Q,E]of y){let v=new Map;for(let N of E){let P=N.cross?.parentId??null;if(!P)continue;let H=v.get(P)??[];H.push(N.cross.id),v.set(P,H)}let w=new Set;a.set(Q,w);let D=N=>{if(!w.has(N)){w.add(N);for(let P of v.get(N)??[])D(P)}};for(let N of E)m(N.title)&&D(N.cross.id)}}let l=C=>{let m=i.filters;if(o||a)if(C.cross){let B=a?.get(C.cross.folder);if(!B||!B.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 B=this.createdMsFor(C);if(B==null||m.before!=null&&B>=m.before||m.after!=null&&B<=m.after||m.on&&(B<m.on.start||B>=m.on.end))return!1}return!0},A=C=>n(C.toLowerCase()),d=this.notes.filter(C=>!C.cross),h=this.notes.filter(C=>C.cross),g=(C,m)=>({id:C.cross?`cross:${C.cross.folder}:${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,crossId:C.cross?.id}),I=C=>{let m=[];for(let B of C)if(l(B))if(this.opts.mode==="search"){if(!e){m.push(g(B,-1));continue}let y=n(B.title.toLowerCase()),Q=B.body.split(/\r?\n/),E=[];for(let w=0;w<Q.length;w++)A(Q[w])&&E.push(w);let v=E.length>0||n(B.body.toLowerCase());if(!y&&!v)continue;if(E.length===0)m.push(g(B,-1));else{let w=[],D=-100;for(let P of E)P-D>5&&w.push(P),D=P;let N=5;for(let P of w.slice(0,N))m.push(g(B,P))}}else{if(e&&!n(B.title.toLowerCase())&&!n(B.body.toLowerCase()))continue;m.push(g(B,-1))}return m},p=I(d),u=[...p];if(this.opts.mode==="search"?e?!0:p.length<10:!!e){let C=I(h);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(B=>{let y=B.split("/").pop()??B;return n(`${B.toLowerCase()} ${y.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=B=>B.kind==="note"&&(B.id===F||B.crossId===F)&&n(B.label.toLowerCase()),m=u.filter(C);if(m.length>0){let B=u.filter(y=>!C(y));u.splice(0,u.length,...m,...B)}}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(` +`)),await t()}))},["slug","stopwords","filename","title"])),i.foldersStorage.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 x.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 l of n)this.renderFolderScopeRow(a,l)}let o=null;new x.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 l=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new x.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(l),new x.Notice(`Created Stashpad "${l}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(l,2e3),this.update?.()}catch(A){new x.Notice(`Couldn't create: ${A.message}`)}}))},["search","scope","exclude","include","create","new","stashpad","folder"])),i.foldersStorage.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 x.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.composerCopy.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.windowsTabs.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.windowsTabs.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.composerCopy.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}encryptionItems(){let t=this.plugin.encryption,e=[];return e.push(this.sectionDef("Vault encryption","Set one password to encrypt content in this vault. Stored only on this device \u2014 there is no recovery if you lose it.",i=>{i.addClass("stashpad-encryption-section");let s=i.createDiv({cls:"stashpad-beta-row"});s.createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),s.createEl("span",{cls:"stashpad-beta-note",text:"Encryption is in beta \u2014 keep your own backups of anything important."}),i.createEl("div",{cls:"stashpad-ai-disclaimer"}).setText("\u26A0\uFE0F AI-built, NOT human-audited. This encryption was written by an AI assistant \u2014 not designed, reviewed, or security-audited by a human, and not tested by any security professional. It may carry real security, privacy, and DATA-LOSS risks. Treat it as a best-effort nice-to-have that might buy a little time against a casual snoop \u2014 nothing is guaranteed. Do NOT rely on it for anything sensitive, and always keep your own unencrypted backups of anything important."),i.createEl("p",{cls:"setting-item-description"}).setText("\u26A0\uFE0F Encryption protects what you lock in this vault. Each device unlocks with its own password (which never leaves the device); the vault key is shared with collaborators by approving their device \u2014 no shared password. If everyone with access loses their password, anything encrypted is gone for good. While encrypting, avoid a sync/cloud service writing the vault mid-operation \u2014 it can corrupt files.");let n=()=>t.argonProbe(),o=()=>this.plugin.settings.authorName?.trim()||"This device",a=t.accessState();t.refresh().then(()=>{t.accessState()!==a&&this.update?.()});let l=a;if(l==="none"){new x.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(g=>g.setButtonText("Set up password\u2026").setCta().onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:I,remember:p})=>{if(!I)return"Enter a password.";try{await t.setup(I,p,o())}catch(u){return u.message}return new x.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}if(l==="outsider"&&!t.isUnlocked()){t.hasSharedPassword()&&new x.Setting(i).setName("This vault is encrypted").setDesc("Enter the shared password (ask whoever set it up \u2014 they'll send it via a password manager or secure message).").addButton(g=>g.setButtonText("Unlock with shared password\u2026").setCta().onClick(()=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:I,remember:p})=>await t.unlock(I,p)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password (or the keyfile hasn't synced here yet)."}).open()})),new x.Setting(i).setName(t.hasSharedPassword()?"Or request device approval":"This vault is encrypted by a collaborator").setDesc("Request access \u2014 pick a password for THIS device, then ask an existing member to approve it. Once approved (and the keyfile syncs to you), you'll unlock with that password. No shared secret.").addButton(g=>g.setButtonText("Request access\u2026").onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:I,remember:p})=>{if(!I)return"Choose a password for this device.";try{await t.requestAccess(o(),I,p)}catch(u){return u.message}return new x.Notice("Access requested. An existing member can now approve this device."),this.update?.(),null}}).open()}));return}if(l==="pending"){new x.Setting(i).setName("Access requested \u2014 waiting for approval").setDesc("An existing member needs to approve this device. After they do and the keyfile syncs here, reopen this page to unlock with the password you chose.").addButton(g=>g.setButtonText("Try unlock now").setCta().onClick(()=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:I,remember:p})=>await t.unlock(I,p)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Not approved yet (or wrong password). Ask a member to approve this device, then try again."}).open()})).addButton(g=>g.setButtonText("Cancel request").onClick(async()=>{let I=t.myIdentityId();I&&await t.denyJoinRequest(I),new x.Notice("Access request cancelled."),this.update?.()}));return}let A=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",d=t.isRemembered()?" \xB7 remembered on this device":"";if(new x.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${A?` \xB7 ${A}`:""}${d}`),t.isUnlocked()?new x.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(g=>g.setButtonText("Lock now").onClick(()=>{t.lock(),new x.Notice("Encryption locked."),this.update?.()})):new x.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(g=>g.setButtonText("Unlock\u2026").setCta().onClick(()=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:I,remember:p})=>await t.unlock(I,p)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),t.keychainAvailable()&&t.isRemembered()&&new x.Setting(i).setName("Forget password on this device").setDesc("Drops ONLY the copy saved in this device's keychain \u2014 your encryption stays set up and nothing is decrypted or deleted. You'll just re-type the password next session. (To turn encryption off entirely, use \u201CRemove encryption\u201D below.)").addButton(g=>g.setButtonText("Forget on this device").onClick(async()=>{await t.forgetKeychain(),new x.Notice("Removed from this device's keychain \u2014 encryption still set up."),this.update?.()})),t.amIMember()&&new x.Setting(i).setName("Change this device's password").setDesc("Re-wraps THIS device's key under a new password \u2014 doesn't re-encrypt files or affect other people.").addButton(g=>g.setButtonText("Change\u2026").onClick(()=>{new vt(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:I,next:p,remember:u})=>await t.changePassword(I,p,u)?(new x.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),t.amIMember()&&new x.Setting(i).setName("Remove encryption").setDesc("Erases the key for this vault so you can start fresh. If anything is still encrypted, you'll be offered to decrypt it (needs your password) or \u2014 if you've lost the password \u2014 permanently delete it. Then just type the confirmation phrase; no password needed.").addButton(g=>{let I=async()=>{let p=await this.plugin.encryptionStateStrict();if(p.live){let f=()=>{new ot(this.app,"Delete all locked content forever?","This PERMANENTLY destroys every locked note and folder \u2014 there is NO decrypted copy and NO recovery. Only do this if you've lost the password and want to start fresh.","Delete locked content forever",async m=>{if(!m)return;let B=await this.plugin.purgeAllLockedContent();new x.Notice(`Deleted ${B} locked item${B===1?"":"s"}.`),I()}).open()},C=async()=>{if(await this.plugin.unlockAllInVault(),(await this.plugin.encryptionStateStrict()).live){new x.Notice("Some notes are still locked (decryption was cancelled or failed) \u2014 removal cancelled.",1e4);return}I()};new ot(this.app,"Encrypted notes are still locked",`Some notes or folders are still encrypted (locked) and have no plaintext copy. Before removing encryption: + +\u2022 Decrypt everything \u2014 unlock them back to normal notes (needs your password). +\u2022 Delete locked content \u2014 permanently destroy them (only if you've lost the password).`,"Decrypt everything",m=>{m?C():f()},"Delete locked content").open();return}let u=(f,C)=>{new Bi(this.app,{title:"Remove encryption?",body:`This erases the encryption key for this vault. No locked notes/folders exist, so your live content is safe.${f} You'll need to set a new password to encrypt again later, and anything previously exported with this key stays locked to its passphrase.`,phrase:"REMOVE ENCRYPTION",confirmText:"Remove encryption",onConfirm:async()=>{let m=await this.plugin.encryptionStateStrict();if(m.live){new x.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}if(m.trash&&!C){new x.Notice("Encrypted trash appeared while this dialog was open \u2014 removal cancelled. Re-open Remove encryption to handle it.",1e4);return}let B=await this.plugin.listDeletedTrash();for(let y of B)await this.plugin.purgeDeletedAt(y.blob);await t.clear(),new x.Notice("Encryption removed."),this.update?.()}}).open()};if(p.trash){let f=async()=>{let m=await this.plugin.restoreAllTrash();if((await this.plugin.encryptionStateStrict()).trash){new x.Notice("Some encrypted-trash items couldn't be decrypted \u2014 removal cancelled. Check the trash tab and try again.",1e4);return}u(m>0?` (${m} trash item${m===1?"":"s"} were decrypted back to their folders.)`:"",!0)},C=()=>{new ot(this.app,"Discard encrypted trash?","The encrypted-trash items will be PERMANENTLY lost the moment the key is erased \u2014 there is no recovery. Continue?","Confirm",m=>{m&&u(" \u26A0\uFE0F The encrypted trash is being permanently discarded.",!0)}).open()};new ot(this.app,"Encrypted notes in the trash",`There are encrypted, deleted notes in the trash. Removing encryption makes them PERMANENTLY unreadable. + +\u2022 Decrypt Trash \u2014 restore them to their original folders first (recommended). +\u2022 Discard trash \u2014 let them be permanently erased with the key.`,"Decrypt Trash",m=>{m?f():C()},"Discard trash").open();return}u("",!1)};g.setButtonText("Remove\u2026").onClick(()=>void I()),g.buttonEl.addClass("mod-warning")}),new x.Setting(i).setName("Sharing").setHeading(),t.isUnlocked()?t.hasSharedPassword()?new x.Setting(i).setName("Shared password").setDesc("ON \u2014 anyone who knows it can unlock this vault (no approval). Share it via a password manager or secure message; don't send it in the clear.").addButton(g=>g.setButtonText("Change\u2026").onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Change shared password",intro:"Everyone who unlocks with the shared password will need the new one. Re-share it securely after changing.",onSubmit:async({next:I})=>{if(!I)return"Enter a password.";try{await t.setSharedPassword(I)}catch(p){return p.message}return new x.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(g=>{g.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new x.Notice("Shared password turned off."),this.update?.()}),g.buttonEl.addClass("mod-warning")}):new x.Setting(i).setName("Shared password").setDesc("OFF \u2014 set one passphrase that everyone types to unlock (the simplest way to share). Anyone who knows it can unlock; turning it off later doesn't claw back copies already synced elsewhere.").addButton(g=>g.setButtonText("Set shared password\u2026").onClick(()=>{new vt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Set shared password",intro:"One passphrase everyone types to unlock this vault. Anyone who knows it gets in \u2014 share it ONLY through a password manager or secure message, never in the clear. You can turn it off later.",onSubmit:async({next:I})=>{if(!I)return"Enter a password.";try{await t.setSharedPassword(I)}catch(p){return p.message}return new x.Notice("Shared password set \u2014 share it securely with your collaborators."),this.update?.(),null}}).open()})):i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to manage how this vault is shared."),new x.Setting(i).setName("Collaborators (device approval)").setHeading(),i.createEl("p",{cls:"setting-item-description"}).setText("Everyone who can unlock this vault, and devices waiting for access. Approving a request shares the vault key with that device \u2014 it never sees a password. Removing a member revokes future access (existing synced copies they already hold aren't clawed back \u2014 rotate the key for that, a future feature)."),new x.Setting(i).setName("Synced from the vault keyfile").addButton(g=>g.setButtonText("Refresh").onClick(async()=>{await t.refresh(),this.update?.()})),!t.isUnlocked())i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to approve or remove collaborators.");else{let g=t.myIdentityId();for(let p of t.members()){let u=p.id===g,f=new x.Setting(i).setName(`${p.label}${u?" \u2014 this device":""}`).setDesc(u?"You":"Member");u||f.addButton(C=>{C.setButtonText("Remove").onClick(async()=>{await t.removeMember(p.id),new x.Notice(`Removed ${p.label}. (Not full revocation without rotating the key.)`),this.update?.()}),C.buttonEl.addClass("mod-warning")})}let I=t.pendingJoinRequests();if(I.length===0)i.createEl("p",{cls:"setting-item-description"}).setText("No pending access requests.");else for(let p of I)new x.Setting(i).setName(p.label).setDesc("Wants access to this vault").addButton(u=>u.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(p.id)}catch(f){new x.Notice(f.message);return}new x.Notice(`Approved ${p.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(u=>u.setButtonText("Deny").onClick(async()=>{await t.denyJoinRequest(p.id),new x.Notice("Request denied."),this.update?.()}))}},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private","collaborator","share","team","member","approve"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{this.plugin.settings.encryptTrash=n,await this.plugin.saveSettings()})),["trash","delete","encrypt"])),e.push(this.renderDef("Encrypt trash filenames","Hide the filename + origin folder of encrypted-trashed items (opaque names on disk; shown under \u201CHidden\u201D in the trash tab). Default OFF so you can still tell what to restore when working outside the app.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFilenames).onChange(async n=>{this.plugin.settings.encryptTrashFilenames=n,await this.plugin.saveSettings()})),["trash","filename","encrypt"])),e.push(this.renderDef("Follow Obsidian's trash setting instead","OFF (recommended): encrypted-deleted notes go to Stashpad's own \u201C_deleted/\u201D store \u2014 the only trash location Stashpad fully controls, so it can encrypt, list, and restore them. ON: deletes follow Obsidian's \u201CDeleted files\u201D setting instead (system/OS trash or permanent). \u26A0\uFE0F Stashpad CANNOT encrypt or recover notes that go to the system trash \u2014 so the encrypted trash + recoverable trash view won't apply. Only turn this on if you specifically want Obsidian's native trash behavior.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFollowObsidian??!1).onChange(async n=>{this.plugin.settings.encryptTrashFollowObsidian=n||void 0,await this.plugin.saveSettings()})),["trash","obsidian","system","delete","encrypt"])),e.push(this.renderDef("Auto-lock after idle minutes","Forget the password from memory after this many idle minutes (0 = never). Re-prompts on the next encryption action.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.encryptionIdleLockMinutes??0)).onChange(async n=>{let o=Math.max(0,Math.floor(Number(n)||0));this.plugin.settings.encryptionIdleLockMinutes=o,await this.plugin.saveSettings()})),["auto-lock","idle","timeout","lock"])),e.push(this.renderDef("Hide titles of locked notes","Show a generic label on \u{1F512} locked placeholders instead of the note's title, so a glance at the vault doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.renderDef("Default archive folder",`Where the "Move selection to archive" command sends notes (they're auto-encrypted on arrival). Leaving this blank is fine \u2014 the command will just show you a list of your archive folders to pick from each time (or use the only one if you have a single archive). Mark a folder as an archive via the folder panel \u2192 right-click \u2192 "Mark as archive".`,i=>{let s=this.plugin.settings.archiveFolders??[];i.addDropdown(n=>{n.addOption("",s.length?"\u2014 pick from list each time \u2014":"\u2014 no archive folders yet \u2014");for(let a of s)n.addOption(a,a);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async a=>{this.plugin.settings.defaultArchiveFolder=a||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e}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=Ze.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=new x.Setting(t).setName("JD Index Builder").setHeading();e.settingEl.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 x.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(l=>{l.addOption("vault","Entire vault"),l.addOption("folder","Single folder"),l.setValue(this.plugin.settings.jdIndexScope??"vault"),l.onChange(async A=>{this.plugin.settings.jdIndexScope=A==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new x.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(l=>{new ze(this.app,l.inputEl),l.setPlaceholder("Path/To/Folder"),l.setValue(this.plugin.settings.jdIndexScopeFolder??""),l.onChange(async A=>{this.plugin.settings.jdIndexScopeFolder=(A||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new x.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(l=>{l.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),l.onChange(async A=>{this.plugin.settings.jdIndexIncludeStashpadFolders=A,await this.plugin.saveSettings(),this.display()})}),new x.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(l=>{new ze(this.app,l.inputEl),l.setPlaceholder(s[0]??"(pick a Stashpad folder)"),l.setValue(this.plugin.settings.jdIndexStashpadFolder??""),l.onChange(async A=>{this.plugin.settings.jdIndexStashpadFolder=(A||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new x.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(l=>{l.addOption("natural","Natural (numeric \u2192 alphabetical)"),l.addOption("created","By creation time"),l.setValue(this.plugin.settings.jdIndexSort??"natural"),l.onChange(async A=>{this.plugin.settings.jdIndexSort=A==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=$e(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 x.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(l=>{l.setButtonText("Preview"),l.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),l.onClick(async()=>{try{let A=await as(this.app,this.plugin,this.plugin.settings);if(A.error==="no-dest"){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(A.error==="no-home"){new x.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}rs(this.app,A),this.display()}catch(A){console.error("[stashpad] preview failed",A),new x.Notice(`Preview failed: ${A?.message??A}`,8e3)}})}).addButton(l=>{l.setButtonText("Build Stashpad notes"),l.setCta(),l.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),l.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Fi(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let h=await En(this.app,this.plugin,this.plugin.settings);if(h.error==="no-dest"){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(h.error==="dest-not-stashpad"){new x.Notice(`"${h.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 x.Notice(`Built: ${h.created} created, ${h.updated} updated, ${h.skipped} skipped \u2192 ${h.destFolder}`,6e3),this.display()}catch(h){console.error("[stashpad] build failed",h),new x.Notice(`Build failed: ${h?.message??h}`,8e3)}}).open()})}).addButton(l=>{l.setButtonText(`Reveal in ${wl()}`),l.setTooltip("Open the designated Stashpad folder in your OS file browser."),l.onClick(async()=>{let A=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!A){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(A)){new x.Notice(`Folder "${A}" doesn't exist yet.`,5e3);return}try{let h=this.app.vault.adapter.basePath;if(h){let{shell:g}=window.require?.("electron")??{},I=`${h}/${A}`;g?.openPath?.(I)}else new x.Notice("Reveal in file system not supported on this platform.",4e3)}catch(h){new x.Notice(`Couldn't open folder: ${h?.message??h}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new x.Setting(t).setName("Color aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=ne()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new x.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(h=>[h.hex,h.count])),l=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},A=new Set([...a.keys(),...Object.keys(l)]);if(A.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 d=[...A].map(h=>({hex:h,count:a.get(h)??0}));d.sort((h,g)=>g.count-h.count||h.hex.localeCompare(g.hex));for(let h of d)this.renderColorAliasRow(s,i,h.hex,h.count,n)};n()}authorshipItems(){let t=[];t.push(this.renderDef("Author name","Your display name. Used in the note footer + as the author/contributor link target. Leave blank to opt out (notes won't be stamped).",i=>i.addText(s=>s.setValue(this.plugin.settings.authorName).onChange(async n=>{this.plugin.settings.authorName=n.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=tt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["author","name","identity","stamp"])),t.push(this.renderDef("Author id (auto-assigned)","Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. To reset it, clear and retype your author name.",i=>i.addText(s=>s.setValue(this.plugin.settings.authorId).setDisabled(!0)),["author","id"])),t.push(this.renderDef("Title / role",'Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorRole).onChange(async n=>{this.plugin.settings.authorRole=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["role","title","job"])),t.push(this.renderDef("Department / team",'Optional. Shown on your author page (e.g. "Engineering", "Growth").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorDepartment).onChange(async n=>{this.plugin.settings.authorDepartment=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["department","team"]));let e=(i,s,n,o)=>this.renderDef(i,"",a=>a.addToggle(l=>l.setValue(s()).onChange(async A=>{n(A),await this.plugin.saveSettings()})),o);return t.push(e("Show author in note footer",()=>this.plugin.settings.showAuthor,i=>{this.plugin.settings.showAuthor=i},["author","footer","show"])),t.push(e("Show contributors in note footer",()=>this.plugin.settings.showContributors,i=>{this.plugin.settings.showContributors=i},["contributors","footer","show"])),t.push(e("Show last edit time in note footer",()=>this.plugin.settings.showLastEdit,i=>{this.plugin.settings.showLastEdit=i},["last edit","modified","footer","time"])),t.push(this.sectionDef("Folders you've worked in","Folders where you've authored or contributed notes. Click one to open it.",i=>this.renderAuthoredFolders(i),["folders","authored","contributed","worked"])),t.push(this.sectionDef("Known authors","Everyone the plugin has seen, with role/department + rename history; rebuild/restore the registry.",i=>this.renderKnownAuthorsSection(i),["authors","registry","rename","known","rebuild"])),t}renderAuthoredFolders(t){let e=this.plugin.collectAuthoredFolders();if(e.length===0){t.createEl("p",{cls:"setting-item-description",text:"No authored or contributed folders yet."});return}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=l=>{l.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(", ")}`})}}templatesItems(){return[this.sectionDef("Color aliases","Give your note colors friendly names, per Stashpad folder.",t=>this.renderColorAliasesSection(t),["color","colour","alias","name","swatch","palette","label"]),this.sectionDef("Note templates","Per-Stashpad note templates \u2014 content stamped into new notes.",t=>this.renderNoteTemplatesSection(t),["template","note","default","boilerplate","snippet"])]}jdIndexItems(){return[this.sectionDef("JD Index (Johnny Decimal)","Build a Johnny-Decimal-style index from dotted-prefix note titles \u2014 set the scope, preview, then build.",t=>this.renderJdIndexSection(t),["jd","johnny","decimal","index","scope","build","preview","hierarchy","folder"])]}okfItems(){return[this.sectionDef("Open Knowledge Format (OKF)","Turn a Stashpad folder into a browsable OKF bundle \u2014 markdown concept files with OKF frontmatter, a generated index.md, and relative-markdown cross-links \u2014 that LLMs/agents can read. Complements (never replaces) Stashpad's own frontmatter and links.",t=>this.renderOkfSection(t),["okf","open knowledge format","knowledge","catalog","index","export","bundle","tarball","agent","google"])]}appendCode(t,e){e.split(/`([^`]+)`/g).forEach((i,s)=>{s%2===1?t.createEl("code",{text:i}):i&&t.appendText(i)})}codeDesc(t){let e=document.createDocumentFragment();return this.appendCode(e,t),e}renderOkfSection(t){if(t.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),new x.Setting(t).setName("Enable OKF").setDesc(this.codeDesc("Master switch. When on, you choose which folders use OKF by assigning the OKF template to them in Settings \u2192 Templates (all / some / none \u2014 your call). Those folders then get OKF frontmatter and a maintained `index.md`. Turning this off leaves existing OKF files in place; it just stops maintaining them.")).addToggle(i=>i.setValue(this.plugin.settings.okfEnabled).onChange(async s=>{if(this.plugin.settings.okfEnabled=s,await this.plugin.saveSettings(),s)try{await this.plugin.ensureOkfTemplate()}catch(n){console.warn("[Stashpad] OKF template create failed",n)}new x.Notice(s?`OKF on. Next: assign the template "${this.plugin.okfTemplatePathOrDefault()}" to a folder \u2014 use \u201CCreate template + open Templates\u201D below. Heads-up: OKF frontmatter + index.md refresh automatically but NOT instantly (a few seconds after changes); hit Rebuild for an immediate pass.`:"OKF disabled.",s?0:4e3),this.update?.()})),this.plugin.settings.okfEnabled){let i=this.plugin.okfTemplatePathOrDefault(),s=this.plugin.okfActiveFolders().length,n=t.createEl("div",{cls:"setting-item-description stashpad-okf-howto"});n.createEl("p",{text:"How to use OKF in a folder:"});let o=n.createEl("ol");if(this.appendCode(o.createEl("li"),`Open Templates and set a folder's template to \`${i}\` (archive folders are skipped).`),this.appendCode(o.createEl("li"),"Hit Rebuild below to write OKF frontmatter (`okfParent`/`okfChildren` + `okfType`/`okfTitle`/`okfTimestamp`) and generate that folder's `index.md`."),this.appendCode(o.createEl("li"),"Right-click a note (or a selection) \u2192 \u201CExport as OKF\u2026\u201D to save a `.zip` / `.tar.gz` bundle (or `.stash`)."),n.createEl("p",{cls:"stashpad-okf-soon",text:"OKF frontmatter + index.md refresh automatically a few seconds after you add, move, or delete notes \u2014 NOT instantly. Use Rebuild for an immediate pass."}),s===0){let a=t.createEl("p",{cls:"stashpad-okf-cta"});this.appendCode(a,"\u{1F449} No folder is using OKF yet. Click \u201CCreate template + open Templates\u201D below, then set a folder's template to `"+i+"`.")}else n.createEl("p",{cls:"stashpad-okf-soon",text:`Currently ${s} folder${s===1?"":"s"} actively using OKF.`});new x.Setting(t).setName("Assign OKF to folders").setDesc(this.codeDesc(`Creates the OKF template if needed (never duplicates it), then opens Templates \u2014 set a folder's template to \`${i}\` there.`)).addButton(a=>{a.setButtonText("Create template + open Templates").setCta(),a.onClick(async()=>{let l;try{l=await this.plugin.ensureOkfTemplate()}catch(A){new x.Notice(`Couldn't create the OKF template: ${A.message}`);return}new x.Notice(`OKF template ready at "${l}" \u2014 set a folder's template to that path.`),this.update?.(),this.openSettingsPage("Templates")})}),new x.Setting(t).setName("Rebuild OKF frontmatter").setDesc(this.codeDesc("Write/refresh OKF fields for every folder using the OKF template \u2014 `okfParent`/`okfChildren` relative links (managed) plus `okfType`/`okfTitle`/`okfTimestamp` defaults (yours to edit after). Heads-up: adding, moving, or deleting notes already auto-refreshes the folder, but NOT instantly \u2014 it waits ~a few seconds after you stop. Use this button for an immediate rebuild (e.g. right after first assigning the template). Complements Stashpad's own links; nothing is removed.")).addButton(a=>a.setButtonText("Rebuild now").onClick(async()=>{let l=await this.plugin.rebuildAllOkf();new x.Notice(l.folders===0?"No folders use the OKF template yet \u2014 assign it in Templates first.":`OKF: updated ${l.written} of ${l.checked} notes across ${l.folders} folder${l.folders===1?"":"s"}.`),this.update?.()}))}let e=new x.Setting(t).setName("Learn about OKF").setDesc("Google's open, vendor-neutral spec for sharing curated knowledge with agents.");e.addButton(i=>i.setButtonText("Spec / repo").onClick(()=>window.open("https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf"))),e.addButton(i=>i.setButtonText("Announcement").onClick(()=>window.open("https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing/")))}openSettingsPage(t){let e=()=>new x.Notice(`Open Settings \u2192 Stashpad \u2192 ${t}.`);try{let i=this.app.setting;if(!i?.openTabById){e();return}i.openTabById("stashpad"),window.setTimeout(()=>{let s=i.modalEl?.querySelector(".vertical-tab-content");if(!s){e();return}let o=Array.from(s.querySelectorAll("*")).find(a=>a.childElementCount===0&&a.textContent?.trim()===t&&!a.closest(".vertical-tab-header"))?.closest("[class*='nav'], .setting-item, button, a");o&&!o.closest(".vertical-tab-header")?o.click():e()},60)}catch{e()}}renderAuthorshipSection(t){new x.Setting(t).setName("Authorship").setHeading(),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 x.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=tt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new x.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 x.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 x.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 x.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 x.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 x.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){new x.Setting(t).setName("Folders you've worked in").setHeading();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=l=>{l.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){new x.Setting(t).setName("Known authors (registry)").setHeading(),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 x.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 x.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new x.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 x.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new x.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 l=n.createDiv({cls:"stashpad-known-author-history"}),A=s.renames.map(d=>`${d.from} \u2192 ${d.to}`).join(", ");l.setText(`Renamed: ${A}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;if(new x.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."),this.plugin.settings.okfEnabled){let n=this.plugin.okfTemplatePathOrDefault();this.appendCode(t.createEl("p",{cls:"setting-item-description"}),`\u{1F4A1} OKF tip: type \`${n}\` into a folder's template field below to turn that folder into an OKF bundle (OKF frontmatter + a maintained \`index.md\`). Assign it to all, some, or none of your folders \u2014 it's per-folder. Manage OKF itself in Settings \u2192 OKF.`)}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 A=a.createDiv({cls:"stashpad-note-template-input-wrap"}),d=A.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});d.value=(this.plugin.settings.noteTemplates??{})[o]??"";let h=A.createDiv({cls:"stashpad-note-template-suggest"});h.setCssStyles({display:"none"});let g=[],I=[],p=-1,u=()=>h.style.display!=="none"&&g.length>0,f=w=>{p=w,I.forEach((D,N)=>D.toggleClass("is-active",N===w)),w>=0&&I[w]&&I[w].scrollIntoView({block:"nearest"})},C=()=>{h.setCssStyles({display:"none"}),p=-1},m=async w=>{d.value=w,await E(),C()},B=a.createDiv({cls:"stashpad-note-template-warn"});B.setCssStyles({display:"none"});let y=()=>this.app.vault.getMarkdownFiles().map(w=>w.path).filter(w=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(w)).sort(),Q=()=>{h.empty(),I=[];let w=d.value.trim().toLowerCase().split(/\s+/).filter(Boolean),D=N=>{let P=N.toLowerCase();return w.every(H=>P.includes(H))};if(g=y().filter(N=>D(N)).slice(0,12),g.length===0){C();return}h.setCssStyles({display:""}),g.forEach((N,P)=>{let H=h.createDiv({cls:"stashpad-note-template-suggest-item",text:N});I.push(H),H.addEventListener("mousemove",()=>f(P)),H.addEventListener("mousedown",async b=>{b.preventDefault(),await m(N)})}),p=p>=0&&p<g.length?p:-1,p>=0&&f(p)},E=async()=>{let w=d.value.trim(),D={...this.plugin.settings.noteTemplates??{}};w?D[o]=w:delete D[o],this.plugin.settings.noteTemplates=D,await this.plugin.saveSettings(),v()},v=()=>{B.empty(),B.setCssStyles({display:"none"});let w=d.value.trim();if(!w)return;let D=this.app.vault.getAbstractFileByPath(w);if(!D||D.extension!=="md"){B.setCssStyles({display:""}),B.setText(`\u26A0 "${w}" is not a markdown file in this vault.`);return}let N=this.app.metadataCache.getFileCache(D)?.frontmatter??{},H=Zt.filter(b=>{let S=N[b];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.length===0)});H.length!==0&&(B.setCssStyles({display:""}),B.setText(`\u26A0 Template defines ${H.join(", ")} \u2014 Stashpad always sets ${H.length===1?"this":"these"} on new notes, so the template value${H.length===1?"":"s"} will be ignored.`))};d.addEventListener("focus",Q),d.addEventListener("input",()=>{p=-1,Q()}),d.addEventListener("blur",()=>{setTimeout(C,150)}),d.addEventListener("change",()=>{E()}),d.addEventListener("keydown",w=>{if(w.key==="ArrowDown")w.preventDefault(),u()?f((p+1)%g.length):(Q(),g.length&&f(0));else if(w.key==="ArrowUp"){if(!u())return;w.preventDefault(),f((p-1+g.length)%g.length)}else if(w.key==="Enter")u()&&p>=0&&(w.preventDefault(),m(g[p]));else if(w.key==="Escape")u()&&(w.preventDefault(),C());else if(w.key==="Tab"&&!w.shiftKey){if(!u())return;let D=g[p>=0?p:0],N=d.value,P;if(D.toLowerCase().startsWith(N.toLowerCase())){let H=D.indexOf("/",N.length);P=H>=0?D.slice(0,H+1):D}else P=D;P&&P!==N&&(w.preventDefault(),d.value=P,p=-1,Q(),g.length===1&&f(0))}}),v()};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.setCssStyles({background:i}),a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let h=this.plugin.settings.customPalette??[];new Ne(this.app,i,h,async g=>{if((g??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(g&&g.toLowerCase()===i){n();return}let I=await this.plugin.recolorAllInFolder(e,i,g??null);if(I>0)new x.Notice(`Recolored ${I} note${I===1?"":"s"}.`);else if(s===0){let p=this.plugin.getColorAlias(e,i);p&&(await this.plugin.setColorAlias(e,i,""),g&&await this.plugin.setColorAlias(e,g,p))}n()},async g=>{let I=(this.plugin.settings.customPalette??[]).filter(p=>p.toLowerCase()!==g.toLowerCase());return this.plugin.settings.customPalette=I,await this.plugin.saveSettings(),I}).open()};let l=o.createDiv({cls:"stashpad-color-alias-meta"});l.createSpan({cls:"stashpad-color-alias-hex",text:i}),l.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let A=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});A.value=this.plugin.getColorAlias(e,i)??"",A.onchange=async()=>{await this.plugin.setColorAlias(e,i,A.value),!A.value.trim()&&s===0&&n()};let d=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});A.value||d.setCssStyles({visibility:"hidden"}),d.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(A.value="",d.setCssStyles({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),l=()=>{let d=a();n.toggleClass("is-right",d),n.setAttribute("aria-checked",String(d)),o.setText(d?"X":"\u2713"),s.setText(d?"Excluded":"Included"),s.toggleClass("is-excluded",d),n.title=d?"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."},A=async()=>{let d=new Set(this.plugin.settings.searchExcludedFolders??[]);d.has(e)?d.delete(e):d.add(e),this.plugin.settings.searchExcludedFolders=[...d].sort(),l(),await this.plugin.saveSettings()};n.onclick=()=>void A(),n.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),A())},l()}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 l=t.createDiv({cls:"stashpad-folder-list"});for(let A of a){let d=l.createDiv({cls:"stashpad-folder-row"});d.createSpan({cls:"stashpad-folder-row-label",text:A});let h=d.createEl("button",{text:o.action});h.onclick=()=>void n(A)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=I=>{let p=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=p.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=Si(i()[I]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=I==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{na(u,async Q=>{this.plugin.settings.bindings[e.id][I]=Q,u.value=Si(Q),f(),await this.plugin.saveSettings(),o(),y()})};let m=p.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][I]="",u.value="",f(),await this.plugin.saveSettings(),o(),y()};let B=p.createEl("button",{cls:"stashpad-binding-revert"});(0,x.setIcon)(B,"rotate-ccw");let y=()=>{let E=i()[I]!==C;B.toggleClass("is-hidden",!E),B.title=C?`Revert to default (${Si(C)})`:"Revert to default (no binding)"};return B.onclick=async()=>{this.plugin.settings.bindings[e.id][I]=C,u.value=Si(C),f(),await this.plugin.saveSettings(),o(),y()},y(),u};s=a("primary"),n=a("secondary");let l=t.controlEl.createDiv({cls:"stashpad-binding-pill"});l.setAttribute("role","switch"),l.setAttribute("tabindex","0");let A=l.createDiv({cls:"stashpad-binding-pill-knob"}),d=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),h=d.createEl("input",{type:"checkbox"});h.title="Use both bindings simultaneously (overrides the L/R toggle)",d.createSpan({text:"Use both"}),h.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=h.checked,await this.plugin.saveSettings(),o()},o=()=>{let I=i(),p=!!(I.primary&&I.secondary);h.checked=!!I.useBoth,h.disabled=!p,d.toggleClass("is-disabled",!p);let u=!!I.useBoth&&p;l.toggleClass("is-disabled",!p||u),l.toggleClass("is-right",I.preferRight),l.setAttribute("aria-checked",String(I.preferRight)),l.setAttribute("aria-disabled",String(!p||u)),A.setText(I.preferRight?"R":"L"),l.title=p?u?'Overridden by "Use both"':I.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let g=async()=>{let I=i();!I.primary||!I.secondary||(this.plugin.settings.bindings[e.id].preferRight=!I.preferRight,o(),await this.plugin.saveSettings())};l.onclick=()=>void g(),l.onkeydown=I=>{(I.key===" "||I.key==="Enter")&&(I.preventDefault(),g())},o()}};var je=class{constructor(r,t){this.app=r;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 r=this.detectTrigger();if(!r){this.close();return}this.openFor(r)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=r=>{r.key==="Escape"&&(!this.state||!this.items.length||(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),this.close()))};this.onKeyDown=r=>{!this.state||!this.items.length||(r.key==="ArrowDown"?(r.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):r.key==="ArrowUp"?(r.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):r.key==="Enter"||r.key==="Tab"?(r.preventDefault(),r.stopPropagation(),this.commit()):r.key==="Escape"&&(r.preventDefault(),r.stopPropagation(),r.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let r=this.ta.ownerDocument??document;r.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>r.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 r of this.vaultListeners)r();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let r=Z().inheritObsidianExclusions,t=r?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!To(i.path)&&!Ho(i.path)&&!(r&&Po(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 r=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=r.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(r){this.buildIndex();let t=r.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 r.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(r){if(this.state=r,this.items=this.buildItems(r),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let r=new ka.Scope(this.app.scope);r.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=r,this.app.keymap?.pushScope(r)}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 r=this.popupEl;r.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],i=r.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 r=this.popupEl.children;for(let e=0;e<r.length;e++)r[e].toggleClass("is-active",e===this.activeIdx);let t=r[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let r=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=r.top-t-4,i=r.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,r.width)}px`}commit(){if(!this.state||!this.items.length)return;let r=this.items[this.activeIdx];if(!r)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),i=r.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()}};lt();var vs=class extends Et.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 we}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?.()===J&&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?.()===J&&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 p=t.createDiv({cls:"stashpad-detail-empty"});(0,Et.setIcon)(p.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),p.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"}),l=a.createDiv({cls:"stashpad-detail-header"}),A=l.createDiv({cls:"stashpad-detail-titlerow"});A.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let d=A.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,Et.setIcon)(d,"arrow-up-right"),d.title="Open this note in a new Stashpad tab",d.onclick=()=>{this.openInStashpad(s.folder,s.id)};let h=l.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&h.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let p=h.createSpan({cls:"stashpad-detail-meta-color"});p.style.background=o.color,p.title=o.color}if(o.completed===!0&&h.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let p=Date.parse(String(o.due)),u=Number.isNaN(p)?String(o.due):_t(p,this.plugin.settings);h.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${u}`})}if(Array.isArray(o.tags))for(let p of o.tags.filter(u=>typeof u=="string"))h.createSpan({cls:"stashpad-detail-meta-tag",text:`#${p.replace(/^#/,"")}`});let g=a.createDiv({cls:"stashpad-detail-body"});try{let p=await this.app.vault.cachedRead(n),u=this.stripFrontmatter(p);await Et.MarkdownRenderer.render(this.app,u,g,n.path,this)}catch(p){g.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${p.message}`})}this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s);let I=this.composerInputEl;if(e&&I&&(I.focus(),i!=null)){let p=Math.min(i,I.value.length);try{I.setSelectionRange(p,p)}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,Et.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 je(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?.()!==J||typeof i.createNoteUnder!="function"){new Et.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new Et.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?.()!==J)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 l=a.createDiv({cls:"stashpad-detail-children-list"});for(let A of o)A.file&&this.renderDetailChildRow(l,s,n,e,A,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},l=typeof a.color=="string"?a.color:null,A=a.completed===!0,d=i.getChildren(n.id),h=d.length>0,g=`${s}|${n.id}`,I=this.expanded.has(g),p=t.createDiv({cls:"stashpad-detail-child-row"});A&&p.addClass("is-completed"),o>0&&(p.style.paddingLeft=`${o*16}px`),p.draggable=!0,p.dataset.id=n.id,p.addEventListener("dragstart",B=>{B.dataTransfer?.setData("text/plain",n.id),B.dataTransfer&&(B.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",B=>{B.preventDefault(),B.dataTransfer&&(B.dataTransfer.dropEffect="move");let y=p.getBoundingClientRect(),Q=B.clientY-y.top<y.height/2;p.toggleClass("drop-before",Q),p.toggleClass("drop-after",!Q)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",B=>{B.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let y=B.dataTransfer?.getData("text/plain");if(!y||y===n.id)return;let Q=p.getBoundingClientRect(),E=B.clientY-Q.top<Q.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([y],n.id,E?"before":"after")}),p.oncontextmenu=B=>{B.preventDefault();let y=i.get(n.id);y&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(B,y)};let u=p.createSpan({cls:"stashpad-detail-child-toggle"});if(h&&(de(u,d.length,I),u.onclick=B=>{B.stopPropagation(),this.expanded.has(g)?this.expanded.delete(g):this.expanded.add(g),this.render()}),Le(a,"task")||a.task===!0||a.completed!==void 0){let B=p.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Et.setIcon)(B,A?"check-square":"square"),B.title=A?"Mark not done":"Mark done",B.addEventListener("mousedown",y=>y.stopPropagation()),B.addEventListener("dblclick",y=>{y.preventDefault(),y.stopPropagation()}),B.onclick=y=>{y.preventDefault(),y.stopPropagation();let Q=i.get(n.id);Q&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(Q)}}let C=p.createSpan({cls:"stashpad-detail-child-icon"});(0,Et.setIcon)(C,h?"folder-tree":"file-text"),l&&(C.style.color=l);let m=p.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},h&&I)for(let B of d)this.renderDetailChildRow(t,e,i,s,B,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(l=>typeof l=="string").map(l=>this.stripWikiLink(l));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 l=n.createDiv({cls:"stashpad-detail-meta-line"});l.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),l.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)?_t(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==F&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new Et.Notice(`Couldn't open: ${i.message}`)}}};async function Fs(c){let r=c.workspace.getLeavesOfType(we);if(r.length>0){c.workspace.revealLeaf(r[0]);return}let t=c.workspace.getRightLeaf(!1);if(!t){new Et.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:we,active:!0}),c.workspace.revealLeaf(t)}var k=require("obsidian");lt();var Ie=require("obsidian");lt();function Fl(c,r){let t=c.vault.getAbstractFileByPath(r);if(!(t instanceof Ie.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof Ie.TFile?n.extension==="md"&&e.push(n):n instanceof Ie.TFolder&&(ci.has(n.name)||i.push(n))}return e}var ks=class{constructor(r){this.app=r;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(F,{id:F,parent:null,children:[],file:null,created:""})}setOrderProvider(r){this.orderProvider=r}onChange(r){return this.listeners.add(r),()=>this.listeners.delete(r)}emit(){for(let r of this.listeners)r()}rebuild(r){r!==void 0&&(this.currentFolder=r);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(F,{id:F,parent:null,children:[],file:null,created:""});let s=t?Fl(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 A=e.get(n.path),d=A?i.get(A):void 0,h=this.synthetic.get(n.path),g=d??h;g&&(this.nodes.set(g.id,{...g,children:[],file:n}),this.byPath.set(n.path,g.id));continue}if(this.synthetic.delete(n.path),a===F){let A=this.nodes.get(F);A.file=n,A.created=o?.created??"",this.byPath.set(n.path,F);continue}let l=o?.parent??null;l===a&&(l=null),this.nodes.set(a,{id:a,parent:l??F,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===F)continue;let o=n.parent??F;(this.nodes.get(o)??this.nodes.get(F)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let l=this.nodes.get(o),A=this.nodes.get(a);return(l.created||"").localeCompare(A.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((l,A)=>a.set(l,A)),n.children.sort((l,A)=>{let d=a.has(l)?a.get(l):1/0,h=a.has(A)?a.get(A):1/0;return d===h?0:d-h})}}this.emit()}insertSynthetic(r){if(!r.file)return;let t=r.file.path;this.synthetic.set(t,r),this.nodes.set(r.id,r),this.byPath.set(t,r.id);let e=r.parent??F,i=this.nodes.get(e);i&&!i.children.includes(r.id)&&i.children.push(r.id),this.emit()}get(r){return this.nodes.get(r)}getRoot(){return this.nodes.get(F)}getChildren(r){let t=this.nodes.get(r);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let r=0;for(let t of this.nodes.values())t.file&&r++;return r}pathTo(r){let t=[],e=new Set,i=this.nodes.get(r);for(;i&&i.id!==F&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(r){return this.byPath.get(r)}snapshot(){let r={};for(let t of this.nodes.values())t.id===F||!t.file||(r[t.id]={parent:t.parent===F?null:t.parent,path:t.file.path});return r}hookMetadataCache(r){let t=l=>{let A=this.currentFolder;return A?typeof l!="string"?!1:l===A||l.startsWith(A+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),r())},16))},s=l=>{l instanceof Ie.TFile&&t(l.path)&&l.extension==="md"&&(this.applyChange(l),i())},n=l=>{l instanceof Ie.TFile&&t(l.path)&&l.extension==="md"&&this.applyChange(l)&&i()},o=l=>{let A=l?.path;typeof A=="string"&&t(A)&&this.applyDelete(A)&&i()},a=(l,A)=>{if(!(l instanceof Ie.TFile))return;let d=typeof A=="string"?A:null;!t(l.path)&&!t(d)||this.applyRename(l,d??"")&&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(r){if(qe(r.path))return this.byPath.has(r.path)?this.applyDelete(r.path):!1;let t=this.app.metadataCache.getFileCache(r)?.frontmatter,e=t?.id,i=this.byPath.get(r.path);if(!e){if(i){let A=this.nodes.get(i);if(A&&A.file!==r)return A.file=r,!0}return!1}if(this.synthetic.delete(r.path),e===F){let A=this.nodes.get(F),d=t?.created??"",h=!1;return A.file!==r&&(A.file=r,h=!0),A.created!==d&&(A.created=d,h=!0),this.byPath.get(r.path)!==F&&(this.byPath.set(r.path,F),h=!0),h}let s=t?.parent??F,n=t?.created??"";if(!(s===F||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 A={id:e,parent:s,children:[],file:r,created:n};return this.nodes.set(e,A),this.byPath.set(r.path,e),this.attachToParent(A),this.resortChildrenOf(s),!0}let l=!1;if(a.file!==r&&(a.file=r,l=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??F),l=!0),a.parent!==s){let A=a.parent??F;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(A),this.resortChildrenOf(s),l=!0}return l}applyDelete(r){let t=this.byPath.get(r);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(r),this.synthetic.delete(r),!0;this.detachFromParent(e);let i=this.nodes.get(F);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=F,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(F),this.nodes.delete(t),this.byPath.delete(r),this.synthetic.delete(r),!0}applyRename(r,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||r.path===e||r.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(r);if(qe(r.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(r);this.byPath.delete(t),this.byPath.set(r.path,n);let o=this.nodes.get(n);return o&&(o.file=r),!0}detachFromParent(r){let t=this.nodes.get(r.parent??F);if(!t)return;let e=t.children.indexOf(r.id);e>=0&&t.children.splice(e,1)}attachToParent(r){let t=this.nodes.get(r.parent??F);t||(t=this.nodes.get(F)),t.children.includes(r.id)||t.children.push(r.id)}resortChildrenOf(r){let t=this.nodes.get(r);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(r);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 zn=class{constructor(){this.enabled=!1;this.buckets=new Map}record(r,t){if(!this.enabled)return;let e=this.buckets.get(r);e||(e={count:0,total:0,max:0},this.buckets.set(r,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(r,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(r,performance.now()-e)}}async timeAsync(r,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(r,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let r=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(r.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 r)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` +`)}},wt=new zn;var Sa=".stashpad-order.json",_e=class{constructor(r){this.app=r;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(r){if(this.cache.has(r))return this.cache.get(r);let t=`${r}/${Sa}`,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(l=>typeof l=="string")&&(i[o]=a)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(r,i),i}async save(r){this.scheduleWrite(r)}async flush(r){let t=this.pendingTimers.get(r);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(r)),await this.writeNow(r)}scheduleWrite(r){let t=this.pendingTimers.get(r);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(r),this.writeNow(r)},150);this.pendingTimers.set(r,e)}async writeNow(r){let e=(this.writeInFlight.get(r)??Promise.resolve()).then(()=>this.doWrite(r));this.writeInFlight.set(r,e);try{await e}finally{this.writeInFlight.get(r)===e&&this.writeInFlight.delete(r)}}async doWrite(r){let t=this.cache.get(r)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(r,e);let i=`${r}/${Sa}`,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(r,t){return this.cache.get(r)?.[t]?.slice()??[]}setOrder(r,t,e){let i=this.cache.get(r)??{};i[t]=e.slice(),this.cache.set(r,i)}appendChild(r,t,e){let i=this.cache.get(r)??{},s=i[t]??[];s.includes(e)||s.push(e),i[t]=s,this.cache.set(r,i)}removeChild(r,t){let e=this.cache.get(r);if(e)for(let i of Object.values(e)){let s=i.indexOf(t);s>=0&&i.splice(s,1)}}invalidate(r){this.cache.delete(r)}};var Ui={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"},Vn=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],kl=new Set(Vn),Da=".stashpad-sort.json",Ss=class{constructor(r){this.app=r;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(r){if(this.cache.has(r))return this.cache.get(r);let t=`${r}/${Da}`,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"&&kl.has(o)&&(i[n]=o)}}catch(s){console.warn("Stashpad: sort load failed",s)}return this.cache.set(r,i),i}async save(r){this.scheduleWrite(r)}async flush(r){let t=this.pendingTimers.get(r);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(r)),await this.writeNow(r)}scheduleWrite(r){let t=this.pendingTimers.get(r);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(r),this.writeNow(r)},150);this.pendingTimers.set(r,e)}async writeNow(r){let e=(this.writeInFlight.get(r)??Promise.resolve()).then(()=>this.doWrite(r));this.writeInFlight.set(r,e);try{await e}finally{this.writeInFlight.get(r)===e&&this.writeInFlight.delete(r)}}async doWrite(r){let t=this.cache.get(r)??{},e=`${r}/${Da}`,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(r,t){return this.cache.get(r)?.[t]??"manual"}setMode(r,t,e){let i=this.cache.get(r)??{};e==="manual"?delete i[t]:i[t]=e,this.cache.set(r,i)}removeParent(r,t){let e=this.cache.get(r);e&&delete e[t]}invalidate(r){this.cache.delete(r)}};lt();var ue="parentLink",ti="children";var Ns=class Ns{constructor(r,t){this.app=r;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(r){return this.activityListeners.add(r),()=>this.activityListeners.delete(r)}emitActivity(){let r=this.pending.size;for(let t of this.activityListeners)try{t(r)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(r){if(!r||!Z().writeRecoveryLinks)return;let t=this.pending.size;this.pending.add(r),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(r,t,e){this.schedule(r),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(r){let t=this.getTree(),e=i=>{this.schedule(i);for(let s of t.getChildren(i))e(s.id)};e(r)}scheduleParentOfDeleted(r){r&&this.schedule(r)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let r=this.pending.values().next().value;if(r===void 0)break;this.pending.delete(r),this.emitActivity(),await this.syncOne(r)}}pendingCount(){return this.pending.size}onError(r){return this.errorListeners.add(r),()=>this.errorListeners.delete(r)}emitError(r,t){for(let e of this.errorListeners)try{e(r,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(),Ns.PACING_MS))}async tick(){this.timer=null;let r=this.pending.values().next().value;if(r!==void 0){this.pending.delete(r),this.emitActivity();try{await this.syncOne(r)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(r){let e=this.getTree().get(r);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[ue]=="string"?n[ue]:null,a=n?.[ti],l=Array.isArray(a)?a.filter(A=>typeof A=="string"):[];if((o??null)!==(i??null)||l.length!==s.length)return!0;for(let A=0;A<l.length;A++)if(l[A]!==s[A])return!0;return!1}async syncOne(r){let e=this.getTree().get(r);if(!e||!e.file||!this.wouldWrite(r))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await wt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[ue]=i:delete n[ue],s.length>0?n[ti]=s:delete n[ti]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(r){if(r.id===F)return null;let t=this.getTree();if(!r.parent||r.parent===F){let i=t.getRoot();return i&&i.id!==r.id&&i.file?Ds(i.file.path):null}let e=t.get(r.parent);return e?.file?Ds(e.file.path):null}computeChildrenLinks(r){return this.getTree().getChildren(r.id).filter(e=>!!e.file).map(e=>Ds(e.file.path))}};Ns.PACING_MS=100;var bs=Ns;async function ei(c,r){let t=r.endsWith("/")?r:r+"/",e=new Map,i=new Map;for(let A of c.vault.getMarkdownFiles()){if(A.path!==r&&!A.path.startsWith(t))continue;let d=c.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id:null;if(!h)continue;let g=typeof d?.parent=="string"?d.parent:F;e.set(h,{file:A,id:h,parent:g});let I=i.get(g)??[];I.push(h),i.set(g,I)}let s=A=>Ds(A.file.path),n=A=>{if(A.id===F)return null;if(A.parent===F||!A.parent){let h=e.get(F);return h?s(h):null}let d=e.get(A.parent);return d?s(d):null},o=A=>{let d=i.get(A.id)??[],h=[];for(let g of d){let I=e.get(g);I&&h.push(s(I))}return h},a=0,l=0;for(let A of e.values()){a+=1;let d=n(A),h=o(A),g=c.metadataCache.getFileCache(A.file)?.frontmatter,I=g&&typeof g[ue]=="string"?g[ue]:null,p=g?.[ti],u=Array.isArray(p)?p.filter(m=>typeof m=="string"):[],f=(I??null)===(d??null),C=u.length===h.length&&u.every((m,B)=>m===h[B]);if(!(f&&C))try{await c.fileManager.processFrontMatter(A.file,m=>{d?m[ue]=d:delete m[ue],h.length>0?m[ti]=h:delete m[ti]}),l+=1,await new Promise(m=>setTimeout(m,50))}catch(m){console.warn("[Stashpad] rebootstrap fm sync failed",A.file.path,m)}}return{checked:a,written:l}}function Ds(c){return`[[${c.replace(/\.md$/i,"")}]]`}Ht();Ye();var xs=class{constructor(r,t){this.tree=r;this.log=t}async sweep(r){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!r)return!0;let o=r.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 pt=require("obsidian");lt();Cn();var ft=pt.moment;function Wn(c){let r=c.trim().toLowerCase();if(!r)return null;let t=Date.now(),e=p=>ft(p).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=r,a=i.exec(r);if(a&&(a[3]||a[2])){let p=parseInt(a[1],10),u=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&p<12&&(p+=12),f==="am"&&p===12&&(p=0),p>=0&&p<24&&u>=0&&u<60&&(s=(p*3600+u*60)*1e3,n=!0,o=r.replace(a[0]," ").replace(/\s+/g," ").trim())}let l=p=>n?p+s:p;if(o===""||o==="today")return l(e(t));if(o==="yesterday")return l(e(t)-864e5);if(o==="tomorrow")return l(e(t)+864e5);let A=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=["sun","mon","tue","wed","thu","fri","sat"],h=A.indexOf(o)>=0?A.indexOf(o):d.indexOf(o);if(h>=0){let p=ft().startOf("day"),f=(p.day()-h+7)%7;return l(p.subtract(f,"days").valueOf())}let g=/^(\d+)\s*([dwmy])$/.exec(o);if(g){let p=parseInt(g[1],10),u={d:"days",w:"weeks",m:"months",y:"years"}[g[2]];return l(ft().subtract(p,u).startOf("day").valueOf())}let I=ft(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return I.isValid()?l(I.startOf("day").valueOf()):null}function ba(c){let r={text:[],filters:{}},t=(c||"").trim();if(!t)return r;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")r.filters.in=o.toLowerCase();else if(n==="before"){let a=Wn(o);a!=null&&(r.filters.before=a)}else if(n==="after"){let a=Wn(o);a!=null&&(r.filters.after=a)}else if(n==="on"){let a=Wn(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))r.filters.on={start:a-6e4,end:a+6e4};else{let A=ft(a).startOf("day").valueOf();r.filters.on={start:A,end:A+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&r.text.push(n.toLowerCase());return r}var $t=class c extends pt.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!==F?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===F&&this.notes.push({node:a,title:i,body:""});for(let l of this.tree.getChildren(n))s(l.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(F))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=ba(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=Q=>C.every(E=>Q.toLowerCase().includes(E)),B=Q=>{if(!o.has(Q)){o.add(Q);for(let E of this.tree.getChildren(Q))B(E.id)}};for(let Q of this.notes)!Q.node||Q.cross||m(Q.title)&&B(Q.node.id);let y=new Map;for(let Q of this.notes){if(!Q.cross)continue;let E=y.get(Q.cross.folder)??[];E.push(Q),y.set(Q.cross.folder,E)}for(let[Q,E]of y){let v=new Map;for(let N of E){let P=N.cross?.parentId??null;if(!P)continue;let H=v.get(P)??[];H.push(N.cross.id),v.set(P,H)}let w=new Set;a.set(Q,w);let D=N=>{if(!w.has(N)){w.add(N);for(let P of v.get(N)??[])D(P)}};for(let N of E)m(N.title)&&D(N.cross.id)}}let l=C=>{let m=i.filters;if(o||a)if(C.cross){let B=a?.get(C.cross.folder);if(!B||!B.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 B=this.createdMsFor(C);if(B==null||m.before!=null&&B>=m.before||m.after!=null&&B<=m.after||m.on&&(B<m.on.start||B>=m.on.end))return!1}return!0},A=C=>n(C.toLowerCase()),d=this.notes.filter(C=>!C.cross),h=this.notes.filter(C=>C.cross),g=(C,m)=>({id:C.cross?`cross:${C.cross.folder}:${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,crossId:C.cross?.id}),I=C=>{let m=[];for(let B of C)if(l(B))if(this.opts.mode==="search"){if(!e){m.push(g(B,-1));continue}let y=n(B.title.toLowerCase()),Q=B.body.split(/\r?\n/),E=[];for(let w=0;w<Q.length;w++)A(Q[w])&&E.push(w);let v=E.length>0||n(B.body.toLowerCase());if(!y&&!v)continue;if(E.length===0)m.push(g(B,-1));else{let w=[],D=-100;for(let P of E)P-D>5&&w.push(P),D=P;let N=5;for(let P of w.slice(0,N))m.push(g(B,P))}}else{if(e&&!n(B.title.toLowerCase())&&!n(B.body.toLowerCase()))continue;m.push(g(B,-1))}return m},p=I(d),u=[...p];if(this.opts.mode==="search"?e?!0:p.length<10:!!e){let C=I(h);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(B=>{let y=B.split("/").pop()??B;return n(`${B.toLowerCase()} ${y.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=B=>B.kind==="note"&&(B.id===F||B.crossId===F)&&n(B.label.toLowerCase()),m=u.filter(C);if(m.length>0){let B=u.filter(y=>!C(y));u.splice(0,u.length,...m,...B)}}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 I=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),p=I.createSpan({cls:"stashpad-search-excluded-icon"});(0,ht.setIcon)(p,"folder-search"),I.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(I=>t.crossFolder?I.cross?.folder===t.crossFolder&&I.cross?.id===t.crossId:I.node?.id===t.id),n=rr(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 l=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let I=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(I,t.bodyPreview,n)}let A="";if(t.crossFolder?A=s?.cross?.parentBlurb??"":A=this.parentBlurbFor(t.node),A){let I=i.createDiv({cls:"stashpad-suggest-preview"});I.appendText("Parent: "),this.highlightInto(I,A,n)}let d=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),h=t.crossFolder??this.opts.localFolder??null;if(h||d){let I=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[h?h.split("/").pop()||h:"",d].filter(f=>f&&f.length>0).join(" \u203A ");u&&I.setText(u)}let g=s?this.createdMsFor(s):null;if(g!=null||l){let I=e.createDiv({cls:"stashpad-suggest-rail"});if(g!=null){let p=I.createDiv({cls:"stashpad-suggest-time"});p.setText(this.formatRelativeTime(g)),p.title=Ct(g).format("YYYY-MM-DD HH:mm")}l&&I.createDiv({cls:"stashpad-suggest-folder-badge",text:l.split("/").pop()||l})}}formatRelativeTime(t){let e=Ct(t),i=Ct().startOf("day").diff(Ct(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(A=>A&&A.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let A of s){let d=0;for(;(d=n.indexOf(A,d))!==-1;)o.push([d,d+A.length]),d+=A.length}if(!o.length){t.appendText(e);return}o.sort((A,d)=>A[0]-d[0]);let a=[];for(let A of o){let d=a[a.length-1];d&&A[0]<=d[1]?d[1]=Math.max(d[1],A[1]):a.push([A[0],A[1]])}let l=0;for(let[A,d]of a)A>l&&t.appendText(e.slice(l,A)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(A,d)}),l=d;l<e.length&&t.appendText(e.slice(l))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===F)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==F&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==F?this.tree.get(s.parent):void 0;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let l of this.notes){if(!l.cross)continue;let A=this.crossFolderIndex.get(l.cross.folder);A||(A=new Map,this.crossFolderIndex.set(l.cross.folder,A)),A.set(l.cross.id,l.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.crossId??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===F)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&&!ht.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(ht.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",A=>{if(A.key==="["){A.preventDefault();let d=t.selectionStart??t.value.length,h=t.selectionEnd??d,g=t.value.slice(0,d),I=t.value.slice(d,h),p=t.value.slice(h);t.value=`${g}[${I}]${p}`;let u=d+1+I.length;t.setSelectionRange(u,u),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(A.key==="]"){let d=t.selectionStart??-1;d>=0&&t.value[d]==="]"&&(A.preventDefault(),t.setSelectionRange(d+1,d+1));return}if(A.key==="Backspace"&&!A.metaKey&&!A.ctrlKey&&!A.altKey&&t.selectionStart===t.selectionEnd){let d=t.selectionStart??-1;if(d>0&&t.value[d-1]==="["&&t.value[d]==="]"){A.preventDefault();let h=t.value.slice(0,d-1),g=t.value.slice(d+1);t.value=`${h}${g}`,t.setSelectionRange(d-1,d-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",A=>{A.preventDefault()}),n.addEventListener("click",A=>{A.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),A.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",A=>{A.preventDefault()}),o.addEventListener("click",A=>{A.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),A.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new ht.Scope(this.scope),l=A=>{let d=document.activeElement;return d?.classList?.contains("stashpad-search-filter-chip")?(A.preventDefault(),d.click(),!1):A.key==="Enter"&&!A.isComposing?(A.preventDefault(),this.selectActiveSuggestion?.(A),!1):!0};a.register([],"Enter",l),a.register([]," ",l),a.register(["Mod"],"f",A=>{A.preventDefault();let d=this.inputEl;return d&&(d.focus(),d.select()),!1}),a.register([],"Tab",A=>{let d=this.modalEl,h=this.inputEl;if(!d)return!0;let g=Array.from(d.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1&&u.offsetParent!==null);if(g.length===0)return!0;let I=document.activeElement,p=I?g.indexOf(I):-1;if(A.shiftKey){if(p<=0)return A.preventDefault(),g[g.length-1].focus(),!1}else if(p===g.length-1)return A.preventDefault(),(h??g[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="]",l=i;t.value=`${s}${o}${l}${a}`;let A=s.length+o.length+l.length;if(t.setSelectionRange(A,A+0),!l){let d=s.length+o.length;t.setSelectionRange(d,d)}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="":m==="between"&&u.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=u.id;for(let B in a)a[B].toggleClass("is-active",B===u.id);p()}),a[u.id]=f,n.appendChild(f)}s.appendChild(n);let l=document.createElement("div");l.className="stashpad-when-body",s.appendChild(l);let A=(u,f,C="single")=>{let m=Ct().format("YYYY-MM-DD"),B=!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 B?Ct().format("HH:mm"):"23:59";case"before":return B?Ct().format("HH:mm"):"23:59";default:return"23:59"}},d=(u,f)=>{u.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},h=(u,f)=>{let C=u.selectionStart??u.value.length,m=u.selectionEnd??u.value.length,y=`${C>0&&!/\s$/.test(u.value.slice(0,C))?" ":""}${f}`,Q=u.value.slice(0,C)+y+u.value.slice(m);u.value=Q;let E=C+y.length;u.setSelectionRange(E,E),u.focus(),u.dispatchEvent(new Event("input",{bubbles:!0}))},g=(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},I=(u,f,C,m)=>{let B=l.createDiv({cls:"stashpad-when-input-wrap has-icons"}),y=B.createDiv({cls:"stashpad-when-icon-slot"}),Q=y.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});Q.type="button",Q.title="Pick date",(0,ht.setIcon)(Q,"calendar-days");let E=y.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});E.tabIndex=-1;let v=B.createDiv({cls:"stashpad-when-icon-slot"}),w=v.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});w.type="button",w.title="Pick time",(0,ht.setIcon)(w,"clock");let D=B.createDiv({cls:"stashpad-when-icon-slot"}),N=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});N.type="button",N.title="Pick day",(0,ht.setIcon)(N,"calendar");let P=B.createDiv({cls:"stashpad-when-icon-slot"}),H=P.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});H.type="button",H.title="Pick timeframe",(0,ht.setIcon)(H,"history");let b=B.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:u}});b.value=f(),b.addEventListener("input",()=>C(b.value));let S=B.createEl("button",{cls:"stashpad-when-clear"});S.type="button",S.textContent="\xD7",S.title="Clear";for(let z of[Q,w,N,H,S])z.addEventListener("mousedown",$=>$.preventDefault());let T=null,U=(z,$)=>{T&&T();let R=z.createDiv({cls:"stashpad-when-popover"}),V=new ht.Scope(this.scope),O=null,Y=X=>{O=X},it=!1,at=X=>{!R.contains(X.target)&&X.target!==z&&!z.contains(X.target)&&_()},_=()=>{if(!it){it=!0,R.remove(),document.removeEventListener("mousedown",at,!0);try{this.app.keymap?.popScope(V)}catch{}T===_&&(T=null)}};T=_,V.register([],"Escape",X=>(X.preventDefault(),_(),!1)),V.register([],"Enter",X=>(X.preventDefault(),O&&O(),!1));try{$(R,_,Y)}catch(X){console.error("[stashpad] popover fill threw:",X),R.remove(),T=null;return}this.app.keymap?.pushScope(V),this.pendingCleanups.push(_),setTimeout(()=>document.addEventListener("mousedown",at,!0),0)};H.addEventListener("click",z=>{z.preventDefault(),U(P,($,R,V)=>{let O=this.whenMode==="on",Y=(st,Bt)=>{if(!O)return`${st}${Bt}`;let ye={d:"days",w:"weeks",m:"months",y:"years"}[Bt];return Ct().subtract(st,ye).format("YYYY-MM-DD")},it=$.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 st of at){let Bt=it.createEl("button",{cls:"stashpad-when-pop-chip",text:st.label});Bt.type="button",Bt.addEventListener("mousedown",ye=>ye.preventDefault()),Bt.addEventListener("click",ye=>{ye.preventDefault(),h(b,Y(st.n,st.unit)),R()})}let _=$.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});_.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let X=_.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),mt=_.createEl("select",{cls:"stashpad-when-pop-unit"});for(let st of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let Bt=mt.createEl("option",{text:st.label});Bt.value=st.v}let ct=_.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ct.type="button";let St=()=>{let st=parseInt(X.value,10);!Number.isFinite(st)||st<1||(h(b,Y(st,mt.value)),R())};ct.addEventListener("mousedown",st=>st.preventDefault()),ct.addEventListener("click",st=>{st.preventDefault(),St()}),V(St),X.focus(),X.select()})});let L=(z,$,R,V,O)=>{U($,(Y,it,at)=>{ji(Y,{seedH:R,seedM:V,seedPeriod:O,close:it,setOnEnter:at,onFinalize:_=>h(z,zo(_))})})};N.addEventListener("click",z=>{z.preventDefault(),U(D,($,R,V)=>{let O=$.createDiv({cls:"stashpad-when-pop-row"});for(let X of["Today","Yesterday"]){let mt=O.createEl("button",{cls:"stashpad-when-pop-chip",text:X});mt.type="button",mt.addEventListener("mousedown",ct=>ct.preventDefault()),mt.addEventListener("click",ct=>{ct.preventDefault(),h(b,X),R()})}let Y=$.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),it=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],_=(Ct().day()+6)%7;for(let X=0;X<it.length;X++){let mt=it[X],ct=Y.createEl("button",{cls:"stashpad-when-pop-chip",text:mt.slice(0,3)});ct.type="button",ct.title=mt,X===_&&ct.addClass("is-today"),ct.addEventListener("mousedown",St=>St.preventDefault()),ct.addEventListener("click",St=>{if(St.preventDefault(),m==="betweenEnd"){let st=X,Bt=Ct().startOf("day"),ye=(Bt.day()+6)%7,cn=(st-ye+7)%7;cn===0&&(cn=7);let Dr=Bt.clone().add(cn,"days").format("YYYY-MM-DD");h(b,Dr)}else h(b,mt);R()})}})});let W=(z,$)=>{z.value||(z.value=$);let R=z;if(typeof R.showPicker=="function")try{R.showPicker();return}catch{}z.focus(),z.click()};return Q.addEventListener("click",z=>{z.preventDefault(),W(E,Ct().format("YYYY-MM-DD"))}),E.addEventListener("change",()=>{E.value&&h(b,E.value)}),w.addEventListener("click",z=>{z.preventDefault();let $=b.selectionStart??b.value.length,R=g(b.value,$),V=A(this.whenMode,R,m),[O,Y]=V.split(":"),it=parseInt(O,10),at=parseInt(Y,10),_=it%12;_===0&&(_=12);let X=it>=12?"pm":"am";L(b,v,_,at,X)}),S.addEventListener("click",z=>{z.preventDefault(),b.value="",C(""),b.focus()}),b},p=()=>{if(l.empty(),this.whenMode==="between"){let u=I("start (date / day / timeframe)",()=>this.whenSingleText,Q=>{this.whenSingleText=Q},"betweenStart"),f=I("end (date / day / timeframe)",()=>this.whenBetweenEndText,Q=>{this.whenBetweenEndText=Q},"betweenEnd"),C=l.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",Q=>Q.preventDefault());let B=()=>{let Q=u.value.trim(),E=f.value.trim();Q&&this.appendFilterToInput(t,"after",Q),E&&this.appendFilterToInput(t,"before",E),this.closeWhenBuilder()};m.addEventListener("click",Q=>{Q.preventDefault(),B()});let y=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});y.type="button",y.addEventListener("mousedown",Q=>Q.preventDefault()),y.addEventListener("click",Q=>{Q.preventDefault(),this.closeWhenBuilder()}),d(u,B),d(f,B),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}else{let u=I("date / day / timeframe",()=>this.whenSingleText,y=>{this.whenSingleText=y},"single"),f=l.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",y=>y.preventDefault());let m=()=>{let y=u.value.trim();y&&this.appendFilterToInput(t,this.whenMode,y),this.closeWhenBuilder()};C.addEventListener("click",y=>{y.preventDefault(),m()});let B=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});B.type="button",B.addEventListener("mousedown",y=>y.preventDefault()),B.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),d(u,m),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}};p(),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=g=>{s=!0;let I=g.split("/").pop()??g;this.opts.onPick({id:`folder:${g}`,label:`Open folder \u201C${I}\u201D in a new tab`,node:null,kind:"folder-open",folder:g})},o=new Io(this.app,e,n),a=o.onClose.bind(o),l=this.tree,A=this.titleFn,d=this.opts,h=this.app;o.onClose=()=>{if(a(),!s){let g=new c(h,l,A,d);g.open(),setTimeout(()=>{let I=g.inputEl;I&&(i&&(I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0}))),I.focus(),I.setSelectionRange(I.value.length,I.value.length))},0)}},o.open();return}this.opts.onPick(t)}},Io=class extends ht.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 lr=require("obsidian");rt();var Js=class extends lr.SuggestModal{constructor(r){super(r),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:lA(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(r){return this.commands.filter(t=>Xi(r,t.name))}renderSuggestion(r,t){t.createDiv({text:r.name,cls:"stashpad-cmd-palette-name"})}onChooseSuggestion(r){this.app.commands?.executeCommandById?.(r.id)}};function lA(c){return c.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||c}Ft();var uo=require("obsidian");function AA(c,r){return!r||c.metaKey||c.ctrlKey||c.altKey?!1:c.key.toLowerCase()===r.toLowerCase()}function si(c,r){return r?r.includes("+")?cA(c,r):AA(c,r):!1}function G(c,r){if(!r)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=r;return t&&e?s?si(c,t)||si(c,e):i?si(c,e):si(c,t):si(c,t)||si(c,e)}function Ki(c){if(!c)return"";let r=uo.Platform.isMacOS;return c.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?r?"Cmd":"Ctrl":e.toLowerCase()==="alt"?r?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function cA(c,r){if(!r)return!1;let t=r.split("+").map(h=>h.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(h=>h.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"),l=i.has("shift"),d=uo.Platform.isMacOS?c.metaKey:c.ctrlKey;return s&&!d||n&&!c.ctrlKey||o&&!c.metaKey||a!==c.altKey||l!==c.shiftKey||!s&&(!n&&c.ctrlKey||!o&&c.metaKey)?!1:c.key.toLowerCase()===e}var He=require("obsidian");Ft();var Nt=class Nt{constructor(r){this.host=r;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let r of this.contribTimers.values())clearTimeout(r);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let r=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!r||!t)return null;let e=r.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=r.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:r,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 r=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==r&&!e.startsWith(r+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(r,t){for(let s=0;s<r.length;s++){let n=this.host.app.vault.getAbstractFileByPath(r[s]);if(n instanceof He.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,r[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",r[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(r){let t=this.currentAuthorLink();if(!t){new He.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=r.scope==="selection"?this.host.getActionTargets().map(g=>g.file).filter(g=>!!g):this.fileBackedNotesInFolder();if(i.length===0){new He.Notice(r.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let g of i){let I=this.host.app.metadataCache.getFileCache(g)?.frontmatter,p=typeof I?.author=="string"?I.author:"";if(!p.trim()){s.push(g.path);continue}if(p.includes(e)||!r.contributorMode)continue;(Array.isArray(I?.contributors)?I.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(g.path)}let o=s.length+n.length;if(o===0){new He.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(r.scope==="folder"){let g=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&g.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(p=>{new pt(this.host.app,"Claim authorship",`${g.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",p).open()}))return}let a=this.host.noteFolder,l=t.link,A=new Set,d=async()=>{await this.pacedFrontmatter(s,(g,I)=>{typeof g.author=="string"&&g.author.trim()||(g.author=l),Array.isArray(g.contributors)&&g.contributors.some(p=>typeof p=="string"&&p.includes(e))&&(g.contributors=g.contributors.filter(p=>!(typeof p=="string"&&p.includes(e))),A.add(I))}),await this.pacedFrontmatter(n,g=>{let I=Array.isArray(g.contributors)?g.contributors.filter(p=>typeof p=="string"):[];I.some(p=>p.includes(e))||I.push(l),g.contributors=I})};this.ensureAuthorFile(t),await d(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(g,I)=>{if(typeof g.author=="string"&&g.author.includes(e)&&delete g.author,A.has(I)){let p=Array.isArray(g.contributors)?g.contributors.filter(u=>typeof u=="string"):[];p.some(u=>u.includes(e))||p.push(l),g.contributors=p}}),await this.pacedFrontmatter(n,g=>{Array.isArray(g.contributors)&&(g.contributors=g.contributors.filter(I=>!(typeof I=="string"&&I.includes(e))))}),this.host.debouncedRender()},redo:async()=>{A.clear(),await d(),this.host.debouncedRender()}});let h=[];s.length&&h.push(`authored ${s.length}`),n.length&&h.push(`contributing to ${n.length}`),new He.Notice(`Claimed authorship: ${h.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(r){try{r.id&&this.host.plugin.authorRegistry.record({id:r.id,name:r.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(r.path))return;let e=r.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:r.id,name:r.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(r.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(r){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 r){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 r=Date.now(),t=Nt.EXTERNAL_WRITE_GRACE_MS*20,e=Nt.EXTERNAL_QUIESCENCE_MS*12;for(let[i,s]of this.recentSelfWrites)r-s>t&&this.recentSelfWrites.delete(i);for(let[i,s]of this.lastExternalModify)r-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(r){let t=Date.now(),e=this.recentSelfWrites.get(r.path);e!==void 0&&t-e<Nt.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(r.path,t),this.scheduleContribution(r)}scheduleContribution(r){let t=this.contribTimers.get(r.path);t&&clearTimeout(t);let e=this.isFileActivelyEdited(r),i=Nt.CONTRIB_DEBOUNCE_MS+(e?Nt.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),s=setTimeout(()=>{if(this.contribTimers.delete(r.path),this.isFileActivelyEdited(r)){this.scheduleContribution(r);return}let n=this.lastExternalModify.get(r.path);if(n!==void 0&&Date.now()-n<Nt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(r);return}this.maybeRecordContribution(r)},i);this.contribTimers.set(r.path,s)}isFileActivelyEdited(r){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==r.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(r){let t="";try{t=await this.host.app.vault.cachedRead(r)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(r.path);if(this.knownBodies.set(r.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(r.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(r,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(g=>typeof g=="string"):[],A=`-${s.id}`,d=a.includes(A),h=l.some(g=>g.includes(A));!d&&!h&&l.push(s.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Nt.CONTRIB_DEBOUNCE_MS=4e3,Nt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Nt.EXTERNAL_WRITE_GRACE_MS=1500,Nt.EXTERNAL_QUIESCENCE_MS=5e3;var Ks=Nt;var Os=class{constructor(r){this.host=r;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(r,t,e){r.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=r.offsetHeight,r.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.setCssStyles({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,l=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let A,d="before";a&&a.classList.contains("stashpad-note")?(A=a.dataset.id,d="before"):l&&l.classList.contains("stashpad-note")&&(A=l.dataset.id,d="after"),A&&this.host.reorderToTarget(o,A,d)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(r,12,12)}catch{}}}),r.addEventListener("dragend",()=>{r.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),r.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,r);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),r.addClass("drop-into")):(r.removeClass("drop-into"),this.placePlaceholder(r,s==="drop-above"?"before":"after"))}),r.addEventListener("dragleave",i=>{let s=r.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&r.removeClass("drop-into")}),r.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,r);this.clearDropIndicators(),this.removeDragPlaceholder(),r.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(r){r.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(r.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")}}),r.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(r,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?r:r.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===r||t==="after"&&this.dragPlaceholder.previousSibling===r)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),this.dragPlaceholder.setCssStyles({opacity:"1"}),i?this.dragPlaceholder.setCssStyles({height:`${this.dragRowHeight}px`}):(this.dragPlaceholder.setCssStyles({height:"0px"}),this.dragPlaceholder.offsetHeight,this.dragPlaceholder.setCssStyles({height:`${this.dragRowHeight}px`}))}removeDragPlaceholder(){if(!this.dragPlaceholder?.parentElement)return;let r=this.dragPlaceholder;r.setCssStyles({height:"0px",opacity:"0"}),setTimeout(()=>{r.parentElement&&r.remove()},150)}dropZone(r,t){let e=t.getBoundingClientRect(),i=r.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 r of Array.from(this.host.listEl.querySelectorAll(".drop-into")))r.removeClass("drop-into")}};var Ar=require("obsidian");var Ys=class{constructor(r,t,e){this.host=r;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(r){let t=this.renderCache.get(r.path);if(t&&t.mtime===r.stat.mtime)return wt.record("render.row.cacheHit",0),t;let e=await wt.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(r)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await wt.timeAsync("render.row.markdown",()=>Ar.MarkdownRenderer.render(this.host.app,s,o,r.path,this.component));let a=o.innerHTML,l={mtime:r.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(r.path,l),l}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(r=>{for(let t of r){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(r){let t=this.renderCache.get(r.path);return!!t&&t.mtime===r.stat.mtime}defer(r,t){this.lazyBodies.set(r,t),this.bodyObserver?.observe(r)}splitAttachments(r){let t=[];return{text:r.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 I=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),p=I.createSpan({cls:"stashpad-search-excluded-icon"});(0,pt.setIcon)(p,"folder-search"),I.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(I=>t.crossFolder?I.cross?.folder===t.crossFolder&&I.cross?.id===t.crossId:I.node?.id===t.id),n=ba(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 l=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let I=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(I,t.bodyPreview,n)}let A="";if(t.crossFolder?A=s?.cross?.parentBlurb??"":A=this.parentBlurbFor(t.node),A){let I=i.createDiv({cls:"stashpad-suggest-preview"});I.appendText("Parent: "),this.highlightInto(I,A,n)}let d=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),h=t.crossFolder??this.opts.localFolder??null;if(h||d){let I=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[h?h.split("/").pop()||h:"",d].filter(f=>f&&f.length>0).join(" \u203A ");u&&I.setText(u)}let g=s?this.createdMsFor(s):null;if(g!=null||l){let I=e.createDiv({cls:"stashpad-suggest-rail"});if(g!=null){let p=I.createDiv({cls:"stashpad-suggest-time"});p.setText(this.formatRelativeTime(g)),p.title=ft(g).format("YYYY-MM-DD HH:mm")}l&&I.createDiv({cls:"stashpad-suggest-folder-badge",text:l.split("/").pop()||l})}}formatRelativeTime(t){let e=ft(t),i=ft().startOf("day").diff(ft(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(A=>A&&A.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let A of s){let d=0;for(;(d=n.indexOf(A,d))!==-1;)o.push([d,d+A.length]),d+=A.length}if(!o.length){t.appendText(e);return}o.sort((A,d)=>A[0]-d[0]);let a=[];for(let A of o){let d=a[a.length-1];d&&A[0]<=d[1]?d[1]=Math.max(d[1],A[1]):a.push([A[0],A[1]])}let l=0;for(let[A,d]of a)A>l&&t.appendText(e.slice(l,A)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(A,d)}),l=d;l<e.length&&t.appendText(e.slice(l))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===F)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==F&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==F?this.tree.get(s.parent):void 0;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let l of this.notes){if(!l.cross)continue;let A=this.crossFolderIndex.get(l.cross.folder);A||(A=new Map,this.crossFolderIndex.set(l.cross.folder,A)),A.set(l.cross.id,l.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.crossId??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===F)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&&!pt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(pt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",A=>{if(A.key==="["){A.preventDefault();let d=t.selectionStart??t.value.length,h=t.selectionEnd??d,g=t.value.slice(0,d),I=t.value.slice(d,h),p=t.value.slice(h);t.value=`${g}[${I}]${p}`;let u=d+1+I.length;t.setSelectionRange(u,u),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(A.key==="]"){let d=t.selectionStart??-1;d>=0&&t.value[d]==="]"&&(A.preventDefault(),t.setSelectionRange(d+1,d+1));return}if(A.key==="Backspace"&&!A.metaKey&&!A.ctrlKey&&!A.altKey&&t.selectionStart===t.selectionEnd){let d=t.selectionStart??-1;if(d>0&&t.value[d-1]==="["&&t.value[d]==="]"){A.preventDefault();let h=t.value.slice(0,d-1),g=t.value.slice(d+1);t.value=`${h}${g}`,t.setSelectionRange(d-1,d-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",A=>{A.preventDefault()}),n.addEventListener("click",A=>{A.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),A.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",A=>{A.preventDefault()}),o.addEventListener("click",A=>{A.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),A.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new pt.Scope(this.scope),l=A=>{let d=document.activeElement;return d?.classList?.contains("stashpad-search-filter-chip")?(A.preventDefault(),d.click(),!1):A.key==="Enter"&&!A.isComposing?(A.preventDefault(),this.selectActiveSuggestion?.(A),!1):!0};a.register([],"Enter",l),a.register([]," ",l),a.register(["Mod"],"f",A=>{A.preventDefault();let d=this.inputEl;return d&&(d.focus(),d.select()),!1}),a.register([],"Tab",A=>{let d=this.modalEl,h=this.inputEl;if(!d)return!0;let g=Array.from(d.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1&&u.offsetParent!==null);if(g.length===0)return!0;let I=document.activeElement,p=I?g.indexOf(I):-1;if(A.shiftKey){if(p<=0)return A.preventDefault(),g[g.length-1].focus(),!1}else if(p===g.length-1)return A.preventDefault(),(h??g[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="]",l=i;t.value=`${s}${o}${l}${a}`;let A=s.length+o.length+l.length;if(t.setSelectionRange(A,A+0),!l){let d=s.length+o.length;t.setSelectionRange(d,d)}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="":m==="between"&&u.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=u.id;for(let B in a)a[B].toggleClass("is-active",B===u.id);p()}),a[u.id]=f,n.appendChild(f)}s.appendChild(n);let l=document.createElement("div");l.className="stashpad-when-body",s.appendChild(l);let A=(u,f,C="single")=>{let m=ft().format("YYYY-MM-DD"),B=!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 B?ft().format("HH:mm"):"23:59";case"before":return B?ft().format("HH:mm"):"23:59";default:return"23:59"}},d=(u,f)=>{u.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},h=(u,f)=>{let C=u.selectionStart??u.value.length,m=u.selectionEnd??u.value.length,y=`${C>0&&!/\s$/.test(u.value.slice(0,C))?" ":""}${f}`,Q=u.value.slice(0,C)+y+u.value.slice(m);u.value=Q;let E=C+y.length;u.setSelectionRange(E,E),u.focus(),u.dispatchEvent(new Event("input",{bubbles:!0}))},g=(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},I=(u,f,C,m)=>{let B=l.createDiv({cls:"stashpad-when-input-wrap has-icons"}),y=B.createDiv({cls:"stashpad-when-icon-slot"}),Q=y.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});Q.type="button",Q.title="Pick date",(0,pt.setIcon)(Q,"calendar-days");let E=y.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});E.tabIndex=-1;let v=B.createDiv({cls:"stashpad-when-icon-slot"}),w=v.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});w.type="button",w.title="Pick time",(0,pt.setIcon)(w,"clock");let D=B.createDiv({cls:"stashpad-when-icon-slot"}),N=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});N.type="button",N.title="Pick day",(0,pt.setIcon)(N,"calendar");let P=B.createDiv({cls:"stashpad-when-icon-slot"}),H=P.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});H.type="button",H.title="Pick timeframe",(0,pt.setIcon)(H,"history");let b=B.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:u}});b.value=f(),b.addEventListener("input",()=>C(b.value));let S=B.createEl("button",{cls:"stashpad-when-clear"});S.type="button",S.textContent="\xD7",S.title="Clear";for(let $ of[Q,w,N,H,S])$.addEventListener("mousedown",z=>z.preventDefault());let T=null,U=($,z)=>{T&&T();let R=$.createDiv({cls:"stashpad-when-popover"}),V=new pt.Scope(this.scope),K=null,O=X=>{K=X},it=!1,rt=X=>{!R.contains(X.target)&&X.target!==$&&!$.contains(X.target)&&_()},_=()=>{if(!it){it=!0,R.remove(),document.removeEventListener("mousedown",rt,!0);try{this.app.keymap?.popScope(V)}catch{}T===_&&(T=null)}};T=_,V.register([],"Escape",X=>(X.preventDefault(),_(),!1)),V.register([],"Enter",X=>(X.preventDefault(),K&&K(),!1));try{z(R,_,O)}catch(X){console.error("[stashpad] popover fill threw:",X),R.remove(),T=null;return}this.app.keymap?.pushScope(V),this.pendingCleanups.push(_),setTimeout(()=>document.addEventListener("mousedown",rt,!0),0)};H.addEventListener("click",$=>{$.preventDefault(),U(P,(z,R,V)=>{let K=this.whenMode==="on",O=(st,Bt)=>{if(!K)return`${st}${Bt}`;let Qe={d:"days",w:"weeks",m:"months",y:"years"}[Bt];return ft().subtract(st,Qe).format("YYYY-MM-DD")},it=z.createDiv({cls:"stashpad-when-pop-row"}),rt=[{label:"Last 7d",n:7,unit:"d"},{label:"Last 30d",n:30,unit:"d"},{label:"This week",n:1,unit:"w"},{label:"This month",n:1,unit:"m"}];for(let st of rt){let Bt=it.createEl("button",{cls:"stashpad-when-pop-chip",text:st.label});Bt.type="button",Bt.addEventListener("mousedown",Qe=>Qe.preventDefault()),Bt.addEventListener("click",Qe=>{Qe.preventDefault(),h(b,O(st.n,st.unit)),R()})}let _=z.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});_.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let X=_.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),mt=_.createEl("select",{cls:"stashpad-when-pop-unit"});for(let st of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let Bt=mt.createEl("option",{text:st.label});Bt.value=st.v}let dt=_.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});dt.type="button";let St=()=>{let st=parseInt(X.value,10);!Number.isFinite(st)||st<1||(h(b,O(st,mt.value)),R())};dt.addEventListener("mousedown",st=>st.preventDefault()),dt.addEventListener("click",st=>{st.preventDefault(),St()}),V(St),X.focus(),X.select()})});let L=($,z,R,V,K)=>{U(z,(O,it,rt)=>{_i(O,{seedH:R,seedM:V,seedPeriod:K,close:it,setOnEnter:rt,onFinalize:_=>h($,$o(_))})})};N.addEventListener("click",$=>{$.preventDefault(),U(D,(z,R,V)=>{let K=z.createDiv({cls:"stashpad-when-pop-row"});for(let X of["Today","Yesterday"]){let mt=K.createEl("button",{cls:"stashpad-when-pop-chip",text:X});mt.type="button",mt.addEventListener("mousedown",dt=>dt.preventDefault()),mt.addEventListener("click",dt=>{dt.preventDefault(),h(b,X),R()})}let O=z.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),it=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],_=(ft().day()+6)%7;for(let X=0;X<it.length;X++){let mt=it[X],dt=O.createEl("button",{cls:"stashpad-when-pop-chip",text:mt.slice(0,3)});dt.type="button",dt.title=mt,X===_&&dt.addClass("is-today"),dt.addEventListener("mousedown",St=>St.preventDefault()),dt.addEventListener("click",St=>{if(St.preventDefault(),m==="betweenEnd"){let st=X,Bt=ft().startOf("day"),Qe=(Bt.day()+6)%7,cn=(st-Qe+7)%7;cn===0&&(cn=7);let Sr=Bt.clone().add(cn,"days").format("YYYY-MM-DD");h(b,Sr)}else h(b,mt);R()})}})});let W=($,z)=>{$.value||($.value=z);let R=$;if(typeof R.showPicker=="function")try{R.showPicker();return}catch{}$.focus(),$.click()};return Q.addEventListener("click",$=>{$.preventDefault(),W(E,ft().format("YYYY-MM-DD"))}),E.addEventListener("change",()=>{E.value&&h(b,E.value)}),w.addEventListener("click",$=>{$.preventDefault();let z=b.selectionStart??b.value.length,R=g(b.value,z),V=A(this.whenMode,R,m),[K,O]=V.split(":"),it=parseInt(K,10),rt=parseInt(O,10),_=it%12;_===0&&(_=12);let X=it>=12?"pm":"am";L(b,v,_,rt,X)}),S.addEventListener("click",$=>{$.preventDefault(),b.value="",C(""),b.focus()}),b},p=()=>{if(l.empty(),this.whenMode==="between"){let u=I("start (date / day / timeframe)",()=>this.whenSingleText,Q=>{this.whenSingleText=Q},"betweenStart"),f=I("end (date / day / timeframe)",()=>this.whenBetweenEndText,Q=>{this.whenBetweenEndText=Q},"betweenEnd"),C=l.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",Q=>Q.preventDefault());let B=()=>{let Q=u.value.trim(),E=f.value.trim();Q&&this.appendFilterToInput(t,"after",Q),E&&this.appendFilterToInput(t,"before",E),this.closeWhenBuilder()};m.addEventListener("click",Q=>{Q.preventDefault(),B()});let y=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});y.type="button",y.addEventListener("mousedown",Q=>Q.preventDefault()),y.addEventListener("click",Q=>{Q.preventDefault(),this.closeWhenBuilder()}),d(u,B),d(f,B),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}else{let u=I("date / day / timeframe",()=>this.whenSingleText,y=>{this.whenSingleText=y},"single"),f=l.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",y=>y.preventDefault());let m=()=>{let y=u.value.trim();y&&this.appendFilterToInput(t,this.whenMode,y),this.closeWhenBuilder()};C.addEventListener("click",y=>{y.preventDefault(),m()});let B=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});B.type="button",B.addEventListener("mousedown",y=>y.preventDefault()),B.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),d(u,m),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}};p(),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=g=>{s=!0;let I=g.split("/").pop()??g;this.opts.onPick({id:`folder:${g}`,label:`Open folder \u201C${I}\u201D in a new tab`,node:null,kind:"folder-open",folder:g})},o=new Xn(this.app,e,n),a=o.onClose.bind(o),l=this.tree,A=this.titleFn,d=this.opts,h=this.app;o.onClose=()=>{if(a(),!s){let g=new c(h,l,A,d);g.open(),setTimeout(()=>{let I=g.inputEl;I&&(i&&(I.value=i,I.dispatchEvent(new Event("input",{bubbles:!0}))),I.focus(),I.setSelectionRange(I.value.length,I.value.length))},0)}},o.open();return}this.opts.onPick(t)}},Xn=class extends pt.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 Na=require("obsidian");lt();var Ms=class extends Na.SuggestModal{constructor(r){super(r),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:Sl(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(r){return this.commands.filter(t=>Zi(r,t.name))}renderSuggestion(r,t){t.createDiv({text:r.name,cls:"stashpad-cmd-palette-name"})}onChooseSuggestion(r){this.app.commands?.executeCommandById?.(r.id)}};function Sl(c){return c.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||c}Ft();var Zn=require("obsidian");function Dl(c,r){return!r||c.metaKey||c.ctrlKey||c.altKey?!1:c.key.toLowerCase()===r.toLowerCase()}function ii(c,r){return r?r.includes("+")?bl(c,r):Dl(c,r):!1}function G(c,r){if(!r)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=r;return t&&e?s?ii(c,t)||ii(c,e):i?ii(c,e):ii(c,t):ii(c,t)||ii(c,e)}function Gi(c){if(!c)return"";let r=Zn.Platform.isMacOS;return c.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?r?"Cmd":"Ctrl":e.toLowerCase()==="alt"?r?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function bl(c,r){if(!r)return!1;let t=r.split("+").map(h=>h.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(h=>h.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"),l=i.has("shift"),d=Zn.Platform.isMacOS?c.metaKey:c.ctrlKey;return s&&!d||n&&!c.ctrlKey||o&&!c.metaKey||a!==c.altKey||l!==c.shiftKey||!s&&(!n&&c.ctrlKey||!o&&c.metaKey)?!1:c.key.toLowerCase()===e}var Te=require("obsidian");Ft();var Dt=class Dt{constructor(r){this.host=r;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let r of this.contribTimers.values())clearTimeout(r);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let r=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!r||!t)return null;let e=r.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=r.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:r,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 r=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==r&&!e.startsWith(r+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(r,t){for(let s=0;s<r.length;s++){let n=this.host.app.vault.getAbstractFileByPath(r[s]);if(n instanceof Te.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,r[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",r[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(r){let t=this.currentAuthorLink();if(!t){new Te.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=r.scope==="selection"?this.host.getActionTargets().map(g=>g.file).filter(g=>!!g):this.fileBackedNotesInFolder();if(i.length===0){new Te.Notice(r.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let g of i){let I=this.host.app.metadataCache.getFileCache(g)?.frontmatter,p=typeof I?.author=="string"?I.author:"";if(!p.trim()){s.push(g.path);continue}if(p.includes(e)||!r.contributorMode)continue;(Array.isArray(I?.contributors)?I.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(g.path)}let o=s.length+n.length;if(o===0){new Te.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(r.scope==="folder"){let g=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&g.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(p=>{new ot(this.host.app,"Claim authorship",`${g.join(" ")}? +Existing authors are never overwritten. This can be undone.`,"Claim",p).open()}))return}let a=this.host.noteFolder,l=t.link,A=new Set,d=async()=>{await this.pacedFrontmatter(s,(g,I)=>{typeof g.author=="string"&&g.author.trim()||(g.author=l),Array.isArray(g.contributors)&&g.contributors.some(p=>typeof p=="string"&&p.includes(e))&&(g.contributors=g.contributors.filter(p=>!(typeof p=="string"&&p.includes(e))),A.add(I))}),await this.pacedFrontmatter(n,g=>{let I=Array.isArray(g.contributors)?g.contributors.filter(p=>typeof p=="string"):[];I.some(p=>p.includes(e))||I.push(l),g.contributors=I})};this.ensureAuthorFile(t),await d(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(g,I)=>{if(typeof g.author=="string"&&g.author.includes(e)&&delete g.author,A.has(I)){let p=Array.isArray(g.contributors)?g.contributors.filter(u=>typeof u=="string"):[];p.some(u=>u.includes(e))||p.push(l),g.contributors=p}}),await this.pacedFrontmatter(n,g=>{Array.isArray(g.contributors)&&(g.contributors=g.contributors.filter(I=>!(typeof I=="string"&&I.includes(e))))}),this.host.debouncedRender()},redo:async()=>{A.clear(),await d(),this.host.debouncedRender()}});let h=[];s.length&&h.push(`authored ${s.length}`),n.length&&h.push(`contributing to ${n.length}`),new Te.Notice(`Claimed authorship: ${h.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(r){try{r.id&&this.host.plugin.authorRegistry.record({id:r.id,name:r.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(r.path))return;let e=r.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:r.id,name:r.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(r.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(r){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 r){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 r=Date.now(),t=Dt.EXTERNAL_WRITE_GRACE_MS*20,e=Dt.EXTERNAL_QUIESCENCE_MS*12;for(let[i,s]of this.recentSelfWrites)r-s>t&&this.recentSelfWrites.delete(i);for(let[i,s]of this.lastExternalModify)r-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(r){let t=Date.now(),e=this.recentSelfWrites.get(r.path);e!==void 0&&t-e<Dt.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(r.path,t),this.scheduleContribution(r)}scheduleContribution(r){let t=this.contribTimers.get(r.path);t&&clearTimeout(t);let e=this.isFileActivelyEdited(r),i=Dt.CONTRIB_DEBOUNCE_MS+(e?Dt.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),s=setTimeout(()=>{if(this.contribTimers.delete(r.path),this.isFileActivelyEdited(r)){this.scheduleContribution(r);return}let n=this.lastExternalModify.get(r.path);if(n!==void 0&&Date.now()-n<Dt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(r);return}this.maybeRecordContribution(r)},i);this.contribTimers.set(r.path,s)}isFileActivelyEdited(r){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==r.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(r){let t="";try{t=await this.host.app.vault.cachedRead(r)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(r.path);if(this.knownBodies.set(r.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(r.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(r,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(g=>typeof g=="string"):[],A=`-${s.id}`,d=a.includes(A),h=l.some(g=>g.includes(A));!d&&!h&&l.push(s.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Dt.CONTRIB_DEBOUNCE_MS=4e3,Dt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Dt.EXTERNAL_WRITE_GRACE_MS=1500,Dt.EXTERNAL_QUIESCENCE_MS=5e3;var Ts=Dt;var Hs=class{constructor(r){this.host=r;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(r,t,e){r.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=r.offsetHeight,r.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.setCssStyles({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,l=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let A,d="before";a&&a.classList.contains("stashpad-note")?(A=a.dataset.id,d="before"):l&&l.classList.contains("stashpad-note")&&(A=l.dataset.id,d="after"),A&&this.host.reorderToTarget(o,A,d)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(r,12,12)}catch{}}}),r.addEventListener("dragend",()=>{r.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),r.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,r);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),r.addClass("drop-into")):(r.removeClass("drop-into"),this.placePlaceholder(r,s==="drop-above"?"before":"after"))}),r.addEventListener("dragleave",i=>{let s=r.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&r.removeClass("drop-into")}),r.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,r);this.clearDropIndicators(),this.removeDragPlaceholder(),r.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(r){r.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(r.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")}}),r.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(r,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?r:r.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===r||t==="after"&&this.dragPlaceholder.previousSibling===r)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),this.dragPlaceholder.setCssStyles({opacity:"1"}),i?this.dragPlaceholder.setCssStyles({height:`${this.dragRowHeight}px`}):(this.dragPlaceholder.setCssStyles({height:"0px"}),this.dragPlaceholder.offsetHeight,this.dragPlaceholder.setCssStyles({height:`${this.dragRowHeight}px`}))}removeDragPlaceholder(){if(!this.dragPlaceholder?.parentElement)return;let r=this.dragPlaceholder;r.setCssStyles({height:"0px",opacity:"0"}),setTimeout(()=>{r.parentElement&&r.remove()},150)}dropZone(r,t){let e=t.getBoundingClientRect(),i=r.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 r of Array.from(this.host.listEl.querySelectorAll(".drop-into")))r.removeClass("drop-into")}};var xa=require("obsidian");var Ps=class{constructor(r,t,e){this.host=r;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(r){let t=this.renderCache.get(r.path);if(t&&t.mtime===r.stat.mtime)return wt.record("render.row.cacheHit",0),t;let e=await wt.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(r)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await wt.timeAsync("render.row.markdown",()=>xa.MarkdownRenderer.render(this.host.app,s,o,r.path,this.component));let a=o.innerHTML,l={mtime:r.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(r.path,l),l}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(r=>{for(let t of r){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(r){let t=this.renderCache.get(r.path);return!!t&&t.mtime===r.stat.mtime}defer(r,t){this.lazyBodies.set(r,t),this.bodyObserver?.observe(r)}splitAttachments(r){let t=[];return{text:r.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` -`).trim(),attachments:t}}};function dr(c,r,t){return c.tree.getChildren(r).slice().sort((i,s)=>dA(c,i,s,t)).map(i=>i.id)}function dA(c,r,t,e){switch(e){case"created-asc":return(r.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(r.created||"");case"modified-asc":case"modified-desc":{let i=cr(c,r)||r.created||"",s=cr(c,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=c.titleForNode(r),s=c.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 cr(c,r){if(!r.file)return"";let t=c.app.metadataCache.getFileCache(r.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var ni=require("obsidian");gi();async function fo(c){let r=c.getActionTargets();if(!r.length)return;let t=j().prefixTimestampsOnCopy,e=[];for(let i of r){if(!i.file)continue;let s=await c.app.vault.cachedRead(i.file),n=c.stripFrontmatter(s).trim();e.push(t?`${c.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function Ta(c,r,t){return c.tree.getChildren(r).slice().sort((i,s)=>Nl(c,i,s,t)).map(i=>i.id)}function Nl(c,r,t,e){switch(e){case"created-asc":return(r.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(r.created||"");case"modified-asc":case"modified-desc":{let i=Ma(c,r)||r.created||"",s=Ma(c,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=c.titleForNode(r),s=c.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 Ma(c,r){if(!r.file)return"";let t=c.app.metadataCache.getFileCache(r.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var si=require("obsidian");gi();async function jn(c){let r=c.getActionTargets();if(!r.length)return;let t=Z().prefixTimestampsOnCopy,e=[];for(let i of r){if(!i.file)continue;let s=await c.app.vault.cachedRead(i.file),n=c.stripFrontmatter(s).trim();e.push(t?`${c.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` -`)),c.plugin.notifications.show({message:`Copied ${c.titleList(r)} to clipboard`,kind:"success",category:"system",affectedIds:r.map(i=>i.id),folder:c.noteFolder})}async function hr(c){let r=c.getActionTargets();if(!r.length||!r[0].file){new ni.Notice("Nothing to copy from.");return}let t=r[0],e=await c.app.vault.cachedRead(t.file),i=c.stripFrontmatter(e),s=Jo(i);if(s.length===0){c.plugin.notifications.show({message:`No codeblock found in "${c.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:c.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),c.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${c.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:c.noteFolder});return}let n=s.map((a,l)=>({kind:"one",idx:l,label:`${l+1}. ${a.lang||"(no language)"} \u2014 ${a.code.split(` +`)),c.plugin.notifications.show({message:`Copied ${c.titleList(r)} to clipboard`,kind:"success",category:"system",affectedIds:r.map(i=>i.id),folder:c.noteFolder})}async function Ha(c){let r=c.getActionTargets();if(!r.length||!r[0].file){new si.Notice("Nothing to copy from.");return}let t=r[0],e=await c.app.vault.cachedRead(t.file),i=c.stripFrontmatter(e),s=Jo(i);if(s.length===0){c.plugin.notifications.show({message:`No codeblock found in "${c.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:c.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),c.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${c.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:c.noteFolder});return}let n=s.map((a,l)=>({kind:"one",idx:l,label:`${l+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 ni.SuggestModal{getSuggestions(a){let l=a.trim().toLowerCase();if(!l)return n;let A=l.split(/\s+/).filter(Boolean);return n.filter(d=>{let h=d.label.toLowerCase();return A.every(g=>h.includes(g))})}renderSuggestion(a,l){l.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let l=a.kind==="all"?s.map(A=>A.code).join(` +`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends si.SuggestModal{getSuggestions(a){let l=a.trim().toLowerCase();if(!l)return n;let A=l.split(/\s+/).filter(Boolean);return n.filter(d=>{let h=d.label.toLowerCase();return A.every(g=>h.includes(g))})}renderSuggestion(a,l){l.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let l=a.kind==="all"?s.map(A=>A.code).join(` -`):s[a.idx].code;await navigator.clipboard.writeText(l),c.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${c.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${c.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:c.noteFolder})}}(c.app);o.setPlaceholder(`${s.length} codeblocks in "${c.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function pr(c){let r=c.getActionTargets();if(r.length===0){let n=c.tree.get(c.focusId);n?.file&&(r=[n])}if(r.length===0){new ni.Notice("Nothing to copy.");return}let t=j().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await c.app.vault.cachedRead(n.file),l=c.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),A=t?`${c.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${A}${l}`)}for(let a of c.tree.getChildren(n.id))await i(a,o+1)};for(let n of r)await i(n,0);let s=e.join(` -`);await navigator.clipboard.writeText(s),c.plugin.clearNoteClipboard(),c.plugin.noteClipboard={mode:"copy",folder:c.noteFolder,ids:r.map(n=>n.id),text:s},c.render(),c.plugin.notifications.show({message:`Copied tree of ${c.titleList(r)} (${e.length} entries) \u2014 paste in the list to clone, in a note to drop the outline in`,kind:"success",category:"system",affectedIds:r.map(n=>n.id),folder:c.noteFolder})}async function gr(c){let r=c.getActionTargets();if(r.length===0){let i=c.tree.get(c.focusId);i?.file&&(r=[i])}if(r.length===0){new ni.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 c.tree.getChildren(i.id))e(o,s+1)};for(let i of r)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),c.plugin.notifications.show({message:`Copied outline of ${c.titleList(r)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:r.map(i=>i.id),folder:c.noteFolder})}var xt=require("obsidian");rt();_i();Ft();function pA(c){return c.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function Ir(c,r){let t=fr(c,r);if(t.length===0){new xt.Notice("Nothing to export.");return}let e=Cr(c,t);if(e.length===0){new xt.Notice("No exportable notes (no files attached).");return}let i=(c.noteFolder.split("/").pop()||c.noteFolder).trim(),s=t.length===1?c.titleForNode(t[0]):`${i}-${t.length}notes`;new Ci(c.app,s,e.length,(n,o,a)=>{gA(c,t,e,n,o,a)},ps).open()}async function ur(c,r){let t=fr(c,r);if(t.length===0){new xt.Notice("Nothing to export.");return}let e=Cr(c,t);if(e.length===0){new xt.Notice("No exportable notes.");return}let i=(c.noteFolder.split("/").pop()||c.noteFolder).trim(),s=t.length===1?c.titleForNode(t[0]):`${i}-okf`;new Ei(c.app,s,e.length,(n,o)=>{(async()=>{try{let a=await c.plugin.exportOkf(c.noteFolder,t.map(l=>l.id),n,o);if(!a.length){new xt.Notice("Nothing exported.");return}c.plugin.notifications.show({message:`Exported OKF \u2014 ${a.length} file${a.length===1?"":"s"} \u2192 \`${c.noteFolder}/${c.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:a,folder:c.noteFolder,duration:0}),await c.log.append({type:"stash_export",id:t[0].id,payload:{okf:!0,paths:a,noteCount:e.length,rootIds:t.map(l=>l.id)}})}catch(a){new xt.Notice(`OKF export failed: ${a.message}`),console.error(a)}})()}).open()}async function gA(c,r,t,e,i,s=!1){try{let n=await ge(c.app,{rootNotes:r.filter(I=>!!I.file).map(I=>({id:I.id,file:I.file})),allDescendants:t.filter(I=>!r.some(p=>p.id===I.id)).filter(I=>!!I.file).map(I=>({id:I.id,file:I.file})),sourceFolder:c.noteFolder}),o="";if(i){let I=await We(n,i);n=I.data;let p=ua[I.kdf];o=p.strong?` (encrypted \xB7 ${p.label})`:` (encrypted \xB7 ${p.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,xt.moment)().format("YYYYMMDD-HHmmss"),l=pA(e),A=(c.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),d=`${c.noteFolder}/${A}`;await c.ensureFolder(d);let h=`${l}-${a}`,g=`${d}/${h}.${oe}`;if(await c.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let I=c.app.secretStorage;try{I?.setSecret(Ii(h),i)}catch(p){console.warn("[Stashpad] couldn't save export passphrase to secret storage",p)}}await c.log.append({type:"stash_export",id:r[0].id,payload:{path:g,noteCount:t.length,rootIds:r.map(I=>I.id)}}),c.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${g}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[g],folder:c.noteFolder,actions:c.actionsForFile(g),duration:0})}catch(n){c.plugin.notifications.show({message:`Stashpad: export failed +`):s[a.idx].code;await navigator.clipboard.writeText(l),c.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${c.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${c.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:c.noteFolder})}}(c.app);o.setPlaceholder(`${s.length} codeblocks in "${c.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function Pa(c){let r=c.getActionTargets();if(r.length===0){let n=c.tree.get(c.focusId);n?.file&&(r=[n])}if(r.length===0){new si.Notice("Nothing to copy.");return}let t=Z().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await c.app.vault.cachedRead(n.file),l=c.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),A=t?`${c.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${A}${l}`)}for(let a of c.tree.getChildren(n.id))await i(a,o+1)};for(let n of r)await i(n,0);let s=e.join(` +`);await navigator.clipboard.writeText(s),c.plugin.clearNoteClipboard(),c.plugin.noteClipboard={mode:"copy",folder:c.noteFolder,ids:r.map(n=>n.id),text:s},c.render(),c.plugin.notifications.show({message:`Copied tree of ${c.titleList(r)} (${e.length} entries) \u2014 paste in the list to clone, in a note to drop the outline in`,kind:"success",category:"system",affectedIds:r.map(n=>n.id),folder:c.noteFolder})}async function Ua(c){let r=c.getActionTargets();if(r.length===0){let i=c.tree.get(c.focusId);i?.file&&(r=[i])}if(r.length===0){new si.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 c.tree.getChildren(i.id))e(o,s+1)};for(let i of r)e(i,0);await navigator.clipboard.writeText(t.join(` +`)),c.plugin.notifications.show({message:`Copied outline of ${c.titleList(r)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:r.map(i=>i.id),folder:c.noteFolder})}var Nt=require("obsidian");lt();var Js=require("obsidian");qs();Ht();lt();var re="stash",sr=1;function er(c){let t=(c.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var po=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Ce(c,r){let t=[],e=tA([...r.rootNotes,...r.allDescendants]),i=new Map,s=[];for(let o of e){let a=await c.vault.read(o.file),l=a,A=nr(a);for(let d of A){let h=c.metadataCache.getFirstLinkpathDest(d,o.file.path);if(!h){s.push(`Missing attachment "${d}" in ${o.file.path}`);continue}let g=h.name;i.has(g)||i.set(g,await c.vault.readBinary(h)),l=eA(l,d,g)}l=nA(l,c,o.file.path),t.push({name:`notes/${o.file.name}`,data:l})}for(let[o,a]of i)t.push({name:`attachments/${o}`,data:a});let n={stashSchema:sr,exportedAt:new Date().toISOString(),sourceFolder:r.sourceFolder,noteCount:e.length,rootIds:r.rootNotes.map(o=>o.id)};return t.push({name:"manifest.json",data:JSON.stringify(n,null,2)}),s.length&&t.push({name:"warnings.txt",data:s.join(` +`)}),Ki(t,6)}async function Wt(c,r,t,e,i={}){let s=await Oi(r),n=s["manifest.json"];if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(Ls(n));if(typeof o.stashSchema!="number"||o.stashSchema>sr)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await ir(c,t);let a=Object.entries(s).filter(([E])=>E.startsWith("notes/")&&E.endsWith(".md")),l=[];for(let[E,v]of a){let w=Ls(v),{fm:D,body:N}=ct(w),P=er(E.slice(6))||`${D.id||"imported-"+tt(4)}.md`;l.push({originalName:P,fm:D,body:N})}let A=new Map,d=0;for(let E of l){let v=E.fm.id;v&&(i.forceNewIds?A.set(v,tt(6)):e.has(v)||A.has(v)?(A.set(v,`${v}-${tt(4)}-Imported`),d++):A.set(v,v))}let h=new Date().toISOString(),g=[],I=`${t}/_attachments`,p=0,u=Object.entries(s).filter(([E])=>E.startsWith("attachments/")),f=new Map,C=null;if(i.dedupeExisting){C=new Map;for(let E of c.vault.getFiles())C.has(E.name)||C.set(E.name,E.path)}let m=(E,v)=>{if(E.length!==v.length)return!1;for(let w=0;w<E.length;w++)if(E[w]!==v[w])return!1;return!0},B=!1;for(let[E,v]of u){let w=er(E.slice(12));if(!w)continue;let D=v,N=[],P=C?.get(w);P&&N.push(P);let H=`${I}/${w}`;await c.vault.adapter.exists(H)&&N.push(H);let b=null;for(let T of N)try{if(m(new Uint8Array(await c.vault.adapter.readBinary(T)),D)){b=T;break}}catch{}if(b){f.set(w,b);continue}let S=H;for(let T=1;await c.vault.adapter.exists(S);T++)S=`${I}/${iA(w,T)}`;f.set(w,S),B||(await ir(c,I),B=!0),await c.vault.createBinary(S,D.buffer),p++}let y=0;for(let E of l){let v=E.fm.id;if(!v){g.push(`Skipped ${E.originalName} \u2014 no id in frontmatter`);continue}let w=A.get(v),D=E.fm.parent??null,N=D;!D||D===F?N=i.reparentRootsTo??D??F:A.has(D)?N=A.get(D):N=e.has(D)?D:i.reparentRootsTo??F;let P=sA(E.body,f,I),H={...E.fm,id:w,parent:N,import_date:h};Array.isArray(H.attachments)&&(H.attachments=H.attachments.map(U=>{let L=or(ve(U));return Ot(f.get(L)??`${I}/${L}`)}));let b=me(H,P),S=w===v?E.originalName:aA(E.originalName,v,w),T=`${t}/${S}`;await c.vault.adapter.exists(T)&&(S=`${S.replace(/\.md$/,"")}-${tt(4)}.md`,T=`${t}/${S}`),await c.vault.create(T,b),y++}let Q;if(o.colorAliases&&typeof o.colorAliases=="object"){let E={};for(let[v,w]of Object.entries(o.colorAliases)){let D=String(v).trim().toLowerCase(),N=String(w??"").trim();/^#([0-9a-f]{6})$/.test(D)&&N&&(E[D]=N.slice(0,60))}Object.keys(E).length&&(Q=E)}return{notesWritten:y,attachmentsWritten:p,collisionsRenamed:d,warnings:g,colorAliases:Q,idRemap:Object.fromEntries(A)}}function tA(c){let r=new Set,t=[];for(let e of c)r.has(e.id)||(r.add(e.id),t.push(e));return t}function nr(c){let r=new Set,t;for(po.lastIndex=0;(t=po.exec(c))!==null;)r.add(t[1]);return[...r]}async function Ks(c,r){let t=await c.vault.read(r),e=[],i=new Set;for(let s of nr(t)){let n=c.metadataCache.getFirstLinkpathDest(s,r.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function eA(c,r,t){return c.replace(new RegExp(`!\\[\\[${oA(r)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function iA(c,r){let t=c.lastIndexOf(".");return t>0?`${c.slice(0,t)}-${r}${c.slice(t)}`:`${c}-${r}`}function sA(c,r,t){return c.replace(po,(e,i,s)=>{if(i.includes("/"))return e;let n=r.get(i)??`${t}/${i}`;return e.replace(i,n)})}function nA(c,r,t){let e=ct(c);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return c;let i=e.fm.attachments.map(n=>{let o=r.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:or(n)}),s={...e.fm,attachments:i};return me(s,e.body)}function oA(c){return c.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function or(c){let r=c.lastIndexOf("/");return r<0?c:c.slice(r+1)}function aA(c,r,t){return c.includes(r)?c.replace(r,t):c.replace(/\.md$/,`-${t}.md`)}function ct(c){if(!c.startsWith("---"))return{fm:{},body:c};let r=c.indexOf(` +---`,3);if(r<0)return{fm:{},body:c};let t=c.slice(3,r).replace(/^\n/,""),e=c.slice(r+4),i={};try{i=(0,Js.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` +`)?e.slice(1):e;return{fm:i,body:s}}function me(c,r){return`--- +${(0,Js.stringifyYaml)(c).trimEnd()} +--- +${r}`}async function ir(c,r){if(!(!r||await c.vault.adapter.exists(r)))try{await c.vault.createFolder(r)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}ts();Ft();function rA(c){return c.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function ar(c,r){let t=lr(c,r);if(t.length===0){new Nt.Notice("Nothing to export.");return}let e=Ar(c,t);if(e.length===0){new Nt.Notice("No exportable notes (no files attached).");return}let i=(c.noteFolder.split("/").pop()||c.noteFolder).trim(),s=t.length===1?c.titleForNode(t[0]):`${i}-${t.length}notes`;new Ci(c.app,s,e.length,(n,o,a)=>{lA(c,t,e,n,o,a)},gs).open()}async function rr(c,r){let t=lr(c,r);if(t.length===0){new Nt.Notice("Nothing to export.");return}let e=Ar(c,t);if(e.length===0){new Nt.Notice("No exportable notes.");return}let i=(c.noteFolder.split("/").pop()||c.noteFolder).trim(),s=t.length===1?c.titleForNode(t[0]):`${i}-okf`;new Ei(c.app,s,e.length,(n,o)=>{(async()=>{try{let a=await c.plugin.exportOkf(c.noteFolder,t.map(l=>l.id),n,o);if(!a.length){new Nt.Notice("Nothing exported.");return}c.plugin.notifications.show({message:`Exported OKF \u2014 ${a.length} file${a.length===1?"":"s"} \u2192 \`${c.noteFolder}/${c.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:a,folder:c.noteFolder,duration:0}),await c.log.append({type:"stash_export",id:t[0].id,payload:{okf:!0,paths:a,noteCount:e.length,rootIds:t.map(l=>l.id)}})}catch(a){new Nt.Notice(`OKF export failed: ${a.message}`),console.error(a)}})()}).open()}async function lA(c,r,t,e,i,s=!1){try{let n=await Ce(c.app,{rootNotes:r.filter(I=>!!I.file).map(I=>({id:I.id,file:I.file})),allDescendants:t.filter(I=>!r.some(p=>p.id===I.id)).filter(I=>!!I.file).map(I=>({id:I.id,file:I.file})),sourceFolder:c.noteFolder}),o="";if(i){let I=await We(n,i);n=I.data;let p=ua[I.kdf];o=p.strong?` (encrypted \xB7 ${p.label})`:` (encrypted \xB7 ${p.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,Nt.moment)().format("YYYYMMDD-HHmmss"),l=rA(e),A=(c.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),d=`${c.noteFolder}/${A}`;await c.ensureFolder(d);let h=`${l}-${a}`,g=`${d}/${h}.${re}`;if(await c.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let I=c.app.secretStorage;try{I?.setSecret(Ii(h),i)}catch(p){console.warn("[Stashpad] couldn't save export passphrase to secret storage",p)}}await c.log.append({type:"stash_export",id:r[0].id,payload:{path:g,noteCount:t.length,rootIds:r.map(I=>I.id)}}),c.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${g}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[g],folder:c.noteFolder,actions:c.actionsForFile(g),duration:0})}catch(n){c.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 fr(c,r){if(r?.file)return[r];if(c.selection.size>0)return[...c.selection].map(e=>c.tree.get(e)).filter(e=>!!e?.file);if(c.cursorIdx>=0&&c.currentChildren[c.cursorIdx])return[c.currentChildren[c.cursorIdx]];let t=c.tree.get(c.focusId);return t?.file?[t]:[]}function Cr(c,r){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 c.tree.getChildren(s.id))i(n)}};for(let s of r)i(s);return e}async function mr(c){let r=c.app.vault.getFiles().filter(e=>e.extension===oe);if(r.length===0){new xt.Notice("No .stash files found in this vault.");return}let t=new class extends xt.FuzzySuggestModal{getItems(){return r}getItemText(e){return e.path}onChooseItem(e){Co(c,e)}}(c.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Co(c,r){try{let t=new Uint8Array(await c.app.vault.readBinary(r)),e=await Xe(c.app,t,{secretId:Ii(r.basename)});if(!e)return;let i=await Vt(c.app,e,c.noteFolder,IA(c));c.tree.rebuild(c.noteFolder),c.render(),await c.log.append({type:"stash_import",id:F,payload:{from:r.path,into:c.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await c.app.fileManager.trashFile(r)}catch{}c.plugin.importService.clearPendingEncrypted(r.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)`),c.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:c.noteFolder})}catch(t){c.plugin.notifications.show({message:`Stashpad: import failed +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function lr(c,r){if(r?.file)return[r];if(c.selection.size>0)return[...c.selection].map(e=>c.tree.get(e)).filter(e=>!!e?.file);if(c.cursorIdx>=0&&c.currentChildren[c.cursorIdx])return[c.currentChildren[c.cursorIdx]];let t=c.tree.get(c.focusId);return t?.file?[t]:[]}function Ar(c,r){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 c.tree.getChildren(s.id))i(n)}};for(let s of r)i(s);return e}async function cr(c){let r=c.app.vault.getFiles().filter(e=>e.extension===re);if(r.length===0){new Nt.Notice("No .stash files found in this vault.");return}let t=new class extends Nt.FuzzySuggestModal{getItems(){return r}getItemText(e){return e.path}onChooseItem(e){go(c,e)}}(c.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function go(c,r){try{let t=new Uint8Array(await c.app.vault.readBinary(r)),e=await Xe(c.app,t,{secretId:Ii(r.basename)});if(!e)return;let i=await Wt(c.app,e,c.noteFolder,AA(c));c.tree.rebuild(c.noteFolder),c.render(),await c.log.append({type:"stash_import",id:F,payload:{from:r.path,into:c.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await c.app.fileManager.trashFile(r)}catch{}c.plugin.importService.clearPendingEncrypted(r.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)`),c.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:c.noteFolder})}catch(t){c.plugin.notifications.show({message:`Stashpad: import failed File: \`${r.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:[r.path],actions:c.actionsForFile(r.path)}),console.error(t)}}function IA(c){let r=new Set,t=e=>{if(r.add(e),!!c.tree.get(e))for(let s of c.tree.getChildren(e))t(s.id)};return t(F),r}gi();gi();var fA=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),zs={nested:"Nested",flat:"Flat",everything:"Everything"},$s=[{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"}],Oi=class Oi extends k.ItemView{constructor(t,e){super(t);this.focusId=F;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.bulkRenderDepth=0;this.bulkSettleTimer=null;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.pendingCursorId=null;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.tapSettleUntil=0;this.aimedTapTargetId=null;this.aimedTapAt=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.activeVersionByGroup=new Map;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||qo(t.target))return;let e=j().bindings;if(G(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(G(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(G(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(G(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(G(t,e.lockSelection)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdLockSelection();return}if(G(t,e.unlockAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUnlockAll();return}if(G(t,e.moveToArchive)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToArchive();return}if(G(t,e.encryptDelete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdEncryptDelete();return}if(G(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(G(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(G(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(G(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(G(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 l=this.composerInputEl;if(l){t.preventDefault(),t.stopPropagation(),l.focus();let A=l.value.length;l.setSelectionRange(A,A);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 l=this.listEl,A=!!l&&l.scrollTop+l.clientHeight>=l.scrollHeight-2,d=l?.scrollTop??0;if(this.render(),l){let h=A?l.scrollHeight:d;l.scrollTop=h,requestAnimationFrame(()=>{l.scrollTop=A?l.scrollHeight:d}),setTimeout(()=>{l.scrollTop=A?l.scrollHeight:d},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(G(t,j().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(G(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(G(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(G(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(G(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(G(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(G(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(G(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(G(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(G(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(G(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(G(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(G(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let l=this.composerInputEl;if(l){l.focus();let A=l.value.length;l.setSelectionRange(A,A)}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 l=this.currentChildren[this.cursorIdx];l&&(t.preventDefault(),this.navigateTo(l.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;if(this.plugin.noteClipboard&&this.plugin.noteClipboard.folder===this.noteFolder){this.plugin.clearNoteClipboard(),this.render();return}let l=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,l){let A=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,A>=0&&(this.cursorIdx=A)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=j().bindings;if(G(t,o.pasteNotes)&&this.plugin.noteClipboard){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdPasteNotes();return}if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(G(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(G(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(G(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(G(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(G(t,o.copyNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyNotes();return}if(G(t,o.cutNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCutNotes();return}if(G(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(G(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(G(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(G(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let l=this.tree.get(this.focusId);l?.file&&this.cmdOpenInEditor(l)}else this.cmdOpenInEditor();return}if(G(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(G(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(G(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(G(t,o.forkNote)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdForkNote();return}if(G(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(G(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(G(t,o.expandAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExpandAll();return}if(G(t,o.collapseAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCollapseAll();return}if(G(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(G(t,o.listPin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleListPin();return}if(G(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(G(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(G(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(G(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(G(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(G(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.listPinnedState=new Map;this.pendingFocusIds=null;this.onFileModify=t=>{!(t instanceof k.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 k.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Ps(this.app),this.log=e.newLog(),this.integrity=new qs(this.tree,this.log),this.order=new ti(this.app),this.sortStore=new Us(this.app),this.fmSync=new Rs(this.app,()=>this.tree),this.tree.setOrderProvider(i=>{let s=this.noteFolder,n=this.sortStore.getMode(s,i),o=n==="manual"?this.order.getOrder(s,i):dr(this,i,n);return this.hoistListPinned(i,o)}),this.debouncedRender=(0,k.debounce)(()=>{this.renderSuppressed()||this.render()},80),this.authorship=new Ks(this),this.dnd=new Os(this),this.bodyRenderer=new Ys(this,this,this.plugin.renderCacheStore)}getViewType(){return K}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==F){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} \xB7 ${this.focusId}`}}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",()=>bs(this)),this.viewRoot.addEventListener("click",()=>bs(this)),this.viewRoot.addEventListener("mouseup",l=>{l.button===3?(l.preventDefault(),this.navigateBack()):l.button===4&&(l.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",l=>{l.button===3?(l.preventDefault(),this.navigateBack()):l.button===4&&(l.preventDefault(),this.navigateForward())}),bs(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new k.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 l=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,l){let A=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,A>=0&&(this.cursorIdx=A)}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",l=>{let A=l.relatedTarget;A&&this.viewRoot&&this.viewRoot.contains(A)||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",l=>{if(l.extension!=="md")return;let A=this.app.metadataCache.getFileCache(l)?.frontmatter;this.completedState.set(l.path,!!A?.completed),this.taskTaggedState.set(l.path,this.taggedFromFm(A))})),this.registerEvent(this.app.vault.on("rename",(l,A)=>{for(let d of[this.completedState,this.taskTaggedState])d.has(A)&&(d.set(l.path,d.get(A)),d.delete(A))})),this.registerEvent(this.app.vault.on("delete",l=>{this.completedState.delete(l.path),this.taskTaggedState.delete(l.path);let A=l.path.lastIndexOf("/"),d=(A>=0?l.path.slice(0,A):"").replace(/\/+$/,"");l.path.endsWith(".md")&&d===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=sr(()=>{this.loadConfig();let l=this.plugin.settings.drafts?.[this.noteFolder]??"",A=this.composerInputEl?.value??"";l===""&&this.composerDraft!==""&&A===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):l===""&&A!==""&&(this.composerDraft=A),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(l){let A=l?.message??"";/already exists/i.test(A)||console.warn("[Stashpad] bootstrapFolder failed:",l)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let l=this.plugin.loadLastCursor(this.noteFolder);for(let[A,d]of l)this.lastCursorByFocus.set(A,d);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder),this.activeVersionByGroup=this.plugin.loadActiveVersions(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",l=>{l===this.leaf?this.focusComposer():this.stickToListBottom=!1}))}renderSuppressed(){return this.bulkRenderDepth>0||this.bulkSettleTimer!=null||this.plugin.rebootstrapInProgress||this.plugin.okfRebuildingFolders.has(this.noteFolder)}beginBulkRender(){this.bulkRenderDepth++,this.bulkSettleTimer!=null&&(window.clearTimeout(this.bulkSettleTimer),this.bulkSettleTimer=null)}endBulkRender(t=500){this.bulkRenderDepth>0&&this.bulkRenderDepth--,!(this.bulkRenderDepth>0)&&(this.bulkSettleTimer!=null&&window.clearTimeout(this.bulkSettleTimer),this.bulkSettleTimer=window.setTimeout(()=>{this.bulkSettleTimer=null,this.viewRoot?.isConnected&&(this.tree.rebuild(this.noteFolder),this.render())},t))}forceReconcileRender(){this.viewRoot?.isConnected&&(this.tree.rebuild(this.noteFolder),this.render())}scheduleTreeReconcile(){this.renderSuppressed()||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(!j().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(){tr(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 A=this.plugin.loadLastCursor(this.noteFolder);for(let[d,h]of A)this.lastCursorByFocus.set(d,h);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder),this.activeVersionByGroup=this.plugin.loadActiveVersions(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 l=this.foldRestoredSelection(o);l&&(this.pendingFocusIds=l),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(l=>l.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 k.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=F,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 k.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 k.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 k.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 l of t)!l.file||s.has(l.file.path)||(s.add(l.file.path),i.push(l.file));let n=await Promise.all(i.map(l=>this.app.vault.read(l))),o=i.map((l,A)=>({path:l.path,content:n[A]})),a=[];if(e){let l=new Set,A=[];for(let h of n)for(let g of this.extractAttachments(this.stripFrontmatter(h))){let I=this.app.metadataCache.getFirstLinkpathDest(g,"");I&&!l.has(I.path)&&(l.add(I.path),A.push(I))}let d=await Promise.all(A.map(h=>this.app.vault.readBinary(h)));for(let h=0;h<A.length;h++)a.push({path:A[h].path,data:d[h]})}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,k.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()}currentEncryptionFilter(){return this.plugin.settings.encryptionFilter?.[this.noteFolder]??"all"}async setEncryptionFilter(t){let e={...this.plugin.settings.encryptionFilter??{}};t==="all"?delete e[this.noteFolder]:e[this.noteFolder]=t,this.plugin.settings.encryptionFilter=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 k.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof k.TFolder){s.push(o);continue}if(!(o instanceof k.TFile)||o.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let l of a.attachments){if(typeof l!="string")continue;let A=Fe(l),d=this.app.metadataCache.getFirstLinkpathDest(A,o.path);d?t.add(d.path):t.add(A)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof k.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],l=[i];for(;l.length;){let A=l.pop();for(let d of A.children){if(d instanceof k.TFolder){let h=d.name;if(A===i&&o.has(h)||A===i&&h==="_attachments"&&!s)continue;l.push(d);continue}d instanceof k.TFile&&d.extension!=="md"&&(d.name===".stashpad-order.json"||d.name===".stashpad-sort.json"||!s&&n.has(d.path)||a.push(d))}}return a}populateListBody(t,e){if(this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),this.pendingCursorId){let d=this.currentChildren.findIndex(h=>h.id===this.pendingCursorId);d>=0&&(this.cursorIdx=d,this.selection.clear(),this.selection.add(this.pendingCursorId),this.lastSelected=this.pendingCursorId,this.pendingCursorId=null)}e.file&&k.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode(),s=i==="everything"?this.collectFileItems(e.id):[],n=d=>d.created&&Number.isFinite(Date.parse(d.created))?Date.parse(d.created):Number.POSITIVE_INFINITY,o=this.currentEncryptionFilter(),a;if(o==="unlocked")a=[];else if(i==="nested")a=this.plugin.lockedSubtreesFor(this.noteFolder,e.id);else{let d=new Set([e.id,...this.currentChildren.map(g=>g.id)]),h=new Set;a=[];for(let g of d)for(let I of this.plugin.lockedSubtreesFor(this.noteFolder,g))h.has(I.blob)||(h.add(I.blob),a.push(I))}let l=a.map(d=>({lk:d,ts:n(d)})).sort((d,h)=>d.ts-h.ts),A=i==="nested"&&this.sortStore.getMode(this.noteFolder,e.id)==="manual";if(this.currentChildren.length===0&&s.length===0&&l.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(A&&l.length>0){let d=new Map(this.currentChildren.map((u,f)=>[u.id,f])),h=new Map;for(let{lk:u}of l)u.rootId&&h.set(u.rootId,u);let g=this.currentChildren.map(u=>u.id),I=l.map(({lk:u})=>u).filter(u=>u.rootId).sort((u,f)=>n(f)-n(u)),p=!0;for(;I.length&&p;){p=!1;for(let u=0;u<I.length;u++){let f=I[u],C=f.prevSibling??null,m;if(C==null)m=0;else{let B=g.indexOf(C);if(B<0)continue;m=B+1}g.splice(m,0,f.rootId),I.splice(u,1),u--,p=!0}}for(let u of I)g.push(u.rootId);for(let u of g){let f=d.get(u);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let C=h.get(u);C&&this.renderLockedPlaceholder(t,C)}}for(let u of s.slice().sort((f,C)=>f.stat.ctime-C.stat.ctime))this.renderFileRow(t,u)}else if(s.length===0){let d=0;for(let h=0;h<this.currentChildren.length;h++){let g=Number.isFinite(Date.parse(this.currentChildren[h].created))?Date.parse(this.currentChildren[h].created):0;for(;d<l.length&&l[d].ts<=g;)this.renderLockedPlaceholder(t,l[d].lk),d++;this.renderNote(t,this.currentChildren[h],h)}for(;d<l.length;)this.renderLockedPlaceholder(t,l[d].lk),d++}else{let d=[...this.currentChildren.map((h,g)=>({kind:"note",ts:Number.isFinite(Date.parse(h.created))?Date.parse(h.created):0,idx:g})),...s.map(h=>({kind:"file",ts:h.stat.ctime,file:h})),...l.map(h=>({kind:"lock",ts:h.ts,lk:h.lk}))];d.sort((h,g)=>h.ts-g.ts);for(let h of d)h.kind==="note"?this.renderNote(t,this.currentChildren[h.idx],h.idx):h.kind==="file"?this.renderFileRow(t,h.file):this.renderLockedPlaceholder(t,h.lk)}e.file&&k.Platform.isMobile&&this.installFocusedMiniObserver(t)}renderLockedPlaceholder(t,e){let i=t.createDiv({cls:"stashpad-locked-row"});e.created&&i.createSpan({cls:"stashpad-note-time stashpad-locked-time",text:this.formatTime(e.created)});let s=i.createSpan({cls:"stashpad-locked-icon"});(0,k.setIcon)(s,"lock");let n=(this.plugin.settings.hideLockedTitles??!1)||!e.title;i.createSpan({cls:"stashpad-locked-title",text:n?"Locked note":e.title}),i.createSpan({cls:"stashpad-locked-count",text:e.count>1?`${e.count} notes \xB7 locked`:"locked"});let o=i.createEl("button",{cls:"stashpad-locked-unlock",text:"Unlock"});(0,k.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async A=>{A.preventDefault(),A.stopPropagation();let d=(this.plugin.settings.lockedSubtrees??[]).find(u=>u.blob===e.blob),h=e.rootId??d?.rootId??null,g=e.parentId??d?.parentId??F,I=e.prevSibling??d?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,h){let u=this.order.getOrder(this.noteFolder,g),f=this.sortStore.getMode(this.noteFolder,g)==="manual";if(u.length===0&&f&&(u=this.tree.getChildren(g).map(C=>C.id)),u.length>0){let C=u.filter(B=>B!==h),m=I&&C.includes(I)?C.indexOf(I)+1:0;C.splice(Math.max(0,m),0,h),this.order.setOrder(this.noteFolder,g,C),this.order.flush(this.noteFolder)}this.pendingCursorId=h}this.render()}};o.onclick=a;let l=A=>{A.preventDefault(),A.stopPropagation();let d=new k.Menu;if(d.addItem(h=>h.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(A))),!k.Platform.isMobile){let h=k.Platform.isMacOS?"Finder":k.Platform.isWin?"File Explorer":"file manager";d.addItem(g=>g.setTitle(`Show in ${h}`).setIcon("folder-search").onClick(()=>{try{let I=window.require?.("electron")?.shell,p=this.app.vault.adapter?.getFullPath?.(e.blob);p&&I?.showItemInFolder&&I.showItemInFolder(p)}catch(I){console.warn("[Stashpad] showItemInFolder failed",I)}}))}d.addItem(h=>h.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let g=e.blob;if(!k.Platform.isMobile)try{g=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(g),new k.Notice("Path copied.")})),d.showAtMouseEvent(A)};if(i.oncontextmenu=l,k.Platform.isMobile){let A=i.createEl("button",{cls:"stashpad-locked-menu"});(0,k.setIcon)(A,"more-vertical"),A.setAttr("aria-label","Locked note menu"),A.onclick=d=>l(d)}i.setAttr("aria-label",`${n?"Locked note":`Locked: ${e.title}`}. Use the Unlock button to decrypt.`)}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){if(this.currentEncryptionFilter()==="locked")return;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(l=>l.children.length>0):s;if(e==="nested")return n;let o=[],a=l=>{o.push(l);for(let A of this.tree.getChildren(l.id))a(A)};for(let l of n)a(l);return o}filterChildren(t){t=this.collapseVersions(t);let e=this.timeFilterCutoff(),i=this.tagFilter?.toLowerCase(),s=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),o=this.currentAttachmentsOnly(),a=this.importedOnly,l=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!a&&!l?t:t.filter(A=>{if(a&&(!A.file||this.app.metadataCache.getFileCache(A.file)?.frontmatter?.imported!==!0))return!1;if(l){if(!A.file)return!1;let d=Ae(this.app.metadataCache.getFileCache(A.file)?.frontmatter?.author);if(!d||d.id!==l)return!1}if(e&&A.created){let d=Date.parse(A.created);if(!Number.isNaN(d)&&d<e)return!1}if(i){if(!A.file)return!1;if(this.tagFilter===Se){if(!this.nodeHasAnyTag(A))return!1}else if(this.tagFilter===De){if(this.nodeHasAnyTag(A))return!1}else if(!this.nodeHasTag(A,i))return!1}return!(s&&(this.colorForNode(A)?.toLowerCase()??null)!==s||n&&this.isCompleted(A)&&!this.hasIncompleteDescendant(A)||o&&!this.hasAttachmentInSubtree(A))})}collapseVersions(t){if(!this.plugin.settings.enableSheetVersions)return t;let e=new Map,i=!1;for(let n of t){let o=ut(this.app,n);if(!li(o))continue;i=!0;let a=Kt(o),l=e.get(a);l?l.push(n):e.set(a,[n])}if(!i)return t;let s=new Set;for(let[n,o]of e){let a=this.activeVersionNode(n,o);a&&s.add(a.id)}return t.filter(n=>li(ut(this.app,n))?s.has(n.id):!0)}activeVersionNode(t,e){let i=this.activeVersionByGroup.get(t);if(i){let s=e.find(n=>n.id===i);if(s)return s}return xo(this.app,e)}setActiveVersion(t,e){this.activeVersionByGroup.set(t,e),this.plugin.saveActiveVersion(this.noteFolder,t,e),this.render()}nodeHasAnyTag(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file);if(!e)return!1;if(e.tags&&e.tags.length>0)return!0;let i=e.frontmatter?.tags;return!!(i&&(Array.isArray(i)?i:[i]).some(n=>typeof n=="string"&&n.trim().length>0))}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 l=(a.tag||"").replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let l of a){if(typeof l!="string")continue;let A=l.replace(/^#/,"");A&&t.set(A,(t.get(A)??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){wt.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",k.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let l=this.containerEl.closest(".workspace-leaf");l&&(l.classList.toggle("stashpad-is-tiny",this.tinyMode),l.classList.toggle("stashpad-is-compact",this.compactMode));let A=this.containerEl.closest(".workspace-tabs");A&&A.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let d=this.tree.get(this.focusId)??this.tree.getRoot();d.file&&!k.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,d),this.currentChildren=this.filterChildren(this.collectViewItems(d.id));let h=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let p=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(p.id),this.lastSelected=p.id,this.autoSelectNewest=!1,h=!0}else if(this.pendingFocusIds){let p=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let u=-1;for(let f of p){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=p.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let g=e.createDiv({cls:"stashpad-list"});if(this.listEl=g,this.dnd.attachListDnD(g),this.populateListBody(g,d),this.renderComposer(e),k.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(wt.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),h&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let p=this.pendingComposerCaret;this.pendingComposerCaret=null;let u=this.composerInputEl;if(u&&u.isConnected){if(u.focus({preventScroll:!0}),p!=null){let f=Math.min(p,u.value.length);try{u.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),p!=null)){let C=Math.min(p,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let I=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,I&&this.listEl){let p=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,I.kind){case"preserve":p?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=I.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=I.id,f=I.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let B=C.querySelector(`[data-id="${u}"]`);B&&B.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 p=this.listEl,u=p.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){p.scrollTop=p.scrollHeight,u=p.scrollTop;return}let m=Math.max(0,p.scrollHeight-p.clientHeight);p.scrollTop<u&&u<=m?p.scrollTop=u:u=p.scrollTop});f.observe(p),this.listResizeObserver=f,p.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;p.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),p.addEventListener("touchmove",m=>{let B=m.touches[0]?.clientY??C;B>C&&(this.stickToListBottom=!1),C=B},{passive:!0}),p.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),p.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,k.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:[r.path],actions:c.actionsForFile(r.path)}),console.error(t)}}function AA(c){let r=new Set,t=e=>{if(r.add(e),!!c.tree.get(e))for(let s of c.tree.getChildren(e))t(s.id)};return t(F),r}gi();gi();var dA=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),Os={nested:"Nested",flat:"Flat",everything:"Everything"},Ys=[{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"}],Yi=class Yi extends k.ItemView{constructor(t,e){super(t);this.focusId=F;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.bulkRenderDepth=0;this.bulkSettleTimer=null;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.pendingCursorId=null;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.tapSettleUntil=0;this.aimedTapTargetId=null;this.aimedTapAt=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.activeVersionByGroup=new Map;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||qo(t.target))return;let e=Z().bindings;if(G(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(G(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(G(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(G(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(G(t,e.lockSelection)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdLockSelection();return}if(G(t,e.unlockAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUnlockAll();return}if(G(t,e.moveToArchive)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToArchive();return}if(G(t,e.encryptDelete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdEncryptDelete();return}if(G(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(G(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(G(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(G(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(G(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 l=this.composerInputEl;if(l){t.preventDefault(),t.stopPropagation(),l.focus();let A=l.value.length;l.setSelectionRange(A,A);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 l=this.listEl,A=!!l&&l.scrollTop+l.clientHeight>=l.scrollHeight-2,d=l?.scrollTop??0;if(this.render(),l){let h=A?l.scrollHeight:d;l.scrollTop=h,requestAnimationFrame(()=>{l.scrollTop=A?l.scrollHeight:d}),setTimeout(()=>{l.scrollTop=A?l.scrollHeight:d},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(G(t,Z().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(G(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(G(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(G(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(G(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(G(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(G(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(G(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(G(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(G(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(G(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(G(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(G(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let l=this.composerInputEl;if(l){l.focus();let A=l.value.length;l.setSelectionRange(A,A)}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 l=this.currentChildren[this.cursorIdx];l&&(t.preventDefault(),this.navigateTo(l.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;if(this.plugin.noteClipboard&&this.plugin.noteClipboard.folder===this.noteFolder){this.plugin.clearNoteClipboard(),this.render();return}let l=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,l){let A=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,A>=0&&(this.cursorIdx=A)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=Z().bindings;if(G(t,o.pasteNotes)&&this.plugin.noteClipboard){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdPasteNotes();return}if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(G(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(G(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(G(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(G(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(G(t,o.copyNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyNotes();return}if(G(t,o.cutNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCutNotes();return}if(G(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(G(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(G(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(G(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let l=this.tree.get(this.focusId);l?.file&&this.cmdOpenInEditor(l)}else this.cmdOpenInEditor();return}if(G(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(G(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(G(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(G(t,o.forkNote)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdForkNote();return}if(G(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(G(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(G(t,o.expandAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExpandAll();return}if(G(t,o.collapseAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCollapseAll();return}if(G(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(G(t,o.listPin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleListPin();return}if(G(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(G(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(G(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(G(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(G(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(G(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.listPinnedState=new Map;this.pendingFocusIds=null;this.onFileModify=t=>{!(t instanceof k.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 k.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new ks(this.app),this.log=e.newLog(),this.integrity=new xs(this.tree,this.log),this.order=new _e(this.app),this.sortStore=new Ss(this.app),this.fmSync=new bs(this.app,()=>this.tree),this.tree.setOrderProvider(i=>{let s=this.noteFolder,n=this.sortStore.getMode(s,i),o=n==="manual"?this.order.getOrder(s,i):Ta(this,i,n);return this.hoistListPinned(i,o)}),this.debouncedRender=(0,k.debounce)(()=>{this.renderSuppressed()||this.render()},80),this.authorship=new Ts(this),this.dnd=new Hs(this),this.bodyRenderer=new Ps(this,this,this.plugin.renderCacheStore)}getViewType(){return J}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==F){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} \xB7 ${this.focusId}`}}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",()=>Qs(this)),this.viewRoot.addEventListener("click",()=>Qs(this)),this.viewRoot.addEventListener("mouseup",l=>{l.button===3?(l.preventDefault(),this.navigateBack()):l.button===4&&(l.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",l=>{l.button===3?(l.preventDefault(),this.navigateBack()):l.button===4&&(l.preventDefault(),this.navigateForward())}),Qs(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new k.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 l=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,l){let A=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,A>=0&&(this.cursorIdx=A)}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",l=>{let A=l.relatedTarget;A&&this.viewRoot&&this.viewRoot.contains(A)||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",l=>{if(l.extension!=="md")return;let A=this.app.metadataCache.getFileCache(l)?.frontmatter;this.completedState.set(l.path,!!A?.completed),this.taskTaggedState.set(l.path,this.taggedFromFm(A))})),this.registerEvent(this.app.vault.on("rename",(l,A)=>{for(let d of[this.completedState,this.taskTaggedState])d.has(A)&&(d.set(l.path,d.get(A)),d.delete(A))})),this.registerEvent(this.app.vault.on("delete",l=>{this.completedState.delete(l.path),this.taskTaggedState.delete(l.path);let A=l.path.lastIndexOf("/"),d=(A>=0?l.path.slice(0,A):"").replace(/\/+$/,"");l.path.endsWith(".md")&&d===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=Fa(()=>{this.loadConfig();let l=this.plugin.settings.drafts?.[this.noteFolder]??"",A=this.composerInputEl?.value??"";l===""&&this.composerDraft!==""&&A===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):l===""&&A!==""&&(this.composerDraft=A),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(l){let A=l?.message??"";/already exists/i.test(A)||console.warn("[Stashpad] bootstrapFolder failed:",l)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let l=this.plugin.loadLastCursor(this.noteFolder);for(let[A,d]of l)this.lastCursorByFocus.set(A,d);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder),this.activeVersionByGroup=this.plugin.loadActiveVersions(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",l=>{l===this.leaf?this.focusComposer():this.stickToListBottom=!1}))}renderSuppressed(){return this.bulkRenderDepth>0||this.bulkSettleTimer!=null||this.plugin.rebootstrapInProgress||this.plugin.okfRebuildingFolders.has(this.noteFolder)}beginBulkRender(){this.bulkRenderDepth++,this.bulkSettleTimer!=null&&(window.clearTimeout(this.bulkSettleTimer),this.bulkSettleTimer=null)}endBulkRender(t=500){this.bulkRenderDepth>0&&this.bulkRenderDepth--,!(this.bulkRenderDepth>0)&&(this.bulkSettleTimer!=null&&window.clearTimeout(this.bulkSettleTimer),this.bulkSettleTimer=window.setTimeout(()=>{this.bulkSettleTimer=null,this.viewRoot?.isConnected&&(this.tree.rebuild(this.noteFolder),this.render())},t))}forceReconcileRender(){this.viewRoot?.isConnected&&(this.tree.rebuild(this.noteFolder),this.render())}scheduleTreeReconcile(){this.renderSuppressed()||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(!Z().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(){Ea(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 A=this.plugin.loadLastCursor(this.noteFolder);for(let[d,h]of A)this.lastCursorByFocus.set(d,h);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder),this.activeVersionByGroup=this.plugin.loadActiveVersions(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 l=this.foldRestoredSelection(o);l&&(this.pendingFocusIds=l),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(l=>l.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 k.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=F,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 k.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 k.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 k.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 l of t)!l.file||s.has(l.file.path)||(s.add(l.file.path),i.push(l.file));let n=await Promise.all(i.map(l=>this.app.vault.read(l))),o=i.map((l,A)=>({path:l.path,content:n[A]})),a=[];if(e){let l=new Set,A=[];for(let h of n)for(let g of this.extractAttachments(this.stripFrontmatter(h))){let I=this.app.metadataCache.getFirstLinkpathDest(g,"");I&&!l.has(I.path)&&(l.add(I.path),A.push(I))}let d=await Promise.all(A.map(h=>this.app.vault.readBinary(h)));for(let h=0;h<A.length;h++)a.push({path:A[h].path,data:d[h]})}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,k.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()}currentEncryptionFilter(){return this.plugin.settings.encryptionFilter?.[this.noteFolder]??"all"}async setEncryptionFilter(t){let e={...this.plugin.settings.encryptionFilter??{}};t==="all"?delete e[this.noteFolder]:e[this.noteFolder]=t,this.plugin.settings.encryptionFilter=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 k.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof k.TFolder){s.push(o);continue}if(!(o instanceof k.TFile)||o.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let l of a.attachments){if(typeof l!="string")continue;let A=ve(l),d=this.app.metadataCache.getFirstLinkpathDest(A,o.path);d?t.add(d.path):t.add(A)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof k.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],l=[i];for(;l.length;){let A=l.pop();for(let d of A.children){if(d instanceof k.TFolder){let h=d.name;if(A===i&&o.has(h)||A===i&&h==="_attachments"&&!s)continue;l.push(d);continue}d instanceof k.TFile&&d.extension!=="md"&&(d.name===".stashpad-order.json"||d.name===".stashpad-sort.json"||!s&&n.has(d.path)||a.push(d))}}return a}populateListBody(t,e){if(this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),this.pendingCursorId){let d=this.currentChildren.findIndex(h=>h.id===this.pendingCursorId);d>=0&&(this.cursorIdx=d,this.selection.clear(),this.selection.add(this.pendingCursorId),this.lastSelected=this.pendingCursorId,this.pendingCursorId=null)}e.file&&k.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode(),s=i==="everything"?this.collectFileItems(e.id):[],n=d=>d.created&&Number.isFinite(Date.parse(d.created))?Date.parse(d.created):Number.POSITIVE_INFINITY,o=this.currentEncryptionFilter(),a;if(o==="unlocked")a=[];else if(i==="nested")a=this.plugin.lockedSubtreesFor(this.noteFolder,e.id);else{let d=new Set([e.id,...this.currentChildren.map(g=>g.id)]),h=new Set;a=[];for(let g of d)for(let I of this.plugin.lockedSubtreesFor(this.noteFolder,g))h.has(I.blob)||(h.add(I.blob),a.push(I))}let l=a.map(d=>({lk:d,ts:n(d)})).sort((d,h)=>d.ts-h.ts),A=i==="nested"&&this.sortStore.getMode(this.noteFolder,e.id)==="manual";if(this.currentChildren.length===0&&s.length===0&&l.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(A&&l.length>0){let d=new Map(this.currentChildren.map((u,f)=>[u.id,f])),h=new Map;for(let{lk:u}of l)u.rootId&&h.set(u.rootId,u);let g=this.currentChildren.map(u=>u.id),I=l.map(({lk:u})=>u).filter(u=>u.rootId).sort((u,f)=>n(f)-n(u)),p=!0;for(;I.length&&p;){p=!1;for(let u=0;u<I.length;u++){let f=I[u],C=f.prevSibling??null,m;if(C==null)m=0;else{let B=g.indexOf(C);if(B<0)continue;m=B+1}g.splice(m,0,f.rootId),I.splice(u,1),u--,p=!0}}for(let u of I)g.push(u.rootId);for(let u of g){let f=d.get(u);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let C=h.get(u);C&&this.renderLockedPlaceholder(t,C)}}for(let u of s.slice().sort((f,C)=>f.stat.ctime-C.stat.ctime))this.renderFileRow(t,u)}else if(s.length===0){let d=0;for(let h=0;h<this.currentChildren.length;h++){let g=Number.isFinite(Date.parse(this.currentChildren[h].created))?Date.parse(this.currentChildren[h].created):0;for(;d<l.length&&l[d].ts<=g;)this.renderLockedPlaceholder(t,l[d].lk),d++;this.renderNote(t,this.currentChildren[h],h)}for(;d<l.length;)this.renderLockedPlaceholder(t,l[d].lk),d++}else{let d=[...this.currentChildren.map((h,g)=>({kind:"note",ts:Number.isFinite(Date.parse(h.created))?Date.parse(h.created):0,idx:g})),...s.map(h=>({kind:"file",ts:h.stat.ctime,file:h})),...l.map(h=>({kind:"lock",ts:h.ts,lk:h.lk}))];d.sort((h,g)=>h.ts-g.ts);for(let h of d)h.kind==="note"?this.renderNote(t,this.currentChildren[h.idx],h.idx):h.kind==="file"?this.renderFileRow(t,h.file):this.renderLockedPlaceholder(t,h.lk)}e.file&&k.Platform.isMobile&&this.installFocusedMiniObserver(t)}renderLockedPlaceholder(t,e){let i=t.createDiv({cls:"stashpad-locked-row"});e.created&&i.createSpan({cls:"stashpad-note-time stashpad-locked-time",text:this.formatTime(e.created)});let s=i.createSpan({cls:"stashpad-locked-icon"});(0,k.setIcon)(s,"lock");let n=(this.plugin.settings.hideLockedTitles??!1)||!e.title;i.createSpan({cls:"stashpad-locked-title",text:n?"Locked note":e.title}),i.createSpan({cls:"stashpad-locked-count",text:e.count>1?`${e.count} notes \xB7 locked`:"locked"});let o=i.createEl("button",{cls:"stashpad-locked-unlock",text:"Unlock"});(0,k.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async A=>{A.preventDefault(),A.stopPropagation();let d=(this.plugin.settings.lockedSubtrees??[]).find(u=>u.blob===e.blob),h=e.rootId??d?.rootId??null,g=e.parentId??d?.parentId??F,I=e.prevSibling??d?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,h){let u=this.order.getOrder(this.noteFolder,g),f=this.sortStore.getMode(this.noteFolder,g)==="manual";if(u.length===0&&f&&(u=this.tree.getChildren(g).map(C=>C.id)),u.length>0){let C=u.filter(B=>B!==h),m=I&&C.includes(I)?C.indexOf(I)+1:0;C.splice(Math.max(0,m),0,h),this.order.setOrder(this.noteFolder,g,C),this.order.flush(this.noteFolder)}this.pendingCursorId=h}this.render()}};o.onclick=a;let l=A=>{A.preventDefault(),A.stopPropagation();let d=new k.Menu;if(d.addItem(h=>h.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(A))),!k.Platform.isMobile){let h=k.Platform.isMacOS?"Finder":k.Platform.isWin?"File Explorer":"file manager";d.addItem(g=>g.setTitle(`Show in ${h}`).setIcon("folder-search").onClick(()=>{try{let I=window.require?.("electron")?.shell,p=this.app.vault.adapter?.getFullPath?.(e.blob);p&&I?.showItemInFolder&&I.showItemInFolder(p)}catch(I){console.warn("[Stashpad] showItemInFolder failed",I)}}))}d.addItem(h=>h.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let g=e.blob;if(!k.Platform.isMobile)try{g=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(g),new k.Notice("Path copied.")})),d.showAtMouseEvent(A)};if(i.oncontextmenu=l,k.Platform.isMobile){let A=i.createEl("button",{cls:"stashpad-locked-menu"});(0,k.setIcon)(A,"more-vertical"),A.setAttr("aria-label","Locked note menu"),A.onclick=d=>l(d)}i.setAttr("aria-label",`${n?"Locked note":`Locked: ${e.title}`}. Use the Unlock button to decrypt.`)}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){if(this.currentEncryptionFilter()==="locked")return;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(l=>l.children.length>0):s;if(e==="nested")return n;let o=[],a=l=>{o.push(l);for(let A of this.tree.getChildren(l.id))a(A)};for(let l of n)a(l);return o}filterChildren(t){t=this.collapseVersions(t);let e=this.timeFilterCutoff(),i=this.tagFilter?.toLowerCase(),s=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),o=this.currentAttachmentsOnly(),a=this.importedOnly,l=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!a&&!l?t:t.filter(A=>{if(a&&(!A.file||this.app.metadataCache.getFileCache(A.file)?.frontmatter?.imported!==!0))return!1;if(l){if(!A.file)return!1;let d=ce(this.app.metadataCache.getFileCache(A.file)?.frontmatter?.author);if(!d||d.id!==l)return!1}if(e&&A.created){let d=Date.parse(A.created);if(!Number.isNaN(d)&&d<e)return!1}if(i){if(!A.file)return!1;if(this.tagFilter===ke){if(!this.nodeHasAnyTag(A))return!1}else if(this.tagFilter===Se){if(this.nodeHasAnyTag(A))return!1}else if(!this.nodeHasTag(A,i))return!1}return!(s&&(this.colorForNode(A)?.toLowerCase()??null)!==s||n&&this.isCompleted(A)&&!this.hasIncompleteDescendant(A)||o&&!this.hasAttachmentInSubtree(A))})}collapseVersions(t){if(!this.plugin.settings.enableSheetVersions)return t;let e=new Map,i=!1;for(let n of t){let o=ut(this.app,n);if(!li(o))continue;i=!0;let a=Kt(o),l=e.get(a);l?l.push(n):e.set(a,[n])}if(!i)return t;let s=new Set;for(let[n,o]of e){let a=this.activeVersionNode(n,o);a&&s.add(a.id)}return t.filter(n=>li(ut(this.app,n))?s.has(n.id):!0)}activeVersionNode(t,e){let i=this.activeVersionByGroup.get(t);if(i){let s=e.find(n=>n.id===i);if(s)return s}return xo(this.app,e)}setActiveVersion(t,e){this.activeVersionByGroup.set(t,e),this.plugin.saveActiveVersion(this.noteFolder,t,e),this.render()}nodeHasAnyTag(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file);if(!e)return!1;if(e.tags&&e.tags.length>0)return!0;let i=e.frontmatter?.tags;return!!(i&&(Array.isArray(i)?i:[i]).some(n=>typeof n=="string"&&n.trim().length>0))}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 l=(a.tag||"").replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let l of a){if(typeof l!="string")continue;let A=l.replace(/^#/,"");A&&t.set(A,(t.get(A)??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){wt.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",k.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let l=this.containerEl.closest(".workspace-leaf");l&&(l.classList.toggle("stashpad-is-tiny",this.tinyMode),l.classList.toggle("stashpad-is-compact",this.compactMode));let A=this.containerEl.closest(".workspace-tabs");A&&A.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let d=this.tree.get(this.focusId)??this.tree.getRoot();d.file&&!k.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,d),this.currentChildren=this.filterChildren(this.collectViewItems(d.id));let h=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let p=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(p.id),this.lastSelected=p.id,this.autoSelectNewest=!1,h=!0}else if(this.pendingFocusIds){let p=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let u=-1;for(let f of p){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=p.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let g=e.createDiv({cls:"stashpad-list"});if(this.listEl=g,this.dnd.attachListDnD(g),this.populateListBody(g,d),this.renderComposer(e),k.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(wt.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),h&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let p=this.pendingComposerCaret;this.pendingComposerCaret=null;let u=this.composerInputEl;if(u&&u.isConnected){if(u.focus({preventScroll:!0}),p!=null){let f=Math.min(p,u.value.length);try{u.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),p!=null)){let C=Math.min(p,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let I=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,I&&this.listEl){let p=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,I.kind){case"preserve":p?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=I.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=I.id,f=I.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let B=C.querySelector(`[data-id="${u}"]`);B&&B.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 p=this.listEl,u=p.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){p.scrollTop=p.scrollHeight,u=p.scrollTop;return}let m=Math.max(0,p.scrollHeight-p.clientHeight);p.scrollTop<u&&u<=m?p.scrollTop=u:u=p.scrollTop});f.observe(p),this.listResizeObserver=f,p.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;p.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),p.addEventListener("touchmove",m=>{let B=m.touches[0]?.clientY??C;B>C&&(this.stickToListBottom=!1),C=B},{passive:!0}),p.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),p.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,k.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=I=>{I.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});Mt(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=I=>{I.preventDefault(),this.openSearchModal()},k.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"}),l=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,k.setIcon)(l,this.timeFilterCalendar?"calendar":"history"),l.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&&l.addClass("is-active"),l.onclick=I=>{I.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let I of $s){let p=this.timeFilterCalendar?I.calShort:I.rollShort,u=this.timeFilterCalendar?I.calLong:I.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:p});f.title=u,this.timeFilter===I.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(I.key)}}let A=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let I of $s){let p=this.timeFilterCalendar?I.calLong:I.rollLong,u=A.createEl("option",{text:p});u.value=I.key,this.timeFilter===I.key&&(u.selected=!0)}A.onchange=()=>this.setTimeFilter(A.value);let d=e.createDiv({cls:"stashpad-view-mode-btns"});if(!k.Platform.isMobile){let I=d.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(I,"minimize-2"),I.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",I.onclick=p=>{p.preventDefault(),this.plugin.openTinyWindow()}}let h=d.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,k.setIcon)(h,this.compactMode?"panel-top":"rows-2"),h.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&&h.addClass("is-active"),h.onclick=I=>{I.preventDefault(),this.toggleCompactMode()},k.Platform.isMobile)return;let g=d.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(g,"external-link"),g.title=j().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.)",g.onclick=I=>{I.preventDefault();let p=j().popoutDuplicates;try{let u=this.app.workspace;if(p){let f=this.leaf.getViewState(),C=u.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new k.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else u.moveLeafToPopout?.(this.leaf)}catch(u){new k.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"});Mt(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==F;i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=d=>{d.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Mt(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=d=>{d.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),l=this.mobileSelectMode;Mt(a,l?"check-square":"square",l?"\u2611":"\u2610"),a.title=l?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",l&&a.addClass("is-active"),a.onclick=d=>{if(d.preventDefault(),this.mobileSelectMode){let h=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),h){let g=this.currentChildren.findIndex(I=>I.id===h);this.selection.add(h),this.lastSelected=h,g>=0&&(this.cursorIdx=g)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let h=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),h&&(this.selection.add(h.id),this.lastSelected=h.id,this.firstSelectedId=h.id),this.render(),new k.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let A=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Mt(A,"zap","\u26A1"),A.title="Actions (move, delete, undo, \u2026)",A.onclick=d=>{d.preventDefault(),this.openMobileActionsMenu(A)}}openMobileActionsMenu(t){let e=new k.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.addItem(o=>o.setTitle("Reload without saving").setIcon("rotate-ccw").onClick(()=>this.plugin.reloadAppForUpdate())),e.addSeparator(),e.addItem(o=>o.setTitle("Expand all").setIcon("unfold-vertical").onClick(()=>this.cmdExpandAll())),e.addItem(o=>o.setTitle("Collapse all").setIcon("fold-vertical").onClick(()=>this.cmdCollapseAll())),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())),this.plugin.settings.enableSheetVersions&&(e.addItem(o=>o.setTitle("Fork as a version (draft)").setIcon("git-fork").setDisabled(!i||!s).onClick(()=>void this.cmdForkVersion())),e.addItem(o=>o.setTitle("Mark version as final").setIcon("star").setDisabled(!i||!s).onClick(()=>void this.cmdMarkVersionFinal()))),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 Js(this.app).open()}tagFilterLabel(){return this.tagFilter===Se?"Tagged":this.tagFilter===De?"Untagged":this.tagFilter?`#${this.formatTagLabel(this.tagFilter)}`:this.collectFolderTags().length===0?"No tags":"All tags"}renderTagFilterDropdown(t){let e=this.collectFolderTags(),i=t.createDiv({cls:"stashpad-tag-filter-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-tag-filter-btn-icon"});Mt(s,"tag","#"),i.createSpan({cls:"stashpad-tag-filter-label",text:this.tagFilterLabel()}),e.length===0&&!this.tagFilter&&i.addClass("is-disabled");let n=o=>{o.preventDefault(),!(e.length===0&&!this.tagFilter)&&this.openTagFilterMenu(i)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openTagFilterMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-tag-filter-popover").forEach(y=>y.remove());let i=e.body.createDiv({cls:"stashpad-tag-filter-popover"}),s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${Math.max(s.width,200)}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=new k.Scope(this.app.scope),o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(n)}catch{}},a=y=>{!i.contains(y.target)&&y.target!==t&&!t.contains(y.target)&&o()},l=i.createDiv({cls:"stashpad-tag-filter-search"}),A=l.createSpan({cls:"stashpad-tag-filter-search-icon"});Mt(A,"search","\u2315");let d=l.createEl("input",{type:"text",cls:"stashpad-tag-filter-input",attr:{placeholder:"Filter tags\u2026"}}),h=l.createSpan({cls:"stashpad-tag-filter-clear",attr:{"aria-label":"Clear"}});Mt(h,"x","\xD7"),h.setCssStyles({display:"none"});let g=i.createDiv({cls:"stashpad-tag-filter-list"}),I=this.collectFolderTags(),p=[],u=0,f=y=>{this.setTagFilter(y),o()},C=y=>{if(p.length===0){u=0;return}u=(y+p.length)%p.length,p.forEach((Q,E)=>Q.el.toggleClass("is-highlighted",E===u)),p[u].el.scrollIntoView({block:"nearest"})},m=(y,Q,E,v)=>{let w=g.createDiv({cls:"stashpad-tag-filter-row"});v&&w.addClass("is-active"),w.createSpan({cls:"stashpad-tag-filter-row-label",text:y}),typeof E=="number"&&w.createSpan({cls:"stashpad-tag-filter-row-count",text:String(E)});let D=p.length;p.push({value:Q,el:w}),w.onmousedown=N=>{N.preventDefault(),f(Q)},w.onmouseenter=()=>C(D)},B=()=>{let y=d.value;h.setCssStyles({display:y?"":"none"}),g.empty(),p=[];let Q=this.tagFilter?.toLowerCase();if(y.trim()){let E=Oo(y,I);if(E.length===0)g.createDiv({cls:"stashpad-tag-filter-empty",text:"No matching tags"});else for(let v of E)m(`#${v.label}`,v.raw,v.count,Q===v.raw.toLowerCase())}else{m("All tags",null,void 0,!this.tagFilter),m("Tagged",Se,void 0,this.tagFilter===Se),m("Untagged",De,void 0,this.tagFilter===De);for(let E of I)m(`#${E.label}`,E.raw,E.count,Q===E.raw.toLowerCase())}C(0)};h.onclick=()=>{d.value="",B(),d.focus()},d.addEventListener("input",B),d.addEventListener("keydown",y=>{y.key==="ArrowDown"?(y.preventDefault(),C(u+1)):y.key==="ArrowUp"?(y.preventDefault(),C(u-1)):y.key==="Enter"&&(y.preventDefault(),p[u]&&f(p[u].value))}),n.register([],"Escape",y=>(y.preventDefault(),o(),!1)),this.app.keymap?.pushScope(n),B(),setTimeout(()=>{e.addEventListener("mousedown",a,!0),d.focus()},0)}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 l=this.colorFilter.toLowerCase();o.setCssStyles({background:l});let A=this.plugin.getColorAlias(this.noteFolder,l);a.setText(A??l)}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(A=>A.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.setCssStyles({left:`${Math.max(8,n.left)}px`,top:`${n.bottom+4}px`,minWidth:`${n.width}px`,maxWidth:"min(280px, calc(100vw - 16px))",width:"max-content"});let o=new k.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",l,!0);try{this.app.keymap?.popScope(o)}catch{}},l=A=>{!s.contains(A.target)&&A.target!==t&&!t.contains(A.target)&&a()};o.register([],"Escape",A=>(A.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",l,!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 l=a.createSpan({cls:"stashpad-sort-icon"});(0,k.setIcon)(l,"arrow-up-down");let A=a.createSpan({cls:"stashpad-sort-label"});o?(A.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${zs[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(A.setText(Ji[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: ${Ji[s]}. Drag-reorder will revert this parent to Manual.`);let d=h=>{o||(h.preventDefault(),this.openSortMenu(a))};a.onclick=d,a.onkeydown=h=>{o||(h.key==="Enter"||h.key===" ")&&d(h)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(l=>l.remove());let i=e.body.createDiv({cls:"stashpad-sort-popover"}),s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${s.width}px`,maxWidth:"min(280px, calc(100vw - 16px))",width:"max-content"});let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateSortMenuBody(i,n);let a=new k.Scope(this.app.scope);a.register([],"Escape",l=>(l.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,k.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",l=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||a||l)&&e.addClass("is-active");let A=d=>{d.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=A,e.onkeydown=d=>{(d.key==="Enter"||d.key===" ")&&A(d)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(g=>g.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.setCssStyles({right:`${Math.max(8,n.innerWidth-s.right)}px`,left:"auto",top:`${s.bottom+4}px`,maxWidth:"min(360px, calc(100vw - 16px))",width:"max-content",minWidth:"260px"});let o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(h)}catch{}},a=g=>{!i.contains(g.target)&&g.target!==t&&!t.contains(g.target)&&o()},l=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:g=>this.populateTagMenuBody(g,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:g=>this.populateColorMenuBody(g,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let g=$s.find(I=>I.key===this.timeFilter);return g?this.timeFilterCalendar?g.calShort:g.rollShort:"All"},populate:g=>this.populateTimeMenuBody(g,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":Ji[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:g=>{if(this.currentViewMode()!=="nested"){g.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(g,o)}},{key:"view",title:"View",summary:()=>zs[this.currentViewMode()],populate:g=>this.populateViewMenuBody(g,o)}],A="",d=()=>{i.empty();for(let g of l){let I=i.createDiv({cls:"stashpad-mobile-filters-section"}),p=I.createDiv({cls:"stashpad-mobile-filters-header"}),u=p.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,k.setIcon)(u,A===g.key?"chevron-down":"chevron-right"),p.createSpan({cls:"stashpad-mobile-filters-title",text:g.title}),p.createSpan({cls:"stashpad-mobile-filters-summary",text:g.summary()}),p.onclick=f=>{f.preventDefault(),f.stopPropagation(),A=A===g.key?"":g.key,d()},A===g.key){let f=I.createDiv({cls:"stashpad-mobile-filters-body"});g.populate(f)}}};d();let h=new k.Scope(this.app.scope);h.register([],"Escape",g=>(g.preventDefault(),o(),!1)),this.app.keymap?.pushScope(h),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,k.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(zs[e]),(e!=="nested"||this.currentEncryptionFilter()!=="all")&&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(l=>l.remove());let i=e.body.createDiv({cls:"stashpad-view-popover"});k.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${s.width}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateViewMenuBody(i,n);let a=new k.Scope(this.app.scope);a.register([],"Escape",l=>(l.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(Q,E)=>{let v=t.createDiv({cls:"stashpad-view-popover-row"});Q===i&&v.addClass("is-active"),v.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:zs[Q]}),v.createDiv({cls:"stashpad-view-popover-desc",text:E}),v.onclick=async D=>{D.preventDefault(),D.stopPropagation(),e(),Q!==i&&(await this.setViewMode(Q),this.render())}};if(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"}),this.plugin.encryption?.isConfigured?.()){let Q=this.currentEncryptionFilter(),E=(v,w,D)=>{let N=t.createDiv({cls:"stashpad-view-popover-row"});v===Q&&N.addClass("is-active"),N.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:w}),N.createDiv({cls:"stashpad-view-popover-desc",text:D}),N.onclick=async P=>{P.preventDefault(),P.stopPropagation(),v!==Q&&(await this.setEncryptionFilter(v),this.refreshList()),e()}};E("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),E("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),E("unlocked","Encryption: decrypted only","Hide locked \u{1F512} stubs."),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 Q=>{Q.target!==o&&(Q.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"}),l=a.createEl("input",{type:"checkbox"});l.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 Q=>{Q.target!==l&&(Q.preventDefault(),l.checked=!l.checked),await this.setHideCompleted(l.checked),this.refreshList()};let A=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),d=A.createEl("input",{type:"checkbox"});d.checked=this.currentAttachmentsOnly(),A.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),A.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),A.onclick=async Q=>{Q.target!==d&&(Q.preventDefault(),d.checked=!d.checked),await this.setAttachmentsOnly(d.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let h=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&h.addClass("is-disabled");let g=h.createEl("input",{type:"checkbox"});g.checked=this.currentIncludeAttachments(),g.disabled=i!=="everything",h.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),h.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."}),h.onclick=async Q=>{i==="everything"&&(Q.target!==g&&(Q.preventDefault(),g.checked=!g.checked),await this.setIncludeAttachments(g.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let I=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),p=I.createEl("input",{type:"checkbox"});p.checked=this.importedOnly,I.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),I.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),I.onclick=Q=>{Q.target!==p&&(Q.preventDefault(),p.checked=!p.checked),this.importedOnly=p.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let u=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let Q of this.app.vault.getMarkdownFiles()){if((Q.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let E=Ae(this.app.metadataCache.getFileCache(Q)?.frontmatter?.author);E&&u.set(E.id,E.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 B=m.createEl("select",{cls:"stashpad-view-author-select"}),y=B.createEl("option",{text:"All authors",value:""});this.authorFilter||(y.selected=!0);for(let[Q,E]of[...u.entries()].sort((v,w)=>v[1].localeCompare(w[1]))){let v=B.createEl("option",{text:E,value:Q});this.authorFilter===Q&&(v.selected=!0)}B.onclick=Q=>Q.stopPropagation(),B.onchange=()=>{this.authorFilter=B.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 po){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:Ji[o]}),a.onclick=async l=>{l.preventDefault(),l.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 $s){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=l=>{l.preventDefault(),l.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,a)=>{let l=t.createDiv({cls:"stashpad-color-filter-popover-row"}),A=l.createSpan({cls:"stashpad-color-filter-swatch"});o?A.setCssStyles({background:o}):A.addClass("is-empty");let d=l.createSpan({cls:"stashpad-color-filter-popover-label"});d.setText(n),o&&(d.style.color=o),l.onclick=h=>{h.preventDefault(),h.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=d=>{d.preventDefault(),d.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null),s("Tagged",Se),s("Untagged",De);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"});Mt(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==F||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Mt(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(),l=this.focusId===F?a:`${a} / ${this.titleForNode(o).trim()}`,A=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),d=A.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,k.setIcon)(d,"folder"),A.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:l}),A.title=`${this.noteFolder}${this.focusId!==F?` / ${this.titleForNode(o).trim()}`:""} -Click to switch / create folder.`,A.onclick=u=>{u.preventDefault(),this.plugin.openFolderPicker()};let h=e.createDiv({cls:"stashpad-tiny-sticky"}),g=h.createEl("input",{type:"checkbox"});if(g.checked=this.tinyAlwaysOnTop,h.createSpan({text:"Sticky"}),g.onchange=()=>{this.tinyAlwaysOnTop=g.checked,this.applyTinyAlwaysOnTop()},!k.Platform.isMobile){let u=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,k.setIcon)(u,"contrast"),u.title="Window transparency",this.tinyOpacity<1&&u.addClass("is-active"),u.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(u)}}let I=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,k.setIcon)(I,this.compactMode?"panel-top":"rows-2"),I.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&I.addClass("is-active"),I.onclick=()=>{this.toggleCompactMode()};let p=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,k.setIcon)(p,"maximize-2"),p.title="Exit tiny mode",p.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 d=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=d/100,s.setText(`${d}%`),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.setCssStyles({top:`${n.bottom-o.top+4}px`,left:`${Math.max(4,Math.min(n.left-o.left,o.width-180))}px`});let a=d=>{e.contains(d.target)||d.target===t||t.contains(d.target)||A()},l=d=>{d.key==="Escape"&&A()},A=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",l,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",l,!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"],l=(o?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];l.length===1?s=l[0]:l.length>1&&(s=o?.getFocusedWindow?.()??null??l[l.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),k.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(k.Platform.isMobile?((0,k.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(F),this.focusId===F){let d=this.tree.getChildren(this.focusId).length;if(d>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${d}`}).title=`${d} direct child${d===1?"":"ren"}`),this.compactMode){let h=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(h,"panel-top"),h.title="Exit compact mode",h.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(d=>{let h=this.titleForNode(d),g=h.length>s?h.slice(0,s-1)+"\u2026":h;return{id:d.id,label:g}}),l=d=>d.reduce((h,g)=>h+g.label.length+3,0);if(l(a)>n&&a.length>2){let d=!1;for(;l(a)>n&&a.length>2;)a.splice(1,1),d||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),d=!0)}for(let d of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),d.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:d.label}).title=o.map(h=>this.titleForNode(h)).join(" / ");else{let h=d.id,g=e.createSpan({cls:"stashpad-crumb",text:d.label});g.title=d.label,g.onclick=()=>this.navigateTo(h),g.oncontextmenu=I=>{I.preventDefault(),this.openCrumbMenu(I,h)},k.Platform.isMobile&&this.attachLongPress(g,()=>this.openCrumbMenu(null,h))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",d=>{d.preventDefault(),this.openCrumbMenu(d,F)}),k.Platform.isMobile){let d=e.querySelector(".stashpad-crumb-home");d&&this.attachLongPress(d,()=>this.openCrumbMenu(null,F))}let A=this.tree.getChildren(this.focusId).length;if(A>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${A}`}).title=`${A} direct child${A===1?"":"ren"}`),this.compactMode){let d=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(d,"panel-top"),d.title="Exit compact mode",d.onclick=h=>{h.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 l=a.touches[0];s=l?.clientX??0,n=l?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let l=a.touches[0];l&&(Math.abs(l.clientX-s)>10||Math.abs(l.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 k.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,k.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",h=>this.handleRenderedClick(h,e));let l=s.createDiv({cls:"stashpad-focused-actions"}),A=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,k.setIcon)(A,"pencil"),A.title="Edit in new tab",A.onclick=()=>void this.openFileAtEnd(i);let d=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,k.setIcon)(d,"copy"),d.title="Open this Stashpad in a new tab (clone)",d.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:k.Platform.isMobile,toggleHost:l,toggleAnchor:A})}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,l)=>{let A=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});A.title=`Focus into "${this.titleForNode(a)}"`,A.onclick=d=>{d.stopPropagation(),this.navigateTo(a.id)},l<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return cs(this.app,t,k.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=I=>{I.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});Tt(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=I=>{I.preventDefault(),this.openSearchModal()},k.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"}),l=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,k.setIcon)(l,this.timeFilterCalendar?"calendar":"history"),l.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&&l.addClass("is-active"),l.onclick=I=>{I.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let I of Ys){let p=this.timeFilterCalendar?I.calShort:I.rollShort,u=this.timeFilterCalendar?I.calLong:I.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:p});f.title=u,this.timeFilter===I.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(I.key)}}let A=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let I of Ys){let p=this.timeFilterCalendar?I.calLong:I.rollLong,u=A.createEl("option",{text:p});u.value=I.key,this.timeFilter===I.key&&(u.selected=!0)}A.onchange=()=>this.setTimeFilter(A.value);let d=e.createDiv({cls:"stashpad-view-mode-btns"});if(!k.Platform.isMobile){let I=d.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(I,"minimize-2"),I.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",I.onclick=p=>{p.preventDefault(),this.plugin.openTinyWindow()}}let h=d.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,k.setIcon)(h,this.compactMode?"panel-top":"rows-2"),h.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&&h.addClass("is-active"),h.onclick=I=>{I.preventDefault(),this.toggleCompactMode()},k.Platform.isMobile)return;let g=d.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(g,"external-link"),g.title=Z().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.)",g.onclick=I=>{I.preventDefault();let p=Z().popoutDuplicates;try{let u=this.app.workspace;if(p){let f=this.leaf.getViewState(),C=u.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new k.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else u.moveLeafToPopout?.(this.leaf)}catch(u){new k.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"});Tt(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==F;i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=d=>{d.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Tt(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=d=>{d.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),l=this.mobileSelectMode;Tt(a,l?"check-square":"square",l?"\u2611":"\u2610"),a.title=l?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",l&&a.addClass("is-active"),a.onclick=d=>{if(d.preventDefault(),this.mobileSelectMode){let h=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),h){let g=this.currentChildren.findIndex(I=>I.id===h);this.selection.add(h),this.lastSelected=h,g>=0&&(this.cursorIdx=g)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let h=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),h&&(this.selection.add(h.id),this.lastSelected=h.id,this.firstSelectedId=h.id),this.render(),new k.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let A=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Tt(A,"zap","\u26A1"),A.title="Actions (move, delete, undo, \u2026)",A.onclick=d=>{d.preventDefault(),this.openMobileActionsMenu(A)}}openMobileActionsMenu(t){let e=new k.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.addItem(o=>o.setTitle("Reload without saving").setIcon("rotate-ccw").onClick(()=>this.plugin.reloadAppForUpdate())),e.addSeparator(),e.addItem(o=>o.setTitle("Expand all").setIcon("unfold-vertical").onClick(()=>this.cmdExpandAll())),e.addItem(o=>o.setTitle("Collapse all").setIcon("fold-vertical").onClick(()=>this.cmdCollapseAll())),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())),this.plugin.settings.enableSheetVersions&&(e.addItem(o=>o.setTitle("Fork as a version (draft)").setIcon("git-fork").setDisabled(!i||!s).onClick(()=>void this.cmdForkVersion())),e.addItem(o=>o.setTitle("Mark version as final").setIcon("star").setDisabled(!i||!s).onClick(()=>void this.cmdMarkVersionFinal()))),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 Ms(this.app).open()}tagFilterLabel(){return this.tagFilter===ke?"Tagged":this.tagFilter===Se?"Untagged":this.tagFilter?`#${this.formatTagLabel(this.tagFilter)}`:this.collectFolderTags().length===0?"No tags":"All tags"}renderTagFilterDropdown(t){let e=this.collectFolderTags(),i=t.createDiv({cls:"stashpad-tag-filter-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-tag-filter-btn-icon"});Tt(s,"tag","#"),i.createSpan({cls:"stashpad-tag-filter-label",text:this.tagFilterLabel()}),e.length===0&&!this.tagFilter&&i.addClass("is-disabled");let n=o=>{o.preventDefault(),!(e.length===0&&!this.tagFilter)&&this.openTagFilterMenu(i)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openTagFilterMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-tag-filter-popover").forEach(y=>y.remove());let i=e.body.createDiv({cls:"stashpad-tag-filter-popover"}),s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${Math.max(s.width,200)}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=new k.Scope(this.app.scope),o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(n)}catch{}},a=y=>{!i.contains(y.target)&&y.target!==t&&!t.contains(y.target)&&o()},l=i.createDiv({cls:"stashpad-tag-filter-search"}),A=l.createSpan({cls:"stashpad-tag-filter-search-icon"});Tt(A,"search","\u2315");let d=l.createEl("input",{type:"text",cls:"stashpad-tag-filter-input",attr:{placeholder:"Filter tags\u2026"}}),h=l.createSpan({cls:"stashpad-tag-filter-clear",attr:{"aria-label":"Clear"}});Tt(h,"x","\xD7"),h.setCssStyles({display:"none"});let g=i.createDiv({cls:"stashpad-tag-filter-list"}),I=this.collectFolderTags(),p=[],u=0,f=y=>{this.setTagFilter(y),o()},C=y=>{if(p.length===0){u=0;return}u=(y+p.length)%p.length,p.forEach((Q,E)=>Q.el.toggleClass("is-highlighted",E===u)),p[u].el.scrollIntoView({block:"nearest"})},m=(y,Q,E,v)=>{let w=g.createDiv({cls:"stashpad-tag-filter-row"});v&&w.addClass("is-active"),w.createSpan({cls:"stashpad-tag-filter-row-label",text:y}),typeof E=="number"&&w.createSpan({cls:"stashpad-tag-filter-row-count",text:String(E)});let D=p.length;p.push({value:Q,el:w}),w.onmousedown=N=>{N.preventDefault(),f(Q)},w.onmouseenter=()=>C(D)},B=()=>{let y=d.value;h.setCssStyles({display:y?"":"none"}),g.empty(),p=[];let Q=this.tagFilter?.toLowerCase();if(y.trim()){let E=Oo(y,I);if(E.length===0)g.createDiv({cls:"stashpad-tag-filter-empty",text:"No matching tags"});else for(let v of E)m(`#${v.label}`,v.raw,v.count,Q===v.raw.toLowerCase())}else{m("All tags",null,void 0,!this.tagFilter),m("Tagged",ke,void 0,this.tagFilter===ke),m("Untagged",Se,void 0,this.tagFilter===Se);for(let E of I)m(`#${E.label}`,E.raw,E.count,Q===E.raw.toLowerCase())}C(0)};h.onclick=()=>{d.value="",B(),d.focus()},d.addEventListener("input",B),d.addEventListener("keydown",y=>{y.key==="ArrowDown"?(y.preventDefault(),C(u+1)):y.key==="ArrowUp"?(y.preventDefault(),C(u-1)):y.key==="Enter"&&(y.preventDefault(),p[u]&&f(p[u].value))}),n.register([],"Escape",y=>(y.preventDefault(),o(),!1)),this.app.keymap?.pushScope(n),B(),setTimeout(()=>{e.addEventListener("mousedown",a,!0),d.focus()},0)}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 l=this.colorFilter.toLowerCase();o.setCssStyles({background:l});let A=this.plugin.getColorAlias(this.noteFolder,l);a.setText(A??l)}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(A=>A.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.setCssStyles({left:`${Math.max(8,n.left)}px`,top:`${n.bottom+4}px`,minWidth:`${n.width}px`,maxWidth:"min(280px, calc(100vw - 16px))",width:"max-content"});let o=new k.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",l,!0);try{this.app.keymap?.popScope(o)}catch{}},l=A=>{!s.contains(A.target)&&A.target!==t&&!t.contains(A.target)&&a()};o.register([],"Escape",A=>(A.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",l,!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 l=a.createSpan({cls:"stashpad-sort-icon"});(0,k.setIcon)(l,"arrow-up-down");let A=a.createSpan({cls:"stashpad-sort-label"});o?(A.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${Os[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(A.setText(Ui[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: ${Ui[s]}. Drag-reorder will revert this parent to Manual.`);let d=h=>{o||(h.preventDefault(),this.openSortMenu(a))};a.onclick=d,a.onkeydown=h=>{o||(h.key==="Enter"||h.key===" ")&&d(h)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(l=>l.remove());let i=e.body.createDiv({cls:"stashpad-sort-popover"}),s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${s.width}px`,maxWidth:"min(280px, calc(100vw - 16px))",width:"max-content"});let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateSortMenuBody(i,n);let a=new k.Scope(this.app.scope);a.register([],"Escape",l=>(l.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,k.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",l=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||a||l)&&e.addClass("is-active");let A=d=>{d.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=A,e.onkeydown=d=>{(d.key==="Enter"||d.key===" ")&&A(d)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(g=>g.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.setCssStyles({right:`${Math.max(8,n.innerWidth-s.right)}px`,left:"auto",top:`${s.bottom+4}px`,maxWidth:"min(360px, calc(100vw - 16px))",width:"max-content",minWidth:"260px"});let o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(h)}catch{}},a=g=>{!i.contains(g.target)&&g.target!==t&&!t.contains(g.target)&&o()},l=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:g=>this.populateTagMenuBody(g,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:g=>this.populateColorMenuBody(g,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let g=Ys.find(I=>I.key===this.timeFilter);return g?this.timeFilterCalendar?g.calShort:g.rollShort:"All"},populate:g=>this.populateTimeMenuBody(g,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":Ui[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:g=>{if(this.currentViewMode()!=="nested"){g.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(g,o)}},{key:"view",title:"View",summary:()=>Os[this.currentViewMode()],populate:g=>this.populateViewMenuBody(g,o)}],A="",d=()=>{i.empty();for(let g of l){let I=i.createDiv({cls:"stashpad-mobile-filters-section"}),p=I.createDiv({cls:"stashpad-mobile-filters-header"}),u=p.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,k.setIcon)(u,A===g.key?"chevron-down":"chevron-right"),p.createSpan({cls:"stashpad-mobile-filters-title",text:g.title}),p.createSpan({cls:"stashpad-mobile-filters-summary",text:g.summary()}),p.onclick=f=>{f.preventDefault(),f.stopPropagation(),A=A===g.key?"":g.key,d()},A===g.key){let f=I.createDiv({cls:"stashpad-mobile-filters-body"});g.populate(f)}}};d();let h=new k.Scope(this.app.scope);h.register([],"Escape",g=>(g.preventDefault(),o(),!1)),this.app.keymap?.pushScope(h),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,k.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(Os[e]),(e!=="nested"||this.currentEncryptionFilter()!=="all")&&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(l=>l.remove());let i=e.body.createDiv({cls:"stashpad-view-popover"});k.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${s.width}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateViewMenuBody(i,n);let a=new k.Scope(this.app.scope);a.register([],"Escape",l=>(l.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(Q,E)=>{let v=t.createDiv({cls:"stashpad-view-popover-row"});Q===i&&v.addClass("is-active"),v.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:Os[Q]}),v.createDiv({cls:"stashpad-view-popover-desc",text:E}),v.onclick=async D=>{D.preventDefault(),D.stopPropagation(),e(),Q!==i&&(await this.setViewMode(Q),this.render())}};if(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"}),this.plugin.encryption?.isConfigured?.()){let Q=this.currentEncryptionFilter(),E=(v,w,D)=>{let N=t.createDiv({cls:"stashpad-view-popover-row"});v===Q&&N.addClass("is-active"),N.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:w}),N.createDiv({cls:"stashpad-view-popover-desc",text:D}),N.onclick=async P=>{P.preventDefault(),P.stopPropagation(),v!==Q&&(await this.setEncryptionFilter(v),this.refreshList()),e()}};E("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),E("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),E("unlocked","Encryption: decrypted only","Hide locked \u{1F512} stubs."),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 Q=>{Q.target!==o&&(Q.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"}),l=a.createEl("input",{type:"checkbox"});l.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 Q=>{Q.target!==l&&(Q.preventDefault(),l.checked=!l.checked),await this.setHideCompleted(l.checked),this.refreshList()};let A=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),d=A.createEl("input",{type:"checkbox"});d.checked=this.currentAttachmentsOnly(),A.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),A.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),A.onclick=async Q=>{Q.target!==d&&(Q.preventDefault(),d.checked=!d.checked),await this.setAttachmentsOnly(d.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let h=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&h.addClass("is-disabled");let g=h.createEl("input",{type:"checkbox"});g.checked=this.currentIncludeAttachments(),g.disabled=i!=="everything",h.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),h.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."}),h.onclick=async Q=>{i==="everything"&&(Q.target!==g&&(Q.preventDefault(),g.checked=!g.checked),await this.setIncludeAttachments(g.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let I=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),p=I.createEl("input",{type:"checkbox"});p.checked=this.importedOnly,I.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),I.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),I.onclick=Q=>{Q.target!==p&&(Q.preventDefault(),p.checked=!p.checked),this.importedOnly=p.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let u=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let Q of this.app.vault.getMarkdownFiles()){if((Q.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let E=ce(this.app.metadataCache.getFileCache(Q)?.frontmatter?.author);E&&u.set(E.id,E.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 B=m.createEl("select",{cls:"stashpad-view-author-select"}),y=B.createEl("option",{text:"All authors",value:""});this.authorFilter||(y.selected=!0);for(let[Q,E]of[...u.entries()].sort((v,w)=>v[1].localeCompare(w[1]))){let v=B.createEl("option",{text:E,value:Q});this.authorFilter===Q&&(v.selected=!0)}B.onclick=Q=>Q.stopPropagation(),B.onchange=()=>{this.authorFilter=B.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 Vn){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:Ui[o]}),a.onclick=async l=>{l.preventDefault(),l.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 Ys){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=l=>{l.preventDefault(),l.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,a)=>{let l=t.createDiv({cls:"stashpad-color-filter-popover-row"}),A=l.createSpan({cls:"stashpad-color-filter-swatch"});o?A.setCssStyles({background:o}):A.addClass("is-empty");let d=l.createSpan({cls:"stashpad-color-filter-popover-label"});d.setText(n),o&&(d.style.color=o),l.onclick=h=>{h.preventDefault(),h.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=d=>{d.preventDefault(),d.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null),s("Tagged",ke),s("Untagged",Se);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"});Tt(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==F||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Tt(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(),l=this.focusId===F?a:`${a} / ${this.titleForNode(o).trim()}`,A=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),d=A.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,k.setIcon)(d,"folder"),A.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:l}),A.title=`${this.noteFolder}${this.focusId!==F?` / ${this.titleForNode(o).trim()}`:""} +Click to switch / create folder.`,A.onclick=u=>{u.preventDefault(),this.plugin.openFolderPicker()};let h=e.createDiv({cls:"stashpad-tiny-sticky"}),g=h.createEl("input",{type:"checkbox"});if(g.checked=this.tinyAlwaysOnTop,h.createSpan({text:"Sticky"}),g.onchange=()=>{this.tinyAlwaysOnTop=g.checked,this.applyTinyAlwaysOnTop()},!k.Platform.isMobile){let u=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,k.setIcon)(u,"contrast"),u.title="Window transparency",this.tinyOpacity<1&&u.addClass("is-active"),u.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(u)}}let I=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,k.setIcon)(I,this.compactMode?"panel-top":"rows-2"),I.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&I.addClass("is-active"),I.onclick=()=>{this.toggleCompactMode()};let p=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,k.setIcon)(p,"maximize-2"),p.title="Exit tiny mode",p.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 d=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=d/100,s.setText(`${d}%`),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.setCssStyles({top:`${n.bottom-o.top+4}px`,left:`${Math.max(4,Math.min(n.left-o.left,o.width-180))}px`});let a=d=>{e.contains(d.target)||d.target===t||t.contains(d.target)||A()},l=d=>{d.key==="Escape"&&A()},A=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",l,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",l,!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"],l=(o?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];l.length===1?s=l[0]:l.length>1&&(s=o?.getFocusedWindow?.()??null??l[l.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),k.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(k.Platform.isMobile?((0,k.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(F),this.focusId===F){let d=this.tree.getChildren(this.focusId).length;if(d>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${d}`}).title=`${d} direct child${d===1?"":"ren"}`),this.compactMode){let h=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(h,"panel-top"),h.title="Exit compact mode",h.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(d=>{let h=this.titleForNode(d),g=h.length>s?h.slice(0,s-1)+"\u2026":h;return{id:d.id,label:g}}),l=d=>d.reduce((h,g)=>h+g.label.length+3,0);if(l(a)>n&&a.length>2){let d=!1;for(;l(a)>n&&a.length>2;)a.splice(1,1),d||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),d=!0)}for(let d of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),d.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:d.label}).title=o.map(h=>this.titleForNode(h)).join(" / ");else{let h=d.id,g=e.createSpan({cls:"stashpad-crumb",text:d.label});g.title=d.label,g.onclick=()=>this.navigateTo(h),g.oncontextmenu=I=>{I.preventDefault(),this.openCrumbMenu(I,h)},k.Platform.isMobile&&this.attachLongPress(g,()=>this.openCrumbMenu(null,h))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",d=>{d.preventDefault(),this.openCrumbMenu(d,F)}),k.Platform.isMobile){let d=e.querySelector(".stashpad-crumb-home");d&&this.attachLongPress(d,()=>this.openCrumbMenu(null,F))}let A=this.tree.getChildren(this.focusId).length;if(A>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${A}`}).title=`${A} direct child${A===1?"":"ren"}`),this.compactMode){let d=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(d,"panel-top"),d.title="Exit compact mode",d.onclick=h=>{h.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 l=a.touches[0];s=l?.clientX??0,n=l?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let l=a.touches[0];l&&(Math.abs(l.clientX-s)>10||Math.abs(l.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 k.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,k.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",h=>this.handleRenderedClick(h,e));let l=s.createDiv({cls:"stashpad-focused-actions"}),A=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,k.setIcon)(A,"pencil"),A.title="Edit in new tab",A.onclick=()=>void this.openFileAtEnd(i);let d=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,k.setIcon)(d,"copy"),d.title="Open this Stashpad in a new tab (clone)",d.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:k.Platform.isMobile,toggleHost:l,toggleAnchor:A})}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,l)=>{let A=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});A.title=`Focus into "${this.titleForNode(a)}"`,A.onclick=d=>{d.stopPropagation(),this.navigateTo(a.id)},l<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return ds(this.app,t,k.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||this.currentEncryptionFilter()==="locked")return;let s=e.file,n=this.tree.getChildren(e.id).length,o=this.selection.has(e.id),a=i===this.cursorIdx,l=this.inListPicker?.activeIdx===i,A=t.createDiv({cls:"stashpad-note"});o&&A.addClass("is-selected"),a&&A.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&A.addClass("is-cursor-expanded"),l&&A.addClass("is-pick-target"),this.isCompleted(e)&&A.addClass("is-completed"),this.isListPinned(e.id)&&A.addClass("is-list-pinned"),this.isCutPending(e.id)?A.addClass("is-cut-pending"):this.isCopyPending(e.id)&&A.addClass("is-copy-pending"),A.dataset.idx=String(i),A.dataset.id=e.id;let d=this.currentViewMode()==="nested";A.draggable=d,d&&this.dnd.attachRowDnD(A,e,i),A.addEventListener("click",E=>this.handleRowClick(E,i,e)),A.addEventListener("dblclick",E=>{if(!this.plugin.settings.doubleClickToFocus)return;let v=this.shouldAbsorbDismissTap();if(v&&this.aimedTapTargetId&&Date.now()-this.aimedTapAt<=Oi.AIMED_TAP_WINDOW_MS){let D=this.aimedTapTargetId;this.aimedTapTargetId=null,this.traceTap("dblclick",E,i,!1),E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(D);return}if(this.traceTap("dblclick",E,i,v),v){E.preventDefault();return}E.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let h=this.isTask(e)||this.compactMode;h&&(A.addClass("is-task"),k.Platform.isMobile||this.addTaskCheckbox(A,e));let g=A.createDiv({cls:"stashpad-note-meta"}),I=g.createDiv({cls:"stashpad-note-meta-top"});I.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let p=this.colorForNode(e),u=I.createDiv({cls:"stashpad-note-grip"});p&&u.addClass("has-color"),(0,k.setIcon)(u,"grip-vertical"),u.title=p?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=d,d||(u.title=p?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),p&&u.style.setProperty("--stashpad-note-color",p);let f=h&&k.Platform.isMobile,C=this.isListPinned(e.id);if(n>0||f||C){let E=g.createDiv({cls:"stashpad-note-meta-bottom"});if(C){let v=E.createSpan({cls:"stashpad-note-listpin"});(0,k.setIcon)(v,"pin"),v.setAttr("aria-label","Pinned to top of list")}if(f&&this.addTaskCheckbox(E,e),n>0){let v=E.createSpan({cls:"stashpad-note-enter"});p&&(v.style.color=p),(0,k.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)}}}if(p)A.addClass("has-color"),A.style.setProperty("--stashpad-note-color",p);else{let E=this.inheritedColorForNode(e);E&&E.depth>0&&(A.addClass("has-inherited-color"),A.style.setProperty("--stashpad-inherited-color",E.hex),A.style.setProperty("--stashpad-inherited-depth",String(E.depth)))}let m=A.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(m,e);let B=m.createDiv({cls:"stashpad-note-body-content"}),y=A.createDiv({cls:"stashpad-note-actions"}),Q;if(k.Platform.isMobile){let E=y.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,k.setIcon)(E,"ellipsis-vertical"),E.title="Actions",E.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},Q=E}else{let E=y.createEl("button",{cls:"stashpad-pencil"});(0,k.setIcon)(E,"pencil"),E.title="Edit in new tab",E.onclick=w=>{w.stopPropagation(),this.openFileAtEnd(s)};let v=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,k.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)},Q=E}this.renderNoteBody(B,e,{clamp:!0,toggleHost:y,toggleAnchor:Q}),this.renderVersionTabs(m,e),A.oncontextmenu=E=>{E.preventDefault(),this.openNoteMenu(E,e)}}renderVersionTabs(t,e){if(!this.plugin.settings.enableSheetVersions||!li(ut(this.app,e)))return;let i=Kt(ut(this.app,e)),s=e.parent??this.focusId,n=this.tree.getChildren(s),o=pn(this.app,n.filter(A=>{let d=ut(this.app,A);return li(d)&&Kt(d)===i}));if(o.length<2)return;let a=t.createDiv({cls:"stashpad-version-tabs"});for(let A of o){let d=A.id===e.id,h=ut(this.app,A),g=Ai(h),I=Do(h),p=a.createDiv({cls:"stashpad-version-tab"+(d?" is-active":"")+(g?" is-final":"")+(I?" is-original":"")});g&&p.createSpan({cls:"stashpad-version-star",text:"\u2605"}),p.createSpan({cls:"stashpad-version-tab-label",text:Mo(this.app,A,this.titleForNode(A).trim()||"Untitled")});let u=this.titleForNode(A).trim();p.title=I?`${u} (original)`:`${u} (forked)`,d||(p.onclick=f=>{f.stopPropagation(),this.setActiveVersion(i,A.id)})}let l=a.createEl("button",{cls:"stashpad-version-add",text:"+"});l.title="New version",l.onclick=A=>{A.stopPropagation(),this.cmdForkVersion(e,!0)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,k.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:l,html:A}=o;t.empty();let d=t.createDiv({cls:"stashpad-note-text"}),h=this.isNoteExpanded(e.id);if(i.clamp&&!h&&d.addClass("is-clamped"),this.compactMode||this.tinyMode?(d.addClass("is-plain"),d.textContent=a):d.append((0,k.sanitizeHTMLToDom)(A)),l.length>0&&this.renderAttachmentRail(t,l),this.renderAuthorshipFooter(t,e),!i.clamp)return;let g=this.lastListWidth;if(o.ovW===g&&o.ovV!==void 0&&!h){o.ovV?this.attachExpandToggle(i,t,e,h):d.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let I=d.scrollHeight>d.clientHeight+4;if(o.ovW=g,o.ovV=I,!I&&!h){d.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,h)})})}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||k.Platform.isMobile?((0,k.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=l=>{l.stopPropagation(),this.setNoteExpanded(i.id,!this.isNoteExpanded(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&&fA.has(o)){let l=a.createEl("img",{cls:"stashpad-att-img"});l.src=this.app.vault.getResourcePath(n),l.alt=s}else{a.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let l=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:l})}a.onclick=l=>{l.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=j(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=t.createDiv({cls:"stashpad-composer"}),a=n.createDiv({cls:"stashpad-composer-input-wrap"}).createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});a.value=this.composerDraft,this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,k.debounce)(b=>{this.saveDraft(b)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value)}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let l=null,A=()=>{l||(l=new k.Scope(this.app.scope),l.register([],"Escape",()=>(this.composerExitAt=Date.now(),a.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),l.register(["Mod"],"z",()=>!0),l.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(l))},d=()=>{if(l){try{this.app.keymap?.popScope(l)}catch{}l=null}};if(a.addEventListener("focus",A),a.addEventListener("blur",d),document.activeElement===a&&A(),k.Platform.isMobile){let b=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),b()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),b(),this.tapSettleUntil=Date.now()+300,k.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new _e(this.app,a),this.composerAutocomplete.attach();let h=async b=>{let S="";for(let T of b){let U=await this.importAttachment(T);if(!U)continue;let L=a.value+S,W=L&&!L.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||this.currentEncryptionFilter()==="locked")return;let s=e.file,n=this.tree.getChildren(e.id).length,o=this.selection.has(e.id),a=i===this.cursorIdx,l=this.inListPicker?.activeIdx===i,A=t.createDiv({cls:"stashpad-note"});o&&A.addClass("is-selected"),a&&A.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&A.addClass("is-cursor-expanded"),l&&A.addClass("is-pick-target"),this.isCompleted(e)&&A.addClass("is-completed"),this.isListPinned(e.id)&&A.addClass("is-list-pinned"),this.isCutPending(e.id)?A.addClass("is-cut-pending"):this.isCopyPending(e.id)&&A.addClass("is-copy-pending"),A.dataset.idx=String(i),A.dataset.id=e.id;let d=this.currentViewMode()==="nested";A.draggable=d,d&&this.dnd.attachRowDnD(A,e,i),A.addEventListener("click",E=>this.handleRowClick(E,i,e)),A.addEventListener("dblclick",E=>{if(!this.plugin.settings.doubleClickToFocus)return;let v=this.shouldAbsorbDismissTap();if(v&&this.aimedTapTargetId&&Date.now()-this.aimedTapAt<=Yi.AIMED_TAP_WINDOW_MS){let D=this.aimedTapTargetId;this.aimedTapTargetId=null,this.traceTap("dblclick",E,i,!1),E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(D);return}if(this.traceTap("dblclick",E,i,v),v){E.preventDefault();return}E.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let h=this.isTask(e)||this.compactMode;h&&(A.addClass("is-task"),k.Platform.isMobile||this.addTaskCheckbox(A,e));let g=A.createDiv({cls:"stashpad-note-meta"}),I=g.createDiv({cls:"stashpad-note-meta-top"});I.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let p=this.colorForNode(e),u=I.createDiv({cls:"stashpad-note-grip"});p&&u.addClass("has-color"),(0,k.setIcon)(u,"grip-vertical"),u.title=p?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=d,d||(u.title=p?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),p&&u.style.setProperty("--stashpad-note-color",p);let f=h&&k.Platform.isMobile,C=this.isListPinned(e.id);if(n>0||f||C){let E=g.createDiv({cls:"stashpad-note-meta-bottom"});if(C){let v=E.createSpan({cls:"stashpad-note-listpin"});(0,k.setIcon)(v,"pin"),v.setAttr("aria-label","Pinned to top of list")}if(f&&this.addTaskCheckbox(E,e),n>0){let v=E.createSpan({cls:"stashpad-note-enter"});p&&(v.style.color=p),(0,k.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)}}}if(p)A.addClass("has-color"),A.style.setProperty("--stashpad-note-color",p);else{let E=this.inheritedColorForNode(e);E&&E.depth>0&&(A.addClass("has-inherited-color"),A.style.setProperty("--stashpad-inherited-color",E.hex),A.style.setProperty("--stashpad-inherited-depth",String(E.depth)))}let m=A.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(m,e);let B=m.createDiv({cls:"stashpad-note-body-content"}),y=A.createDiv({cls:"stashpad-note-actions"}),Q;if(k.Platform.isMobile){let E=y.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,k.setIcon)(E,"ellipsis-vertical"),E.title="Actions",E.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},Q=E}else{let E=y.createEl("button",{cls:"stashpad-pencil"});(0,k.setIcon)(E,"pencil"),E.title="Edit in new tab",E.onclick=w=>{w.stopPropagation(),this.openFileAtEnd(s)};let v=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,k.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)},Q=E}this.renderNoteBody(B,e,{clamp:!0,toggleHost:y,toggleAnchor:Q}),this.renderVersionTabs(m,e),A.oncontextmenu=E=>{E.preventDefault(),this.openNoteMenu(E,e)}}renderVersionTabs(t,e){if(!this.plugin.settings.enableSheetVersions||!li(ut(this.app,e)))return;let i=Kt(ut(this.app,e)),s=e.parent??this.focusId,n=this.tree.getChildren(s),o=pn(this.app,n.filter(A=>{let d=ut(this.app,A);return li(d)&&Kt(d)===i}));if(o.length<2)return;let a=t.createDiv({cls:"stashpad-version-tabs"});for(let A of o){let d=A.id===e.id,h=ut(this.app,A),g=Ai(h),I=Do(h),p=a.createDiv({cls:"stashpad-version-tab"+(d?" is-active":"")+(g?" is-final":"")+(I?" is-original":"")});g&&p.createSpan({cls:"stashpad-version-star",text:"\u2605"}),p.createSpan({cls:"stashpad-version-tab-label",text:Mo(this.app,A,this.titleForNode(A).trim()||"Untitled")});let u=this.titleForNode(A).trim();p.title=I?`${u} (original)`:`${u} (forked)`,d||(p.onclick=f=>{f.stopPropagation(),this.setActiveVersion(i,A.id)})}let l=a.createEl("button",{cls:"stashpad-version-add",text:"+"});l.title="New version",l.onclick=A=>{A.stopPropagation(),this.cmdForkVersion(e,!0)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,k.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:l,html:A}=o;t.empty();let d=t.createDiv({cls:"stashpad-note-text"}),h=this.isNoteExpanded(e.id);if(i.clamp&&!h&&d.addClass("is-clamped"),this.compactMode||this.tinyMode?(d.addClass("is-plain"),d.textContent=a):d.append((0,k.sanitizeHTMLToDom)(A)),l.length>0&&this.renderAttachmentRail(t,l),this.renderAuthorshipFooter(t,e),!i.clamp)return;let g=this.lastListWidth;if(o.ovW===g&&o.ovV!==void 0&&!h){o.ovV?this.attachExpandToggle(i,t,e,h):d.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let I=d.scrollHeight>d.clientHeight+4;if(o.ovW=g,o.ovV=I,!I&&!h){d.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,h)})})}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||k.Platform.isMobile?((0,k.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=l=>{l.stopPropagation(),this.setNoteExpanded(i.id,!this.isNoteExpanded(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&&dA.has(o)){let l=a.createEl("img",{cls:"stashpad-att-img"});l.src=this.app.vault.getResourcePath(n),l.alt=s}else{a.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let l=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:l})}a.onclick=l=>{l.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=Z(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=t.createDiv({cls:"stashpad-composer"}),a=n.createDiv({cls:"stashpad-composer-input-wrap"}).createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});a.value=this.composerDraft,this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,k.debounce)(b=>{this.saveDraft(b)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value)}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let l=null,A=()=>{l||(l=new k.Scope(this.app.scope),l.register([],"Escape",()=>(this.composerExitAt=Date.now(),a.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),l.register(["Mod"],"z",()=>!0),l.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(l))},d=()=>{if(l){try{this.app.keymap?.popScope(l)}catch{}l=null}};if(a.addEventListener("focus",A),a.addEventListener("blur",d),document.activeElement===a&&A(),k.Platform.isMobile){let b=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),b()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),b(),this.tapSettleUntil=Date.now()+300,k.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new je(this.app,a),this.composerAutocomplete.attach();let h=async b=>{let S="";for(let T of b){let U=await this.importAttachment(T);if(!U)continue;let L=a.value+S,W=L&&!L.endsWith(` `)?` `:"";S+=`${W}${U} -`}S&&(a.value=a.value+S,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",b=>{if(!(!b.dataTransfer||!Array.from(b.dataTransfer.types).includes("Files"))){b.preventDefault(),b.stopPropagation();try{b.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",b=>{let S=Array.from(b.dataTransfer?.files??[]);S.length!==0&&(b.preventDefault(),b.stopPropagation(),h(S))}),a.addEventListener("paste",b=>{let S=this.plugin.noteClipboard;if(S?.mode==="cut"&&S.text&&b.clipboardData?.getData("text/plain")===S.text){if(this.focusedInsideCut(S.ids)){b.preventDefault(),new k.Notice("Can't paste a cut note into the note you're cutting.");return}b.preventDefault(),this.completeCutIntoComposer();return}let T=[],U=b.clipboardData;if(U){for(let L of Array.from(U.files??[]))T.push(L);if(T.length===0){for(let L of Array.from(U.items??[]))if(L.kind==="file"){let W=L.getAsFile();W&&T.push(W)}}T.length!==0&&(b.preventDefault(),b.stopPropagation(),h(T))}});let g=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});g.setCssStyles({display:"none"});let I=n.createDiv({cls:"stashpad-composer-btn-rail"}),p=I.createDiv({cls:"stashpad-composer-btn-group"}),u=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(u,"list-end");let f=di[j().splitMode].toLowerCase();u.title=s?`Split: ON \u2014 ${f} (Mod+/ to toggle, right-click to change)`:`Split into notes (Mod+/) \u2014 right-click to choose: ${f}`,s&&u.addClass("is-active"),u.onmousedown=b=>b.preventDefault(),u.onclick=b=>{b.preventDefault(),this.toggleSplit()},u.oncontextmenu=b=>{b.preventDefault();let S=new k.Menu,T=j().splitMode;["lines","paragraphs","headings"].forEach(U=>{S.addItem(L=>L.setTitle(di[U]).setChecked(U===T).onClick(async()=>{this.plugin.settings.splitMode=U,await this.plugin.saveSettings(),this.render()}))}),S.showAtMouseEvent(b)};let C=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(C,"map-pin"),this.nextDestination&&C.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),C.title="Set destination (Mod+D)",this.nextDestination&&C.addClass("is-active"),C.onmousedown=b=>b.preventDefault(),C.onclick=b=>{b.preventDefault();let S=document.activeElement===a;this.openDestinationPicker(S)};let m=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(m,i?"corner-down-left":"arrow-big-down-dash"),m.title=i?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",m.onmousedown=b=>b.preventDefault(),m.onclick=b=>{b.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let B=b=>{let S=a.value&&!a.value.endsWith(` +`}S&&(a.value=a.value+S,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",b=>{if(!(!b.dataTransfer||!Array.from(b.dataTransfer.types).includes("Files"))){b.preventDefault(),b.stopPropagation();try{b.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",b=>{let S=Array.from(b.dataTransfer?.files??[]);S.length!==0&&(b.preventDefault(),b.stopPropagation(),h(S))}),a.addEventListener("paste",b=>{let S=this.plugin.noteClipboard;if(S?.mode==="cut"&&S.text&&b.clipboardData?.getData("text/plain")===S.text){if(this.focusedInsideCut(S.ids)){b.preventDefault(),new k.Notice("Can't paste a cut note into the note you're cutting.");return}b.preventDefault(),this.completeCutIntoComposer();return}let T=[],U=b.clipboardData;if(U){for(let L of Array.from(U.files??[]))T.push(L);if(T.length===0){for(let L of Array.from(U.items??[]))if(L.kind==="file"){let W=L.getAsFile();W&&T.push(W)}}T.length!==0&&(b.preventDefault(),b.stopPropagation(),h(T))}});let g=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});g.setCssStyles({display:"none"});let I=n.createDiv({cls:"stashpad-composer-btn-rail"}),p=I.createDiv({cls:"stashpad-composer-btn-group"}),u=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(u,"list-end");let f=di[Z().splitMode].toLowerCase();u.title=s?`Split: ON \u2014 ${f} (Mod+/ to toggle, right-click to change)`:`Split into notes (Mod+/) \u2014 right-click to choose: ${f}`,s&&u.addClass("is-active"),u.onmousedown=b=>b.preventDefault(),u.onclick=b=>{b.preventDefault(),this.toggleSplit()},u.oncontextmenu=b=>{b.preventDefault();let S=new k.Menu,T=Z().splitMode;["lines","paragraphs","headings"].forEach(U=>{S.addItem(L=>L.setTitle(di[U]).setChecked(U===T).onClick(async()=>{this.plugin.settings.splitMode=U,await this.plugin.saveSettings(),this.render()}))}),S.showAtMouseEvent(b)};let C=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(C,"map-pin"),this.nextDestination&&C.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),C.title="Set destination (Mod+D)",this.nextDestination&&C.addClass("is-active"),C.onmousedown=b=>b.preventDefault(),C.onclick=b=>{b.preventDefault();let S=document.activeElement===a;this.openDestinationPicker(S)};let m=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(m,i?"corner-down-left":"arrow-big-down-dash"),m.title=i?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",m.onmousedown=b=>b.preventDefault(),m.onclick=b=>{b.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let B=b=>{let S=a.value&&!a.value.endsWith(` `)?` `:"";a.value+=`${S}${b} -`,this.composerDraft=a.value},y=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(y,"paperclip"),y.title="Attach files",y.onmousedown=b=>b.preventDefault(),y.onclick=b=>{b.preventDefault();let S=document.activeElement===a;if(g.click(),S){let T=()=>{a.focus()};setTimeout(T,100),setTimeout(T,500)}},g.addEventListener("change",async()=>{let b=Array.from(g.files??[]);g.value="";for(let S of b){let T=await this.importAttachment(S);T&&B(T)}a.focus()});let Q=I.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,k.setIcon)(Q,"chevron-left"),Q.title="Show more composer options",I.insertBefore(Q,p);let E=b=>{I.toggleClass("is-expanded",b),Q.title=b?"Hide options":"Show more composer options",(0,k.setIcon)(Q,b?"chevron-right":"chevron-left")};Q.onmousedown=b=>b.preventDefault(),Q.onclick=b=>{b.preventDefault(),E(!I.hasClass("is-expanded"))},E(!1);let v=()=>n.clientWidth<700,w=()=>{let b=v();n.toggleClass("is-narrow",b),E(!b)};w(),requestAnimationFrame(w);let D=new ResizeObserver(w);D.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=D;let N=I.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});N.title="Send (Enter)",(0,k.setIcon)(N,"arrow-up");let P=async()=>{let b=a.value.trim();if(!b)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(b)}catch{}let S=this.modeSplit??j().splitOnLines,T=this.nextDestination,U=this.nextDestinationFolder,L=!!U&&U!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!L,this.scrollToBottomOnNextRender=!L;let W=L?{targetFolder:U}:void 0,z=T??this.focusId;if(S){let $=hi(b,j().splitMode);$.length===1?await this.createNoteUnder($[0],z,W):$.length>1&&await this.createNotesBatch($,z,W,b,L?U:this.noteFolder)}else await this.createNoteUnder(b,z,W);j().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,L&&this.composerInputEl?.focus())};N.onclick=()=>void P(),a.addEventListener("keydown",b=>{let S=this.modeEnterSubmits;if(b.key==="Escape"){b.preventDefault(),b.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(b.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(b.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let T=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,U=T?this.currentChildren.findIndex(L=>L.id===T):-1;this.cursorIdx=U>=0?U:this.currentChildren.length-1,this.selectCursor(!1)}return}b.key==="Enter"&&!b.isComposing&&(S?!b.shiftKey:b.shiftKey)&&(b.preventDefault(),b.stopPropagation(),b.stopImmediatePropagation(),P())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return k.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=j().bindings,o=h=>{let g=n[h];return g.primary&&g.secondary?g.preferRight?g.secondary:g.primary:g.primary||g.secondary},a=Ki(o("toggleSplit")),l=Ki(o("pickDestination")),A=Ki(o("search")),d=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${l} destination \xB7 ${A} search${d}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===F)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(F),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 l=this.app.internalPlugins?.plugins?.["global-search"],A=l?.instance?.openGlobalSearch?.bind(l.instance);A&&A(`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=this.shouldAbsorbDismissTap();if(this.traceTap("click",t,e,s),s){(!this.aimedTapTargetId||Date.now()-this.aimedTapAt>Oi.AIMED_TAP_WINDOW_MS)&&(this.aimedTapTargetId=i.id,this.aimedTapAt=Date.now()),t.stopPropagation();return}this.aimedTapTargetId=null;let n=t.target,o=n?.closest?.(".tag");if(o){t.preventDefault(),t.stopPropagation();let d=(o.getAttribute("href")||o.textContent||"").replace(/^#/,"").trim();if(d){let h=this.app.internalPlugins?.plugins?.["global-search"],g=h?.instance?.openGlobalSearch?.bind(h.instance);g&&g(`tag:#${d}`)}return}let a=n?.closest?.(".internal-link");if(a){t.preventDefault(),t.stopPropagation();let A=a.getAttribute("data-href")||a.getAttribute("href");if(A){let d=i.file?.path||"";this.app.workspace.openLinkText(A,d,!0)}return}if(n?.tagName==="A"&&n.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}let l=this.selection.size===0;if(t.shiftKey&&this.lastSelected){this.cursorIdx=e;let A=this.currentChildren.findIndex(d=>d.id===this.lastSelected);if(l&&(this.firstSelectedId=this.lastSelected),A!==-1){let[d,h]=A<e?[A,e]:[e,A];for(let g=d;g<=h;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 A=this.lastSelected??[...this.selection][this.selection.size-1],d=A?this.currentChildren.findIndex(h=>h.id===A):-1;d>=0&&(this.cursorIdx=d)}else this.cursorIdx=e,l&&(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,l=s.bottom-o;if(k.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let A=this.viewRoot?.querySelector(".stashpad-composer");A&&(l=Math.min(l,A.getBoundingClientRect().top-o))}n.top<a?i.scrollTop+=n.top-a:n.bottom>l&&(i.scrollTop+=n.bottom-l)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}shouldAbsorbDismissTap(){return k.Platform.isMobile&&Date.now()<this.tapSettleUntil}traceTap(t,e,i,s){if(!this.plugin.settings.debugTrace||!this.listEl)return;let n=this.listEl,o=window.visualViewport,a=n.querySelector(`.stashpad-note[data-idx="${i}"]`)?.getBoundingClientRect();this.plugin.trace(`tap:${t}`,{absorbed:s,clientY:Math.round(e.clientY),clientX:Math.round(e.clientX),idx:i,rowTop:a?Math.round(a.top):null,listTop:Math.round(n.getBoundingClientRect().top),listScrollTop:Math.round(n.scrollTop),listScrollH:Math.round(n.scrollHeight),listClientH:Math.round(n.clientHeight),innerH:window.innerHeight,vvHeight:o?Math.round(o.height):null,vvOffsetTop:o?Math.round(o.offsetTop):null,tapSettleInMs:Math.max(0,this.tapSettleUntil-Date.now()),kbOpen:document.body.classList.contains("stashpad-keyboard-open")})}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]:[]}async cmdLockSelection(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(o=>o.id)),i=new Set((this.plugin.settings.lockedSubtrees??[]).map(o=>o.rootId).filter(o=>!!o)),s=t.filter(o=>{if(i.has(o.id))return!1;let a=o.parent;for(;a;){if(e.has(a))return!1;a=this.tree.get(a)?.parent??null}return!0});if(s.length===0){new k.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??F),l=a.indexOf(o.id),A=l>0?a[l-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,A,{silent:!0})&&n++}n>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Locked ${n} stash${n===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}async cmdMoveToArchive(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=(this.plugin.settings.archiveFolders??[]).filter(o=>o!==this.noteFolder);if(t.length===0){new k.Notice("No archive folder available. Mark a folder as archive first (folder panel \u2192 right-click \u2192 \u201CMark as archive\u201D).",8e3);return}let e=this.getActionTargets();if(e.length===0)return;let i=this.plugin.settings.defaultArchiveFolder,s=i&&t.includes(i)?i:t.length===1?t[0]:null,n=o=>{this.archiveSources(e,o)};if(s){n(s);return}new mo(this.app,t,n).open()}async archiveSources(t,e){let i=this.noteFolder,s=new Set(t.map(A=>A.id)),n=t.filter(A=>{let d=A.parent;for(;d;){if(s.has(d))return!1;d=this.tree.get(d)?.parent??null}return!0});if(n.length===0)return;let o=n.map(A=>A.id),a=[];for(let A of n){let d=this.order.getOrder(i,A.parent??F),h=d.indexOf(A.id),g=h>0?d[h-1]:null,I=await this.plugin.lockNoteSubtree(i,A.id,g,{silent:!0,blobFolder:e});I&&a.push(I.blobPath)}if(a.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let l=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${a.length} note${a.length===1?"":"s"} \u2192 \u201C${l}\u201D. Undo to bring ${a.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${a.length})`,undo:async()=>{for(let A of a)try{await this.plugin.unlockBundleAt(A,{silent:!0,destFolder:i})}catch(d){console.warn("[Stashpad] archive undo failed",A,d)}a=[],this.tree.rebuild(i),this.render()},redo:async()=>{a=[];for(let A of o){let d=await this.plugin.lockNoteSubtree(i,A,null,{silent:!0,blobFolder:e});d&&a.push(d.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(n=>n.id)),i=t.filter(n=>{let o=n.parent;for(;o;){if(e.has(o))return!1;o=this.tree.get(o)?.parent??null}return!0});if(i.length===0)return;let s=i.length;new pt(this.app,`Encrypt & delete ${s} note${s===1?"":"s"}?`,[`The selected note${s===1?"":"s"} (and any children) will be encrypted and moved to Stashpad's encrypted trash.`,"","\u2022 The readable copy is permanently removed from the folder.",`\u2022 You can restore ${s===1?"it":"them"} later from the encrypted trash \u2014 you'll need your encryption password.`,`\u2022 If you lose your password, ${s===1?"it's":"they're"} gone for good.`].join(` -`),"Encrypt & delete",async n=>{n&&await this.secureDeleteSources(i)}).open()}async secureDeleteSources(t){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let e=new Set(t.map(a=>a.id)),i=t.filter(a=>{let l=a.parent;for(;l;){if(e.has(l))return!1;l=this.tree.get(l)?.parent??null}return!0});if(i.length===0)return;let s=this.noteFolder,n=i.map(a=>a.id),o=[];for(let a of n){let l=await this.plugin.encryptDeleteSubtree(s,a);l&&o.push(l)}o.length!==0&&(this.selection.clear(),this.lastSelected=null,this.tree.rebuild(s),this.render(),this.plugin.notifications.show({message:`Securely deleted ${o.length} note${o.length===1?"":"s"} \u2192 encrypted trash. Undo to bring ${o.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:s}),this.plugin.getUndoStack(s).push({label:`Secure delete (${o.length})`,undo:async()=>{for(let a of o)try{await this.plugin.restoreDeletedAt(a,{silent:!0})}catch(l){console.warn("[Stashpad] secure-delete undo failed",a,l)}o=[],this.tree.rebuild(s),this.render()},redo:async()=>{o=[];for(let a of n){let l=await this.plugin.encryptDeleteSubtree(s,a);l&&o.push(l)}this.tree.rebuild(s),this.render()}}))}async cmdUnlockAll(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=new Set,e=new Set,i=this.getActionTargets().map(n=>n.id);for(;i.length;){let n=i.pop();if(!e.has(n)){e.add(n);for(let o of this.tree.getChildren(n))i.push(o.id)}}for(let n of e)for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob);if(t.size===0){let n=(this.tree.get(this.focusId)??this.tree.getRoot()).id;for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob)}if(t.size===0){new k.Notice("No locked notes to unlock here.");return}if(!await this.plugin.ensureEncryptionUnlocked())return;let s=0;for(let n of t)try{await this.plugin.unlockBundleAt(n,{silent:!0})&&s++}catch(o){console.warn("[Stashpad] batch unlock skipped",n,o)}s>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Unlocked ${s} stash${s===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}toggleSplit(){let t=this.modeSplit??j().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Wt(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.crossId??i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===F?"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===F&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:F,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!==F&&!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===F},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Wt(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 Wt(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 Wt(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.crossId??n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!o)return;let l=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",A=this.app.workspace,d=A.getLeaf("tab");await d.setViewState({type:K,active:!0,state:{focusId:o,folderOverride:a===l?null:a}}),A.revealLeaf(d);let h=d.view;if(h&&typeof h.createNoteUnder=="function"){let g=await h.createNoteUnder(s,o);g&&typeof h.navigateTo=="function"&&h.navigateTo(g)}}}).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.crossId??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===F&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:F,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 l=n.get(a);l||(l=[],n.set(a,l)),l.push(o)}for(let o of i){let a=n.get(o)??[],l=new Map;for(let A of a){let d=this.app.metadataCache.getFileCache(A)?.frontmatter;typeof d?.id=="string"&&l.set(d.id,A)}for(let A of a){let d=this.app.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id:"";if(!h||h===F)continue;let g=A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),I,p=d?.parent??null;if(p&&p!==F){let u=l.get(p);u&&(I=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:A,folder:o,id:h,title:g,body:"",parentBlurb:I,parentId:p??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===F){i.push(s.id);continue}let o=n.parent??F;await this.changeParent(s,o),e.push(s)}if(e.length===0){new k.Notice(i.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),i.length&&this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:e,suffix:i.length?`(${i.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e.map(s=>s.id),folder:this.noteFolder}),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 xe(this.app,i,s,async(n,o)=>{let a=[];for(let h of t)if(h.file){a.push({id:h.id,path:h.file.path,was:this.colorForNode(h)??null});try{await this.app.fileManager.processFrontMatter(h.file,g=>{n?g.color=n:delete g.color})}catch(g){new k.Notice(`Couldn't set color for ${h.id}: ${g.message}`)}}if(o.addToPalette&&typeof n=="string"){let h=[...this.plugin.settings.customPalette??[]],g=n.toLowerCase();h.some(I=>I.toLowerCase()===g)||(h.push(n),this.plugin.settings.customPalette=h,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:F,payload:{color:n}}))}this.render();let l=this.noteFolder,A=n,d=async h=>{for(let g of h){let I=this.app.vault.getAbstractFileByPath(g.path);if(I)try{await this.app.fileManager.processFrontMatter(I,p=>{g.col?p.color=g.col:delete p.color})}catch{}}this.tree.rebuild(l),this.render()};this.plugin.getUndoStack(l).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>d(a.map(h=>({path:h.path,col:h.was}))),redo:()=>d(a.map(h=>({path:h.path,col:A})))})},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:F,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Wt(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.crossId??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 k.Notice("Target folder is empty");return}let n=[],o=new Set;for(let g of this.app.vault.getMarkdownFiles())(g.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(g.path);let a=(g,I)=>{if(!g.file)return;let p=g.file,u=`${s}/${p.name}`;if(o.has(u)){let f=p.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:p.basename,m=f?f[2]:"";for(let B=1;B<1e3;B++){let y=`${C}-${B}${m}.md`,Q=`${s}/${y}`;if(!o.has(Q)){u=Q;break}}}o.add(u),n.push({id:g.id,file:p,oldPath:p.path,newPath:u,oldParent:g.parent,isRoot:I});for(let f of this.tree.getChildren(g.id))a(f,!1)};for(let g of t)a(g,!0);if(!n.length)return;await this.ensureFolder(s);for(let g of n)try{await this.app.fileManager.renameFile(g.file,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(g.file,I=>{I.parent=i}),await this.log.append({type:"parent_change",id:g.id,payload:{from:g.oldParent,to:g.isRoot?i:g.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(I){new k.Notice(`Move failed for ${g.id}: ${I.message}`)}if(j().writeRecoveryLinks){let g=this.noteFolder;window.setTimeout(()=>{ii(this.app,g),ii(this.app,s)},350)}let l=this.titleList(t);this.tree.rebuild(this.noteFolder);let A=i===F?"Open home":"Open parent",d=Math.max(0,n.length-t.length),h=t.length===1?`Moved ${l}${d>0?` and its ${d} nested note${d===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${l}${d>0?` (${d} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:h,kind:"success",category:"move",duration:0,affectedIds:t.map(g=>g.id),folder:this.noteFolder,actions:[{label:A,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let g of n){let I=this.app.vault.getAbstractFileByPath(g.newPath);if(I)try{await this.app.fileManager.renameFile(I,g.oldPath),g.isRoot&&await this.app.fileManager.processFrontMatter(I,p=>{p.parent=g.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let g of n){let I=this.app.vault.getAbstractFileByPath(g.oldPath);if(I)try{await this.app.fileManager.renameFile(I,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(I,p=>{p.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=j().bindings.move,i=Ki(e.primary||e.secondary||"M");new k.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)return;let a=this.currentChildren.findIndex(l=>l.id===t.id);a<0||this.selection.size===1&&this.selection.has(t.id)&&this.cursorIdx===a||(this.selection.clear(),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 k.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 l=a.map(u=>u.trim()).filter(Boolean).join(` +`,this.composerDraft=a.value},y=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(y,"paperclip"),y.title="Attach files",y.onmousedown=b=>b.preventDefault(),y.onclick=b=>{b.preventDefault();let S=document.activeElement===a;if(g.click(),S){let T=()=>{a.focus()};setTimeout(T,100),setTimeout(T,500)}},g.addEventListener("change",async()=>{let b=Array.from(g.files??[]);g.value="";for(let S of b){let T=await this.importAttachment(S);T&&B(T)}a.focus()});let Q=I.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,k.setIcon)(Q,"chevron-left"),Q.title="Show more composer options",I.insertBefore(Q,p);let E=b=>{I.toggleClass("is-expanded",b),Q.title=b?"Hide options":"Show more composer options",(0,k.setIcon)(Q,b?"chevron-right":"chevron-left")};Q.onmousedown=b=>b.preventDefault(),Q.onclick=b=>{b.preventDefault(),E(!I.hasClass("is-expanded"))},E(!1);let v=()=>n.clientWidth<700,w=()=>{let b=v();n.toggleClass("is-narrow",b),E(!b)};w(),requestAnimationFrame(w);let D=new ResizeObserver(w);D.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=D;let N=I.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});N.title="Send (Enter)",(0,k.setIcon)(N,"arrow-up");let P=async()=>{let b=a.value.trim();if(!b)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(b)}catch{}let S=this.modeSplit??Z().splitOnLines,T=this.nextDestination,U=this.nextDestinationFolder,L=!!U&&U!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!L,this.scrollToBottomOnNextRender=!L;let W=L?{targetFolder:U}:void 0,$=T??this.focusId;if(S){let z=hi(b,Z().splitMode);z.length===1?await this.createNoteUnder(z[0],$,W):z.length>1&&await this.createNotesBatch(z,$,W,b,L?U:this.noteFolder)}else await this.createNoteUnder(b,$,W);Z().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,L&&this.composerInputEl?.focus())};N.onclick=()=>void P(),a.addEventListener("keydown",b=>{let S=this.modeEnterSubmits;if(b.key==="Escape"){b.preventDefault(),b.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(b.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(b.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let T=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,U=T?this.currentChildren.findIndex(L=>L.id===T):-1;this.cursorIdx=U>=0?U:this.currentChildren.length-1,this.selectCursor(!1)}return}b.key==="Enter"&&!b.isComposing&&(S?!b.shiftKey:b.shiftKey)&&(b.preventDefault(),b.stopPropagation(),b.stopImmediatePropagation(),P())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return k.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=Z().bindings,o=h=>{let g=n[h];return g.primary&&g.secondary?g.preferRight?g.secondary:g.primary:g.primary||g.secondary},a=Gi(o("toggleSplit")),l=Gi(o("pickDestination")),A=Gi(o("search")),d=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${l} destination \xB7 ${A} search${d}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===F)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(F),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 l=this.app.internalPlugins?.plugins?.["global-search"],A=l?.instance?.openGlobalSearch?.bind(l.instance);A&&A(`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=this.shouldAbsorbDismissTap();if(this.traceTap("click",t,e,s),s){(!this.aimedTapTargetId||Date.now()-this.aimedTapAt>Yi.AIMED_TAP_WINDOW_MS)&&(this.aimedTapTargetId=i.id,this.aimedTapAt=Date.now()),t.stopPropagation();return}this.aimedTapTargetId=null;let n=t.target,o=n?.closest?.(".tag");if(o){t.preventDefault(),t.stopPropagation();let d=(o.getAttribute("href")||o.textContent||"").replace(/^#/,"").trim();if(d){let h=this.app.internalPlugins?.plugins?.["global-search"],g=h?.instance?.openGlobalSearch?.bind(h.instance);g&&g(`tag:#${d}`)}return}let a=n?.closest?.(".internal-link");if(a){t.preventDefault(),t.stopPropagation();let A=a.getAttribute("data-href")||a.getAttribute("href");if(A){let d=i.file?.path||"";this.app.workspace.openLinkText(A,d,!0)}return}if(n?.tagName==="A"&&n.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}let l=this.selection.size===0;if(t.shiftKey&&this.lastSelected){this.cursorIdx=e;let A=this.currentChildren.findIndex(d=>d.id===this.lastSelected);if(l&&(this.firstSelectedId=this.lastSelected),A!==-1){let[d,h]=A<e?[A,e]:[e,A];for(let g=d;g<=h;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 A=this.lastSelected??[...this.selection][this.selection.size-1],d=A?this.currentChildren.findIndex(h=>h.id===A):-1;d>=0&&(this.cursorIdx=d)}else this.cursorIdx=e,l&&(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,l=s.bottom-o;if(k.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let A=this.viewRoot?.querySelector(".stashpad-composer");A&&(l=Math.min(l,A.getBoundingClientRect().top-o))}n.top<a?i.scrollTop+=n.top-a:n.bottom>l&&(i.scrollTop+=n.bottom-l)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}shouldAbsorbDismissTap(){return k.Platform.isMobile&&Date.now()<this.tapSettleUntil}traceTap(t,e,i,s){if(!this.plugin.settings.debugTrace||!this.listEl)return;let n=this.listEl,o=window.visualViewport,a=n.querySelector(`.stashpad-note[data-idx="${i}"]`)?.getBoundingClientRect();this.plugin.trace(`tap:${t}`,{absorbed:s,clientY:Math.round(e.clientY),clientX:Math.round(e.clientX),idx:i,rowTop:a?Math.round(a.top):null,listTop:Math.round(n.getBoundingClientRect().top),listScrollTop:Math.round(n.scrollTop),listScrollH:Math.round(n.scrollHeight),listClientH:Math.round(n.clientHeight),innerH:window.innerHeight,vvHeight:o?Math.round(o.height):null,vvOffsetTop:o?Math.round(o.offsetTop):null,tapSettleInMs:Math.max(0,this.tapSettleUntil-Date.now()),kbOpen:document.body.classList.contains("stashpad-keyboard-open")})}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]:[]}async cmdLockSelection(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(o=>o.id)),i=new Set((this.plugin.settings.lockedSubtrees??[]).map(o=>o.rootId).filter(o=>!!o)),s=t.filter(o=>{if(i.has(o.id))return!1;let a=o.parent;for(;a;){if(e.has(a))return!1;a=this.tree.get(a)?.parent??null}return!0});if(s.length===0){new k.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??F),l=a.indexOf(o.id),A=l>0?a[l-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,A,{silent:!0})&&n++}n>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Locked ${n} stash${n===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}async cmdMoveToArchive(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=(this.plugin.settings.archiveFolders??[]).filter(o=>o!==this.noteFolder);if(t.length===0){new k.Notice("No archive folder available. Mark a folder as archive first (folder panel \u2192 right-click \u2192 \u201CMark as archive\u201D).",8e3);return}let e=this.getActionTargets();if(e.length===0)return;let i=this.plugin.settings.defaultArchiveFolder,s=i&&t.includes(i)?i:t.length===1?t[0]:null,n=o=>{this.archiveSources(e,o)};if(s){n(s);return}new Io(this.app,t,n).open()}async archiveSources(t,e){let i=this.noteFolder,s=new Set(t.map(A=>A.id)),n=t.filter(A=>{let d=A.parent;for(;d;){if(s.has(d))return!1;d=this.tree.get(d)?.parent??null}return!0});if(n.length===0)return;let o=n.map(A=>A.id),a=[];for(let A of n){let d=this.order.getOrder(i,A.parent??F),h=d.indexOf(A.id),g=h>0?d[h-1]:null,I=await this.plugin.lockNoteSubtree(i,A.id,g,{silent:!0,blobFolder:e});I&&a.push(I.blobPath)}if(a.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let l=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${a.length} note${a.length===1?"":"s"} \u2192 \u201C${l}\u201D. Undo to bring ${a.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${a.length})`,undo:async()=>{for(let A of a)try{await this.plugin.unlockBundleAt(A,{silent:!0,destFolder:i})}catch(d){console.warn("[Stashpad] archive undo failed",A,d)}a=[],this.tree.rebuild(i),this.render()},redo:async()=>{a=[];for(let A of o){let d=await this.plugin.lockNoteSubtree(i,A,null,{silent:!0,blobFolder:e});d&&a.push(d.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(n=>n.id)),i=t.filter(n=>{let o=n.parent;for(;o;){if(e.has(o))return!1;o=this.tree.get(o)?.parent??null}return!0});if(i.length===0)return;let s=i.length;new ot(this.app,`Encrypt & delete ${s} note${s===1?"":"s"}?`,[`The selected note${s===1?"":"s"} (and any children) will be encrypted and moved to Stashpad's encrypted trash.`,"","\u2022 The readable copy is permanently removed from the folder.",`\u2022 You can restore ${s===1?"it":"them"} later from the encrypted trash \u2014 you'll need your encryption password.`,`\u2022 If you lose your password, ${s===1?"it's":"they're"} gone for good.`].join(` +`),"Encrypt & delete",async n=>{n&&await this.secureDeleteSources(i)}).open()}async secureDeleteSources(t){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let e=new Set(t.map(a=>a.id)),i=t.filter(a=>{let l=a.parent;for(;l;){if(e.has(l))return!1;l=this.tree.get(l)?.parent??null}return!0});if(i.length===0)return;let s=this.noteFolder,n=i.map(a=>a.id),o=[];for(let a of n){let l=await this.plugin.encryptDeleteSubtree(s,a);l&&o.push(l)}o.length!==0&&(this.selection.clear(),this.lastSelected=null,this.tree.rebuild(s),this.render(),this.plugin.notifications.show({message:`Securely deleted ${o.length} note${o.length===1?"":"s"} \u2192 encrypted trash. Undo to bring ${o.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:s}),this.plugin.getUndoStack(s).push({label:`Secure delete (${o.length})`,undo:async()=>{for(let a of o)try{await this.plugin.restoreDeletedAt(a,{silent:!0})}catch(l){console.warn("[Stashpad] secure-delete undo failed",a,l)}o=[],this.tree.rebuild(s),this.render()},redo:async()=>{o=[];for(let a of n){let l=await this.plugin.encryptDeleteSubtree(s,a);l&&o.push(l)}this.tree.rebuild(s),this.render()}}))}async cmdUnlockAll(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=new Set,e=new Set,i=this.getActionTargets().map(n=>n.id);for(;i.length;){let n=i.pop();if(!e.has(n)){e.add(n);for(let o of this.tree.getChildren(n))i.push(o.id)}}for(let n of e)for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob);if(t.size===0){let n=(this.tree.get(this.focusId)??this.tree.getRoot()).id;for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob)}if(t.size===0){new k.Notice("No locked notes to unlock here.");return}if(!await this.plugin.ensureEncryptionUnlocked())return;let s=0;for(let n of t)try{await this.plugin.unlockBundleAt(n,{silent:!0})&&s++}catch(o){console.warn("[Stashpad] batch unlock skipped",n,o)}s>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Unlocked ${s} stash${s===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}toggleSplit(){let t=this.modeSplit??Z().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new $t(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.crossId??i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===F?"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===F&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:F,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!==F&&!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===F},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new $t(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 $t(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 $t(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.crossId??n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!o)return;let l=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",A=this.app.workspace,d=A.getLeaf("tab");await d.setViewState({type:J,active:!0,state:{focusId:o,folderOverride:a===l?null:a}}),A.revealLeaf(d);let h=d.view;if(h&&typeof h.createNoteUnder=="function"){let g=await h.createNoteUnder(s,o);g&&typeof h.navigateTo=="function"&&h.navigateTo(g)}}}).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.crossId??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===F&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:F,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 l=n.get(a);l||(l=[],n.set(a,l)),l.push(o)}for(let o of i){let a=n.get(o)??[],l=new Map;for(let A of a){let d=this.app.metadataCache.getFileCache(A)?.frontmatter;typeof d?.id=="string"&&l.set(d.id,A)}for(let A of a){let d=this.app.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id:"";if(!h||h===F)continue;let g=A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),I,p=d?.parent??null;if(p&&p!==F){let u=l.get(p);u&&(I=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:A,folder:o,id:h,title:g,body:"",parentBlurb:I,parentId:p??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===F){i.push(s.id);continue}let o=n.parent??F;await this.changeParent(s,o),e.push(s)}if(e.length===0){new k.Notice(i.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),i.length&&this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:e,suffix:i.length?`(${i.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e.map(s=>s.id),folder:this.noteFolder}),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 Ne(this.app,i,s,async(n,o)=>{let a=[];for(let h of t)if(h.file){a.push({id:h.id,path:h.file.path,was:this.colorForNode(h)??null});try{await this.app.fileManager.processFrontMatter(h.file,g=>{n?g.color=n:delete g.color})}catch(g){new k.Notice(`Couldn't set color for ${h.id}: ${g.message}`)}}if(o.addToPalette&&typeof n=="string"){let h=[...this.plugin.settings.customPalette??[]],g=n.toLowerCase();h.some(I=>I.toLowerCase()===g)||(h.push(n),this.plugin.settings.customPalette=h,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:F,payload:{color:n}}))}this.render();let l=this.noteFolder,A=n,d=async h=>{for(let g of h){let I=this.app.vault.getAbstractFileByPath(g.path);if(I)try{await this.app.fileManager.processFrontMatter(I,p=>{g.col?p.color=g.col:delete p.color})}catch{}}this.tree.rebuild(l),this.render()};this.plugin.getUndoStack(l).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>d(a.map(h=>({path:h.path,col:h.was}))),redo:()=>d(a.map(h=>({path:h.path,col:A})))})},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:F,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new $t(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let o=e.crossId??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 k.Notice("Target folder is empty");return}let n=[],o=new Set;for(let g of this.app.vault.getMarkdownFiles())(g.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(g.path);let a=(g,I)=>{if(!g.file)return;let p=g.file,u=`${s}/${p.name}`;if(o.has(u)){let f=p.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:p.basename,m=f?f[2]:"";for(let B=1;B<1e3;B++){let y=`${C}-${B}${m}.md`,Q=`${s}/${y}`;if(!o.has(Q)){u=Q;break}}}o.add(u),n.push({id:g.id,file:p,oldPath:p.path,newPath:u,oldParent:g.parent,isRoot:I});for(let f of this.tree.getChildren(g.id))a(f,!1)};for(let g of t)a(g,!0);if(!n.length)return;await this.ensureFolder(s);for(let g of n)try{await this.app.fileManager.renameFile(g.file,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(g.file,I=>{I.parent=i}),await this.log.append({type:"parent_change",id:g.id,payload:{from:g.oldParent,to:g.isRoot?i:g.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(I){new k.Notice(`Move failed for ${g.id}: ${I.message}`)}if(Z().writeRecoveryLinks){let g=this.noteFolder;window.setTimeout(()=>{ei(this.app,g),ei(this.app,s)},350)}let l=this.titleList(t);this.tree.rebuild(this.noteFolder);let A=i===F?"Open home":"Open parent",d=Math.max(0,n.length-t.length),h=t.length===1?`Moved ${l}${d>0?` and its ${d} nested note${d===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${l}${d>0?` (${d} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:h,kind:"success",category:"move",duration:0,affectedIds:t.map(g=>g.id),folder:this.noteFolder,actions:[{label:A,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let g of n){let I=this.app.vault.getAbstractFileByPath(g.newPath);if(I)try{await this.app.fileManager.renameFile(I,g.oldPath),g.isRoot&&await this.app.fileManager.processFrontMatter(I,p=>{p.parent=g.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let g of n){let I=this.app.vault.getAbstractFileByPath(g.oldPath);if(I)try{await this.app.fileManager.renameFile(I,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(I,p=>{p.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=Z().bindings.move,i=Gi(e.primary||e.secondary||"M");new k.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)return;let a=this.currentChildren.findIndex(l=>l.id===t.id);a<0||this.selection.size===1&&this.selection.has(t.id)&&this.cursorIdx===a||(this.selection.clear(),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 k.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 l=a.map(u=>u.trim()).filter(Boolean).join(` `),A=await this.app.vault.read(e.file),d=A.startsWith("---")?A.indexOf(` ---`,3)+4:0,g=`${A.slice(0,d)} ${l} -`;await this.app.vault.modify(e.file,g);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 I=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${I}"`}),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(B=>B.id===u);m<0||(this.selection.add(u),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let p=this.noteFolder;this.plugin.getUndoStack(p).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(p),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,g);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(p),this.render()}})}cmdCopy(){return fo(this)}cmdCopyCodeBlock(){return hr(this)}cmdCopyTree(){return pr(this)}cmdCopyOutline(){return gr(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.isNoteExpanded(i.id));for(let i of t)this.setNoteExpanded(i.id,e);this.render()}isNoteExpanded(t){let e=this.expandedNotes.has(t);return this.plugin.settings.expandBodiesByDefault?!e:e}setNoteExpanded(t,e){let i=this.plugin.settings.expandBodiesByDefault;e===i?this.expandedNotes.delete(t):this.expandedNotes.add(t)}cmdExpandAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!0);this.render()}cmdCollapseAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!1);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new k.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),l=this.app.metadataCache.getFileCache(n)?.frontmatter??{},A=tt(),d=Qt(a,this.activeStopwords()),h=yt(d,A),g=`${this.noteFolder}/${h}`,I=new Date().toISOString(),p=this.extractAttachments(a),u=["---",`id: ${A}`,`parent: ${e}`,`created: ${I}`];if(p.length>0){u.push("attachments:");for(let C of p)u.push(` - "${C.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(g,u.join(` -`)),i.push(g);let f=this.app.vault.getAbstractFileByPath(g);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,B]of Object.entries(l))Xt.includes(m)||Vi.includes(m)||(C[m]=B)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:A,parent:e,children:[],file:f,created:I})}catch{}this.fmSync.scheduleParentChange(A,null,e)}for(let C of s)await this.cloneSubtree(C,A,i);return A}async cmdClone(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let l of t){if(!l.file)continue;let A=l.parent??this.focusId,d=await this.cloneSubtree(l,A,i);d&&s.push(d)}if(!s.length)return;this.tree.rebuild(e),this.pendingFocusIds=s.slice(),this.render();let n=i.map(l=>this.app.vault.getAbstractFileByPath(l)).filter(l=>!!l&&l.extension==="md").map(l=>({id:de(l.basename)??l.basename,parent:null,children:[],file:l,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 l of[...i].reverse()){let A=this.app.vault.getAbstractFileByPath(l);if(A)try{await this.app.fileManager.trashFile(A)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(l=>this.tree.get(l)).filter(l=>!!l);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})}cmdForkNote(){let t=this.getActionTargets()[0];if(!t?.file){new k.Notice("Nothing to fork.");return}let e=t.parent??F,i=e===F?null:this.tree.get(e),s=i?this.titleForNode(i):"Home";new Wt(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",allowCreate:!0,placeholder:`Fork "${this.titleForNode(t)}" under\u2026 (default: ${s})`,onPick:n=>{if(n.crossFolder){new k.Notice("Fork stays in this folder for now.");return}this.forkNoteUnder(t,n.id)},onCreate:n=>{(async()=>{let o=await this.createNoteUnder(n,this.focusId);o&&await this.forkNoteUnder(t,o)})()}}).open()}async forkNoteUnder(t,e){if(!t.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(t,e,s);if(!n)return;let o=s[0]?this.app.vault.getAbstractFileByPath(s[0]):null;if(o)try{await this.app.fileManager.processFrontMatter(o,d=>{d[Ge]=`[[${t.file.basename}]]`})}catch{}this.tree.rebuild(i),this.pendingFocusIds=[n],this.render(),await this.syncForkSiblings(this.forkFamilyFiles({originName:t.file.basename,include:[t.file,o]}));let a=s.map(d=>this.app.vault.getAbstractFileByPath(d)).filter(d=>!!d&&d.extension==="md").map(d=>({id:de(d.basename)??d.basename,parent:null,children:[],file:d,created:new Date().toISOString()})),l=await this.snapshotNotes(a,!1);this.plugin.getUndoStack(i).push({label:"Fork note",undo:async()=>{for(let d of[...s].reverse()){let h=this.app.vault.getAbstractFileByPath(d);if(h)try{await this.app.fileManager.trashFile(h)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(l,[n])}});let A=this.tree.get(n);this.plugin.notifications.show({message:A?`Forked "${this.titleForNode(t)}" \u2192 "${this.titleForNode(A)}" (${s.length} file${s.length===1?"":"s"})`:"Forked note",kind:"success",category:"clone",affectedIds:[n],folder:i})}async ensureSheetGroup(t){let e=Kt(this.app.metadataCache.getFileCache(t)?.frontmatter);if(e)return e;let i=No();return await this.app.fileManager.processFrontMatter(t,s=>{s[Pe]=i,typeof s[qt]!="number"&&(s[qt]=0),s[Ue]=!0}),i}forkFamilyFiles(t){let e=new Map,i=s=>{s&&e.set(s.path,s)};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;t.gid&&Kt(n)===t.gid&&i(s),t.originName&&(s.basename===t.originName||bo(n)===t.originName)&&i(s)}for(let s of t.include??[])i(s);return[...e.values()]}async syncForkSiblings(t){for(let e of t){let i=t.filter(s=>s.path!==e.path).map(s=>`[[${s.basename}]]`);await this.app.fileManager.processFrontMatter(e,s=>{i.length?s[Jt]=i:delete s[Jt]})}}async cmdForkVersion(t,e=!1){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings(),new k.Notice("Sheet versions enabled."));let i=t??this.getActionTargets()[0];if(!i?.file){new k.Notice("Select a note to version.");return}let s=this.noteFolder,n={...this.app.metadataCache.getFileCache(i.file)?.frontmatter??{}},o=await this.ensureSheetGroup(i.file),a=i.parent??this.focusId,l=typeof n[qt]=="number"?n[qt]:0;for(let p of this.tree.getChildren(a)){if(p.id===i.id)continue;let u=ut(this.app,p);if(Kt(u)!==o)continue;let f=u?.[qt];typeof f=="number"&&f>l&&(l=f)}let A=l+1,d=[],h;if(e){let p=tt(),u=yt(Qt("",this.activeStopwords()),p),f=`${s}/${u}`,C=new Date().toISOString();await this.ensureFolder(s),await this.app.vault.create(f,["---",`id: ${p}`,`parent: ${a}`,`created: ${C}`,"attachments: []","---",""].join(` -`));let m=this.app.vault.getAbstractFileByPath(f);if(!m){new k.Notice("Sheets: could not create version.");return}await this.app.fileManager.processFrontMatter(m,B=>{for(let[y,Q]of Object.entries(n))Xt.includes(y)||Vi.includes(y)||(B[y]=Q);B[Pe]=o,B[qt]=A,delete B[Ee],delete B[Ue],B[Ge]=`[[${i.file.basename}]]`});try{this.tree.insertSynthetic({id:p,parent:a,children:[],file:m,created:C})}catch{}this.fmSync.scheduleParentChange(p,null,a),d.push(f),h=p}else{let p=await this.cloneSubtree(i,a,d);if(!p||!d.length){new k.Notice("Sheets: could not create version.");return}h=p;let u=this.app.vault.getAbstractFileByPath(d[0]);u&&await this.app.fileManager.processFrontMatter(u,f=>{f[Pe]=o,f[qt]=A,delete f[Ee],delete f[Ue],f[Ge]=`[[${i.file.basename}]]`})}this.tree.rebuild(s),this.activeVersionByGroup.set(o,h),this.plugin.saveActiveVersion(s,o,h),this.render();let g=this.app.vault.getAbstractFileByPath(d[0]);await this.syncForkSiblings(this.forkFamilyFiles({gid:o,include:[i.file,g]})),this.plugin.getUndoStack(s).push({label:e?"New version":"Fork version",undo:async()=>{for(let p of[...d].reverse()){let u=this.app.vault.getAbstractFileByPath(p);if(u)try{await this.app.fileManager.trashFile(u)}catch{}}this.activeVersionByGroup.delete(o),this.tree.rebuild(s),this.render()},redo:async()=>{}});let I=d.length;new k.Notice(e?"New version added":`Forked a new version${I>1?` (${I} notes)`:""}`)}async cmdMarkVersionFinal(t){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings());let e=t??this.getActionTargets()[0];if(!e?.file)return;let i=Kt(ut(this.app,e));if(!i){new k.Notice("Not a versioned note.");return}let s=!Ai(ut(this.app,e)),n=e.parent??this.focusId,o=this.tree.getChildren(n).filter(a=>Kt(ut(this.app,a))===i);for(let a of o){if(!a.file)continue;let l=Ai(ut(this.app,a)),A=s&&a.id===e.id;l!==A&&await this.app.fileManager.processFrontMatter(a.file,d=>{A?d[Ee]=!0:delete d[Ee]})}this.render()}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to copy.");return}await fo(this),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"copy",folder:this.noteFolder,ids:t.map(e=>e.id)},this.render()}isCutPending(t){let e=this.plugin.noteClipboard;return!!e&&e.mode==="cut"&&e.folder===this.noteFolder&&e.ids.includes(t)}isCopyPending(t){let e=this.plugin.noteClipboard;return!!e&&e.mode==="copy"&&e.folder===this.noteFolder&&e.ids.includes(t)}insertIntoComposer(t){let e=this.composerInputEl;if(!e){this.composerDraft=this.composerDraft?`${this.composerDraft} +`;await this.app.vault.modify(e.file,g);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 I=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${I}"`}),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(B=>B.id===u);m<0||(this.selection.add(u),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let p=this.noteFolder;this.plugin.getUndoStack(p).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(p),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,g);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(p),this.render()}})}cmdCopy(){return jn(this)}cmdCopyCodeBlock(){return Ha(this)}cmdCopyTree(){return Pa(this)}cmdCopyOutline(){return Ua(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.isNoteExpanded(i.id));for(let i of t)this.setNoteExpanded(i.id,e);this.render()}isNoteExpanded(t){let e=this.expandedNotes.has(t);return this.plugin.settings.expandBodiesByDefault?!e:e}setNoteExpanded(t,e){let i=this.plugin.settings.expandBodiesByDefault;e===i?this.expandedNotes.delete(t):this.expandedNotes.add(t)}cmdExpandAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!0);this.render()}cmdCollapseAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!1);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new k.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),l=this.app.metadataCache.getFileCache(n)?.frontmatter??{},A=tt(),d=Qt(a,this.activeStopwords()),h=yt(d,A),g=`${this.noteFolder}/${h}`,I=new Date().toISOString(),p=this.extractAttachments(a),u=["---",`id: ${A}`,`parent: ${e}`,`created: ${I}`];if(p.length>0){u.push("attachments:");for(let C of p)u.push(` - "${C.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(g,u.join(` +`)),i.push(g);let f=this.app.vault.getAbstractFileByPath(g);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,B]of Object.entries(l))Zt.includes(m)||Wi.includes(m)||(C[m]=B)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:A,parent:e,children:[],file:f,created:I})}catch{}this.fmSync.scheduleParentChange(A,null,e)}for(let C of s)await this.cloneSubtree(C,A,i);return A}async cmdClone(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let l of t){if(!l.file)continue;let A=l.parent??this.focusId,d=await this.cloneSubtree(l,A,i);d&&s.push(d)}if(!s.length)return;this.tree.rebuild(e),this.pendingFocusIds=s.slice(),this.render();let n=i.map(l=>this.app.vault.getAbstractFileByPath(l)).filter(l=>!!l&&l.extension==="md").map(l=>({id:he(l.basename)??l.basename,parent:null,children:[],file:l,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 l of[...i].reverse()){let A=this.app.vault.getAbstractFileByPath(l);if(A)try{await this.app.fileManager.trashFile(A)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(l=>this.tree.get(l)).filter(l=>!!l);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})}cmdForkNote(){let t=this.getActionTargets()[0];if(!t?.file){new k.Notice("Nothing to fork.");return}let e=t.parent??F,i=e===F?null:this.tree.get(e),s=i?this.titleForNode(i):"Home";new $t(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",allowCreate:!0,placeholder:`Fork "${this.titleForNode(t)}" under\u2026 (default: ${s})`,onPick:n=>{if(n.crossFolder){new k.Notice("Fork stays in this folder for now.");return}this.forkNoteUnder(t,n.id)},onCreate:n=>{(async()=>{let o=await this.createNoteUnder(n,this.focusId);o&&await this.forkNoteUnder(t,o)})()}}).open()}async forkNoteUnder(t,e){if(!t.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(t,e,s);if(!n)return;let o=s[0]?this.app.vault.getAbstractFileByPath(s[0]):null;if(o)try{await this.app.fileManager.processFrontMatter(o,d=>{d[Ge]=`[[${t.file.basename}]]`})}catch{}this.tree.rebuild(i),this.pendingFocusIds=[n],this.render(),await this.syncForkSiblings(this.forkFamilyFiles({originName:t.file.basename,include:[t.file,o]}));let a=s.map(d=>this.app.vault.getAbstractFileByPath(d)).filter(d=>!!d&&d.extension==="md").map(d=>({id:he(d.basename)??d.basename,parent:null,children:[],file:d,created:new Date().toISOString()})),l=await this.snapshotNotes(a,!1);this.plugin.getUndoStack(i).push({label:"Fork note",undo:async()=>{for(let d of[...s].reverse()){let h=this.app.vault.getAbstractFileByPath(d);if(h)try{await this.app.fileManager.trashFile(h)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(l,[n])}});let A=this.tree.get(n);this.plugin.notifications.show({message:A?`Forked "${this.titleForNode(t)}" \u2192 "${this.titleForNode(A)}" (${s.length} file${s.length===1?"":"s"})`:"Forked note",kind:"success",category:"clone",affectedIds:[n],folder:i})}async ensureSheetGroup(t){let e=Kt(this.app.metadataCache.getFileCache(t)?.frontmatter);if(e)return e;let i=No();return await this.app.fileManager.processFrontMatter(t,s=>{s[Pe]=i,typeof s[qt]!="number"&&(s[qt]=0),s[Ue]=!0}),i}forkFamilyFiles(t){let e=new Map,i=s=>{s&&e.set(s.path,s)};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;t.gid&&Kt(n)===t.gid&&i(s),t.originName&&(s.basename===t.originName||bo(n)===t.originName)&&i(s)}for(let s of t.include??[])i(s);return[...e.values()]}async syncForkSiblings(t){for(let e of t){let i=t.filter(s=>s.path!==e.path).map(s=>`[[${s.basename}]]`);await this.app.fileManager.processFrontMatter(e,s=>{i.length?s[Jt]=i:delete s[Jt]})}}async cmdForkVersion(t,e=!1){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings(),new k.Notice("Sheet versions enabled."));let i=t??this.getActionTargets()[0];if(!i?.file){new k.Notice("Select a note to version.");return}let s=this.noteFolder,n={...this.app.metadataCache.getFileCache(i.file)?.frontmatter??{}},o=await this.ensureSheetGroup(i.file),a=i.parent??this.focusId,l=typeof n[qt]=="number"?n[qt]:0;for(let p of this.tree.getChildren(a)){if(p.id===i.id)continue;let u=ut(this.app,p);if(Kt(u)!==o)continue;let f=u?.[qt];typeof f=="number"&&f>l&&(l=f)}let A=l+1,d=[],h;if(e){let p=tt(),u=yt(Qt("",this.activeStopwords()),p),f=`${s}/${u}`,C=new Date().toISOString();await this.ensureFolder(s),await this.app.vault.create(f,["---",`id: ${p}`,`parent: ${a}`,`created: ${C}`,"attachments: []","---",""].join(` +`));let m=this.app.vault.getAbstractFileByPath(f);if(!m){new k.Notice("Sheets: could not create version.");return}await this.app.fileManager.processFrontMatter(m,B=>{for(let[y,Q]of Object.entries(n))Zt.includes(y)||Wi.includes(y)||(B[y]=Q);B[Pe]=o,B[qt]=A,delete B[ye],delete B[Ue],B[Ge]=`[[${i.file.basename}]]`});try{this.tree.insertSynthetic({id:p,parent:a,children:[],file:m,created:C})}catch{}this.fmSync.scheduleParentChange(p,null,a),d.push(f),h=p}else{let p=await this.cloneSubtree(i,a,d);if(!p||!d.length){new k.Notice("Sheets: could not create version.");return}h=p;let u=this.app.vault.getAbstractFileByPath(d[0]);u&&await this.app.fileManager.processFrontMatter(u,f=>{f[Pe]=o,f[qt]=A,delete f[ye],delete f[Ue],f[Ge]=`[[${i.file.basename}]]`})}this.tree.rebuild(s),this.activeVersionByGroup.set(o,h),this.plugin.saveActiveVersion(s,o,h),this.render();let g=this.app.vault.getAbstractFileByPath(d[0]);await this.syncForkSiblings(this.forkFamilyFiles({gid:o,include:[i.file,g]})),this.plugin.getUndoStack(s).push({label:e?"New version":"Fork version",undo:async()=>{for(let p of[...d].reverse()){let u=this.app.vault.getAbstractFileByPath(p);if(u)try{await this.app.fileManager.trashFile(u)}catch{}}this.activeVersionByGroup.delete(o),this.tree.rebuild(s),this.render()},redo:async()=>{}});let I=d.length;new k.Notice(e?"New version added":`Forked a new version${I>1?` (${I} notes)`:""}`)}async cmdMarkVersionFinal(t){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings());let e=t??this.getActionTargets()[0];if(!e?.file)return;let i=Kt(ut(this.app,e));if(!i){new k.Notice("Not a versioned note.");return}let s=!Ai(ut(this.app,e)),n=e.parent??this.focusId,o=this.tree.getChildren(n).filter(a=>Kt(ut(this.app,a))===i);for(let a of o){if(!a.file)continue;let l=Ai(ut(this.app,a)),A=s&&a.id===e.id;l!==A&&await this.app.fileManager.processFrontMatter(a.file,d=>{A?d[ye]=!0:delete d[ye]})}this.render()}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to copy.");return}await jn(this),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"copy",folder:this.noteFolder,ids:t.map(e=>e.id)},this.render()}isCutPending(t){let e=this.plugin.noteClipboard;return!!e&&e.mode==="cut"&&e.folder===this.noteFolder&&e.ids.includes(t)}isCopyPending(t){let e=this.plugin.noteClipboard;return!!e&&e.mode==="copy"&&e.folder===this.noteFolder&&e.ids.includes(t)}insertIntoComposer(t){let e=this.composerInputEl;if(!e){this.composerDraft=this.composerDraft?`${this.composerDraft} ${t}`:t;return}let i=e.selectionStart??e.value.length,s=e.selectionEnd??e.value.length;e.value=e.value.slice(0,i)+t+e.value.slice(s);let n=i+t.length;try{e.setSelectionRange(n,n)}catch{}this.composerDraft=e.value}focusedInsideCut(t){let e=new Set(t),i=this.focusId,s=0;for(;i&&i!==F&&s++<1e3;){if(e.has(i))return!0;i=this.tree.get(i)?.parent??null}return!1}async cmdCutNotes(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to cut.");return}let e=[];for(let s of t)s.file&&e.push(this.stripFrontmatter(await this.app.vault.cachedRead(s.file)).trim());let i=e.join(` -`);await navigator.clipboard.writeText(i),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"cut",folder:this.noteFolder,ids:t.map(s=>s.id),text:i},this.render(),this.plugin.noteClipboardNotice=this.plugin.notifications.show({message:`Cut ${this.titleList(t)} \u2014 paste in the LIST to move it there as a note; paste in a note's COMPOSER to drop its text in and delete the original (undoable). Esc cancels. Nothing happens until you paste.`,kind:"info",category:"system",affectedIds:t.map(s=>s.id),folder:this.noteFolder,duration:0})}async cmdPasteNotes(){let t=this.plugin.noteClipboard;if(!t){new k.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){let g=(this.currentChildren[this.cursorIdx]??null)?.parent??this.focusId??F,I=t.mode,p=t.folder,u=await this.plugin.crossFolderPaste(p,t.ids,this.noteFolder,g,I);if(!u||!u.rootIds.length)return;I==="cut"&&this.plugin.clearNoteClipboard();let f=this.noteFolder;this.tree.rebuild(f),this.pendingFocusIds=u.rootIds.slice(),this.render(),I==="cut"&&this.plugin.refreshOpenViewsForFolder(p);let C=p.split("/").pop(),m=u.rootIds.length,B=()=>{this.tree.rebuild(f),this.render(),this.plugin.refreshOpenViewsForFolder(p)};this.plugin.getUndoStack(f).push({label:`${I==="cut"?"Move":"Paste"} ${m} note${m===1?"":"s"} from ${C}`,undo:async()=>{await u.undo(),B()},redo:async()=>{await u.redo(),B()}});let y=I==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${y} ${m} note${m===1?"":"s"} (${u.noteCount} total) from "${C}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:I==="cut"?"move":"clone",affectedIds:u.rootIds,folder:f,duration:0});return}let e=t.ids.map(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new k.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??F;if(t.mode==="cut"){let h=new Set(t.ids);for(let I=s;I&&I!==F;I=this.tree.get(I)?.parent??null)if(h.has(I)){new k.Notice("Can't paste cut notes under themselves.");return}let g=i&&!h.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(I=>I.id),s,g,"after");return}let n=this.noteFolder,o=[],a=[];for(let h of e){let g=await this.cloneSubtree(h,s,o);g&&a.push(g)}if(!a.length)return;this.tree.rebuild(n),this.pendingFocusIds=a.slice(),this.render();let l=o.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>!!h&&h.extension==="md").map(h=>({id:de(h.basename)??h.basename,parent:null,children:[],file:h,created:new Date().toISOString()})),A=await this.snapshotNotes(l,!1);this.plugin.getUndoStack(n).push({label:`Paste ${a.length} note${a.length===1?"":"s"}`,undo:async()=>{for(let h of[...o].reverse()){let g=this.app.vault.getAbstractFileByPath(h);if(g)try{await this.app.fileManager.trashFile(g)}catch{}}this.tree.rebuild(n),this.render()},redo:async()=>{await this.restoreSnapshots(A,a)}});let d=a.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:d,suffix:`(${o.length} file${o.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:a,folder:n,duration:0})}async completeCutIntoComposer(){let t=this.plugin.noteClipboard;if(!t||t.mode!=="cut")return;if(t.folder!==this.noteFolder){let g=t.folder,I=t.ids.slice();this.plugin.clearNoteClipboard();let p=await this.plugin.orderedSubtreeNodes(g,I),u=j().prefixTimestampsOnCopy,f=[];for(let{file:Q,created:E,depth:v}of p)try{let w=this.stripFrontmatter(await this.app.vault.cachedRead(Q)).trim().split(/\r?\n/).join(" "),D=u?`${this.formatTimeInline(E)} `:"";f.push(`${" ".repeat(v)}- ${D}${w}`)}catch{}this.insertIntoComposer(f.length?f.join(` -`):t.text??"");let C=await this.plugin.subtreeFilePaths(g,I),m=await this.plugin.snapshotPaths(C),B=await this.plugin.trashSubtrees(g,I);this.plugin.refreshOpenViewsForFolder(g);let y=B.filter(Q=>Q.extension==="md").length;this.plugin.getUndoStack(g).push({label:`Cut ${I.length} note${I.length===1?"":"s"} into composer (from ${g.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(m),this.plugin.refreshOpenViewsForFolder(g)},redo:async()=>{await this.plugin.trashSubtrees(g,I),this.plugin.refreshOpenViewsForFolder(g)}}),this.plugin.notifications.show({message:`Pasted the text of ${I.length} cut note${I.length===1?"":"s"} from "${g.split("/").pop()}" into the composer and removed the original${y===1?"":"s"} (${y} note${y===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:I,folder:g,duration:0});return}this.plugin.clearNoteClipboard();let e=t.ids.map(g=>this.tree.get(g)).filter(g=>!!g&&!!g.file);if(!e.length)return;let i=[],s=new Set,n=(g,I)=>{if(!s.has(g.id)){s.add(g.id),i.push({node:g,depth:I});for(let p of this.tree.getChildren(g.id))n(p,I+1)}};for(let g of e)n(g,0);let o=this.noteFolder,a=j().prefixTimestampsOnCopy,l=[];for(let{node:g,depth:I}of i)if(g.file)try{let p=this.stripFrontmatter(await this.app.vault.cachedRead(g.file)).trim().split(/\r?\n/).join(" "),u=a?`${this.formatTimeInline(g.created)} `:"";l.push(`${" ".repeat(I)}- ${u}${p}`)}catch{}this.insertIntoComposer(l.join(` -`));let A=i.map(g=>g.node),d=await this.snapshotNotes(A,!1);for(let g of[...A].reverse())if(g.file)try{await this.app.fileManager.trashFile(g.file)}catch(I){console.warn("[Stashpad] cut-paste delete failed",g.file.path,I)}this.selection.clear(),this.tree.rebuild(o),this.render();let h=e.map(g=>g.id);this.plugin.getUndoStack(o).push({label:`Cut ${e.length} note${e.length===1?"":"s"} into composer`,undo:async()=>{await this.restoreSnapshots(d,h)},redo:async()=>{for(let g of[...d.notes]){let I=this.app.vault.getAbstractFileByPath(g.path);if(I)try{await this.app.fileManager.trashFile(I)}catch{}}this.tree.rebuild(o),this.render()}}),this.plugin.notifications.show({message:`Pasted the text of ${this.titleList(e)} into the composer and deleted the original${e.length===1?"":"s"} (${A.length} note${A.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:h,folder:o,duration:0})}cmdInsertTemplate(){new Wt(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 k.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(l=>this.app.vault.getAbstractFileByPath(l)).filter(l=>!!l&&l.extension==="md").map(l=>({id:de(l.basename)??l.basename,parent:null,children:[],file:l,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let l of[...s].reverse()){let A=this.app.vault.getAbstractFileByPath(l);if(A)try{await this.app.fileManager.trashFile(A)}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&&this.tagFilter!==Se&&this.tagFilter!==De){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!==F&&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(F)}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 k.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=[F],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 navigator.clipboard.writeText(i),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"cut",folder:this.noteFolder,ids:t.map(s=>s.id),text:i},this.render(),this.plugin.noteClipboardNotice=this.plugin.notifications.show({message:`Cut ${this.titleList(t)} \u2014 paste in the LIST to move it there as a note; paste in a note's COMPOSER to drop its text in and delete the original (undoable). Esc cancels. Nothing happens until you paste.`,kind:"info",category:"system",affectedIds:t.map(s=>s.id),folder:this.noteFolder,duration:0})}async cmdPasteNotes(){let t=this.plugin.noteClipboard;if(!t){new k.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){let g=(this.currentChildren[this.cursorIdx]??null)?.parent??this.focusId??F,I=t.mode,p=t.folder,u=await this.plugin.crossFolderPaste(p,t.ids,this.noteFolder,g,I);if(!u||!u.rootIds.length)return;I==="cut"&&this.plugin.clearNoteClipboard();let f=this.noteFolder;this.tree.rebuild(f),this.pendingFocusIds=u.rootIds.slice(),this.render(),I==="cut"&&this.plugin.refreshOpenViewsForFolder(p);let C=p.split("/").pop(),m=u.rootIds.length,B=()=>{this.tree.rebuild(f),this.render(),this.plugin.refreshOpenViewsForFolder(p)};this.plugin.getUndoStack(f).push({label:`${I==="cut"?"Move":"Paste"} ${m} note${m===1?"":"s"} from ${C}`,undo:async()=>{await u.undo(),B()},redo:async()=>{await u.redo(),B()}});let y=I==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${y} ${m} note${m===1?"":"s"} (${u.noteCount} total) from "${C}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:I==="cut"?"move":"clone",affectedIds:u.rootIds,folder:f,duration:0});return}let e=t.ids.map(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new k.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??F;if(t.mode==="cut"){let h=new Set(t.ids);for(let I=s;I&&I!==F;I=this.tree.get(I)?.parent??null)if(h.has(I)){new k.Notice("Can't paste cut notes under themselves.");return}let g=i&&!h.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(I=>I.id),s,g,"after");return}let n=this.noteFolder,o=[],a=[];for(let h of e){let g=await this.cloneSubtree(h,s,o);g&&a.push(g)}if(!a.length)return;this.tree.rebuild(n),this.pendingFocusIds=a.slice(),this.render();let l=o.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>!!h&&h.extension==="md").map(h=>({id:he(h.basename)??h.basename,parent:null,children:[],file:h,created:new Date().toISOString()})),A=await this.snapshotNotes(l,!1);this.plugin.getUndoStack(n).push({label:`Paste ${a.length} note${a.length===1?"":"s"}`,undo:async()=>{for(let h of[...o].reverse()){let g=this.app.vault.getAbstractFileByPath(h);if(g)try{await this.app.fileManager.trashFile(g)}catch{}}this.tree.rebuild(n),this.render()},redo:async()=>{await this.restoreSnapshots(A,a)}});let d=a.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:d,suffix:`(${o.length} file${o.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:a,folder:n,duration:0})}async completeCutIntoComposer(){let t=this.plugin.noteClipboard;if(!t||t.mode!=="cut")return;if(t.folder!==this.noteFolder){let g=t.folder,I=t.ids.slice();this.plugin.clearNoteClipboard();let p=await this.plugin.orderedSubtreeNodes(g,I),u=Z().prefixTimestampsOnCopy,f=[];for(let{file:Q,created:E,depth:v}of p)try{let w=this.stripFrontmatter(await this.app.vault.cachedRead(Q)).trim().split(/\r?\n/).join(" "),D=u?`${this.formatTimeInline(E)} `:"";f.push(`${" ".repeat(v)}- ${D}${w}`)}catch{}this.insertIntoComposer(f.length?f.join(` +`):t.text??"");let C=await this.plugin.subtreeFilePaths(g,I),m=await this.plugin.snapshotPaths(C),B=await this.plugin.trashSubtrees(g,I);this.plugin.refreshOpenViewsForFolder(g);let y=B.filter(Q=>Q.extension==="md").length;this.plugin.getUndoStack(g).push({label:`Cut ${I.length} note${I.length===1?"":"s"} into composer (from ${g.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(m),this.plugin.refreshOpenViewsForFolder(g)},redo:async()=>{await this.plugin.trashSubtrees(g,I),this.plugin.refreshOpenViewsForFolder(g)}}),this.plugin.notifications.show({message:`Pasted the text of ${I.length} cut note${I.length===1?"":"s"} from "${g.split("/").pop()}" into the composer and removed the original${y===1?"":"s"} (${y} note${y===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:I,folder:g,duration:0});return}this.plugin.clearNoteClipboard();let e=t.ids.map(g=>this.tree.get(g)).filter(g=>!!g&&!!g.file);if(!e.length)return;let i=[],s=new Set,n=(g,I)=>{if(!s.has(g.id)){s.add(g.id),i.push({node:g,depth:I});for(let p of this.tree.getChildren(g.id))n(p,I+1)}};for(let g of e)n(g,0);let o=this.noteFolder,a=Z().prefixTimestampsOnCopy,l=[];for(let{node:g,depth:I}of i)if(g.file)try{let p=this.stripFrontmatter(await this.app.vault.cachedRead(g.file)).trim().split(/\r?\n/).join(" "),u=a?`${this.formatTimeInline(g.created)} `:"";l.push(`${" ".repeat(I)}- ${u}${p}`)}catch{}this.insertIntoComposer(l.join(` +`));let A=i.map(g=>g.node),d=await this.snapshotNotes(A,!1);for(let g of[...A].reverse())if(g.file)try{await this.app.fileManager.trashFile(g.file)}catch(I){console.warn("[Stashpad] cut-paste delete failed",g.file.path,I)}this.selection.clear(),this.tree.rebuild(o),this.render();let h=e.map(g=>g.id);this.plugin.getUndoStack(o).push({label:`Cut ${e.length} note${e.length===1?"":"s"} into composer`,undo:async()=>{await this.restoreSnapshots(d,h)},redo:async()=>{for(let g of[...d.notes]){let I=this.app.vault.getAbstractFileByPath(g.path);if(I)try{await this.app.fileManager.trashFile(I)}catch{}}this.tree.rebuild(o),this.render()}}),this.plugin.notifications.show({message:`Pasted the text of ${this.titleList(e)} into the composer and deleted the original${e.length===1?"":"s"} (${A.length} note${A.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:h,folder:o,duration:0})}cmdInsertTemplate(){new $t(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Insert which note as a template?",allowCreate:!1,onPick:async t=>{if(t.crossFolder){new k.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(l=>this.app.vault.getAbstractFileByPath(l)).filter(l=>!!l&&l.extension==="md").map(l=>({id:he(l.basename)??l.basename,parent:null,children:[],file:l,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let l of[...s].reverse()){let A=this.app.vault.getAbstractFileByPath(l);if(A)try{await this.app.fileManager.trashFile(A)}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&&this.tagFilter!==ke&&this.tagFilter!==Se){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!==F&&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(F)}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 k.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=[F],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!==F)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let A=this.app.vault.getAbstractFileByPath(e);if(A instanceof k.TFile)return A}catch(A){console.warn("[Stashpad] home note rename failed; keeping legacy path",A)}return o}let s=new Date().toISOString(),n=["---",`id: ${F}`,"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===F)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=F}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:F,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:K,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 l=!1;return e.iterateAllLeaves(A=>{A===s&&(l=!0)}),l})())return;e.offref(n),(()=>{let l=!1;return e.iterateAllLeaves(A=>{A===i&&(l=!0)}),l})()&&(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:K,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:K,active:!0,state:{focusId:F,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let d=!1;return s.iterateAllLeaves(h=>{h===o&&(d=!0)}),d})())return;s.offref(a),(()=>{let d=!1;return s.iterateAllLeaves(h=>{h===n&&(d=!0)}),d})()&&(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 k.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 d=!1;return e.iterateAllLeaves(h=>{h===s&&(d=!0)}),d})())return;e.offref(n),(()=>{let d=!1;return e.iterateAllLeaves(h=>{h===i&&(d=!0)}),d})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))}),a=s.view?.editor;a&&requestAnimationFrame(()=>{try{let l=a.lastLine(),A=a.getLine(l)?.length??0;a.setCursor({line:l,ch:A}),a.scrollIntoView({from:{line:l,ch:A},to:{line:l,ch:A}},!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 k.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 k.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new k.Notice(`Unpinned ${s} note${s===1?"":"s"} from sidebar.`)}isListPinned(t){let e=this.tree.get(t);if(!e?.file)return!1;let i=this.listPinnedState.get(e.file.path);return i?i.pinned:this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinned===!0}listPinnedAt(t){let e=this.tree.get(t);if(!e?.file)return 0;let i=this.listPinnedState.get(e.file.path);if(i)return i.at;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinnedAt,n=typeof s=="string"?Date.parse(s):NaN;return Number.isNaN(n)?0:n}hoistListPinned(t,e){let i=this.tree.getChildren(t).map(l=>l.id);if(!i.some(l=>this.isListPinned(l)))return e;let s=new Set(e),n=[...e,...i.filter(l=>!s.has(l))],o=n.filter(l=>this.isListPinned(l)).sort((l,A)=>this.listPinnedAt(l)-this.listPinnedAt(A)),a=n.filter(l=>!this.isListPinned(l));return[...o,...a]}async cmdToggleListPin(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new k.Notice("Nothing to pin.");return}let e=t.some(a=>!this.isListPinned(a.id)),i=[],s=new Date().toISOString(),n=[];for(let a of t){if(!a.file)continue;let l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;i.push({path:a.file.path,listPinned:l?.listPinned,listPinnedAt:l?.listPinnedAt});let A=e?typeof l?.listPinnedAt=="string"&&Date.parse(l.listPinnedAt)||Date.parse(s):0;this.listPinnedState.set(a.file.path,{pinned:e,at:A}),await this.app.fileManager.processFrontMatter(a.file,d=>{e?(d.listPinned=!0,d.listPinnedAt||(d.listPinnedAt=s)):(delete d.listPinned,delete d.listPinnedAt)}),n.push(a.id)}let o=this.noteFolder;this.tree.rebuild(o),this.render(),this.plugin.notifications.show({message:e?`Pinned ${n.length} to top of list`:`Unpinned ${n.length} from list`,kind:"success",category:"edit",affectedIds:n,folder:o}),this.plugin.getUndoStack(o).push({label:e?`Pin to top (${n.length})`:`Unpin from top (${n.length})`,undo:async()=>{for(let a of i){let l=this.app.vault.getAbstractFileByPath(a.path);if(!l)continue;await this.app.fileManager.processFrontMatter(l,h=>{a.listPinned===void 0?delete h.listPinned:h.listPinned=a.listPinned,a.listPinnedAt===void 0?delete h.listPinnedAt:h.listPinnedAt=a.listPinnedAt});let A=a.listPinned===!0,d=typeof a.listPinnedAt=="string"&&Date.parse(a.listPinnedAt)||0;this.listPinnedState.set(a.path,{pinned:A,at:d})}this.tree.rebuild(o),this.render()}})}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 k.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 l=this.isCompleted(a);s.push({id:a.id,path:a.file.path,was:l}),l!==i&&(await this.app.fileManager.processFrontMatter(a.file,A=>{i?A.completed=!0:delete A.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(l=>this.tree.get(l)).filter(l=>!!l);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 l of s){let A=this.app.vault.getAbstractFileByPath(l.path);A&&(await this.app.fileManager.processFrontMatter(A,d=>{l.was?d.completed=!0:delete d.completed}),n.includes(l.id)&&a.push(l.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 l=this.app.vault.getAbstractFileByPath(a.path);l&&await this.app.fileManager.processFrontMatter(l,A=>{i?A.completed=!0:delete A.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?Le(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 k.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.collectKnownAuthors(),o=ke(i??{});new Oe(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 A of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,A.id,A.name);let a=i.map(A=>this.plugin.authorRefFor(this.noteFolder,A.id,A.name));for(let A of t){if(!A.file)continue;let d=this.app.metadataCache.getFileCache(A.file)?.frontmatter,h=this.isTaskTagged(A);s.push({id:A.id,path:A.file.path,due:d?.due,task:d?.task,assignedTo:d?.assignedTo,assignedBy:d?.assignedBy,wasTagged:h}),await this.app.fileManager.processFrontMatter(A.file,I=>{e===null?delete I.due:(I.due=e,I.task=!0),a.length>0?(I.assignedTo=a,o&&(I.assignedBy=o.link),I.task=!0):(delete I.assignedTo,delete I.assignedBy)});let g=e!==null||a.length>0;this.taskTaggedState.set(A.file.path,g||h),n.push(A.id)}if(this.render(),n.length>0){let A=n.map(d=>this.tree.get(d)).filter(d=>!!d);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${jt(Date.parse(e),this.plugin.settings)}`,nodes:A}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let l=this.noteFolder;this.plugin.getUndoStack(l).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let A of s){let d=this.app.vault.getAbstractFileByPath(A.path);d&&(await this.app.fileManager.processFrontMatter(d,h=>{A.due===void 0?delete h.due:h.due=A.due,A.task===void 0?delete h.task:h.task=A.task,A.assignedTo===void 0?delete h.assignedTo:h.assignedTo=A.assignedTo,A.assignedBy===void 0?delete h.assignedBy:h.assignedBy=A.assignedBy}),this.taskTaggedState.set(A.path,A.wasTagged))}this.tree.rebuild(l),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new k.Notice("Nothing to assign.");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.collectKnownAuthors(),o=ke(i??{});new Oe(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o,title:"Assign / schedule task"}).open()}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 k.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 l=this.isTaskTagged(a),A=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:A?.tags,completed:A?.completed,task:A?.task,wasTagged:l}),l===e)continue;let d=!1;await this.app.fileManager.processFrontMatter(a.file,h=>{e?(In(h,"task"),h.completed===void 0&&(h.completed=!1),d=h.completed===!0,delete h.task):(un(h,"task"),delete h.completed,delete h.task,d=!1)}),this.completedState.set(a.file.path,d),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",l;if(s.length===1){let A=this.tree.get(s[0]);l=`"${A&&this.titleForNode(A).trim()||"(untitled)"}" ${a}`}else l=`${s.length} notes ${a}`;this.plugin.notifications.show({message:l,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let a of i){let l=this.app.vault.getAbstractFileByPath(a.path);l&&(await this.app.fileManager.processFrontMatter(l,A=>{a.tags===void 0?delete A.tags:A.tags=a.tags,a.completed===void 0?delete A.completed:A.completed=a.completed,a.task===void 0?delete A.task:A.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 l=this.app.vault.getAbstractFileByPath(a.path);if(!l)continue;let A=!1;await this.app.fileManager.processFrontMatter(l,d=>{e?(In(d,"task"),d.completed===void 0&&(d.completed=!1),A=d.completed===!0,delete d.task):(un(d,"task"),delete d.completed,delete d.task,A=!1)}),this.completedState.set(a.path,A),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!==F&&!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 v of t){let w=this.tree.get(v);w?.file&&(n.push({id:v,path:w.file.path,oldParent:w.parent}),o.add(w.parent??F))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(v=>this.tree.get(v)).filter(v=>!!v)),l=this.noteFolder,A={};for(let v of o)A[v]=this.order.getOrder(l,v).slice();for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.fmSync.scheduleParentChange(v.id,v.oldParent,e),await this.log.append({type:"parent_change",id:v.id,payload:{from:v.oldParent,to:e,reason:"drag"}}),this.order.removeChild(l,v.id))}this.tree.rebuild(l);let d=this.tree.getChildren(e).map(v=>v.id),h=new Set(t),g=d.filter(v=>!h.has(v)),I=g.indexOf(i);I<0&&(I=g.length),s==="after"&&(I+=1);let p=[...g.slice(0,I),...t.filter(v=>!!this.tree.get(v)),...g.slice(I)];this.order.setOrder(l,e,p),await this.order.save(l),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(l),this.render({kind:"follow-cursor"});let m=this.selectionGuardKey,B=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let v=this.currentChildren.findIndex(w=>w.id===f);v<0||(this.selection.add(f),this.cursorIdx=v,this.render({kind:"follow-cursor"}))};setTimeout(B,120),setTimeout(B,400);let y=t.map(v=>this.tree.get(v)).filter(v=>!!v),Q=this.tree.get(e),E=Q?this.titleForNode(Q):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:y,destination:`\u2192 "${E}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:l,actions:e===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(l).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{v.oldParent===null||v.oldParent===void 0?D.parent=F:D.parent=v.oldParent}),await this.log.append({type:"parent_change",id:v.id,payload:{from:e,to:v.oldParent,reason:"drag-undo"}}))}for(let[v,w]of Object.entries(A))if(w.length===0){let D=this.order.cache.get(l)??{};delete D[v],this.order.cache.set(l,D)}else this.order.setOrder(l,v,w);await this.order.save(l),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(l),this.render()},redo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.order.removeChild(l,v.id))}this.order.setOrder(l,e,p),await this.order.save(l),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(l),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??F;if(n.some(m=>(m.parent??F)!==o)){let m=j(),B=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(y=>y.id),o,"","after"):await this.moveAcrossThenReorder(n.map(y=>y.id),o,e,i)};if(m.confirmCrossParentDrag){let y=this.titleForNode(s),Q=n.length,E=i==="into"?"Nest":"Move",v=i==="into"?"as children of":"under";new pt(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${E} ${Q} note${Q===1?"":"s"} ${v} "${y}"? Their parent will change.`,E,w=>{w&&B()}).open()}else await B();return}let l=o,A=n.map(m=>m.id),d=this.tree.getChildren(l).map(m=>m.id),h=new Set(A),g=d.filter(m=>!h.has(m)),I=g.indexOf(e);if(I<0)return;i==="after"&&(I+=1);let p=[...g.slice(0,I),...A,...g.slice(I)];if(fn(p,d))return;let u=this.noteFolder,f=this.order.getOrder(u,l).slice();this.order.setOrder(u,l,p),await this.order.save(u),await this.forceManualMode(l),await this.log.append({type:"reorder",id:l,payload:{dir:"drag",parent:l,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(u),this.render();let C=A.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:A,folder:u}),this.plugin.getUndoStack(u).push({label:`Reorder (drag, ${A.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(u)??{};delete m[l],this.order.cache.set(u,m)}else this.order.setOrder(u,l,f);await this.order.save(u),await this.log.append({type:"reorder",id:l,payload:{dir:"undo",parent:l,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(u),this.render()},redo:async()=>{this.order.setOrder(u,l,p),await this.order.save(u),await this.log.append({type:"reorder",id:l,payload:{dir:"redo:drag",parent:l,ids:A,count:A.length}}),this.pendingFocusIds=A.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 h=[...this.selection].map(I=>this.tree.get(I)).filter(I=>!!I&&!!I.file);if(h.length===0)return;if(new Set(h.map(I=>I.parent)).size>1){new k.Notice("Reorder requires a single-parent selection.");return}e=h}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new k.Notice("Nothing to reorder.");return}let i=e[0].parent??F,s=this.tree.getChildren(i).map(h=>h.id);if(s.length===0)return;let n=new Set(e.map(h=>h.id)),o=s.filter(h=>n.has(h));if(o.length===0)return;let a=Ko(s,o,t);if(fn(a,s))return;let l=this.noteFolder,A=this.order.getOrder(l,i).slice();this.order.setOrder(l,i,a),await this.order.save(l),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(l),this.render({kind:"follow-cursor"});let d=o.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:d,destination:t}),kind:"success",category:"reorder",affectedIds:o,folder:l}),this.plugin.getUndoStack(l).push({label:`Reorder (${t})`,undo:async()=>{if(A.length===0){let h=this.order.cache.get(l)??{};delete h[i],this.order.cache.set(l,h)}else this.order.setOrder(l,i,A);await this.order.save(l),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(l),this.render()},redo:async()=>{this.order.setOrder(l,i,a),await this.order.save(l),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(l),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let p=this.tree.get(this.focusId);p?.file&&(t=[p])}if(t.length===0){new k.Notice("Nothing selected to delete.");return}if((this.plugin.settings.encryptTrash??!1)&&!(this.plugin.settings.encryptTrashFollowObsidian??!1)){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("\u201CEncrypt items sent to trash\u201D is ON but encryption isn't set up (Settings \u2192 Encryption). Nothing was deleted.");return}await this.secureDeleteSources(t);return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],i=new Set,s=p=>{if(!i.has(p.id)){i.add(p.id);for(let u of this.tree.getChildren(p.id))s(u);e.push(p)}};for(let p of t)s(p);let n=e.filter(p=>!!p.file),o=await Promise.all(n.map(p=>this.app.vault.read(p.file))),a=[];for(let p=0;p<n.length;p++){let u=n[p];a.push(...this.extractAttachments(this.stripFrontmatter(o[p])));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(Fe(C))}let l=[...new Set(a)],A=e.length-t.length,d=async p=>{let u=await this.snapshotNotes(e,p),f=0;if(p)for(let H of l){let b=this.app.metadataCache.getFirstLinkpathDest(H,"");if(b)try{await this.app.fileManager.trashFile(b),await this.log.append({type:"attachment_remove",id:F,payload:{path:b.path}}),this.plugin.notifications.show({message:`Deleted attachment "${b.name}"`,kind:"warning",category:"attachment",affectedPaths:[b.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),B=new Set(t.map(H=>H.id)),y=this.currentChildren.map((H,b)=>B.has(H.id)?b:-1).filter(H=>H>=0),Q=y.length>0?y[0]:-1,E=null;if(Q>=0){for(let H=Q+1;H<this.currentChildren.length;H++)if(!B.has(this.currentChildren[H].id)){E=this.currentChildren[H].id;break}if(!E){for(let H=Q-1;H>=0;H--)if(!B.has(this.currentChildren[H].id)){E=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:p?l:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder);for(let H of C)e.some(b=>b.id===H)||this.fmSync.scheduleParentOfDeleted(H);this.render({kind:"follow-cursor"});let v=f>0?` with ${f} attachment${f===1?"":"s"}`:"",w=this.noteFolder,D=t.map(H=>H.id),N=!1,P=async()=>{N||(N=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,D.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:v.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 P()}]}),this.plugin.getUndoStack(w).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await P()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,N=!1,await this.trashNotesAndAttachments(u)}}),this.focusView()},h=j(),g=h.confirmBulkDelete,I=l.length>0&&h.confirmAttachmentDelete;if(!g&&!I){await d(!1);return}new Ke(this.app,`${t.length} selected note${t.length===1?"":"s"}`,A,l.length,I,d).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new k.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 k.Notice("Note is too short to split.");return}let a=s,l=i.path,A=async(h,g,I)=>{if(!h.trim()||!g.trim()){new k.Notice("Split would leave one part empty.");return}try{let p=s.startsWith("---")?s.slice(0,s.indexOf(` +`);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===F)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=F}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:F,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:J,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 l=!1;return e.iterateAllLeaves(A=>{A===s&&(l=!0)}),l})())return;e.offref(n),(()=>{let l=!1;return e.iterateAllLeaves(A=>{A===i&&(l=!0)}),l})()&&(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:J,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:J,active:!0,state:{focusId:F,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let d=!1;return s.iterateAllLeaves(h=>{h===o&&(d=!0)}),d})())return;s.offref(a),(()=>{let d=!1;return s.iterateAllLeaves(h=>{h===n&&(d=!0)}),d})()&&(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 k.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 d=!1;return e.iterateAllLeaves(h=>{h===s&&(d=!0)}),d})())return;e.offref(n),(()=>{let d=!1;return e.iterateAllLeaves(h=>{h===i&&(d=!0)}),d})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))}),a=s.view?.editor;a&&requestAnimationFrame(()=>{try{let l=a.lastLine(),A=a.getLine(l)?.length??0;a.setCursor({line:l,ch:A}),a.scrollIntoView({from:{line:l,ch:A},to:{line:l,ch:A}},!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 k.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 k.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new k.Notice(`Unpinned ${s} note${s===1?"":"s"} from sidebar.`)}isListPinned(t){let e=this.tree.get(t);if(!e?.file)return!1;let i=this.listPinnedState.get(e.file.path);return i?i.pinned:this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinned===!0}listPinnedAt(t){let e=this.tree.get(t);if(!e?.file)return 0;let i=this.listPinnedState.get(e.file.path);if(i)return i.at;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinnedAt,n=typeof s=="string"?Date.parse(s):NaN;return Number.isNaN(n)?0:n}hoistListPinned(t,e){let i=this.tree.getChildren(t).map(l=>l.id);if(!i.some(l=>this.isListPinned(l)))return e;let s=new Set(e),n=[...e,...i.filter(l=>!s.has(l))],o=n.filter(l=>this.isListPinned(l)).sort((l,A)=>this.listPinnedAt(l)-this.listPinnedAt(A)),a=n.filter(l=>!this.isListPinned(l));return[...o,...a]}async cmdToggleListPin(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new k.Notice("Nothing to pin.");return}let e=t.some(a=>!this.isListPinned(a.id)),i=[],s=new Date().toISOString(),n=[];for(let a of t){if(!a.file)continue;let l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;i.push({path:a.file.path,listPinned:l?.listPinned,listPinnedAt:l?.listPinnedAt});let A=e?typeof l?.listPinnedAt=="string"&&Date.parse(l.listPinnedAt)||Date.parse(s):0;this.listPinnedState.set(a.file.path,{pinned:e,at:A}),await this.app.fileManager.processFrontMatter(a.file,d=>{e?(d.listPinned=!0,d.listPinnedAt||(d.listPinnedAt=s)):(delete d.listPinned,delete d.listPinnedAt)}),n.push(a.id)}let o=this.noteFolder;this.tree.rebuild(o),this.render(),this.plugin.notifications.show({message:e?`Pinned ${n.length} to top of list`:`Unpinned ${n.length} from list`,kind:"success",category:"edit",affectedIds:n,folder:o}),this.plugin.getUndoStack(o).push({label:e?`Pin to top (${n.length})`:`Unpin from top (${n.length})`,undo:async()=>{for(let a of i){let l=this.app.vault.getAbstractFileByPath(a.path);if(!l)continue;await this.app.fileManager.processFrontMatter(l,h=>{a.listPinned===void 0?delete h.listPinned:h.listPinned=a.listPinned,a.listPinnedAt===void 0?delete h.listPinnedAt:h.listPinnedAt=a.listPinnedAt});let A=a.listPinned===!0,d=typeof a.listPinnedAt=="string"&&Date.parse(a.listPinnedAt)||0;this.listPinnedState.set(a.path,{pinned:A,at:d})}this.tree.rebuild(o),this.render()}})}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 k.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 l=this.isCompleted(a);s.push({id:a.id,path:a.file.path,was:l}),l!==i&&(await this.app.fileManager.processFrontMatter(a.file,A=>{i?A.completed=!0:delete A.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(l=>this.tree.get(l)).filter(l=>!!l);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 l of s){let A=this.app.vault.getAbstractFileByPath(l.path);A&&(await this.app.fileManager.processFrontMatter(A,d=>{l.was?d.completed=!0:delete d.completed}),n.includes(l.id)&&a.push(l.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 l=this.app.vault.getAbstractFileByPath(a.path);l&&await this.app.fileManager.processFrontMatter(l,A=>{i?A.completed=!0:delete A.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?Le(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 k.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.collectKnownAuthors(),o=Fe(i??{});new Oe(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 A of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,A.id,A.name);let a=i.map(A=>this.plugin.authorRefFor(this.noteFolder,A.id,A.name));for(let A of t){if(!A.file)continue;let d=this.app.metadataCache.getFileCache(A.file)?.frontmatter,h=this.isTaskTagged(A);s.push({id:A.id,path:A.file.path,due:d?.due,task:d?.task,assignedTo:d?.assignedTo,assignedBy:d?.assignedBy,wasTagged:h}),await this.app.fileManager.processFrontMatter(A.file,I=>{e===null?delete I.due:(I.due=e,I.task=!0),a.length>0?(I.assignedTo=a,o&&(I.assignedBy=o.link),I.task=!0):(delete I.assignedTo,delete I.assignedBy)});let g=e!==null||a.length>0;this.taskTaggedState.set(A.file.path,g||h),n.push(A.id)}if(this.render(),n.length>0){let A=n.map(d=>this.tree.get(d)).filter(d=>!!d);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${_t(Date.parse(e),this.plugin.settings)}`,nodes:A}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let l=this.noteFolder;this.plugin.getUndoStack(l).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let A of s){let d=this.app.vault.getAbstractFileByPath(A.path);d&&(await this.app.fileManager.processFrontMatter(d,h=>{A.due===void 0?delete h.due:h.due=A.due,A.task===void 0?delete h.task:h.task=A.task,A.assignedTo===void 0?delete h.assignedTo:h.assignedTo=A.assignedTo,A.assignedBy===void 0?delete h.assignedBy:h.assignedBy=A.assignedBy}),this.taskTaggedState.set(A.path,A.wasTagged))}this.tree.rebuild(l),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new k.Notice("Nothing to assign.");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.collectKnownAuthors(),o=Fe(i??{});new Oe(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o,title:"Assign / schedule task"}).open()}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 k.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 l=this.isTaskTagged(a),A=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:A?.tags,completed:A?.completed,task:A?.task,wasTagged:l}),l===e)continue;let d=!1;await this.app.fileManager.processFrontMatter(a.file,h=>{e?(In(h,"task"),h.completed===void 0&&(h.completed=!1),d=h.completed===!0,delete h.task):(un(h,"task"),delete h.completed,delete h.task,d=!1)}),this.completedState.set(a.file.path,d),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",l;if(s.length===1){let A=this.tree.get(s[0]);l=`"${A&&this.titleForNode(A).trim()||"(untitled)"}" ${a}`}else l=`${s.length} notes ${a}`;this.plugin.notifications.show({message:l,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let a of i){let l=this.app.vault.getAbstractFileByPath(a.path);l&&(await this.app.fileManager.processFrontMatter(l,A=>{a.tags===void 0?delete A.tags:A.tags=a.tags,a.completed===void 0?delete A.completed:A.completed=a.completed,a.task===void 0?delete A.task:A.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 l=this.app.vault.getAbstractFileByPath(a.path);if(!l)continue;let A=!1;await this.app.fileManager.processFrontMatter(l,d=>{e?(In(d,"task"),d.completed===void 0&&(d.completed=!1),A=d.completed===!0,delete d.task):(un(d,"task"),delete d.completed,delete d.task,A=!1)}),this.completedState.set(a.path,A),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!==F&&!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 v of t){let w=this.tree.get(v);w?.file&&(n.push({id:v,path:w.file.path,oldParent:w.parent}),o.add(w.parent??F))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(v=>this.tree.get(v)).filter(v=>!!v)),l=this.noteFolder,A={};for(let v of o)A[v]=this.order.getOrder(l,v).slice();for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.fmSync.scheduleParentChange(v.id,v.oldParent,e),await this.log.append({type:"parent_change",id:v.id,payload:{from:v.oldParent,to:e,reason:"drag"}}),this.order.removeChild(l,v.id))}this.tree.rebuild(l);let d=this.tree.getChildren(e).map(v=>v.id),h=new Set(t),g=d.filter(v=>!h.has(v)),I=g.indexOf(i);I<0&&(I=g.length),s==="after"&&(I+=1);let p=[...g.slice(0,I),...t.filter(v=>!!this.tree.get(v)),...g.slice(I)];this.order.setOrder(l,e,p),await this.order.save(l),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(l),this.render({kind:"follow-cursor"});let m=this.selectionGuardKey,B=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let v=this.currentChildren.findIndex(w=>w.id===f);v<0||(this.selection.add(f),this.cursorIdx=v,this.render({kind:"follow-cursor"}))};setTimeout(B,120),setTimeout(B,400);let y=t.map(v=>this.tree.get(v)).filter(v=>!!v),Q=this.tree.get(e),E=Q?this.titleForNode(Q):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:y,destination:`\u2192 "${E}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:l,actions:e===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(l).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{v.oldParent===null||v.oldParent===void 0?D.parent=F:D.parent=v.oldParent}),await this.log.append({type:"parent_change",id:v.id,payload:{from:e,to:v.oldParent,reason:"drag-undo"}}))}for(let[v,w]of Object.entries(A))if(w.length===0){let D=this.order.cache.get(l)??{};delete D[v],this.order.cache.set(l,D)}else this.order.setOrder(l,v,w);await this.order.save(l),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(l),this.render()},redo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.order.removeChild(l,v.id))}this.order.setOrder(l,e,p),await this.order.save(l),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(l),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??F;if(n.some(m=>(m.parent??F)!==o)){let m=Z(),B=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(y=>y.id),o,"","after"):await this.moveAcrossThenReorder(n.map(y=>y.id),o,e,i)};if(m.confirmCrossParentDrag){let y=this.titleForNode(s),Q=n.length,E=i==="into"?"Nest":"Move",v=i==="into"?"as children of":"under";new ot(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${E} ${Q} note${Q===1?"":"s"} ${v} "${y}"? Their parent will change.`,E,w=>{w&&B()}).open()}else await B();return}let l=o,A=n.map(m=>m.id),d=this.tree.getChildren(l).map(m=>m.id),h=new Set(A),g=d.filter(m=>!h.has(m)),I=g.indexOf(e);if(I<0)return;i==="after"&&(I+=1);let p=[...g.slice(0,I),...A,...g.slice(I)];if(fn(p,d))return;let u=this.noteFolder,f=this.order.getOrder(u,l).slice();this.order.setOrder(u,l,p),await this.order.save(u),await this.forceManualMode(l),await this.log.append({type:"reorder",id:l,payload:{dir:"drag",parent:l,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(u),this.render();let C=A.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:A,folder:u}),this.plugin.getUndoStack(u).push({label:`Reorder (drag, ${A.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(u)??{};delete m[l],this.order.cache.set(u,m)}else this.order.setOrder(u,l,f);await this.order.save(u),await this.log.append({type:"reorder",id:l,payload:{dir:"undo",parent:l,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(u),this.render()},redo:async()=>{this.order.setOrder(u,l,p),await this.order.save(u),await this.log.append({type:"reorder",id:l,payload:{dir:"redo:drag",parent:l,ids:A,count:A.length}}),this.pendingFocusIds=A.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 h=[...this.selection].map(I=>this.tree.get(I)).filter(I=>!!I&&!!I.file);if(h.length===0)return;if(new Set(h.map(I=>I.parent)).size>1){new k.Notice("Reorder requires a single-parent selection.");return}e=h}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new k.Notice("Nothing to reorder.");return}let i=e[0].parent??F,s=this.tree.getChildren(i).map(h=>h.id);if(s.length===0)return;let n=new Set(e.map(h=>h.id)),o=s.filter(h=>n.has(h));if(o.length===0)return;let a=Ko(s,o,t);if(fn(a,s))return;let l=this.noteFolder,A=this.order.getOrder(l,i).slice();this.order.setOrder(l,i,a),await this.order.save(l),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(l),this.render({kind:"follow-cursor"});let d=o.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:d,destination:t}),kind:"success",category:"reorder",affectedIds:o,folder:l}),this.plugin.getUndoStack(l).push({label:`Reorder (${t})`,undo:async()=>{if(A.length===0){let h=this.order.cache.get(l)??{};delete h[i],this.order.cache.set(l,h)}else this.order.setOrder(l,i,A);await this.order.save(l),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(l),this.render()},redo:async()=>{this.order.setOrder(l,i,a),await this.order.save(l),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(l),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let p=this.tree.get(this.focusId);p?.file&&(t=[p])}if(t.length===0){new k.Notice("Nothing selected to delete.");return}if((this.plugin.settings.encryptTrash??!1)&&!(this.plugin.settings.encryptTrashFollowObsidian??!1)){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("\u201CEncrypt items sent to trash\u201D is ON but encryption isn't set up (Settings \u2192 Encryption). Nothing was deleted.");return}await this.secureDeleteSources(t);return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],i=new Set,s=p=>{if(!i.has(p.id)){i.add(p.id);for(let u of this.tree.getChildren(p.id))s(u);e.push(p)}};for(let p of t)s(p);let n=e.filter(p=>!!p.file),o=await Promise.all(n.map(p=>this.app.vault.read(p.file))),a=[];for(let p=0;p<n.length;p++){let u=n[p];a.push(...this.extractAttachments(this.stripFrontmatter(o[p])));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(ve(C))}let l=[...new Set(a)],A=e.length-t.length,d=async p=>{let u=await this.snapshotNotes(e,p),f=0;if(p)for(let H of l){let b=this.app.metadataCache.getFirstLinkpathDest(H,"");if(b)try{await this.app.fileManager.trashFile(b),await this.log.append({type:"attachment_remove",id:F,payload:{path:b.path}}),this.plugin.notifications.show({message:`Deleted attachment "${b.name}"`,kind:"warning",category:"attachment",affectedPaths:[b.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),B=new Set(t.map(H=>H.id)),y=this.currentChildren.map((H,b)=>B.has(H.id)?b:-1).filter(H=>H>=0),Q=y.length>0?y[0]:-1,E=null;if(Q>=0){for(let H=Q+1;H<this.currentChildren.length;H++)if(!B.has(this.currentChildren[H].id)){E=this.currentChildren[H].id;break}if(!E){for(let H=Q-1;H>=0;H--)if(!B.has(this.currentChildren[H].id)){E=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:p?l:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder);for(let H of C)e.some(b=>b.id===H)||this.fmSync.scheduleParentOfDeleted(H);this.render({kind:"follow-cursor"});let v=f>0?` with ${f} attachment${f===1?"":"s"}`:"",w=this.noteFolder,D=t.map(H=>H.id),N=!1,P=async()=>{N||(N=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,D.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:v.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 P()}]}),this.plugin.getUndoStack(w).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await P()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,N=!1,await this.trashNotesAndAttachments(u)}}),this.focusView()},h=Z(),g=h.confirmBulkDelete,I=l.length>0&&h.confirmAttachmentDelete;if(!g&&!I){await d(!1);return}new Ke(this.app,`${t.length} selected note${t.length===1?"":"s"}`,A,l.length,I,d).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new k.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 k.Notice("Note is too short to split.");return}let a=s,l=i.path,A=async(h,g,I)=>{if(!h.trim()||!g.trim()){new k.Notice("Split would leave one part empty.");return}try{let p=s.startsWith("---")?s.slice(0,s.indexOf(` ---`,3)+4):"",u=p+(p?` `:"")+h+` `;await this.app.vault.modify(i,u);let f=e.parent??F,C=Date.parse(e.created||""),m=Number.isFinite(C)?new Date(C+1).toISOString():new Date().toISOString(),B=await this.createNoteUnder(g,f,{record:!1,createdOverride:m});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:B,...I}}),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 y=B?this.tree.get(B):void 0,Q=y?.file?.path,E=Q?await this.app.vault.read(y.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(Q){let D=this.app.vault.getAbstractFileByPath(Q);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}let w=this.app.vault.getAbstractFileByPath(l);w&&await this.app.vault.modify(w,a),this.tree.rebuild(v),this.render()},redo:async()=>{let w=this.app.vault.getAbstractFileByPath(l);w&&await this.app.vault.modify(w,u),Q&&E&&!await this.app.vault.adapter.exists(Q)&&await this.app.vault.create(Q,E),this.tree.rebuild(v),this.render()}})}catch(p){new k.Notice(`Stashpad: split failed (${p.message})`),console.error(p)}},d=async h=>{if(!(h.length<2))try{let g=s.startsWith("---")?s.slice(0,s.indexOf(` @@ -78,64 +84,64 @@ Error: ${e.message}`,kind:"error",category:"system",duration:0,affectedPaths:[t] `:"")+I+` `;await this.app.vault.modify(i,p);let u=e.parent??F,f=Date.parse(e.created||""),C=Number.isFinite(f)?f:Date.now(),m=[];this.beginBulkRender();try{for(let Q=1;Q<h.length;Q++)await this.createNoteUnder(h[Q],u,{record:!1,createdOverride:new Date(C+Q).toISOString(),deferRender:!0,collectInto:m})}finally{try{await this.fmSync.flush()}catch{}this.endBulkRender()}await this.log.append({type:"rename",id:e.id,payload:{action:"split-many",parts:h.length}}),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into ${h.length}`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let B=m.slice(),y=this.noteFolder;this.plugin.getUndoStack(y).push({label:`Split note into ${h.length}`,undo:async()=>{for(let{path:E}of B){let v=this.app.vault.getAbstractFileByPath(E);if(v)try{await this.app.fileManager.trashFile(v)}catch{}}let Q=this.app.vault.getAbstractFileByPath(l);Q&&await this.app.vault.modify(Q,a),this.tree.rebuild(y),this.render()},redo:async()=>{let Q=this.app.vault.getAbstractFileByPath(l);Q&&await this.app.vault.modify(Q,p);for(let{path:E,content:v}of B)await this.app.vault.adapter.exists(E)||await this.app.vault.create(E,v);this.tree.rebuild(y),this.render()}})}catch(g){new k.Notice(`Stashpad: split failed (${g.message})`),console.error(g)}};new fi(this.app,n,async h=>{let g=o.slice(0,h).join(` `).replace(/\s+$/,""),I=o.slice(h).join(` -`).replace(/^\s+|\s+$/g,"");await A(g,I,{mode:"line",splitAtLine:h})},async h=>{let g=n.slice(0,h).replace(/\s+$/,""),I=n.slice(h).replace(/^\s+|\s+$/g,"");await A(g,I,{mode:"cursor",splitAtChar:h})},async h=>{await d(h)}).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 Ir(this,t)}cmdExportOkf(t){return ur(this,t)}cmdImportStash(){return mr(this)}processStashFile(t){return Co(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=tt(),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),B=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},B.includes("{{body}}")?t=B.replace(/\{\{body\}\}/g,t):t.trim()?B.trim()&&(t=`${t} +`).replace(/^\s+|\s+$/g,"");await A(g,I,{mode:"line",splitAtLine:h})},async h=>{let g=n.slice(0,h).replace(/\s+$/,""),I=n.slice(h).replace(/^\s+|\s+$/g,"");await A(g,I,{mode:"cursor",splitAtChar:h})},async h=>{await d(h)}).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 ar(this,t)}cmdExportOkf(t){return rr(this,t)}cmdImportStash(){return cr(this)}processStashFile(t){return go(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=tt(),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),B=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},B.includes("{{body}}")?t=B.replace(/\{\{body\}\}/g,t):t.trim()?B.trim()&&(t=`${t} ${B}`):t=B}catch(m){console.warn("[Stashpad] template read failed",m)}}}let l=Qt(t,this.activeStopwords()),A=yt(l,o),d=`${s}/${A}`,h=e??this.focusId,g=i.createdOverride??new Date().toISOString(),I=this.extractAttachments(t),p=this.authorship.currentAuthorLink();p&&this.authorship.ensureAuthorFile(p);let u=["---",`id: ${o}`,`parent: ${h}`,`created: ${g}`,`modified: ${g}`];if(p&&u.push(`author: "${p.link.replace(/"/g,'\\"')}"`),I.length>0){u.push("attachments:");for(let f of I)u.push(` - "${f.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",t);try{let f=u.join(` `);this.plugin.importService.suppress(d,6e4),await wt.timeAsync("write.createNote.file",()=>this.app.vault.create(d,f)),i.collectInto?.push({path:d,content:f});try{let C=this.app.vault.getAbstractFileByPath(d);if(C&&C.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:h,children:[],file:C,created:g}),i.deferRender||this.render(),this.fmSync.scheduleParentChange(o,null,h);else{i.deferRender||this.render();let m=s.split("/").pop()||s,B=(t.split(` -`).find(y=>y.trim())??"note").trim().slice(0,60);i.deferUndo||this.plugin.notifications.show({message:`"${B}" 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[B,y]of Object.entries(a))Xt.includes(B)||Vi.includes(B)||m[B]===void 0&&(m[B]=y)})}catch(m){console.warn("[Stashpad] template fm overlay failed",m)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:d,parent:h}}),i.record!==!1&&!i.deferUndo){let C=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let m=this.app.vault.getAbstractFileByPath(d);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 B=C.length;this.composerInputEl.setSelectionRange(B,B),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(d)||await this.app.vault.create(d,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 k.Notice(`Stashpad: failed to create note (${f.message})`),null}}async createNotesBatch(t,e,i,s,n){let o=t.length,a=[],l=!!i?.targetFolder&&i.targetFolder!==this.noteFolder,A=8,d=null;if(o>=A){let h=new k.Notice("",0),g=h.messageEl;g.empty(),g.createDiv({cls:"stashpad-split-progress-title",text:`Splitting into ${o} notes\u2026`});let p=g.createDiv({cls:"stashpad-split-progress-bar"}).createDiv({cls:"stashpad-split-progress-fill"}),u=g.createDiv({cls:"stashpad-split-progress-label",text:`0 / ${o}`});d={notice:h,fill:p,label:u}}this.beginBulkRender();try{for(let h=0;h<o;h++)if(await this.createNoteUnder(t[h],e,{...i??{},deferRender:!0,deferUndo:!0,collectInto:a}),d){let g=h+1;d.label.setText(`${g} / ${o}`),d.fill.setCssStyles({width:`${Math.round(g/o*100)}%`}),g%5===0&&await new Promise(I=>window.setTimeout(I,0))}}finally{d?.notice.hide();try{await this.fmSync.flush()}catch{}this.endBulkRender()}if(a.length){let h=a.slice();this.plugin.getUndoStack(n).push({label:`Create ${h.length} notes`,undo:async()=>{for(let{path:g}of h){let I=this.app.vault.getAbstractFileByPath(g);if(I)try{await this.app.fileManager.trashFile(I)}catch{}}if(this.composerDraft=s,this.saveDraft(s),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=s;let g=s.length;this.composerInputEl.setSelectionRange(g,g),this.composerInputEl.focus()}l||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let{path:g,content:I}of h)await this.app.vault.adapter.exists(g)||await this.app.vault.create(g,I);this.composerDraft="",this.saveDraft(""),this.composerInputEl&&(this.composerInputEl.value=""),l||this.tree.rebuild(this.noteFolder),this.render()}})}o>=A&&this.plugin.notifications.show({message:`Created ${a.length} notes${l?` in \`${n.split("/").pop()}\``:""}.`,kind:"success",category:"create"})}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 k.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}/${ns(s,n)}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:F,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 k.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(p=>typeof p=="string"&&p.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",l=i.showAuthor&&!!n,A=i.showContributors&&o.length>0,d=i.showLastEdit&&!!a;if(!l&&!A&&!d)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),g=(p,u)=>{let f=u.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,B=C>=0?f.slice(C+1):f.split("/").pop()??f,y=p.createEl("a",{cls:"internal-link",text:B});y.setAttribute("data-href",m),y.setAttribute("href",m)},I=[];l&&I.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"by "}),g(p,n)}),A&&I.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&p.createSpan({text:", "}),g(p,u)})}),d&&I.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"edited "}),p.createSpan({text:this.formatTimeInline(a)})}),I.forEach((p,u)=>{u>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=h.createSpan({cls:"stashpad-authorship-piece"});p(f)}),h.addEventListener("click",p=>this.handleRenderedClick(p,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Yt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,k.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=de(t.basename);if(!e||e===F)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Qt(s,this.activeStopwords()),o=yt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let l=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:l,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,k.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(d=>typeof d=="string").map(d=>Fe(d));if(a.length===s.length&&a.every((d,h)=>d===s[h]))return;let A=s.map(d=>Ot(d));await this.app.fileManager.processFrontMatter(t,d=>{d.attachments=A})}stripFrontmatter(t){let e=t.replace(/^\uFEFF/,""),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,k.moment)(t);if(!e.isValid())return"";if(j().useTemplatesFormat){let s=Ms(this.app);if(s)return`${e.format(s.dateFormat)} +`).find(y=>y.trim())??"note").trim().slice(0,60);i.deferUndo||this.plugin.notifications.show({message:`"${B}" 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[B,y]of Object.entries(a))Zt.includes(B)||Wi.includes(B)||m[B]===void 0&&(m[B]=y)})}catch(m){console.warn("[Stashpad] template fm overlay failed",m)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:d,parent:h}}),i.record!==!1&&!i.deferUndo){let C=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let m=this.app.vault.getAbstractFileByPath(d);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 B=C.length;this.composerInputEl.setSelectionRange(B,B),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(d)||await this.app.vault.create(d,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 k.Notice(`Stashpad: failed to create note (${f.message})`),null}}async createNotesBatch(t,e,i,s,n){let o=t.length,a=[],l=!!i?.targetFolder&&i.targetFolder!==this.noteFolder,A=8,d=null;if(o>=A){let h=new k.Notice("",0),g=h.messageEl;g.empty(),g.createDiv({cls:"stashpad-split-progress-title",text:`Splitting into ${o} notes\u2026`});let p=g.createDiv({cls:"stashpad-split-progress-bar"}).createDiv({cls:"stashpad-split-progress-fill"}),u=g.createDiv({cls:"stashpad-split-progress-label",text:`0 / ${o}`});d={notice:h,fill:p,label:u}}this.beginBulkRender();try{for(let h=0;h<o;h++)if(await this.createNoteUnder(t[h],e,{...i??{},deferRender:!0,deferUndo:!0,collectInto:a}),d){let g=h+1;d.label.setText(`${g} / ${o}`),d.fill.setCssStyles({width:`${Math.round(g/o*100)}%`}),g%5===0&&await new Promise(I=>window.setTimeout(I,0))}}finally{d?.notice.hide();try{await this.fmSync.flush()}catch{}this.endBulkRender()}if(a.length){let h=a.slice();this.plugin.getUndoStack(n).push({label:`Create ${h.length} notes`,undo:async()=>{for(let{path:g}of h){let I=this.app.vault.getAbstractFileByPath(g);if(I)try{await this.app.fileManager.trashFile(I)}catch{}}if(this.composerDraft=s,this.saveDraft(s),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=s;let g=s.length;this.composerInputEl.setSelectionRange(g,g),this.composerInputEl.focus()}l||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let{path:g,content:I}of h)await this.app.vault.adapter.exists(g)||await this.app.vault.create(g,I);this.composerDraft="",this.saveDraft(""),this.composerInputEl&&(this.composerInputEl.value=""),l||this.tree.rebuild(this.noteFolder),this.render()}})}o>=A&&this.plugin.notifications.show({message:`Created ${a.length} notes${l?` in \`${n.split("/").pop()}\``:""}.`,kind:"success",category:"create"})}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 k.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}/${os(s,n)}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:F,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 k.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(p=>typeof p=="string"&&p.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",l=i.showAuthor&&!!n,A=i.showContributors&&o.length>0,d=i.showLastEdit&&!!a;if(!l&&!A&&!d)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),g=(p,u)=>{let f=u.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,B=C>=0?f.slice(C+1):f.split("/").pop()??f,y=p.createEl("a",{cls:"internal-link",text:B});y.setAttribute("data-href",m),y.setAttribute("href",m)},I=[];l&&I.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"by "}),g(p,n)}),A&&I.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&p.createSpan({text:", "}),g(p,u)})}),d&&I.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"edited "}),p.createSpan({text:this.formatTimeInline(a)})}),I.forEach((p,u)=>{u>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=h.createSpan({cls:"stashpad-authorship-piece"});p(f)}),h.addEventListener("click",p=>this.handleRenderedClick(p,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Yt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,k.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=he(t.basename);if(!e||e===F)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Qt(s,this.activeStopwords()),o=yt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let l=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:l,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,k.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(d=>typeof d=="string").map(d=>ve(d));if(a.length===s.length&&a.every((d,h)=>d===s[h]))return;let A=s.map(d=>Ot(d));await this.app.fileManager.processFrontMatter(t,d=>{d.attachments=A})}stripFrontmatter(t){let e=t.replace(/^\uFEFF/,""),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,k.moment)(t);if(!e.isValid())return"";if(Z().useTemplatesFormat){let s=ws(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,k.moment)(t);if(!e.isValid())return"";if(j().useTemplatesFormat){let s=Ms(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,k.Platform.isMobile){let a=0,l=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(l,120))};window.setTimeout(l,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 k.Menu;s.addItem(d=>d.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(d=>d.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(d=>d.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(d=>d.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(d=>d.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(d=>d.setTitle("Fork into a separate note\u2026").setIcon("git-branch").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdForkNote()})),s.addItem(d=>d.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(d=>d.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()})),this.plugin.settings.okfEnabled&&s.addItem(d=>d.setTitle("Export as OKF\u2026").setIcon("book-marked").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportOkf()})),this.plugin.encryption?.isConfigured?.()&&s.addItem(d=>d.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let h=this.order.getOrder(this.noteFolder,e.parent??F),g=h.indexOf(e.id),I=g>0?h[g-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,I)&&this.render()})),s.addSeparator(),s.addItem(d=>d.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(d=>d.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,F),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==F&&this.navigateTo(F)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(d=>d.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)}));let a=this.isListPinned(e.id);s.addItem(d=>d.setTitle(a?"Unpin from top of list":"Pin to top of list").setIcon(a?"pin-off":"arrow-up-to-line").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleListPin()})),s.addItem(d=>d.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 l=()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id)},A=d=>{let h=this.isTask(e);if(h){let g=this.isCompleted(e);d.addItem(I=>I.setTitle(g?"Mark incomplete":"Mark complete").setIcon(g?"circle":"check-circle").onClick(()=>{l(),this.cmdToggleComplete()}))}else d.addItem(g=>g.setTitle("Turn into task").setIcon("check-square").onClick(()=>{l(),this.cmdToggleTask()}));d.addItem(g=>g.setTitle("Assign / schedule\u2026").setIcon("user-plus").onClick(()=>{l(),this.cmdAssign()})),h&&d.addItem(g=>g.setTitle("Remove from tasks").setIcon("square").onClick(()=>{l(),this.cmdToggleTask()}))};s.addItem(d=>{d.setTitle("Task").setIcon("check-square");let h=typeof d.setSubmenu=="function"?d.setSubmenu():null;h&&typeof h.addItem=="function"?A(h):d.onClick(()=>this.openCommandPalette())}),s.addSeparator(),s.addItem(d=>d.setTitle("Delete").setIcon("trash").onClick(async()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),await this.cmdDelete()})),s.addSeparator(),s.addItem(d=>d.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=p=>{for(let u of this.tree.getChildren(p.id))i(u),e.push(u)};i(t);let s=[...e,t],n=s.filter(p=>!!p.file),o=await Promise.all(n.map(p=>this.app.vault.cachedRead(p.file))),a=[];for(let p=0;p<n.length;p++){let u=n[p];a.push(...this.extractAttachments(this.stripFrontmatter(o[p])));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(Fe(C))}let l=[...new Set(a)],A=this.authorship.collectAuthorIds(s),d=async p=>{let u=await this.snapshotNotes(s,p),f=0;if(p)for(let N of l){let P=this.app.metadataCache.getFirstLinkpathDest(N,"");if(P)try{await this.app.fileManager.trashFile(P),await this.log.append({type:"attachment_remove",id:F,payload:{path:P.path}}),this.plugin.notifications.show({message:`Deleted attachment "${P.name}"`,kind:"warning",category:"attachment",affectedPaths:[P.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let N of s)N.parent&&C.add(N.parent);let m=this.currentChildren.findIndex(N=>N.id===t.id),B=null;if(m>=0){for(let N=m+1;N<this.currentChildren.length;N++)if(this.currentChildren[N].id!==t.id){B=this.currentChildren[N].id;break}if(!B){for(let N=m-1;N>=0;N--)if(this.currentChildren[N].id!==t.id){B=this.currentChildren[N].id;break}}}for(let N of s)if(N.file){try{await this.app.fileManager.trashFile(N.file)}catch{}await this.log.append({type:"delete",id:N.id,payload:{path:N.file.path,attachmentsRemoved:p?l:[]}})}this.selection.clear(),this.cursorIdx=-1,B&&(this.pendingFocusIds=[B]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let N of C)s.some(P=>P.id===N)||this.fmSync.scheduleParentOfDeleted(N);let y=this.noteFolder,Q=`Delete "${this.titleForNode(t)}"`,E=t.id,v=f>0?` with ${f} attachment${f===1?"":"s"}`:"",w=!1,D=async()=>{w||(w=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[E]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${v}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:A,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void D()}]}),this.plugin.getUndoStack(y).push({label:Q,undo:async()=>{await D()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,w=!1,await this.trashNotesAndAttachments(u)}})},h=j(),g=e.length>0&&h.confirmBulkDelete,I=l.length>0&&h.confirmAttachmentDelete;if(!g&&!I){await d(!1),this.focusView();return}new Ke(this.app,this.titleForNode(t),e.length,l.length,I,async p=>{await d(p),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new k.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===F){new k.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new k.Notice("Couldn't find the parent note.");return}let i=e.parent??F,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(l=>l.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new pt(this.app,"Swap notes?",a.join(` -`),"Swap",async l=>{l&&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(l=>l.id!==i.id).length,a=[`"${s}" becomes a child of "${n}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new pt(this.app,"Confirm Note Swap",a.join(` -`),"Swap",async l=>{if(!l)return;let A=t.parent??F;await this.swapParentChild(t,i,A)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new k.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(I=>I.id!==e.id).filter(I=>!!I.file),a=o.map(I=>({id:I.id,path:I.file.path,was:I.parent})),l=this.order.getOrder(s,i).slice(),A=this.order.getOrder(s,e.id).slice(),d=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,I=>{I.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let I of o)await this.app.fileManager.processFrontMatter(I.file,p=>{p.parent=e.id}),this.fmSync.scheduleParentChange(I.id,t.id,e.id);if(l.length>0){let I=l.includes(t.id)?l.map(p=>p===t.id?e.id:p):[...l.filter(p=>p!==e.id),e.id];this.order.setOrder(s,i,I)}let h=o.map(I=>I.id),g=[t.id,...A.filter(I=>I!==t.id&&!h.includes(I)),...h];this.order.setOrder(s,e.id,g),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 I of a)await this.log.append({type:"parent_change",id:I.id,payload:{from:I.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,...h],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let I=this.tree.get(t.id),p=this.tree.get(e.id);I?.file&&await this.app.fileManager.processFrontMatter(I.file,u=>{n==null||n===F?(delete u.parent,u.parent=F):u.parent=n}),p?.file&&await this.app.fileManager.processFrontMatter(p.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=F:C.parent=u.was})}this.order.setOrder(s,i,l),this.order.setOrder(s,e.id,A),this.order.setOrder(s,t.id,d),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=l=>l??F;if(o(n)===o(e)){if(!i.quiet){let l=this.titleForNode(t),A=e===F?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${l}" is already under ${A}.`,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!==F&&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,l=>{l.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 l=this.tree.get(e),A=l?this.titleForNode(l):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${A}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let l=this.noteFolder,A=s.path,d=t.id;this.plugin.getUndoStack(l).push({label:"Move note",undo:async()=>{let h=this.app.vault.getAbstractFileByPath(A);if(h){await this.app.fileManager.processFrontMatter(h,g=>{g.parent=n}),this.pendingFocusIds=[d],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(l),this.render({kind:"follow-cursor"});{let g=this.selectionGuardKey,I=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(u=>u.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(I,120),setTimeout(I,400)}}},redo:async()=>{let h=this.app.vault.getAbstractFileByPath(A);if(h){await this.app.fileManager.processFrontMatter(h,g=>{g.parent=e}),this.pendingFocusIds=[d],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(l),this.render({kind:"follow-cursor"});{let g=this.selectionGuardKey,I=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(u=>u.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(I,120),setTimeout(I,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===F?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=l=>i.get(l.id)??0,a;if(t.length===1){let l=this.titleForNode(t[0]),A=o(t[0]);a=A>0?`Moved "${l}" and its ${A} ${A===1?"child":"children"} \u2192 ${n}`:`Moved "${l}" \u2192 ${n}`}else{let l=t.reduce((A,d)=>A+o(d),0);a=l>0?`Moved ${t.length} notes (${l} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===F?void 0:0,affectedIds:t.map(l=>l.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===F?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};Oi.AIMED_TAP_WINDOW_MS=600;var Vs=Oi,mo=class extends k.SuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onPick=i;this.setPlaceholder("Move to which archive folder?")}getSuggestions(t){let e=t.toLowerCase();return this.folders.filter(i=>i.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.split("/").pop()||t}),e.createEl("small",{text:t,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t)}},Ws=class extends k.SuggestModal{constructor(t,e,i){super(t);this.entries=e;this.onPick=i;this.setPlaceholder("Restore which deleted note?")}getSuggestions(t){let e=t.toLowerCase();return this.entries.filter(i=>`${i.label} ${i.folder}`.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.label}),e.createEl("small",{text:`from ${t.folder}`,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t.blob)}};var re=require("obsidian");rt();var CA=re.moment,Xs=class extends re.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0}getViewType(){return Re}getDisplayText(){return"Encrypted trash"}getIcon(){return"trash-2"}async onOpen(){this.containerEl.addClass("stashpad-trash-view"),this.registerEvent(this.app.vault.on("create",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),await this.render()}scheduleRender(){this.renderPending||(this.renderPending=!0,window.setTimeout(()=>{this.renderPending=!1,this.render()},150))}async render(){let t=++this.renderGen,e=this.contentEl;e.empty(),e.addClass("stashpad-trash-view-body");let i=e.createDiv({cls:"stashpad-trash-view-header"});i.createEl("h3",{text:"Encrypted trash"});let s=i.createEl("button",{cls:"stashpad-trash-iconbtn"});if((0,re.setIcon)(s,"refresh-cw"),s.setAttr("aria-label","Refresh"),s.onclick=()=>void this.render(),!this.plugin.encryption?.isConfigured?.()){e.createDiv({cls:"stashpad-trash-empty",text:"Encryption isn't set up."});return}let n=await this.plugin.listDeletedTrash();if(t!==this.renderGen)return;if(n.length===0){e.createDiv({cls:"stashpad-trash-empty",text:"Nothing in the encrypted trash. Notes you securely delete land here, recoverable with your password."});return}let o=i.createEl("button",{cls:"stashpad-trash-restore",text:"Restore all"});(0,re.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),o.onclick=async()=>{o.disabled=!0,await this.plugin.restoreAllTrash(),await this.render()};let a=new Map;for(let A of n){let d=A.meta?.title?A.meta.originalFolder||"(unknown folder)":" hidden";(a.get(d)??a.set(d,[]).get(d)).push(A)}let l=[...a.keys()].sort((A,d)=>A===" hidden"?1:d===" hidden"?-1:A.localeCompare(d));for(let A of l){let d=A===" hidden",h=e.createDiv({cls:"stashpad-trash-group"}),g=h.createDiv({cls:"stashpad-trash-group-head"});(0,re.setIcon)(g.createSpan({cls:"stashpad-trash-group-icon"}),d?"lock":"folder"),g.createSpan({text:d?"Hidden (title obscured)":A.split("/").pop()||A}),g.createSpan({cls:"stashpad-trash-group-count",text:String(a.get(A).length)});for(let I of a.get(A)){let p=h.createDiv({cls:"stashpad-trash-row"}),u=p.createDiv({cls:"stashpad-trash-row-main"});u.createSpan({cls:"stashpad-trash-title",text:d?"Locked note":I.meta?.title||"Locked note"});let f=I.meta?.deletedAt?`deleted ${CA(I.meta.deletedAt).fromNow()}`:"deleted",C=I.meta&&I.meta.count>1?` \xB7 ${I.meta.count} ${I.meta.kind==="rawtrash"?"files":"notes"}`:"";u.createSpan({cls:"stashpad-trash-sub",text:f+C});let m=p.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,re.setIcon)(m.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),m.onclick=async()=>{m.disabled=!0,await this.plugin.restoreDeletedAt(I.blob)?await this.render():m.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function Br(c){let{workspace:r}=c.app,t=r.getLeavesOfType(Re);if(t.length>0){r.revealLeaf(t[0]);return}let e=r.getLeaf("tab");await e.setViewState({type:Re,active:!0}),r.revealLeaf(e)}rt();var J=require("obsidian");rt();Ft();var Zs=class c extends J.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.folderPinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return we}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,J.setIcon)(n,"list"),n.setAttr("aria-label","Pinned view options"),n.onclick=h=>{h.stopPropagation(),this.openPinnedOptionsMenu(h)},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.setCssStyles({flex:"1 1 0"});let l=a.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"}),A=l.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});A.setAttr("aria-label","Open folder switcher"),A.onmousedown=h=>{h.button===0&&(h.preventDefault(),this.plugin.openFolderPicker())};let d=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-newfolder"});if((0,J.setIcon)(d,"folder-plus"),d.setAttr("aria-label","New Stashpad folder"),d.onmousedown=h=>{h.button===0&&(h.preventDefault(),h.stopPropagation(),this.createNewFolderFlow())},this.plugin.encryption?.isConfigured?.()){let h=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-trash"});(0,J.setIcon)(h,"trash-2"),h.setAttr("aria-label","Open encrypted trash"),h.onmousedown=g=>{g.button===0&&(g.preventDefault(),g.stopPropagation(),this.plugin.openEncryptedTrash())}}this.renderFolders(a.createDiv({cls:"stashpad-folderpanel-list"}))}async createNewFolderFlow(){let e=(await new Qo(this.app).prompt()??"").trim().replace(/^\/+|\/+$/g,"");if(e)try{await this.plugin.createNewStashpad(e),await this.plugin.waitForStashpadFolder(e,2e3),await this.plugin.activateViewForFolder(e),this.scheduleRender(),new J.Notice(`Created Stashpad "${e.split("/").pop()}".`)}catch(i){new J.Notice(`Couldn't create folder: ${i.message}`)}}clampFrac(t){return Number.isFinite(t)?Math.max(.15,Math.min(.85,t)):.5}attachDividerDrag(t,e,i){let s=null,n=a=>{let l=t.getBoundingClientRect();if(l.height<=0)return;let A=this.clampFrac((a.clientY-l.top)/l.height);s=A,e.style.flex=`0 0 ${(A*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 J.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.discoverStashpadFolders().filter(n=>this.folderState(n)==="pinned"),i=this.plugin.listPinnedNotes();if(e.length===0&&i.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"Nothing pinned yet \u2014 pin a note or folder from its right-click menu."});return}if(e.length>0){let n=this.openFolders();for(let o of e)this.renderFolderRow(t,o,n)}if(i.length===0)return;if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let n=new Map;i.forEach((l,A)=>{let d=n.get(l.folder);d||(d=[],n.set(l.folder,d)),d.push({...l,idx:A})});let o=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,a=Array.from(n.keys());o&&n.has(o)&&(a.splice(a.indexOf(o),1),a.unshift(o));for(let l of a){let A=t.createDiv({cls:"stashpad-pinned-group-header"});l===o&&A.addClass("is-active-folder"),A.createSpan({cls:"stashpad-pinned-group-name",text:l.split("/").pop()||l});for(let d of n.get(l)??[])this.renderPinNote(t,d.folder,d.id,d.file,d.idx)}}else i.forEach((n,o)=>this.renderPinNote(t,n.folder,n.id,n.file,o))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((d,h)=>h!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],l=n[o],A;!a&&!l?A=Date.now():a?l?A=(a.pinnedAt+l.pinnedAt)/2:A=a.pinnedAt+1e3:A=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=A})}catch(d){console.warn("[Stashpad] pin reorder failed",d)}this.render()}renderPinNote(t,e,i,s,n){let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,l=o.completed===!0,A=this.childrenOf(e,i),d=A.length>0,h=`${e}|${i}`,g=this.pinExpanded.has(h),I=t.createDiv({cls:"stashpad-pinned-row"});a&&(I.addClass("has-color"),I.style.setProperty("--stashpad-note-color",a)),l&&I.addClass("is-completed"),I.draggable=!0,I.dataset.pinIdx=String(n),I.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),I.addClass("is-dragging")}),I.addEventListener("dragend",()=>I.removeClass("is-dragging")),I.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=I.getBoundingClientRect(),B=C.clientY-m.top<m.height/2;I.toggleClass("drop-before",B),I.toggleClass("drop-after",!B)}),I.addEventListener("dragleave",()=>{I.removeClass("drop-before"),I.removeClass("drop-after")}),I.addEventListener("drop",C=>{C.preventDefault(),I.removeClass("drop-before"),I.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let B=I.getBoundingClientRect(),y=C.clientY-B.top<B.height/2;this.reorderPin(m,y?n:n+1)});let p=I.createSpan({cls:"stashpad-pinned-toggle"});d&&(ce(p,A.length,g),p.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(h)?this.pinExpanded.delete(h):this.pinExpanded.add(h),this.render()});let u=I.createSpan({cls:"stashpad-pinned-icon"});(0,J.setIcon)(u,d?"folder-tree":"file-text"),a&&(u.style.color=a);let f=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},I.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),I.oncontextmenu=C=>{C.preventDefault();let m=new J.Menu;m.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},d&&g){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 l=typeof o.color=="string"?o.color:null,A=o.completed===!0,d=this.childrenOf(e,a),h=d.length>0,g=`${e}|${a}`,I=this.pinExpanded.has(g),p=t.createDiv({cls:"stashpad-pinned-subrow"});A&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let u=p.createSpan({cls:"stashpad-pinned-toggle"});h&&(ce(u,d.length,I),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let f=p.createSpan({cls:"stashpad-pinned-icon"});(0,J.setIcon)(f,"file-text"),l&&(f.style.color=l);let C=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},h&&I&&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===F&&(a==null||a===F)){if(o.id===F)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(){J.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(K)){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=c.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=c.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(c.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!==F||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 A of e)switch(this.folderState(A)){case"pinned":s.push(A);break;case"downranked":o.push(A);break;case"hidden":a.push(A);break;default:n.push(A)}let l=[...s,...n,...o];if(l.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let A of l)this.renderFolderRow(t,A,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(c.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 C=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,J.setIcon)(C,"pin"),C.setAttr("aria-label","Pinned")}let l=this.folderHomePinnedNotes(e),A=c.clean(e),d=this.folderPinExpanded.has(A);if(l.length>0){let C=o.createSpan({cls:"stashpad-folderpanel-pinreveal"});ce(C,l.length,d),C.setAttr("aria-label",d?"Hide pinned notes":`${l.length} pinned note${l.length===1?"":"s"}`),C.addEventListener("mousedown",m=>{m.stopPropagation(),m.preventDefault()}),C.onclick=m=>{m.stopPropagation(),this.folderPinExpanded.has(A)?this.folderPinExpanded.delete(A):this.folderPinExpanded.add(A),this.render()}}let h=this.plugin.isArchiveFolder(e),g=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,J.setIcon)(g,h?"archive":"folder"),h&&g.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let I=this.folderHomeColor(e);I&&(g.style.color=I);let p=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:p});let f=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});if((0,J.setIcon)(f,"plus-square"),f.setAttr("aria-label","Open in new tab"),f.onmousedown=C=>{C.button===0&&(C.preventDefault(),C.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",C=>{C.button===0&&(C.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=C=>{C.preventDefault(),this.openFolderMenu(C,e)},l.length>0&&d){let C=t.createDiv({cls:"stashpad-folderpanel-pinlist"});for(let m of l){let B=C.createDiv({cls:"stashpad-folderpanel-pinrow"}),y=this.app.metadataCache.getFileCache(m)?.frontmatter??{},Q=B.createSpan({cls:"stashpad-folderpanel-pinrow-icon"});(0,J.setIcon)(Q,"arrow-up-to-line"),typeof y.color=="string"&&(Q.style.color=y.color),B.createSpan({cls:"stashpad-folderpanel-pinrow-label",text:this.titleFromFile(m)}),B.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(m)}}}}folderHomePinnedNotes(t){return this.childrenOf(t,F).filter(e=>this.app.metadataCache.getFileCache(e)?.frontmatter?.listPinned===!0)}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,J.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.setCssStyles({display:"none"}),s.onclick=()=>{let a=o.style.display!=="none";o.setCssStyles({display:a?"none":""}),(0,J.setIcon)(n,a?"chevron-right":"chevron-down")};for(let a of e){let l=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),A=a.split("/").pop()||a;l.createSpan({cls:"stashpad-folderpanel-row-label",text:A});let d=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,J.setIcon)(d,"eye"),d.setAttr("aria-label","Unhide"),d.onclick=h=>{h.stopPropagation(),this.setFolderState(a,"normal")}}}jumpToFolder(t){this.plugin.openFolderInStashpad(t)}revealFolder(t){let e=this.app.vault.getAbstractFileByPath(t.replace(/\/+$/,""));if(!(e instanceof J.TFolder)){new J.Notice("Couldn't find that folder.");return}let i=this.app.workspace.getLeavesOfType("file-explorer")[0];if(!i){new J.Notice("File explorer isn't available.");return}this.app.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}openFolderMenu(t,e){let i=new J.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);if(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))),this.plugin.encryption?.isConfigured?.()){i.addSeparator(),i.addItem(a=>a.setTitle("Encrypt (lock) all notes in folder").setIcon("lock").onClick(()=>void this.plugin.lockFolder(e))),this.app.vault.getFiles().some(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")===e.replace(/\/+$/,""))&&i.addItem(a=>a.setTitle("Decrypt (unlock) all notes in folder").setIcon("unlock").onClick(()=>void this.plugin.unlockFolder(e)));let n=e.replace(/\/+$/,""),o=this.plugin.isArchiveFolder(n);i.addItem(a=>a.setTitle(o?"Unmark archive folder":"Mark as archive folder\u2026").setIcon("archive").onClick(async()=>{if(o){this.plugin.settings.archiveFolders=(this.plugin.settings.archiveFolders??[]).filter(l=>l!==n),await this.plugin.saveSettings(),new J.Notice(`"${n.split("/").pop()}" is no longer an archive folder. Existing locked notes stay locked.`,0),this.render();return}new pt(this.app,`Make "${n.split("/").pop()}" an archive folder?`,["An archive folder automatically LOCKS (encrypts) any note you move into it.","","What that means in plain terms:",`\u2022 "Encrypting" scrambles the note with your encryption password so its text can't be read by anyone \u2014 or any app \u2014 without that password.`,"\u2022 The normal, readable copy is permanently removed from your vault. What's left is an unreadable, locked \u{1F512} placeholder.","\u2022 To read or edit the note again, you unlock it with your encryption password (one click on the placeholder). Then you can re-archive it later.","\u2022 If you ever lose your encryption password, the locked notes are gone for good \u2014 there is no backdoor or recovery, on purpose.",'\u2022 Notes ALREADY in this folder are not touched \u2014 only notes moved in from now on. (To lock the ones already here, use "Encrypt all notes in folder".)',"","Good for folders of things you want kept private at rest: finished or sensitive material you'd rather not have readable if someone opened your vault."].join(` -`),"Make it an archive folder",async l=>{l&&(this.plugin.settings.archiveFolders=[...this.plugin.settings.archiveFolders??[],n],await this.plugin.saveSettings(),new J.Notice(`"${n.split("/").pop()}" is now an archive folder \u2014 notes moved in will be encrypted.`,0),this.render())}).open()})),i.addItem(a=>a.setTitle("Open encrypted trash").setIcon("rotate-ccw").onClick(()=>this.plugin.openEncryptedTrash()))}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 J.TFolder)){new J.Notice("Couldn't find that folder.");return}let s=i.name;new Bo(this.app,s,async n=>{let o=n.trim().replace(/[\\/:]+/g,"").trim();if(!o||o===s)return;let l=`${i.parent?.path&&i.parent.path!=="/"?`${i.parent.path}/`:""}${o}`;if(this.app.vault.getAbstractFileByPath(l)){new J.Notice(`"${o}" already exists.`);return}try{await this.app.fileManager.renameFile(i,l),(this.plugin.settings.folder||"").replace(/\/+$/,"")===e&&(this.plugin.settings.folder=l,await this.plugin.saveSettings()),new J.Notice(`Renamed to "${o}".`)}catch(A){console.warn("[Stashpad] folder rename failed",A),new J.Notice("Rename failed (see console).")}}).open()}deleteFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof J.TFolder)){new J.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 pt(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()}},Bo=class extends J.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 js(c){let r=c.workspace.getLeavesOfType(we);if(r.length>0){c.workspace.revealLeaf(r[0]);return}let t=c.workspace.getLeftLeaf(!1);if(!t){new J.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:we,active:!0}),c.workspace.revealLeaf(t)}var Qo=class extends J.Modal{constructor(){super(...arguments);this.value="";this.resolved=!1;this.resolve=null}prompt(){return new Promise(t=>{this.resolve=t,this.open()})}onOpen(){this.titleEl.setText("New Stashpad folder");let{contentEl:t}=this;t.createEl("p",{cls:"setting-item-description",text:"Vault-relative folder path. It's created (with intermediates) and seeded with a Home note, then opened."});let e=t.createEl("input",{type:"text",cls:"stashpad-newfolder-input"});e.placeholder="my-stashpad",e.setCssStyles({width:"100%",marginBottom:"12px"}),e.addEventListener("input",()=>{this.value=e.value}),e.addEventListener("keydown",o=>{o.key==="Enter"?(o.preventDefault(),this.finish(e.value)):o.key==="Escape"&&(o.preventDefault(),this.finish(null))});let i=t.createDiv({cls:"modal-button-container"}),s=i.createEl("button",{text:"Create",cls:"mod-cta"});s.onclick=()=>this.finish(this.value);let n=i.createEl("button",{text:"Cancel"});n.onclick=()=>this.finish(null),window.setTimeout(()=>e.focus(),0)}finish(t){this.resolved||(this.resolved=!0,this.resolve?.(t),this.close())}onClose(){this.contentEl.empty(),this.resolved||(this.resolved=!0,this.resolve?.(null))}};Ft();Ye();rt();var yo="OKF Template.md",mA=`--- +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,k.moment)(t);if(!e.isValid())return"";if(Z().useTemplatesFormat){let s=ws(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,k.Platform.isMobile){let a=0,l=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(l,120))};window.setTimeout(l,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 k.Menu;s.addItem(d=>d.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(d=>d.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(d=>d.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(d=>d.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(d=>d.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(d=>d.setTitle("Fork into a separate note\u2026").setIcon("git-branch").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdForkNote()})),s.addItem(d=>d.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(d=>d.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()})),this.plugin.settings.okfEnabled&&s.addItem(d=>d.setTitle("Export as OKF\u2026").setIcon("book-marked").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportOkf()})),this.plugin.encryption?.isConfigured?.()&&s.addItem(d=>d.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let h=this.order.getOrder(this.noteFolder,e.parent??F),g=h.indexOf(e.id),I=g>0?h[g-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,I)&&this.render()})),s.addSeparator(),s.addItem(d=>d.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(d=>d.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,F),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==F&&this.navigateTo(F)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(d=>d.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)}));let a=this.isListPinned(e.id);s.addItem(d=>d.setTitle(a?"Unpin from top of list":"Pin to top of list").setIcon(a?"pin-off":"arrow-up-to-line").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleListPin()})),s.addItem(d=>d.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 l=()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id)},A=d=>{let h=this.isTask(e);if(h){let g=this.isCompleted(e);d.addItem(I=>I.setTitle(g?"Mark incomplete":"Mark complete").setIcon(g?"circle":"check-circle").onClick(()=>{l(),this.cmdToggleComplete()}))}else d.addItem(g=>g.setTitle("Turn into task").setIcon("check-square").onClick(()=>{l(),this.cmdToggleTask()}));d.addItem(g=>g.setTitle("Assign / schedule\u2026").setIcon("user-plus").onClick(()=>{l(),this.cmdAssign()})),h&&d.addItem(g=>g.setTitle("Remove from tasks").setIcon("square").onClick(()=>{l(),this.cmdToggleTask()}))};s.addItem(d=>{d.setTitle("Task").setIcon("check-square");let h=typeof d.setSubmenu=="function"?d.setSubmenu():null;h&&typeof h.addItem=="function"?A(h):d.onClick(()=>this.openCommandPalette())}),s.addSeparator(),s.addItem(d=>d.setTitle("Delete").setIcon("trash").onClick(async()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),await this.cmdDelete()})),s.addSeparator(),s.addItem(d=>d.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=p=>{for(let u of this.tree.getChildren(p.id))i(u),e.push(u)};i(t);let s=[...e,t],n=s.filter(p=>!!p.file),o=await Promise.all(n.map(p=>this.app.vault.cachedRead(p.file))),a=[];for(let p=0;p<n.length;p++){let u=n[p];a.push(...this.extractAttachments(this.stripFrontmatter(o[p])));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(ve(C))}let l=[...new Set(a)],A=this.authorship.collectAuthorIds(s),d=async p=>{let u=await this.snapshotNotes(s,p),f=0;if(p)for(let N of l){let P=this.app.metadataCache.getFirstLinkpathDest(N,"");if(P)try{await this.app.fileManager.trashFile(P),await this.log.append({type:"attachment_remove",id:F,payload:{path:P.path}}),this.plugin.notifications.show({message:`Deleted attachment "${P.name}"`,kind:"warning",category:"attachment",affectedPaths:[P.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let N of s)N.parent&&C.add(N.parent);let m=this.currentChildren.findIndex(N=>N.id===t.id),B=null;if(m>=0){for(let N=m+1;N<this.currentChildren.length;N++)if(this.currentChildren[N].id!==t.id){B=this.currentChildren[N].id;break}if(!B){for(let N=m-1;N>=0;N--)if(this.currentChildren[N].id!==t.id){B=this.currentChildren[N].id;break}}}for(let N of s)if(N.file){try{await this.app.fileManager.trashFile(N.file)}catch{}await this.log.append({type:"delete",id:N.id,payload:{path:N.file.path,attachmentsRemoved:p?l:[]}})}this.selection.clear(),this.cursorIdx=-1,B&&(this.pendingFocusIds=[B]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let N of C)s.some(P=>P.id===N)||this.fmSync.scheduleParentOfDeleted(N);let y=this.noteFolder,Q=`Delete "${this.titleForNode(t)}"`,E=t.id,v=f>0?` with ${f} attachment${f===1?"":"s"}`:"",w=!1,D=async()=>{w||(w=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[E]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${v}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:A,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void D()}]}),this.plugin.getUndoStack(y).push({label:Q,undo:async()=>{await D()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,w=!1,await this.trashNotesAndAttachments(u)}})},h=Z(),g=e.length>0&&h.confirmBulkDelete,I=l.length>0&&h.confirmAttachmentDelete;if(!g&&!I){await d(!1),this.focusView();return}new Ke(this.app,this.titleForNode(t),e.length,l.length,I,async p=>{await d(p),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new k.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===F){new k.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new k.Notice("Couldn't find the parent note.");return}let i=e.parent??F,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(l=>l.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new ot(this.app,"Swap notes?",a.join(` +`),"Swap",async l=>{l&&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(l=>l.id!==i.id).length,a=[`"${s}" becomes a child of "${n}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new ot(this.app,"Confirm Note Swap",a.join(` +`),"Swap",async l=>{if(!l)return;let A=t.parent??F;await this.swapParentChild(t,i,A)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new k.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(I=>I.id!==e.id).filter(I=>!!I.file),a=o.map(I=>({id:I.id,path:I.file.path,was:I.parent})),l=this.order.getOrder(s,i).slice(),A=this.order.getOrder(s,e.id).slice(),d=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,I=>{I.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let I of o)await this.app.fileManager.processFrontMatter(I.file,p=>{p.parent=e.id}),this.fmSync.scheduleParentChange(I.id,t.id,e.id);if(l.length>0){let I=l.includes(t.id)?l.map(p=>p===t.id?e.id:p):[...l.filter(p=>p!==e.id),e.id];this.order.setOrder(s,i,I)}let h=o.map(I=>I.id),g=[t.id,...A.filter(I=>I!==t.id&&!h.includes(I)),...h];this.order.setOrder(s,e.id,g),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 I of a)await this.log.append({type:"parent_change",id:I.id,payload:{from:I.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,...h],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let I=this.tree.get(t.id),p=this.tree.get(e.id);I?.file&&await this.app.fileManager.processFrontMatter(I.file,u=>{n==null||n===F?(delete u.parent,u.parent=F):u.parent=n}),p?.file&&await this.app.fileManager.processFrontMatter(p.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=F:C.parent=u.was})}this.order.setOrder(s,i,l),this.order.setOrder(s,e.id,A),this.order.setOrder(s,t.id,d),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=l=>l??F;if(o(n)===o(e)){if(!i.quiet){let l=this.titleForNode(t),A=e===F?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${l}" is already under ${A}.`,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!==F&&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,l=>{l.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 l=this.tree.get(e),A=l?this.titleForNode(l):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${A}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let l=this.noteFolder,A=s.path,d=t.id;this.plugin.getUndoStack(l).push({label:"Move note",undo:async()=>{let h=this.app.vault.getAbstractFileByPath(A);if(h){await this.app.fileManager.processFrontMatter(h,g=>{g.parent=n}),this.pendingFocusIds=[d],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(l),this.render({kind:"follow-cursor"});{let g=this.selectionGuardKey,I=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(u=>u.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(I,120),setTimeout(I,400)}}},redo:async()=>{let h=this.app.vault.getAbstractFileByPath(A);if(h){await this.app.fileManager.processFrontMatter(h,g=>{g.parent=e}),this.pendingFocusIds=[d],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(l),this.render({kind:"follow-cursor"});{let g=this.selectionGuardKey,I=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(u=>u.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(I,120),setTimeout(I,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===F?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=l=>i.get(l.id)??0,a;if(t.length===1){let l=this.titleForNode(t[0]),A=o(t[0]);a=A>0?`Moved "${l}" and its ${A} ${A===1?"child":"children"} \u2192 ${n}`:`Moved "${l}" \u2192 ${n}`}else{let l=t.reduce((A,d)=>A+o(d),0);a=l>0?`Moved ${t.length} notes (${l} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===F?void 0:0,affectedIds:t.map(l=>l.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===F?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};Yi.AIMED_TAP_WINDOW_MS=600;var $s=Yi,Io=class extends k.SuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onPick=i;this.setPlaceholder("Move to which archive folder?")}getSuggestions(t){let e=t.toLowerCase();return this.folders.filter(i=>i.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.split("/").pop()||t}),e.createEl("small",{text:t,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t)}},zs=class extends k.SuggestModal{constructor(t,e,i){super(t);this.entries=e;this.onPick=i;this.setPlaceholder("Restore which deleted note?")}getSuggestions(t){let e=t.toLowerCase();return this.entries.filter(i=>`${i.label} ${i.folder}`.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.label}),e.createEl("small",{text:`from ${t.folder}`,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t.blob)}};var Xt=require("obsidian");lt();Ft();var hA=Xt.moment,Vs=class extends Xt.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0;this.selected=new Set;this.order=[];this.anchorIdx=null}getViewType(){return Re}getDisplayText(){return"Encrypted trash"}getIcon(){return"trash-2"}async onOpen(){this.containerEl.addClass("stashpad-trash-view"),this.registerEvent(this.app.vault.on("create",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerDomEvent(document,"keydown",t=>{if(this.app.workspace.activeLeaf!==this.leaf)return;let e=t.target;if(!(e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable))&&(t.metaKey||t.ctrlKey)&&!t.altKey&&(t.key==="a"||t.key==="A")){if(this.order.length===0)return;t.preventDefault(),this.selectAll()}}),await this.render()}scheduleRender(){this.renderPending||(this.renderPending=!0,window.setTimeout(()=>{this.renderPending=!1,this.render()},150))}async render(){let t=++this.renderGen,e=this.contentEl;e.empty(),e.addClass("stashpad-trash-view-body");let i=e.createDiv({cls:"stashpad-trash-view-header"});i.createEl("h3",{text:"Encrypted trash"});let s=i.createEl("button",{cls:"stashpad-trash-iconbtn"});if((0,Xt.setIcon)(s,"refresh-cw"),s.setAttr("aria-label","Refresh"),s.onclick=()=>void this.render(),!this.plugin.encryption?.isConfigured?.()){e.createDiv({cls:"stashpad-trash-empty",text:"Encryption isn't set up."});return}let n=await this.plugin.listDeletedTrash();if(t!==this.renderGen)return;if(n.length===0){e.createDiv({cls:"stashpad-trash-empty",text:"Nothing in the encrypted trash. Notes you securely delete land here, recoverable with your password."});return}let o=i.createEl("button",{cls:"stashpad-trash-restore",text:"Restore all"});(0,Xt.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),o.onclick=async()=>{o.disabled=!0,await this.plugin.restoreAllTrash(),this.clearSelection(),await this.render()};let a=new Set(n.map(d=>d.blob));for(let d of[...this.selected])a.has(d)||this.selected.delete(d);if(this.selected.size>0){let d=e.createDiv({cls:"stashpad-trash-selbar"});d.createSpan({cls:"stashpad-trash-selcount",text:`${this.selected.size} selected`});let h=d.createEl("button",{cls:"stashpad-trash-restore",text:"Restore selected"});h.onclick=async()=>{h.disabled=!0;for(let p of[...this.selected])await this.plugin.restoreDeletedAt(p,{silent:!0});this.clearSelection(),await this.render()};let g=d.createEl("button",{cls:"stashpad-trash-delete mod-warning",text:"Delete selected"});g.onclick=()=>this.confirmPurge([...this.selected]);let I=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Clear"});I.onclick=()=>{this.clearSelection(),this.render()}}let l=new Map;for(let d of n){let h=d.meta?.title?d.meta.originalFolder||"(unknown folder)":" hidden";(l.get(h)??l.set(h,[]).get(h)).push(d)}let A=[...l.keys()].sort((d,h)=>d===" hidden"?1:h===" hidden"?-1:d.localeCompare(h));this.order=[];for(let d of A){let h=d===" hidden",g=e.createDiv({cls:"stashpad-trash-group"}),I=g.createDiv({cls:"stashpad-trash-group-head"});(0,Xt.setIcon)(I.createSpan({cls:"stashpad-trash-group-icon"}),h?"lock":"folder"),I.createSpan({text:h?"Hidden (title obscured)":d.split("/").pop()||d}),I.createSpan({cls:"stashpad-trash-group-count",text:String(l.get(d).length)});for(let p of l.get(d)){let u=this.order.length;this.order.push(p.blob);let f=g.createDiv({cls:"stashpad-trash-row"});this.selected.has(p.blob)&&f.addClass("is-selected"),f.addEventListener("click",E=>{E.target.closest("button")||this.onRowClick(u,p.blob,E)});let C=f.createDiv({cls:"stashpad-trash-row-main"});C.createSpan({cls:"stashpad-trash-title",text:h?"Locked note":p.meta?.title||"Locked note"});let m=p.meta?.deletedAt?`deleted ${hA(p.meta.deletedAt).fromNow()}`:"deleted",B=p.meta&&p.meta.count>1?` \xB7 ${p.meta.count} ${p.meta.kind==="rawtrash"?"files":"notes"}`:"";C.createSpan({cls:"stashpad-trash-sub",text:m+B});let y=f.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,Xt.setIcon)(y.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),y.onclick=async()=>{y.disabled=!0,await this.plugin.restoreDeletedAt(p.blob)?await this.render():y.disabled=!1};let Q=f.createEl("button",{cls:"stashpad-trash-delete",attr:{"aria-label":"Delete permanently"}});(0,Xt.setIcon)(Q,"trash-2"),Q.onclick=()=>this.confirmPurge([p.blob])}}}clearSelection(){this.selected.clear(),this.anchorIdx=null}selectAll(){if(this.order.length!==0){for(let t of this.order)this.selected.add(t);this.anchorIdx=this.order.length-1,this.render()}}onRowClick(t,e,i){if(i.shiftKey&&this.anchorIdx!==null){let[s,n]=this.anchorIdx<t?[this.anchorIdx,t]:[t,this.anchorIdx];this.selected.clear();for(let o=s;o<=n;o++)this.selected.add(this.order[o])}else i.metaKey||i.ctrlKey?(this.selected.has(e)?this.selected.delete(e):this.selected.add(e),this.anchorIdx=t):(this.selected.size===1&&this.selected.has(e)?this.selected.clear():(this.selected.clear(),this.selected.add(e)),this.anchorIdx=t);this.render()}confirmPurge(t){if(t.length===0)return;let e=t.length;new ot(this.app,e===1?"Delete permanently?":`Delete ${e} items permanently?`,`${e===1?"This encrypted item":`These ${e} encrypted items`} will be PERMANENTLY deleted and CANNOT be restored \u2014 there is no decrypted copy. Continue?`,"Delete forever",async i=>{if(i){for(let s of t)await this.plugin.purgeDeletedAt(s);this.clearSelection(),await this.render()}}).open()}async onClose(){this.contentEl.empty()}};async function dr(c){let{workspace:r}=c.app,t=r.getLeavesOfType(Re);if(t.length>0){r.revealLeaf(t[0]);return}let e=r.getLeaf("tab");await e.setViewState({type:Re,active:!0}),r.revealLeaf(e)}lt();var Y=require("obsidian");lt();Ft();var Ws=class c extends Y.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.folderPinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return Ee}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,Y.setIcon)(n,"list"),n.setAttr("aria-label","Pinned view options"),n.onclick=h=>{h.stopPropagation(),this.openPinnedOptionsMenu(h)},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.setCssStyles({flex:"1 1 0"});let l=a.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"}),A=l.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});A.setAttr("aria-label","Open folder switcher"),A.onmousedown=h=>{h.button===0&&(h.preventDefault(),this.plugin.openFolderPicker())};let d=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-newfolder"});if((0,Y.setIcon)(d,"folder-plus"),d.setAttr("aria-label","New Stashpad folder (folder switcher)"),d.onmousedown=h=>{h.button===0&&(h.preventDefault(),h.stopPropagation(),this.plugin.openFolderPicker())},this.plugin.encryption?.isConfigured?.()){let h=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-trash"});(0,Y.setIcon)(h,"trash-2"),h.setAttr("aria-label","Open encrypted trash"),h.onmousedown=g=>{g.button===0&&(g.preventDefault(),g.stopPropagation(),this.plugin.openEncryptedTrash())}}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 l=t.getBoundingClientRect();if(l.height<=0)return;let A=this.clampFrac((a.clientY-l.top)/l.height);s=A,e.style.flex=`0 0 ${(A*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 Y.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.discoverStashpadFolders().filter(n=>this.folderState(n)==="pinned"),i=this.plugin.listPinnedNotes();if(e.length===0&&i.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"Nothing pinned yet \u2014 pin a note or folder from its right-click menu."});return}if(e.length>0){let n=this.openFolders();for(let o of e)this.renderFolderRow(t,o,n)}if(i.length===0)return;if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let n=new Map;i.forEach((l,A)=>{let d=n.get(l.folder);d||(d=[],n.set(l.folder,d)),d.push({...l,idx:A})});let o=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,a=Array.from(n.keys());o&&n.has(o)&&(a.splice(a.indexOf(o),1),a.unshift(o));for(let l of a){let A=t.createDiv({cls:"stashpad-pinned-group-header"});l===o&&A.addClass("is-active-folder"),A.createSpan({cls:"stashpad-pinned-group-name",text:l.split("/").pop()||l});for(let d of n.get(l)??[])this.renderPinNote(t,d.folder,d.id,d.file,d.idx)}}else i.forEach((n,o)=>this.renderPinNote(t,n.folder,n.id,n.file,o))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((d,h)=>h!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],l=n[o],A;!a&&!l?A=Date.now():a?l?A=(a.pinnedAt+l.pinnedAt)/2:A=a.pinnedAt+1e3:A=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=A})}catch(d){console.warn("[Stashpad] pin reorder failed",d)}this.render()}renderPinNote(t,e,i,s,n){let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,l=o.completed===!0,A=this.childrenOf(e,i),d=A.length>0,h=`${e}|${i}`,g=this.pinExpanded.has(h),I=t.createDiv({cls:"stashpad-pinned-row"});a&&(I.addClass("has-color"),I.style.setProperty("--stashpad-note-color",a)),l&&I.addClass("is-completed"),I.draggable=!0,I.dataset.pinIdx=String(n),I.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),I.addClass("is-dragging")}),I.addEventListener("dragend",()=>I.removeClass("is-dragging")),I.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=I.getBoundingClientRect(),B=C.clientY-m.top<m.height/2;I.toggleClass("drop-before",B),I.toggleClass("drop-after",!B)}),I.addEventListener("dragleave",()=>{I.removeClass("drop-before"),I.removeClass("drop-after")}),I.addEventListener("drop",C=>{C.preventDefault(),I.removeClass("drop-before"),I.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let B=I.getBoundingClientRect(),y=C.clientY-B.top<B.height/2;this.reorderPin(m,y?n:n+1)});let p=I.createSpan({cls:"stashpad-pinned-toggle"});d&&(de(p,A.length,g),p.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(h)?this.pinExpanded.delete(h):this.pinExpanded.add(h),this.render()});let u=I.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(u,d?"folder-tree":"file-text"),a&&(u.style.color=a);let f=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},I.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),I.oncontextmenu=C=>{C.preventDefault();let m=new Y.Menu;m.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},d&&g){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 l=typeof o.color=="string"?o.color:null,A=o.completed===!0,d=this.childrenOf(e,a),h=d.length>0,g=`${e}|${a}`,I=this.pinExpanded.has(g),p=t.createDiv({cls:"stashpad-pinned-subrow"});A&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let u=p.createSpan({cls:"stashpad-pinned-toggle"});h&&(de(u,d.length,I),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let f=p.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(f,"file-text"),l&&(f.style.color=l);let C=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},h&&I&&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===F&&(a==null||a===F)){if(o.id===F)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(){Y.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(J)){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=c.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=c.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(c.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!==F||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 A of e)switch(this.folderState(A)){case"pinned":s.push(A);break;case"downranked":o.push(A);break;case"hidden":a.push(A);break;default:n.push(A)}let l=[...s,...n,...o];if(l.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let A of l)this.renderFolderRow(t,A,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(c.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 C=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,Y.setIcon)(C,"pin"),C.setAttr("aria-label","Pinned")}let l=this.folderHomePinnedNotes(e),A=c.clean(e),d=this.folderPinExpanded.has(A);if(l.length>0){let C=o.createSpan({cls:"stashpad-folderpanel-pinreveal"});de(C,l.length,d),C.setAttr("aria-label",d?"Hide pinned notes":`${l.length} pinned note${l.length===1?"":"s"}`),C.addEventListener("mousedown",m=>{m.stopPropagation(),m.preventDefault()}),C.onclick=m=>{m.stopPropagation(),this.folderPinExpanded.has(A)?this.folderPinExpanded.delete(A):this.folderPinExpanded.add(A),this.render()}}let h=this.plugin.isArchiveFolder(e),g=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,Y.setIcon)(g,h?"archive":"folder"),h&&g.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let I=this.folderHomeColor(e);I&&(g.style.color=I);let p=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:p});let f=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});if((0,Y.setIcon)(f,"plus-square"),f.setAttr("aria-label","Open in new tab"),f.onmousedown=C=>{C.button===0&&(C.preventDefault(),C.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",C=>{C.button===0&&(C.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=C=>{C.preventDefault(),this.openFolderMenu(C,e)},l.length>0&&d){let C=t.createDiv({cls:"stashpad-folderpanel-pinlist"});for(let m of l){let B=C.createDiv({cls:"stashpad-folderpanel-pinrow"}),y=this.app.metadataCache.getFileCache(m)?.frontmatter??{},Q=B.createSpan({cls:"stashpad-folderpanel-pinrow-icon"});(0,Y.setIcon)(Q,"arrow-up-to-line"),typeof y.color=="string"&&(Q.style.color=y.color),B.createSpan({cls:"stashpad-folderpanel-pinrow-label",text:this.titleFromFile(m)}),B.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(m)}}}}folderHomePinnedNotes(t){return this.childrenOf(t,F).filter(e=>this.app.metadataCache.getFileCache(e)?.frontmatter?.listPinned===!0)}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,Y.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.setCssStyles({display:"none"}),s.onclick=()=>{let a=o.style.display!=="none";o.setCssStyles({display:a?"none":""}),(0,Y.setIcon)(n,a?"chevron-right":"chevron-down")};for(let a of e){let l=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),A=a.split("/").pop()||a;l.createSpan({cls:"stashpad-folderpanel-row-label",text:A});let d=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,Y.setIcon)(d,"eye"),d.setAttr("aria-label","Unhide"),d.onclick=h=>{h.stopPropagation(),this.setFolderState(a,"normal")}}}jumpToFolder(t){this.plugin.openFolderInStashpad(t)}revealFolder(t){let e=this.app.vault.getAbstractFileByPath(t.replace(/\/+$/,""));if(!(e instanceof Y.TFolder)){new Y.Notice("Couldn't find that folder.");return}let i=this.app.workspace.getLeavesOfType("file-explorer")[0];if(!i){new Y.Notice("File explorer isn't available.");return}this.app.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}openFolderMenu(t,e){let i=new Y.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);if(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))),this.plugin.encryption?.isConfigured?.()){i.addSeparator(),i.addItem(a=>a.setTitle("Encrypt (lock) all notes in folder").setIcon("lock").onClick(()=>void this.plugin.lockFolder(e))),this.app.vault.getFiles().some(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")===e.replace(/\/+$/,""))&&i.addItem(a=>a.setTitle("Decrypt (unlock) all notes in folder").setIcon("unlock").onClick(()=>void this.plugin.unlockFolder(e)));let n=e.replace(/\/+$/,""),o=this.plugin.isArchiveFolder(n);i.addItem(a=>a.setTitle(o?"Unmark archive folder":"Mark as archive folder\u2026").setIcon("archive").onClick(async()=>{if(o){this.plugin.settings.archiveFolders=(this.plugin.settings.archiveFolders??[]).filter(l=>l!==n),await this.plugin.saveSettings(),new Y.Notice(`"${n.split("/").pop()}" is no longer an archive folder. Existing locked notes stay locked.`,0),this.render();return}new ot(this.app,`Make "${n.split("/").pop()}" an archive folder?`,["An archive folder automatically LOCKS (encrypts) any note you move into it.","","What that means in plain terms:",`\u2022 "Encrypting" scrambles the note with your encryption password so its text can't be read by anyone \u2014 or any app \u2014 without that password.`,"\u2022 The normal, readable copy is permanently removed from your vault. What's left is an unreadable, locked \u{1F512} placeholder.","\u2022 To read or edit the note again, you unlock it with your encryption password (one click on the placeholder). Then you can re-archive it later.","\u2022 If you ever lose your encryption password, the locked notes are gone for good \u2014 there is no backdoor or recovery, on purpose.",'\u2022 Notes ALREADY in this folder are not touched \u2014 only notes moved in from now on. (To lock the ones already here, use "Encrypt all notes in folder".)',"","Good for folders of things you want kept private at rest: finished or sensitive material you'd rather not have readable if someone opened your vault."].join(` +`),"Make it an archive folder",async l=>{l&&(this.plugin.settings.archiveFolders=[...this.plugin.settings.archiveFolders??[],n],await this.plugin.saveSettings(),new Y.Notice(`"${n.split("/").pop()}" is now an archive folder \u2014 notes moved in will be encrypted.`,0),this.render())}).open()})),i.addItem(a=>a.setTitle("Open encrypted trash").setIcon("rotate-ccw").onClick(()=>this.plugin.openEncryptedTrash()))}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 Y.TFolder)){new Y.Notice("Couldn't find that folder.");return}let s=i.name;new uo(this.app,s,async n=>{let o=n.trim().replace(/[\\/:]+/g,"").trim();if(!o||o===s)return;let l=`${i.parent?.path&&i.parent.path!=="/"?`${i.parent.path}/`:""}${o}`;if(this.app.vault.getAbstractFileByPath(l)){new Y.Notice(`"${o}" already exists.`);return}try{await this.app.fileManager.renameFile(i,l),(this.plugin.settings.folder||"").replace(/\/+$/,"")===e&&(this.plugin.settings.folder=l,await this.plugin.saveSettings()),new Y.Notice(`Renamed to "${o}".`)}catch(A){console.warn("[Stashpad] folder rename failed",A),new Y.Notice("Rename failed (see console).")}}).open()}deleteFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof Y.TFolder)){new Y.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 ot(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()}},uo=class extends Y.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 Xs(c){let r=c.workspace.getLeavesOfType(Ee);if(r.length>0){c.workspace.revealLeaf(r[0]);return}let t=c.workspace.getLeftLeaf(!1);if(!t){new Y.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:Ee,active:!0}),c.workspace.revealLeaf(t)}qs();var He="stashenc",pA="stashmeta";function le(c){return c.replace(/\.stashenc$/,`.${pA}`)}async function hr(c,r){try{return JSON.parse(await c.vault.adapter.read(le(r)))}catch{return null}}async function Be(c,r,t){let e=r.replace(/\/+$/,""),i=[];for(let A of c.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let d;try{d=ct(await c.vault.read(A)).fm}catch{continue}typeof d.id=="string"&&i.push({id:d.id,file:A,parent:typeof d.parent=="string"?d.parent:null,created:typeof d.created=="string"?d.created:""})}let s=i.find(A=>A.id===t);if(!s)return null;let n=new Map;for(let A of i){if(!A.parent)continue;let d=n.get(A.parent)??[];d.push(A),n.set(A.parent,d)}let o=[],a=new Set([t]),l=[t];for(;l.length;){let A=[];for(let d of l)for(let h of n.get(d)??[])a.has(h.id)||(a.add(h.id),o.push(h),A.push(h.id));l=A}return{rootNote:s,descendants:o,parentId:s.parent}}function fo(c){if(!c)return null;let r=c.replace(/\/+$/,"");return!r||r.startsWith("/")||r.includes("\\")||/^[a-zA-Z]:/.test(r)||r.split("/").some(t=>t===".."||t===".")?null:r}async function Co(c,r,t){await c.vault.adapter.writeBinary(r,t);let e;try{e=new Uint8Array(await c.vault.adapter.readBinary(r))}catch(s){throw new Error(`Couldn't read back the encrypted file to verify it (${s.message}). Nothing was deleted.`)}let i=e.length===t.length;if(i){for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}}if(!i){try{await c.vault.adapter.remove(r)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function Zs(c){return c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||c.basename}function ni(c){return(c.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function pr(c,r,t){let e=new Set(r.map(a=>a.file.path)),i=new Map;for(let a of r)for(let l of await Ks(c,a.file))i.set(l.path,l);let s=new Set,n=c.metadataCache.resolvedLinks??{};for(let a of Object.keys(n))if(!e.has(a))for(let l of Object.keys(n[a]??{}))i.has(l)&&s.add(l);let o=[];for(let a of r){let l=t?.get(a.file.path);if(l!=null)try{let A=await c.vault.adapter.stat(a.file.path);if(A&&A.mtime!==l){console.warn("[Stashpad] note changed since it was bundled \u2014 keeping plaintext",a.file.path),o.push(a.file.path);continue}}catch{}try{await c.vault.delete(a.file)}catch(A){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,A),o.push(a.file.path)}}for(let[a,l]of i)if(!s.has(a))try{await c.vault.delete(l)}catch(A){console.warn("[Stashpad] couldn't delete exclusive attachment",a,A),o.push(a)}return{unpurged:o}}async function gr(c,r,t,e,i=null,s=!1,n){let o=await Be(c,r,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:l,parentId:A}=o,d=[a,...l],h=new Map;for(let Q of d)try{let E=await c.vault.adapter.stat(Q.file.path);E&&h.set(Q.file.path,E.mtime)}catch{}let g=await Ce(c,{rootNotes:[{id:a.id,file:a.file}],allDescendants:l.map(Q=>({id:Q.id,file:Q.file})),sourceFolder:r}),I=await xi(g,e),p=await pe(I,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size mismatch).");for(let Q=0;Q<g.length;Q++)if(p[Q]!==g[Q])throw new Error("Encryption self-check failed (content mismatch).");let u=(n??r).replace(/\/+$/,"");n&&!await c.vault.adapter.exists(u)&&await c.vault.adapter.mkdir(u);let f=ni(s?t:Zs(a.file)),C=`${u}/${f}.${He}`;for(let Q=1;await c.vault.adapter.exists(C);Q++)C=`${u}/${f} (${Q}).${He}`;await Co(c,C,I);let m=d,B={v:1,parentId:A,title:s?"":Zs(a.file),count:m.length,created:a.created,rootId:t,prevSibling:i};try{await c.vault.adapter.write(le(C),JSON.stringify(B))}catch(Q){console.warn("[Stashpad] couldn't write lock sidecar",Q)}let{unpurged:y}=await pr(c,m,h);return{blobPath:C,noteCount:m.length,rootId:t,parentId:A,title:B.title,created:a.created,unpurged:y}}async function Ir(c,r,t,e,i){let s=new Uint8Array(await c.vault.adapter.readBinary(r));if(!Gt(s))throw new Error("Not an encrypted bundle.");let n=await pe(s,t),o=fo(i)??r.replace(/\/[^/]*$/,""),a=await Wt(c,n,o,e,{dedupeExisting:!0});await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(le(r))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var xt="_deleted";function gA(c){let r="";for(let t=0;t<c.length;t++)r+=String.fromCharCode(c[t]);return btoa(r)}function IA(c){let r=atob(c),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function mo(c,r,t,e){let i=fo(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=fo(new TextDecoder().decode(await pe(IA(t.originalFolderEnc),e)))}catch{i=null}if(i)return await c.vault.adapter.exists(i)||await c.vault.adapter.mkdir(i),i;let s=r.replace(/\/[^/]*$/,"");if(s===xt||s.startsWith(`${xt}/`))throw new Error("This deleted note's origin folder is unknown (missing or tampered sidecar) \u2014 can't restore it safely. The encrypted copy was kept.");return s}async function ur(c,r,t,e,i,s=!1){let n=await Be(c,r,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:a,parentId:l}=n,A=[o,...a],d=new Map;for(let Q of A)try{let E=await c.vault.adapter.stat(Q.file.path);E&&d.set(Q.file.path,E.mtime)}catch{}let h=await Ce(c,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(Q=>({id:Q.id,file:Q.file})),sourceFolder:r}),g=await xi(h,e),I=await pe(g,e);if(I.length!==h.length)throw new Error("Encryption self-check failed (size).");for(let Q=0;Q<h.length;Q++)if(I[Q]!==h[Q])throw new Error("Encryption self-check failed (content).");await c.vault.adapter.exists(xt)||await c.vault.adapter.mkdir(xt);let p=r.replace(/\/+$/,""),u=p.split("/").pop()||"vault",f=ni(s?t:`${u} ${Zs(o.file)}`),C=`${xt}/${f}.${He}`;for(let Q=1;await c.vault.adapter.exists(C);Q++)C=`${xt}/${f} (${Q}).${He}`;await Co(c,C,g);let m=A,B={v:1,kind:"deleted",originalFolder:s?"":p,...s?{originalFolderEnc:gA(await xi(new TextEncoder().encode(p),e))}:{},parentId:l,title:s?"":Zs(o.file),count:m.length,created:o.created,rootId:t,deletedAt:i};try{await c.vault.adapter.write(le(C),JSON.stringify(B))}catch(Q){console.warn("[Stashpad] couldn't write deleted sidecar",Q)}let{unpurged:y}=await pr(c,m,d);return{blobPath:C,noteCount:m.length,rootId:t,originalFolder:p,title:B.title,unpurged:y}}async function fr(c,r,t,e){let i=new Uint8Array(await c.vault.adapter.readBinary(r));if(!Gt(i))throw new Error("Not an encrypted bundle.");let s=await js(c,r),n=await mo(c,r,s,t),o=await pe(i,t),a=await Wt(c,o,n,e,{dedupeExisting:!0});await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(le(r))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function js(c,r){try{return JSON.parse(await c.vault.adapter.read(le(r)))}catch{return null}}async function Bo(c,r){await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(le(r))}catch{}}var Mt=".trash";async function uA(c,r){let t=[],e=[r];for(;e.length;){let i=e.shift(),s;try{s=await c.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function fA(c){let r=c.split("/").filter(Boolean);if(r.length===0)return null;for(let t of r)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return r.join("/")}async function Cr(c,r,t,e=!1){if(!await c.vault.adapter.exists(Mt))return null;let i=await uA(c,Mt);if(i.length===0)return null;let s=[],n=new Map;for(let I of i){let p=I.slice(Mt.length+1);s.push({name:`files/${p}`,data:await c.vault.adapter.readBinary(I)});try{let u=await c.vault.adapter.stat(I);u&&n.set(I,u.mtime)}catch{}}let o=await Ki(s),a=await xi(o,r),l=await pe(a,r);if(l.length!==o.length)throw new Error("Encryption self-check failed (size).");for(let I=0;I<o.length;I++)if(l[I]!==o[I])throw new Error("Encryption self-check failed (content).");await c.vault.adapter.exists(xt)||await c.vault.adapter.mkdir(xt);let A=ni(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),d=`${xt}/${A}.${He}`;for(let I=1;await c.vault.adapter.exists(d);I++)d=`${xt}/${A} (${I}).${He}`;await Co(c,d,a);let h={v:1,kind:"rawtrash",originalFolder:Mt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await c.vault.adapter.write(le(d),JSON.stringify(h))}catch(I){console.warn("[Stashpad] couldn't write backfill sidecar",I)}let g=[];for(let I of i){let p=n.get(I);try{if(p!=null){let u=await c.vault.adapter.stat(I);if(u&&u.mtime!==p){g.push(I);continue}}await c.vault.adapter.remove(I)}catch(u){console.warn("[Stashpad] couldn't delete trash file",I,u),g.push(I)}}return{blobPath:d,fileCount:i.length,unpurged:g}}async function mr(c,r,t){let e=new Uint8Array(await c.vault.adapter.readBinary(r));if(!Gt(e))throw new Error("Not an encrypted bundle.");let i=await pe(e,t),s=await Oi(i),n=0;for(let[o,a]of Object.entries(s)){if(!o.startsWith("files/"))continue;let l=fA(o.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",o);continue}let A=`${Mt}/${l}`.split("/").slice(0,-1).join("/"),d="";for(let g of A.split("/"))d=d?`${d}/${g}`:g,await c.vault.adapter.exists(d)||await c.vault.adapter.mkdir(d);let h=`${Mt}/${l}`;for(let g=1;await c.vault.adapter.exists(h);g++)h=`${Mt}/${l.replace(/(\.[^./]*)?$/,` (${g})$1`)}`;await c.vault.adapter.writeBinary(h,a.buffer),n++}await c.vault.adapter.remove(r);try{await c.vault.adapter.remove(le(r))}catch{}return{filesWritten:n}}async function Qo(c){if(!await c.vault.adapter.exists(xt))return[];try{return(await c.vault.adapter.list(xt)).files.filter(t=>t.endsWith(`.${He}`))}catch{return[]}}Ft();Ye();lt();var yo="OKF Template.md",CA=`--- okfType: concept --- {{body}} `,Eo=["> Generated by Stashpad \u2014 this folder is an Open Knowledge Format (OKF) bundle.","> Field legend: `okfType`\u2192`type`, `okfTitle`\u2192`title`, `okfDescription`\u2192`description`, `okfTags`\u2192`tags`, `okfTimestamp`\u2192`timestamp`; `okfParent`/`okfChildren` are relative-markdown cross-links. Stashpad's own `id`/`parent` are extensions \u2014 ignore them for OKF."].join(` -`);function Yi(c){return c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||c.basename}function Qr(c){return`[${Yi(c)}](${encodeURI(c.name)})`}async function yr(c,r=yo){try{await c.vault.adapter.exists(r)||await c.vault.create(r,mA)}catch{}return r}function Er(c,r){if(!r)return[];let t=r.replace(/^\/+/,"");return Object.entries(c??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function wo(c,r){let t=r.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of c.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let a;try{a=At(await c.vault.read(o)).fm}catch{continue}let l=typeof a.id=="string"?a.id:null;if(!l)continue;let A=typeof a.parent=="string"?a.parent:F;e.set(l,{file:o,id:l,parent:A,modified:typeof a.modified=="string"?a.modified:"",created:typeof a.created=="string"?a.created:""});let d=i.get(A)??[];d.push(l),i.set(A,d)}let s=0,n=0;for(let o of e.values()){if(o.id===F)continue;s+=1;let a=o.parent&&o.parent!==F&&e.get(o.parent)?Qr(e.get(o.parent).file):null,l=(i.get(o.id)??[]).map(A=>e.get(A)).filter(A=>!!A).map(A=>Qr(A.file));try{let A=!1;await c.fileManager.processFrontMatter(o.file,d=>{a?d.okfParent!==a&&(d.okfParent=a,A=!0):d.okfParent!==void 0&&(delete d.okfParent,A=!0);let h=Array.isArray(d.okfChildren)?d.okfChildren:[],g=h.length===l.length&&h.every((I,p)=>I===l[p]);if(l.length?g||(d.okfChildren=l,A=!0):d.okfChildren!==void 0&&(delete d.okfChildren,A=!0),d.okfType===void 0&&(d.okfType="concept",A=!0),d.okfTitle===void 0&&(d.okfTitle=Yi(o.file),A=!0),d.okfTimestamp===void 0){let I=o.modified||o.created;I&&(d.okfTimestamp=I,A=!0)}}),A&&(n+=1,await new Promise(d=>setTimeout(d,50)))}catch(A){console.warn("[Stashpad] OKF rebuild failed",o.file.path,A)}}try{await c.vault.adapter.write(`${t}/index.md`,await vo(c,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function vo(c,r,t){let e=r.replace(/\/+$/,""),i=new Map,s=new Map;for(let d of c.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e||d.name==="index.md")continue;let h;try{h=At(await c.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===F||t&&!t.has(g)||i.set(g,{id:g,file:d,parent:typeof h.parent=="string"?h.parent:F,title:typeof h.okfTitle=="string"&&h.okfTitle?h.okfTitle:Yi(d),type:typeof h.okfType=="string"&&h.okfType?h.okfType:"concept",position:typeof h.position=="number"?h.position:Number.MAX_SAFE_INTEGER,created:typeof h.created=="string"?h.created:""})}for(let d of i.values()){let h=s.get(d.parent)??[];h.push(d),s.set(d.parent,h)}for(let d of s.values())d.sort((h,g)=>h.position-g.position||h.created.localeCompare(g.created));let n=[],o=(d,h,g)=>{if(!g.has(d.id)){g.add(d.id),n.push(`${" ".repeat(h)}- [${d.title}](${encodeURI(d.file.name)}) \u2014 ${d.type}`);for(let I of s.get(d.id)??[])o(I,h+1,g)}},a=new Set,l=[...i.values()].filter(d=>d.parent===F||!i.has(d.parent)).sort((d,h)=>d.position-h.position||d.created.localeCompare(h.created));for(let d of l)o(d,0,a);let A=e.split("/").pop()||e;return["---","type: index",`title: ${A} (OKF index)`,"---","",`# ${A}`,"",Eo,"","## Concepts",n.length?n.join(` +`);function $i(c){return c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||c.basename}function Br(c){return`[${$i(c)}](${encodeURI(c.name)})`}async function Qr(c,r=yo){try{await c.vault.adapter.exists(r)||await c.vault.create(r,CA)}catch{}return r}function yr(c,r){if(!r)return[];let t=r.replace(/^\/+/,"");return Object.entries(c??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function wo(c,r){let t=r.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of c.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let a;try{a=ct(await c.vault.read(o)).fm}catch{continue}let l=typeof a.id=="string"?a.id:null;if(!l)continue;let A=typeof a.parent=="string"?a.parent:F;e.set(l,{file:o,id:l,parent:A,modified:typeof a.modified=="string"?a.modified:"",created:typeof a.created=="string"?a.created:""});let d=i.get(A)??[];d.push(l),i.set(A,d)}let s=0,n=0;for(let o of e.values()){if(o.id===F)continue;s+=1;let a=o.parent&&o.parent!==F&&e.get(o.parent)?Br(e.get(o.parent).file):null,l=(i.get(o.id)??[]).map(A=>e.get(A)).filter(A=>!!A).map(A=>Br(A.file));try{let A=!1;await c.fileManager.processFrontMatter(o.file,d=>{a?d.okfParent!==a&&(d.okfParent=a,A=!0):d.okfParent!==void 0&&(delete d.okfParent,A=!0);let h=Array.isArray(d.okfChildren)?d.okfChildren:[],g=h.length===l.length&&h.every((I,p)=>I===l[p]);if(l.length?g||(d.okfChildren=l,A=!0):d.okfChildren!==void 0&&(delete d.okfChildren,A=!0),d.okfType===void 0&&(d.okfType="concept",A=!0),d.okfTitle===void 0&&(d.okfTitle=$i(o.file),A=!0),d.okfTimestamp===void 0){let I=o.modified||o.created;I&&(d.okfTimestamp=I,A=!0)}}),A&&(n+=1,await new Promise(d=>setTimeout(d,50)))}catch(A){console.warn("[Stashpad] OKF rebuild failed",o.file.path,A)}}try{await c.vault.adapter.write(`${t}/index.md`,await vo(c,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function vo(c,r,t){let e=r.replace(/\/+$/,""),i=new Map,s=new Map;for(let d of c.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e||d.name==="index.md")continue;let h;try{h=ct(await c.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===F||t&&!t.has(g)||i.set(g,{id:g,file:d,parent:typeof h.parent=="string"?h.parent:F,title:typeof h.okfTitle=="string"&&h.okfTitle?h.okfTitle:$i(d),type:typeof h.okfType=="string"&&h.okfType?h.okfType:"concept",position:typeof h.position=="number"?h.position:Number.MAX_SAFE_INTEGER,created:typeof h.created=="string"?h.created:""})}for(let d of i.values()){let h=s.get(d.parent)??[];h.push(d),s.set(d.parent,h)}for(let d of s.values())d.sort((h,g)=>h.position-g.position||h.created.localeCompare(g.created));let n=[],o=(d,h,g)=>{if(!g.has(d.id)){g.add(d.id),n.push(`${" ".repeat(h)}- [${d.title}](${encodeURI(d.file.name)}) \u2014 ${d.type}`);for(let I of s.get(d.id)??[])o(I,h+1,g)}},a=new Set,l=[...i.values()].filter(d=>d.parent===F||!i.has(d.parent)).sort((d,h)=>d.position-h.position||d.created.localeCompare(h.created));for(let d of l)o(d,0,a);let A=e.split("/").pop()||e;return["---","type: index",`title: ${A} (OKF index)`,"---","",`# ${A}`,"",Eo,"","## Concepts",n.length?n.join(` `):"_No concepts yet._",""].join(` -`)}var BA=new TextEncoder,_s=c=>BA.encode(c);function zi(c){if(typeof c=="number"||typeof c=="boolean")return String(c);let r=String(c??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(r)?JSON.stringify(r):r}function QA(c,r){let{fm:t}=At(c),e=[];e.push(`type: ${zi(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${zi(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:Yi(r))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${zi(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let a of i)e.push(` - ${zi(a)}`)}let s=typeof t.okfTimestamp=="string"&&t.okfTimestamp||typeof t.modified=="string"&&t.modified||typeof t.created=="string"&&t.created||"";s&&e.push(`timestamp: ${zi(s)}`);let n=e.join(` +`)}var mA=new TextEncoder,_s=c=>mA.encode(c);function zi(c){if(typeof c=="number"||typeof c=="boolean")return String(c);let r=String(c??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(r)?JSON.stringify(r):r}function BA(c,r){let{fm:t}=ct(c),e=[];e.push(`type: ${zi(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${zi(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:$i(r))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${zi(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let a of i)e.push(` - ${zi(a)}`)}let s=typeof t.okfTimestamp=="string"&&t.okfTimestamp||typeof t.modified=="string"&&t.modified||typeof t.created=="string"&&t.created||"";s&&e.push(`timestamp: ${zi(s)}`);let n=e.join(` `),o=c.match(/^---\r?\n/);return o?c.slice(0,o[0].length)+n+` `+c.slice(o[0].length):`--- ${n} --- -${c}`}async function wr(c,r,t,e){let i=[],s=new Map;for(let n of r){let o=await c.vault.read(n);i.push({name:n.name,data:_s(QA(o,n))});for(let a of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let l=a.slice(3,-2).split("|")[0].split("#")[0].trim(),A=c.metadataCache.getFirstLinkpathDest(l,n.path);A&&!s.has(A.name)&&s.set(A.name,A)}}for(let[n,o]of s)i.push({name:`_attachments/${n}`,data:new Uint8Array(await c.vault.readBinary(o))});return i.push({name:"index.md",data:_s(await vo(c,t,e))}),i.push({name:"_okf.md",data:_s(`# About this bundle +${c}`}async function Er(c,r,t,e){let i=[],s=new Map;for(let n of r){let o=await c.vault.read(n);i.push({name:n.name,data:_s(BA(o,n))});for(let a of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let l=a.slice(3,-2).split("|")[0].split("#")[0].trim(),A=c.metadataCache.getFirstLinkpathDest(l,n.path);A&&!s.has(A.name)&&s.set(A.name,A)}}for(let[n,o]of s)i.push({name:`_attachments/${n}`,data:new Uint8Array(await c.vault.readBinary(o))});return i.push({name:"index.md",data:_s(await vo(c,t,e))}),i.push({name:"_okf.md",data:_s(`# About this bundle ${Eo.replace(/^> /gm,"")} -`)}),i}async function vr(c){let{zipFiles:r}=await Promise.resolve().then(()=>(ws(),Ra));return r(c.map(t=>({name:t.name,data:t.data})))}function oi(c,r){return c.toString(8).padStart(r-1,"0")+"\0"}function yA(c,r){let t=new Uint8Array(512),e=(s,n,o)=>{let a=_s(s);t.set(a.subarray(0,o),n)};e(c.slice(0,100),0,100),e(oi(420,8),100,8),e(oi(0,8),108,8),e(oi(0,8),116,8),e(oi(r,12),124,12),e(oi(0,12),136,12),e(" ",148,8),t[156]=48,e("ustar\0",257,6),e("00",263,2);let i=0;for(let s=0;s<512;s++)i+=t[s];return e(oi(i,8),148,8),t}function EA(c){let r=[],t=0;for(let s of c){let n=yA(s.name,s.data.length);r.push(n,s.data),t+=512+s.data.length;let o=(512-s.data.length%512)%512;o&&(r.push(new Uint8Array(o)),t+=o)}r.push(new Uint8Array(1024)),t+=1024;let e=new Uint8Array(t),i=0;for(let s of r)e.set(s,i),i+=s.length;return e}async function wA(c){let r=new CompressionStream("gzip"),t=new Response(c).body.pipeThrough(r);return new Uint8Array(await new Response(t).arrayBuffer())}async function Fr(c){return wA(EA(c))}var tn=class{constructor(r,t,e){this.app=r;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 r=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let i of t)e=e?`${e}/${i}`:i,await r.exists(e)||await r.mkdir(e);this.dirOk=!0}append(r){let t=r.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...r};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 r=this.app.vault.adapter;if(!await r.exists(this.statePath))return{};try{return JSON.parse(await r.read(this.statePath))}catch{return{}}}async writeState(r){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(r,null,2))}};rt();var en=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(r){for(this.undoStack.push(r),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let r=this.undoStack.pop();if(!r)return null;try{await r.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(r),r}async redo(){let r=this.redoStack.pop();if(!r)return null;if(r.redo)try{await r.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(r),r}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 sn=class{constructor(r,t){this.app=r;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 r=this.app.vault.adapter;if(await r.exists(this.path)){let t=JSON.parse(await r.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(r){console.warn("[Stashpad] author registry load failed; starting empty",r),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((r,t)=>(t.lastSeen??"").localeCompare(r.lastSeen??""))}get(r){return this.data.authors[r]??null}record(r){let t=(r.id??"").trim();if(!t)return!1;let e=r.at??new Date().toISOString(),i=(r.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:r.role?.trim()||void 0,department:r.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),r.role!==void 0){let o=r.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(r.department!==void 0){let o=r.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(r,t){let e=t??new Date().toISOString(),i={};for(let s of r){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",l=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&l.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:l}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let r=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 r.exists(i)||await r.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(r){console.warn("[Stashpad] author registry save failed",r)}}),this.writeChain}};var et=require("obsidian");rt();Tt();Ye();_i();Ft();var nn=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),kr="_archive",Sr=new Set([oe,"edtz","stashenc","stashmeta"]),ai=class ai{constructor(r){this.plugin=r;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(r){this.armed=r}isArmed(){return this.armed}get app(){return this.plugin.app}enqueue(r){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(r)&&(this.pending.set(r.path,Date.now()),this.arm())}enqueueFolder(r){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(r.path))return;let t=r.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(nn.has(r.name)||(this.pendingFolders.set(r.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),ai.DEBOUNCE_MS)}suppress(r,t=4e3){this.suppressed.add(r),window.setTimeout(()=>this.suppressed.delete(r),t)}async createNote(r,t){this.suppress(r,6e4),await this.app.vault.create(r,t)}isEligiblePath(r){if(this.suppressed.has(r.path)||Sr.has(r.extension))return!1;let t=r.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return nn.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(r){if(!this.isEligiblePath(r))return!1;if(r.extension==="md")try{let{fm:t}=At(await this.app.vault.read(r));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 r=[...this.pending.keys()];this.pending.clear();let t=r.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>h instanceof et.TFile),e=[];for(let h of t)await this.isStillImportable(h)&&e.push(h);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>h instanceof et.TFolder).map(h=>({folder:h,files:this.filesUnder(h.path)})).filter(h=>h.files.length>0),n=s.reduce((h,g)=>h+g.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,l=[],A=e.filter(h=>this.plugin.importLog.findDuplicate(h.name,h.stat?.size??null));if(A.length>0){let h=A.slice(0,5).map(p=>`\u2022 ${p.name}`).join(` +`)}),i}async function wr(c){let{zipFiles:r}=await Promise.resolve().then(()=>(qs(),tr));return r(c.map(t=>({name:t.name,data:t.data})))}function oi(c,r){return c.toString(8).padStart(r-1,"0")+"\0"}function QA(c,r){let t=new Uint8Array(512),e=(s,n,o)=>{let a=_s(s);t.set(a.subarray(0,o),n)};e(c.slice(0,100),0,100),e(oi(420,8),100,8),e(oi(0,8),108,8),e(oi(0,8),116,8),e(oi(r,12),124,12),e(oi(0,12),136,12),e(" ",148,8),t[156]=48,e("ustar\0",257,6),e("00",263,2);let i=0;for(let s=0;s<512;s++)i+=t[s];return e(oi(i,8),148,8),t}function yA(c){let r=[],t=0;for(let s of c){let n=QA(s.name,s.data.length);r.push(n,s.data),t+=512+s.data.length;let o=(512-s.data.length%512)%512;o&&(r.push(new Uint8Array(o)),t+=o)}r.push(new Uint8Array(1024)),t+=1024;let e=new Uint8Array(t),i=0;for(let s of r)e.set(s,i),i+=s.length;return e}async function EA(c){let r=new CompressionStream("gzip"),t=new Response(c).body.pipeThrough(r);return new Uint8Array(await new Response(t).arrayBuffer())}async function vr(c){return EA(yA(c))}var tn=class{constructor(r,t,e){this.app=r;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 r=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let i of t)e=e?`${e}/${i}`:i,await r.exists(e)||await r.mkdir(e);this.dirOk=!0}append(r){let t=r.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...r};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 r=this.app.vault.adapter;if(!await r.exists(this.statePath))return{};try{return JSON.parse(await r.read(this.statePath))}catch{return{}}}async writeState(r){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(r,null,2))}};lt();var en=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(r){for(this.undoStack.push(r),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let r=this.undoStack.pop();if(!r)return null;try{await r.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(r),r}async redo(){let r=this.redoStack.pop();if(!r)return null;if(r.redo)try{await r.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(r),r}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 sn=class{constructor(r,t){this.app=r;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 r=this.app.vault.adapter;if(await r.exists(this.path)){let t=JSON.parse(await r.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(r){console.warn("[Stashpad] author registry load failed; starting empty",r),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((r,t)=>(t.lastSeen??"").localeCompare(r.lastSeen??""))}get(r){return this.data.authors[r]??null}record(r){let t=(r.id??"").trim();if(!t)return!1;let e=r.at??new Date().toISOString(),i=(r.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:r.role?.trim()||void 0,department:r.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),r.role!==void 0){let o=r.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(r.department!==void 0){let o=r.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(r,t){let e=t??new Date().toISOString(),i={};for(let s of r){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",l=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&l.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:l}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let r=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 r.exists(i)||await r.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(r){console.warn("[Stashpad] author registry save failed",r)}}),this.writeChain}};var et=require("obsidian");lt();Ht();Ye();ts();Ft();var nn=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),Fr="_archive",kr=new Set([re,"edtz","stashenc","stashmeta"]),ai=class ai{constructor(r){this.plugin=r;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(r){this.armed=r}isArmed(){return this.armed}get app(){return this.plugin.app}enqueue(r){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(r)&&(this.pending.set(r.path,Date.now()),this.arm())}enqueueFolder(r){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(r.path))return;let t=r.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(nn.has(r.name)||(this.pendingFolders.set(r.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),ai.DEBOUNCE_MS)}suppress(r,t=4e3){this.suppressed.add(r),window.setTimeout(()=>this.suppressed.delete(r),t)}async createNote(r,t){this.suppress(r,6e4),await this.app.vault.create(r,t)}isEligiblePath(r){if(this.suppressed.has(r.path)||kr.has(r.extension))return!1;let t=r.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return nn.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(r){if(!this.isEligiblePath(r))return!1;if(r.extension==="md")try{let{fm:t}=ct(await this.app.vault.read(r));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 r=[...this.pending.keys()];this.pending.clear();let t=r.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>h instanceof et.TFile),e=[];for(let h of t)await this.isStillImportable(h)&&e.push(h);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>h instanceof et.TFolder).map(h=>({folder:h,files:this.filesUnder(h.path)})).filter(h=>h.files.length>0),n=s.reduce((h,g)=>h+g.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,l=[],A=e.filter(h=>this.plugin.importLog.findDuplicate(h.name,h.stat?.size??null));if(A.length>0){let h=A.slice(0,5).map(p=>`\u2022 ${p.name}`).join(` `),g=A.length>5?` \u2026and ${A.length-5} more`:"",I=await this.dupChoice(`${A.length} of these look like files you've imported before: ${h}${g} Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(I==="skip"){let p=new Set(A.map(u=>u.path));if(a=e.filter(u=>!p.has(u.path)),a.length===0&&s.length===0){new et.Notice(`Skipped ${A.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(I==="replace")for(let p of A){let u=this.plugin.importLog.findDuplicate(p.name,p.stat?.size??null);for(let f of u?.notePaths??[]){let C=this.app.vault.getAbstractFileByPath(f);if(C instanceof et.TFile)try{l.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>=ai.BATCH_CONFIRM_AT){let h=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${h}. Proceed? -Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new et.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let d=[];for(let h of a)try{let g=h.stat?.size??null,I=h.extension==="md"?await this.importMarkdown(h):await this.importOtherFile(h);I&&(d.push(I),this.plugin.importLog.append({ts:new Date().toISOString(),folder:I.folder,kind:I.kind,originalName:h.name,size:g,sourcePath:h.path,notePaths:I.kind==="folder"?I.notePaths:[I.notePath]}))}catch(g){console.warn("[Stashpad] import failed",h.path,g)}for(let{folder:h}of s)try{let g=await this.importFolder(h);g&&g.kind==="folder"&&(d.push(g),this.plugin.importLog.append({ts:new Date().toISOString(),folder:g.folder,kind:"folder",originalName:g.originalName,size:null,sourcePath:h.path,notePaths:g.notePaths}))}catch(g){console.warn("[Stashpad] folder import failed",h.path,g)}(d.length>0||l.length>0)&&this.announce(d,l)}finally{this.draining=!1}}}async importMarkdown(r){let t=r.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(r),{fm:i,body:s}=At(e),n=`${t}/${kr}`;await this.ensureFolder(n);let o=await this.uniquePath(n,r.name);if(await this.app.fileManager.renameFile(r,o),!(this.app.vault.getAbstractFileByPath(o)instanceof et.TFile))throw new Error(`archive move failed for ${r.path} \u2014 import aborted to avoid data loss`);let a={};for(let[h,g]of Object.entries(i))Xt.includes(h)||(a[h]=g);a.id=tt(),a.parent=F;let l=this.preservedTimes(i,r);a.created=l.created,l.modified&&(a.modified=l.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 A=Qt(s)||r.basename,d=await this.uniquePath(t,yt(A,a.id));return await this.createNote(d,Ie(a,s)),{kind:"md",folder:t,archivePath:o,notePath:d,originalName:r.name}}async importOtherFile(r){let t=r.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,r.name);await this.app.fileManager.renameFile(r,i);let s=r.basename,n=tt(),o={id:n,parent:F,created:new Date().toISOString(),attachments:[Ot(i)],imported:!0},a=`${s} +Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new et.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let d=[];for(let h of a)try{let g=h.stat?.size??null,I=h.extension==="md"?await this.importMarkdown(h):await this.importOtherFile(h);I&&(d.push(I),this.plugin.importLog.append({ts:new Date().toISOString(),folder:I.folder,kind:I.kind,originalName:h.name,size:g,sourcePath:h.path,notePaths:I.kind==="folder"?I.notePaths:[I.notePath]}))}catch(g){console.warn("[Stashpad] import failed",h.path,g)}for(let{folder:h}of s)try{let g=await this.importFolder(h);g&&g.kind==="folder"&&(d.push(g),this.plugin.importLog.append({ts:new Date().toISOString(),folder:g.folder,kind:"folder",originalName:g.originalName,size:null,sourcePath:h.path,notePaths:g.notePaths}))}catch(g){console.warn("[Stashpad] folder import failed",h.path,g)}(d.length>0||l.length>0)&&this.announce(d,l)}finally{this.draining=!1}}}async importMarkdown(r){let t=r.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(r),{fm:i,body:s}=ct(e),n=`${t}/${Fr}`;await this.ensureFolder(n);let o=await this.uniquePath(n,r.name);if(await this.app.fileManager.renameFile(r,o),!(this.app.vault.getAbstractFileByPath(o)instanceof et.TFile))throw new Error(`archive move failed for ${r.path} \u2014 import aborted to avoid data loss`);let a={};for(let[h,g]of Object.entries(i))Zt.includes(h)||(a[h]=g);a.id=tt(),a.parent=F;let l=this.preservedTimes(i,r);a.created=l.created,l.modified&&(a.modified=l.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 A=Qt(s)||r.basename,d=await this.uniquePath(t,yt(A,a.id));return await this.createNote(d,me(a,s)),{kind:"md",folder:t,archivePath:o,notePath:d,originalName:r.name}}async importOtherFile(r){let t=r.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,r.name);await this.app.fileManager.renameFile(r,i);let s=r.basename,n=tt(),o={id:n,parent:F,created:new Date().toISOString(),attachments:[Ot(i)],imported:!0},a=`${s} ![[${i}]] -`,l=Qt(s)||s,A=await this.uniquePath(t,yt(l,n));return await this.createNote(A,Ie(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:A,originalName:r.name}}preservedTimes(r,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(r.created)?r.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(r.modified)?r.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(r){let t=r.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(r){let t=r.parent.path.replace(/\/+$/,""),e=r.name,i=`${t}/${kr}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(r,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let d of this.app.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let h=this.app.metadataCache.getFileCache(d)?.frontmatter?.id;typeof h=="string"&&h&&o.add(h)}let a=[],l=[],A=await this.createFolderNote(t,e,F,l,o);return n instanceof et.TFolder&&await this.buildNotesFromArchive(n,t,A,l,o,a),a.length&&new et.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:l,attachmentPaths:[],originalName:e}}async createFolderNote(r,t,e,i,s){let n=tt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Qt(t)||t,l=await this.uniquePath(r,yt(a,n));return await this.createNote(l,Ie(o,`${t} -`)),i.push(l),n}async mergeReservedFolder(r,t,e){await this.ensureFolder(t);for(let i of[...r.children])if(i instanceof et.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof et.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(r,t,e,i,s,n){for(let o of[...r.children])if(o instanceof et.TFolder)if(nn.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 et.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:l,body:A}=At(a),d={};for(let[f,C]of Object.entries(l))Xt.includes(f)||(d[f]=C);let h=typeof l.id=="string"&&l.id?l.id:null,g=h&&!s.has(h)?h:tt();s.add(g),d.id=g,d.parent=e;let I=this.preservedTimes(l,o);d.created=I.created,I.modified&&(d.modified=I.modified),d.attachments=Array.isArray(l.attachments)?l.attachments:[];let p=Qt(A)||o.basename,u=await this.uniquePath(t,yt(p,d.id));await this.createNote(u,Ie(d,A)),i.push(u)}else{if(Sr.has(o.extension))continue;{let a=tt(),l={id:a,parent:e,created:new Date().toISOString(),attachments:[Ot(o.path)]},A=`${o.basename} +`,l=Qt(s)||s,A=await this.uniquePath(t,yt(l,n));return await this.createNote(A,me(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:A,originalName:r.name}}preservedTimes(r,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(r.created)?r.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(r.modified)?r.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(r){let t=r.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(r){let t=r.parent.path.replace(/\/+$/,""),e=r.name,i=`${t}/${Fr}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(r,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let d of this.app.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let h=this.app.metadataCache.getFileCache(d)?.frontmatter?.id;typeof h=="string"&&h&&o.add(h)}let a=[],l=[],A=await this.createFolderNote(t,e,F,l,o);return n instanceof et.TFolder&&await this.buildNotesFromArchive(n,t,A,l,o,a),a.length&&new et.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:l,attachmentPaths:[],originalName:e}}async createFolderNote(r,t,e,i,s){let n=tt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Qt(t)||t,l=await this.uniquePath(r,yt(a,n));return await this.createNote(l,me(o,`${t} +`)),i.push(l),n}async mergeReservedFolder(r,t,e){await this.ensureFolder(t);for(let i of[...r.children])if(i instanceof et.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof et.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(r,t,e,i,s,n){for(let o of[...r.children])if(o instanceof et.TFolder)if(nn.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 et.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:l,body:A}=ct(a),d={};for(let[f,C]of Object.entries(l))Zt.includes(f)||(d[f]=C);let h=typeof l.id=="string"&&l.id?l.id:null,g=h&&!s.has(h)?h:tt();s.add(g),d.id=g,d.parent=e;let I=this.preservedTimes(l,o);d.created=I.created,I.modified&&(d.modified=I.modified),d.attachments=Array.isArray(l.attachments)?l.attachments:[];let p=Qt(A)||o.basename,u=await this.uniquePath(t,yt(p,d.id));await this.createNote(u,me(d,A)),i.push(u)}else{if(kr.has(o.extension))continue;{let a=tt(),l={id:a,parent:e,created:new Date().toISOString(),attachments:[Ot(o.path)]},A=`${o.basename} ![[${o.path}]] -`,d=Qt(o.basename)||o.basename,h=await this.uniquePath(t,yt(d,a));await this.createNote(h,Ie(l,A)),i.push(h)}}}recordNotePaths(r){return r.kind==="folder"?r.notePaths:[r.notePath]}announce(r,t=[]){let e=r[0]?.folder??"",i=r.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(r,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:r.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(r,t=[]){for(let e of r)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof et.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof et.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 et.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof et.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 et.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof et.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof et.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 et.Notice(`Undid import of ${r.length} file(s).`)}pickFilesInto(r){let t=document.createElement("input");t.type="file",t.multiple=!0,t.setCssStyles({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(r,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let l=this.app.vault.getAbstractFileByPath(a);l instanceof et.TFile&&i.push(l)}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(r){let t=r.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(r){let t=r.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof et.TFolder))return 0;let i=e.children.filter(n=>n instanceof et.TFolder&&!nn.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 r of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(r)instanceof et.TFile||this.pendingEncryptedStashes.delete(r);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(r){this.pendingEncryptedStashes.delete(r)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(r){this.encryptedNotifySnoozeUntil=r===1/0?Number.MAX_SAFE_INTEGER:Date.now()+r}parkEncrypted(r){return this.pendingEncryptedStashes.has(r)?!1:(this.pendingEncryptedStashes.add(r),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let r=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof et.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)}})&&r++,t)break}return{imported:r,rescheduled:t}}liveRootIds(r){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==r)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(r,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(r));if(i&&Ut(n))return this.pendingEncryptedStashes.add(r.path),!1;let o=await Xe(this.app,n,{...s,secretId:Ii(r.basename)});if(!o)return!1;let a=await Vt(this.app,o,t,e);if(a.colorAliases)for(let[l,A]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,l,A)}catch{}try{await this.app.fileManager.trashFile(r)}catch{}this.pendingEncryptedStashes.delete(r.path);try{await this.plugin.newLog().append({type:"stash_import",id:F,payload:{from:r.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",r.path,n),!1}}async importLooseStashesIn(r,t={}){let e=r.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===oe);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(r,t={}){let e=await this.importLooseFilesIn(r),i=await this.importLooseFoldersIn(r),s=await this.importLooseStashesIn(r,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(r,t,e){return new Promise(i=>{new pt(this.app,r,t,e,i).open()})}dupChoice(r){return new Promise(t=>{new yi(this.app,r,t).open()})}async ensureFolder(r){let t=this.app.vault.adapter,e=r.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(r,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=`${r}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${r}/${s}-${a}${n}`;return o}};ai.DEBOUNCE_MS=900,ai.BATCH_CONFIRM_AT=8;var on=ai;var an=class{constructor(r,t){this.app=r;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 r=this.app.vault.adapter;if(await r.exists(this.path)){let t=await r.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(r){console.warn("[Stashpad] import log load failed",r)}}}recent(){return[...this.entries].reverse()}findDuplicate(r,t){for(let e=this.entries.length-1;e>=0;e--){let i=this.entries[e];if(i.originalName===r&&(t==null||i.size==null||i.size===t))return i}return null}append(r){this.entries.push(r),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(r)+` -`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let r=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 r.exists(i)||await r.mkdir(i);this.dirOk=!0}};var ln=class ln{constructor(r,t){this.app=r;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 r=this.app.vault.adapter;if(await r.exists(this.path)){let t=JSON.parse(await r.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(r){console.warn("[Stashpad] render cache load failed; starting empty",r),this.map.clear()}}}evict(r){this.map.delete(r)&&(this.dirty=!0,this.save())}get(r){return this.map.get(r)}has(r){return this.map.has(r)}set(r,t){this.map.set(r,t),this.dirty=!0,this.scheduleSave()}scheduleSave(){this.saveTimer==null&&(this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},ln.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 r={schema:1,entries:Object.fromEntries(this.map)};await this.app.vault.adapter.write(this.path,JSON.stringify(r))}catch(r){console.warn("[Stashpad] render cache save failed",r)}}),this.writeChain):this.writeChain}async ensureDir(){if(this.dirOk)return;let r=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 r.exists(i)||await r.mkdir(i);this.dirOk=!0}};ln.SAVE_DEBOUNCE_MS=8e3;var rn=ln;var Fo="stashpad:unghost-after-reload",$i=class $i extends M.Plugin{constructor(){super(...arguments);this.settings={...me};this.debugBuffer=[];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.noteClipboard=null;this.noteClipboardNotice=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.okfRebuildTimers=new Map;this.okfRebuildingFolders=new Set;this.archivePending=new Map;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.ACTIVE_VERSIONS_LS_KEY="stashpad:active-versions";this.pendingForkDeletes=new Set;this.writeChain=Promise.resolve()}trace(t,e){if(!this.settings.debugTrace)return;let i="";if(e)try{i=" "+JSON.stringify(e)}catch{i=" [unserializable]"}let s=Math.round(performance.now());this.debugBuffer.push(`+${s}ms ${t}${i}`),this.debugBuffer.length>$i.DEBUG_BUFFER_MAX&&this.debugBuffer.splice(0,this.debugBuffer.length-$i.DEBUG_BUFFER_MAX)}getDebugTrace(){return this.debugBuffer.join(` -`)}clearDebugTrace(){this.debugBuffer=[]}get notifications(){return this._notifications||(this._notifications=new As(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new sn(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new on(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new an(this.app,this.pluginPrivatePath())),this._importLog}clearNoteClipboard(){try{this.noteClipboardNotice?.hide()}catch{}this.noteClipboardNotice=null,this.noteClipboard=null}get renderCacheStore(){return this._renderCacheStore||(this._renderCacheStore=new rn(this.app,this.pluginPrivatePath())),this._renderCacheStore}async onunload(){try{this.encryption?.dispose()}catch{}try{for(let t of this.archivePending.values())window.clearTimeout(t.timer);this.archivePending.clear()}catch{}try{await this._renderCacheStore?.save()}catch{}}pluginPrivatePath(t=""){let i=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${i}/${t.replace(/^\/+/,"")}`:i}newLog(){return new tn(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),l="";for(let A of a)l=l?`${l}/${A}`:A,await t.exists(l)||await t.mkdir(l)},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 l of a.files){let A=l.replace(/^.*\//,""),d=this.pluginPrivatePath(A);if(!await t.exists(d))try{let h=await t.read(l);await t.write(d,h),console.debug("[Stashpad] migrated",l,"\u2192",d)}catch(h){console.warn(`Stashpad: failed to migrate ${l}`,h)}}}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 A of s)n=n?`${n}/${A}`:A,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let A=this.app.vault.getAbstractFileByPath(o);A&&await this.app.fileManager.processFrontMatter(A,d=>{(typeof d.id!="string"||!d.id)&&(d.id=F),"parent"in d||(d.parent=null),(typeof d.created!="string"||!d.created)&&(d.created=new Date().toISOString())});return}let a=new Date().toISOString(),l=["---",`id: ${F}`,"parent: null",`created: ${a}`,"---","Home"].join(` -`);await this.app.vault.create(o,l);try{await this.seedLocalAuthorStub(e)}catch{}try{await this.seedKnownAuthorsInFolder(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,l=typeof a?.color=="string"?a.color.trim():"";if(!l||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(l))continue;let A=l.toLowerCase();e.set(A,(e.get(A)??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 l of this.app.vault.getMarkdownFiles()){let A=l.parent?.path?.replace(/\/+$/,"")??"";if(A!==s&&!A.startsWith(s+"/"))continue;let d=this.app.metadataCache.getFileCache(l)?.frontmatter;if((typeof d?.color=="string"?d.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(l,g=>{i?g.color=i:delete g.color}),o++}catch(g){console.warn(`Stashpad: recolor failed for ${l.path}`,g)}}let a=this.settings.colorAliases?.[s];if(a){let l=a[n];l&&(delete a[n],i&&(a[i.toLowerCase()]=l),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(K)){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(A){console.warn("[Stashpad] couldn't ensure .trash",A)}let o=`${n}/${i}`;for(let A=1;await s.exists(o);A++)o=`${n}/${i} (${A})`;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(A){console.warn("[Stashpad] folder delete failed",A),this.suppressedFolderDeletes.delete(e),new M.Notice("Delete failed (see console).");return}let l=a>0?`Deleted \u201C${i}\u201D \u2014 closed ${a} open tab${a===1?"":"s"}.`:`Deleted \u201C${i}\u201D.`;this.notifications.show({message:l,kind:"warning",category:"delete",duration:0,folder:e,actions:[{label:"Undo",onClick:async()=>{try{if(await s.exists(e)){new M.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 M.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(A){console.warn("[Stashpad] folder undo failed",A),new M.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),s=new Set((this.settings.archiveFolders??[]).map(A=>(A??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(A=>s.has(A)?!1:e.size>0?e.has(A):!i.has(A)),a=(t||"").trim().replace(/\/+$/,""),l=o.filter(A=>A!==a);return a&&l.unshift(a),l}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(A=>A.path===t||A.path.startsWith(t+"/"));for(let A of n){let d=this.app.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id.trim():"";if(!h)continue;let g=d&&"parent"in d?d.parent??null:null;s[h]={parent:g,path:A.path}}let o=await i.readState(),a=A=>A===t||A.startsWith(t+"/");if(!e.silent){for(let[A,d]of Object.entries(s)){let h=o[A];h?h.parent!==d.parent?await i.append({type:"parent_change",id:A,payload:{from:h.parent,to:d.parent}}):h.path!==d.path&&await i.append({type:"rename",id:A,payload:{from:h.path,to:d.path}}):await i.append({type:"create",id:A,payload:{path:d.path,parent:d.parent}})}for(let[A,d]of Object.entries(o))!s[A]&&a(d.path)&&await i.append({type:"missing",id:A,payload:{lastPath:d.path}})}let l={};for(let[A,d]of Object.entries(o))a(d.path)||(l[A]=d);for(let[A,d]of Object.entries(s))l[A]=d;await i.writeState(l)}catch(i){console.warn("Stashpad: integrity sweep failed",i)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new en,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),wt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new ms(this.app,()=>({...Ti(),...this.settings.encryption??{}}),async p=>{this.settings.encryption=p,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.settingTab=new xs(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),this.registerEvent(this.app.vault.on("delete",p=>this.renderCacheStore.evict(p.path))),this.registerEvent(this.app.vault.on("rename",(p,u)=>this.renderCacheStore.evict(u)));let t=(0,M.debounce)(()=>void this.flushForkSiblingPrune(),250,!0);this.registerEvent(this.app.vault.on("delete",p=>{p instanceof M.TFile&&p.extension==="md"&&(this.pendingForkDeletes.add(p.basename),t())})),this.registerEvent(this.app.vault.on("create",p=>this.onOkfFileEvent(p.path))),this.registerEvent(this.app.vault.on("delete",p=>this.onOkfFileEvent(p.path))),this.registerEvent(this.app.vault.on("rename",(p,u)=>{this.onOkfFileEvent(p.path),this.onOkfFileEvent(u)})),await this.authorRegistry.load();{let p=(this.settings.authorId??"").trim();p&&this.authorRegistry.record({id:p,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{this.reconcileLockedRegistry(),window.setTimeout(()=>void this.checkDueReminders(),6e3),this.registerInterval(window.setInterval(()=>void this.checkDueReminders(),5*60*1e3)),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(K,p=>new Vs(p,this)),this.registerView(ve,p=>new Ts(p,this)),this.registerView(le,p=>new is(p,this)),this.registerView(Re,p=>new Xs(p,this)),this.registerView(we,p=>new Zs(p,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",p=>{p&&p.view.getViewType()===K&&(this.lastActiveStashpadLeaf=p,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(ve).length===0&&setTimeout(()=>{Hs(this.app)},0),this.notifyStashpadSelectionChanged())}));let e=()=>{let p=ae(),u=!!p&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===p,f=!!u&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",f),document.body.classList.toggle("stashpad-active",!!u)};this.register(er(e)),this.registerEvent(this.app.workspace.on("active-leaf-change",e));let i=p=>{try{let u=Array.from(document.querySelectorAll("style")).filter(f=>(f.textContent??"").includes(".stashpad-"));for(let f of u){let C=f.id||"",m=C?`style[data-stashpad-source="${C}"]`:null;if(m&&p.head.querySelector(m))continue;let B=p.createElement("style");C?B.setAttribute("data-stashpad-source",C):B.setAttribute("data-stashpad-source","anon"),B.textContent=f.textContent??"",p.head.appendChild(B)}}catch(u){console.warn("[Stashpad] inject popout styles failed",u)}};this.registerEvent(this.app.workspace.on("window-open",p=>{let u=p?.doc??p?.win?.document??null;u&&i(u)})),this.registerEvent(this.app.workspace.on("file-menu",(p,u)=>{if(!(u instanceof M.TFolder))return;let f=u.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(f)&&p.addItem(C=>{C.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(f))})})),setTimeout(()=>{try{let p=this.app.workspace;typeof p.iterateAllLeaves=="function"&&p.iterateAllLeaves(u=>{let f=u?.view?.containerEl?.ownerDocument;f&&f!==document&&i(f)})}catch{}},200),e(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let s=window.visualViewport,n=()=>{let p=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),u=p&&p.isConnected?p.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${u}px`);let f=0;s&&(f=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${f}px`),document.body.classList.toggle("stashpad-keyboard-open",f>100)};n(),s&&(s.addEventListener("resize",n),s.addEventListener("scroll",n),this.register(()=>{s.removeEventListener("resize",n),s.removeEventListener("scroll",n)})),window.addEventListener("resize",n),this.register(()=>window.removeEventListener("resize",n)),requestAnimationFrame(n),setTimeout(n,250),setTimeout(n,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",p=>{p.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{ss(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{js(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{Hs(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()}),this.addCommand({id:"stashpad-lock-encryption",name:"Lock encryption (forget password)",callback:()=>{if(!this.encryption.isConfigured()){new M.Notice("Encryption isn't set up.");return}this.encryption.lock(),new M.Notice("Encryption locked.")}});let a=p=>{let u=ae();u&&typeof u[p]=="function"&&u[p]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>a("toggleSplit")}),this.addCommand({id:"stashpad-fork-version",name:"Fork as a version (alternate draft in this sheet)",callback:()=>a("cmdForkVersion")}),this.addCommand({id:"stashpad-mark-version-final",name:"Mark version as final (sheet)",callback:()=>a("cmdMarkVersionFinal")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>a("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-lock-selection",name:"Encrypt (lock) selection (notes + children)",callback:()=>a("cmdLockSelection")}),this.addCommand({id:"stashpad-unlock-all",name:"Decrypt (unlock) locked notes in view",callback:()=>a("cmdUnlockAll")}),this.addCommand({id:"stashpad-unlock-all-vault",name:"Decrypt (unlock) ALL locked notes in the vault",callback:()=>void this.unlockAllInVault()}),this.addCommand({id:"stashpad-copy-notes",name:"Copy notes (note clipboard \u2014 paste to duplicate)",callback:()=>a("cmdCopyNotes")}),this.addCommand({id:"stashpad-cut-notes",name:"Cut notes (paste in list to move, in composer to extract text)",callback:()=>a("cmdCutNotes")}),this.addCommand({id:"stashpad-paste-notes",name:"Paste notes (from the note clipboard)",callback:()=>a("cmdPasteNotes")}),this.addCommand({id:"stashpad-move-to-archive",name:"Move selection to archive (encrypt)",callback:()=>a("cmdMoveToArchive")}),this.addCommand({id:"stashpad-encrypt-delete",name:"Encrypt & delete selection (to encrypted trash)",callback:()=>a("cmdEncryptDelete")}),this.addCommand({id:"stashpad-restore-trash",name:"Open encrypted trash (restore deleted)\u2026",callback:()=>this.openEncryptedTrash()}),this.addCommand({id:"stashpad-encrypt-existing-trash",name:"Encrypt existing Obsidian trash (backfill .trash into encrypted trash)",callback:()=>void this.encryptExistingTrash()}),this.addCommand({id:"stashpad-close-duplicate-tabs",name:"Close duplicate & orphaned Stashpad tabs (tidy up)",callback:()=>void this.closeDuplicateStashpadTabs()}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>a("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>a("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>a("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>a("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>a("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>a("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>a("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>a("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>a("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>a("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>a("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>a("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>a("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>a("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>a("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>a("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>a("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>a("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>a("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>a("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>a("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>a("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>a("cmdClone")}),this.addCommand({id:"stashpad-fork-note",name:"Fork into a separate note (copy under a chosen parent)",callback:()=>a("cmdForkNote")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>a("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>a("cmdToggleExpand")}),this.addCommand({id:"stashpad-expand-all",name:"Expand all (show every note's full body)",callback:()=>a("cmdExpandAll")}),this.addCommand({id:"stashpad-collapse-all",name:"Collapse all (clamp every note's body)",callback:()=>a("cmdCollapseAll")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>a("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>a("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>a("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>a("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>a("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new M.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let p=wt.report();console.log(p);try{await navigator.clipboard.writeText(p)}catch{}new M.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{wt.reset(),new M.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>a("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>a("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>a("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:p}=await Promise.resolve().then(()=>(Ft(),wi));new p(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:p=>{let u=this.importService.defaultDestination();return p?!!u:(u&&this.runImportLooseFiles(u),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:p=>{let u=this.importService.defaultDestination();return p?!!u:(u&&this.runFolderSlugPass(u),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:p=>{let u=this.importService.defaultDestination();return p?!!u:(u&&this.runFolderFrontmatterBackfill(u),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>a("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>a("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void ss(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void js(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void Hs(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:p=>{let u=this.app.workspace.getActiveFile(),f=!!u&&u.extension==="md"&&this.isStashpadNoteFile(u);return p||f&&u&&this.revealNoteInStashpad(u),f}});let l=Object.keys(vi);for(let p of l){let u=vi[p];this.addCommand({id:`stashpad-open-panels-${p}`,name:`Open Stashpad panel: ${u.label}`,callback:async()=>{await ss(this.app),this.app.workspace.getLeavesOfType(le)[0]?.view?.setActivePanel?.(p)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>a("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>a("cmdTogglePin")}),this.addCommand({id:"stashpad-list-pin",name:"Pin / unpin to top of list",callback:()=>a("cmdToggleListPin")}),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:()=>a("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>a("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>a("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>a("cmdExportStash")}),this.addCommand({id:"stashpad-export-okf",name:"Export selection as OKF bundle (.zip / .tar.gz / .stash)",callback:()=>a("cmdExportOkf")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>a("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:p=>{let u=ae(),f=u&&u.noteFolder;return f?(p||(new M.Notice(`Running integrity check on "${f}"\u2026`),this.runIntegrityCheckOnFolder(f).then(()=>{new M.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 M.Notice("Stashpad: rebuilding author registry\u2026");try{let p=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${p.total} author(s) \u2014 ${p.fromStubs} from stubs, ${p.fromNotes} from note links.`,kind:"success",category:"system"})}catch(p){new M.Notice(`Author registry rebuild failed: ${p.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new M.Notice("Stashpad: restoring author stubs\u2026");try{let p=await this.restoreMissingAuthorStubs();this.notifications.show({message:p.created>0?`Restored ${p.created} author stub(s) across ${p.folders} folder(s).`:`No missing author stubs \u2014 all present across ${p.folders} folder(s).`,kind:"success",category:"system"})}catch(p){new M.Notice(`Restore author stubs failed: ${p.message}`)}}}),this.addCommand({id:"stashpad-sync-authors",name:"Sync authors across all folders (multiplayer)",callback:()=>void this.syncAuthorsAcrossFolders()}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new M.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:p,fmChecked:u,fmWritten:f,slugsRenamed:C,authors:m,imported:B,attachmentsLinked:y,attachmentsRenamed:Q,attachmentsSkipped:E}=await this.rebootstrapAllFolders(),v=[];v.push(`rebootstrapped ${p.length} folder${p.length===1?"":"s"}`),B>0&&v.push(`imported ${B} loose file${B===1?"":"s"}`),y>0&&v.push(`linked attachments on ${y} note${y===1?"":"s"}`),Q>0&&v.push(`renamed ${Q} attachment${Q===1?"":"s"}`),f>0&&v.push(`updated ${f} note${f===1?"":"s"}' metadata`),C>0&&v.push(`renamed ${C} note${C===1?"":"s"}`),m>0&&v.push(`${m} author${m===1?"":"s"} in registry`),v.push(`(checked ${u} total)`),new M.Notice(`Stashpad: ${v.join(" \xB7 ")}`),E>0&&new M.Notice(`Stashpad: ${E} attachment${E===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(p){new M.Notice(`Stashpad: rebootstrap failed (${p.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:p=>{let u=this.app.workspace.getActiveFile();return!u||u.extension!=="md"?!1:(p||this.adoptNote(u),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ft(),wi)).then(({NotificationHistoryModal:p,LogModal:u})=>{new p(this.app,this.notifications,async()=>{let f=this.app.vault.adapter,C=this.pluginPrivatePath("log.jsonl");if(!await f.exists(C)){new M.Notice("No log yet \u2014 make some changes first.");return}let m=await f.read(C);new u(this.app,m,C).open()},this.settings.authorId||null,f=>this.lookupNoteAuthorIds(f)).open()})}});let A=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let p of A){let u=`stashpad-toggle-${String(p.key).replace(/[A-Z]/g,f=>`-${f.toLowerCase()}`)}`;this.addCommand({id:u,name:`Toggle: ${p.label}`,callback:async()=>{let f=!this.settings[p.key];this.settings[p.key]=f,await this.saveSettings(),new M.Notice(`${p.label}: ${f?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.openTabById(this.manifest.id),setTimeout(()=>{p?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let p of Ns)this.addCommand({id:`stashpad-open-settings-${p.id}`,name:`Open Stashpad settings: ${p.label}`,callback:()=>{let u=this.app.setting;!u?.open||!u?.openTabById||(u.open(),u.openTabById(this.manifest.id))}});let d=()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.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:p}=await Promise.resolve().then(()=>(ki(),rs)),u=await p(this.app,this,this.settings);if(u.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(u.error==="no-home"){new M.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:f}=await Promise.resolve().then(()=>(ki(),rs));f(this.app,u)}catch(p){console.error("[stashpad] preview failed",p),new M.Notice(`Preview failed: ${p?.message??p}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:p,scanForJdNotes:u,JdBuildConfirmModal:f}=await Promise.resolve().then(()=>(ki(),rs));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}let m=u(this.app,this,this.settings);new f(this.app,this,this.settings,m.indexed.length,async()=>{try{let y=await p(this.app,this,this.settings);if(y.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(y.error==="dest-not-stashpad"){new M.Notice(`"${y.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),d();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new M.Notice(`Index built: ${y.created} created, ${y.updated} updated, ${y.skipped} skipped \u2192 ${y.destFolder}`,6e3)}catch(y){console.error("[stashpad] build failed",y),new M.Notice(`Build failed: ${y?.message??y}`,8e3)}}).open()}catch(p){console.error("[stashpad] build failed",p),new M.Notice(`Build failed: ${p?.message??p}`,8e3)}}});let h=p=>{if(p.extension!==oe)return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),f=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),C=p.parent?.path||"",m=C.split("/").pop()??"";if(u&&m===u){if(f&&C.endsWith(`/${f}`))return;let B=C.slice(0,C.length-u.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(p,B);return}this.settings.autoImport&&this.importService.isArmed()&&(qe(p.path)||this.discoverStashpadFolders().includes(C)&&this.autoImportStash(p,C))};this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile&&h(p)})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile&&h(p)}));let g=p=>{if(p.extension!=="md")return;let u=p.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(u)&&setTimeout(()=>{this.fixOrphanParentForFile(p)},800)},I=p=>{if(p.extension!=="md")return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!u)return;let f=p.parent?.path?.replace(/\/+$/,"")??"";if((f.split("/").pop()??"")!==u)return;let m=f.slice(0,f.length-u.length).replace(/\/+$/,"");!m||!this.discoverStashpadFolders().includes(m)||setTimeout(()=>{this.adoptMarkdownDrop(p,m)},200)};this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile&&(g(p),I(p))})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile&&(g(p),I(p))})),this.registerEvent(this.app.vault.on("delete",p=>{if(!(p instanceof M.TFolder))return;let u=p.path.replace(/\/+$/,"");this.knownStashpadFolders.has(u)&&this.handleStashpadFolderDeleted(u)})),this.registerEvent(this.app.vault.on("rename",(p,u)=>{p instanceof M.TFile&&this.maybeReHomeOnCrossFolderMove(p,u)})),this.registerEvent(this.app.vault.on("rename",(p,u)=>{p instanceof M.TFile&&this.maybeArchiveOnMoveIn(p,u)})),this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile?this.importService.enqueue(p):p instanceof M.TFolder&&this.importService.enqueueFolder(p)})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile?this.importService.enqueue(p):p instanceof M.TFolder&&this.importService.enqueueFolder(p)})),this.registerEvent(this.app.vault.on("rename",(p,u)=>{p instanceof M.TFile&&this.maybeAdoptAuthorRename(p,u)})),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(Fo,"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 M.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(Fo)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Fo)}catch{}for(let e of this.app.workspace.getLeavesOfType(K))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,l=s[o]??0;if(a!==l)return a>l}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 l=`${n}/${i}-${t}.md`,A=o;if(o.path!==l)try{this.authorRenameInFlight.add(o.path),this.authorRenameInFlight.add(l),await this.app.fileManager.renameFile(o,l);let d=this.app.vault.getAbstractFileByPath(l);d&&(A=d)}catch(d){console.warn("[Stashpad] author file rename failed",d);continue}try{await this.refreshAuthorStub(A)}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):"",l=0;for(;await i.exists(`${e}/${s}`);)l+=1,s=`${o}-${l}${a}`;let A=`${e}/${s}`;await this.app.fileManager.renameFile(t,A);let d=this.app.vault.getAbstractFileByPath(A);d instanceof M.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(d)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[A]})}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,l=!n,A=!o;if(!a&&!l&&!A)return;let{newId:d}=await Promise.resolve().then(()=>(Tt(),ts)),h,g=!1,I=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(h=d(),f.id=h)),l){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=F,g=!0)}A&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),I=!0))}),!h&&!g&&!I)return;let p=this.newLog(),u=h||i;u&&await p.append({type:"parent_change",id:u,payload:{from:null,to:F,reason:"orphan_auto_fix",path:t.path,addedId:!!h,addedParent:g,addedCreated:I}}),new M.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===F||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 l=typeof a.parent=="string"?a.parent.trim():"";l&&l!==F&&(a.parent=F)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:F,reason:"rehome_cross_folder_move",path:t.path}}),new M.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(Ut(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await Xe(this.app,i);if(!s)return;let n=ae(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let A of n.collectExistingIds())o.add(A);else for(let A of this.app.vault.getMarkdownFiles()){if(!A.path.startsWith(e+"/"))continue;let d=this.app.metadataCache.getFileCache(A)?.frontmatter?.id;typeof d=="string"&&o.add(d)}let a=await Vt(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:F,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 l=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&l.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&l.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:l.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed +`,d=Qt(o.basename)||o.basename,h=await this.uniquePath(t,yt(d,a));await this.createNote(h,me(l,A)),i.push(h)}}}recordNotePaths(r){return r.kind==="folder"?r.notePaths:[r.notePath]}announce(r,t=[]){let e=r[0]?.folder??"",i=r.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(r,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:r.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(r,t=[]){for(let e of r)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof et.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof et.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 et.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof et.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 et.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof et.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof et.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 et.Notice(`Undid import of ${r.length} file(s).`)}pickFilesInto(r){let t=document.createElement("input");t.type="file",t.multiple=!0,t.setCssStyles({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(r,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let l=this.app.vault.getAbstractFileByPath(a);l instanceof et.TFile&&i.push(l)}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(r){let t=r.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(r){let t=r.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof et.TFolder))return 0;let i=e.children.filter(n=>n instanceof et.TFolder&&!nn.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 r of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(r)instanceof et.TFile||this.pendingEncryptedStashes.delete(r);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(r){this.pendingEncryptedStashes.delete(r)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(r){this.encryptedNotifySnoozeUntil=r===1/0?Number.MAX_SAFE_INTEGER:Date.now()+r}parkEncrypted(r){return this.pendingEncryptedStashes.has(r)?!1:(this.pendingEncryptedStashes.add(r),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let r=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof et.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)}})&&r++,t)break}return{imported:r,rescheduled:t}}liveRootIds(r){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==r)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(r,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(r));if(i&&Gt(n))return this.pendingEncryptedStashes.add(r.path),!1;let o=await Xe(this.app,n,{...s,secretId:Ii(r.basename)});if(!o)return!1;let a=await Wt(this.app,o,t,e);if(a.colorAliases)for(let[l,A]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,l,A)}catch{}try{await this.app.fileManager.trashFile(r)}catch{}this.pendingEncryptedStashes.delete(r.path);try{await this.plugin.newLog().append({type:"stash_import",id:F,payload:{from:r.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",r.path,n),!1}}async importLooseStashesIn(r,t={}){let e=r.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===re);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(r,t={}){let e=await this.importLooseFilesIn(r),i=await this.importLooseFoldersIn(r),s=await this.importLooseStashesIn(r,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(r,t,e){return new Promise(i=>{new ot(this.app,r,t,e,i).open()})}dupChoice(r){return new Promise(t=>{new yi(this.app,r,t).open()})}async ensureFolder(r){let t=this.app.vault.adapter,e=r.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(r,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=`${r}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${r}/${s}-${a}${n}`;return o}};ai.DEBOUNCE_MS=900,ai.BATCH_CONFIRM_AT=8;var on=ai;var an=class{constructor(r,t){this.app=r;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 r=this.app.vault.adapter;if(await r.exists(this.path)){let t=await r.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(r){console.warn("[Stashpad] import log load failed",r)}}}recent(){return[...this.entries].reverse()}findDuplicate(r,t){for(let e=this.entries.length-1;e>=0;e--){let i=this.entries[e];if(i.originalName===r&&(t==null||i.size==null||i.size===t))return i}return null}append(r){this.entries.push(r),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(r)+` +`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let r=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 r.exists(i)||await r.mkdir(i);this.dirOk=!0}};var ln=class ln{constructor(r,t){this.app=r;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 r=this.app.vault.adapter;if(await r.exists(this.path)){let t=JSON.parse(await r.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(r){console.warn("[Stashpad] render cache load failed; starting empty",r),this.map.clear()}}}evict(r){this.map.delete(r)&&(this.dirty=!0,this.save())}get(r){return this.map.get(r)}has(r){return this.map.has(r)}set(r,t){this.map.set(r,t),this.dirty=!0,this.scheduleSave()}scheduleSave(){this.saveTimer==null&&(this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},ln.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 r={schema:1,entries:Object.fromEntries(this.map)};await this.app.vault.adapter.write(this.path,JSON.stringify(r))}catch(r){console.warn("[Stashpad] render cache save failed",r)}}),this.writeChain):this.writeChain}async ensureDir(){if(this.dirOk)return;let r=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 r.exists(i)||await r.mkdir(i);this.dirOk=!0}};ln.SAVE_DEBOUNCE_MS=8e3;var rn=ln;var Fo="stashpad:unghost-after-reload",Vi=class Vi extends M.Plugin{constructor(){super(...arguments);this.settings={...ge};this.debugBuffer=[];this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.pendingEncBlobs=new Set;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.noteClipboard=null;this.noteClipboardNotice=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.okfRebuildTimers=new Map;this.okfRebuildingFolders=new Set;this.archivePending=new Map;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.ACTIVE_VERSIONS_LS_KEY="stashpad:active-versions";this.pendingForkDeletes=new Set;this.writeChain=Promise.resolve()}trace(t,e){if(!this.settings.debugTrace)return;let i="";if(e)try{i=" "+JSON.stringify(e)}catch{i=" [unserializable]"}let s=Math.round(performance.now());this.debugBuffer.push(`+${s}ms ${t}${i}`),this.debugBuffer.length>Vi.DEBUG_BUFFER_MAX&&this.debugBuffer.splice(0,this.debugBuffer.length-Vi.DEBUG_BUFFER_MAX)}getDebugTrace(){return this.debugBuffer.join(` +`)}clearDebugTrace(){this.debugBuffer=[]}get notifications(){return this._notifications||(this._notifications=new cs(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new sn(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new on(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new an(this.app,this.pluginPrivatePath())),this._importLog}clearNoteClipboard(){try{this.noteClipboardNotice?.hide()}catch{}this.noteClipboardNotice=null,this.noteClipboard=null}get renderCacheStore(){return this._renderCacheStore||(this._renderCacheStore=new rn(this.app,this.pluginPrivatePath())),this._renderCacheStore}async onunload(){try{this.encryption?.dispose()}catch{}try{for(let t of this.archivePending.values())window.clearTimeout(t.timer);this.archivePending.clear()}catch{}try{await this._renderCacheStore?.save()}catch{}}pluginPrivatePath(t=""){let i=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${i}/${t.replace(/^\/+/,"")}`:i}newLog(){return new tn(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),l="";for(let A of a)l=l?`${l}/${A}`:A,await t.exists(l)||await t.mkdir(l)},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 l of a.files){let A=l.replace(/^.*\//,""),d=this.pluginPrivatePath(A);if(!await t.exists(d))try{let h=await t.read(l);await t.write(d,h),console.debug("[Stashpad] migrated",l,"\u2192",d)}catch(h){console.warn(`Stashpad: failed to migrate ${l}`,h)}}}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 A of s)n=n?`${n}/${A}`:A,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let A=this.app.vault.getAbstractFileByPath(o);A&&await this.app.fileManager.processFrontMatter(A,d=>{(typeof d.id!="string"||!d.id)&&(d.id=F),"parent"in d||(d.parent=null),(typeof d.created!="string"||!d.created)&&(d.created=new Date().toISOString())});return}let a=new Date().toISOString(),l=["---",`id: ${F}`,"parent: null",`created: ${a}`,"---","Home"].join(` +`);await this.app.vault.create(o,l);try{await this.seedLocalAuthorStub(e)}catch{}try{await this.seedKnownAuthorsInFolder(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,l=typeof a?.color=="string"?a.color.trim():"";if(!l||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(l))continue;let A=l.toLowerCase();e.set(A,(e.get(A)??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 l of this.app.vault.getMarkdownFiles()){let A=l.parent?.path?.replace(/\/+$/,"")??"";if(A!==s&&!A.startsWith(s+"/"))continue;let d=this.app.metadataCache.getFileCache(l)?.frontmatter;if((typeof d?.color=="string"?d.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(l,g=>{i?g.color=i:delete g.color}),o++}catch(g){console.warn(`Stashpad: recolor failed for ${l.path}`,g)}}let a=this.settings.colorAliases?.[s];if(a){let l=a[n];l&&(delete a[n],i&&(a[i.toLowerCase()]=l),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(J)){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(A){console.warn("[Stashpad] couldn't ensure .trash",A)}let o=`${n}/${i}`;for(let A=1;await s.exists(o);A++)o=`${n}/${i} (${A})`;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(A){console.warn("[Stashpad] folder delete failed",A),this.suppressedFolderDeletes.delete(e),new M.Notice("Delete failed (see console).");return}let l=a>0?`Deleted \u201C${i}\u201D \u2014 closed ${a} open tab${a===1?"":"s"}.`:`Deleted \u201C${i}\u201D.`;this.notifications.show({message:l,kind:"warning",category:"delete",duration:0,folder:e,actions:[{label:"Undo",onClick:async()=>{try{if(await s.exists(e)){new M.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 M.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(A){console.warn("[Stashpad] folder undo failed",A),new M.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),s=new Set((this.settings.archiveFolders??[]).map(A=>(A??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(A=>s.has(A)?!1:e.size>0?e.has(A):!i.has(A)),a=(t||"").trim().replace(/\/+$/,""),l=o.filter(A=>A!==a);return a&&l.unshift(a),l}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(A=>A.path===t||A.path.startsWith(t+"/"));for(let A of n){let d=this.app.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id.trim():"";if(!h)continue;let g=d&&"parent"in d?d.parent??null:null;s[h]={parent:g,path:A.path}}let o=await i.readState(),a=A=>A===t||A.startsWith(t+"/");if(!e.silent){for(let[A,d]of Object.entries(s)){let h=o[A];h?h.parent!==d.parent?await i.append({type:"parent_change",id:A,payload:{from:h.parent,to:d.parent}}):h.path!==d.path&&await i.append({type:"rename",id:A,payload:{from:h.path,to:d.path}}):await i.append({type:"create",id:A,payload:{path:d.path,parent:d.parent}})}for(let[A,d]of Object.entries(o))!s[A]&&a(d.path)&&await i.append({type:"missing",id:A,payload:{lastPath:d.path}})}let l={};for(let[A,d]of Object.entries(o))a(d.path)||(l[A]=d);for(let[A,d]of Object.entries(s))l[A]=d;await i.writeState(l)}catch(i){console.warn("Stashpad: integrity sweep failed",i)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new en,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),wt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new ms(this.app,()=>({...Hi(),...this.settings.encryption??{}}),async p=>{this.settings.encryption=p,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.settingTab=new Es(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),this.registerEvent(this.app.vault.on("delete",p=>this.renderCacheStore.evict(p.path))),this.registerEvent(this.app.vault.on("rename",(p,u)=>this.renderCacheStore.evict(u)));let t=(0,M.debounce)(()=>void this.flushForkSiblingPrune(),250,!0);this.registerEvent(this.app.vault.on("delete",p=>{p instanceof M.TFile&&p.extension==="md"&&(this.pendingForkDeletes.add(p.basename),t())})),this.registerEvent(this.app.vault.on("create",p=>this.onOkfFileEvent(p.path))),this.registerEvent(this.app.vault.on("delete",p=>this.onOkfFileEvent(p.path))),this.registerEvent(this.app.vault.on("rename",(p,u)=>{this.onOkfFileEvent(p.path),this.onOkfFileEvent(u)})),await this.authorRegistry.load();{let p=(this.settings.authorId??"").trim();p&&this.authorRegistry.record({id:p,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.registerEvent(this.app.vault.on("create",p=>{p.path.endsWith(".stashenc")&&this.pendingEncBlobs.delete(p.path)})),this.registerEvent(this.app.vault.on("delete",p=>{p.path.endsWith(".stashenc")&&this.pendingEncBlobs.delete(p.path)})),this.app.workspace.onLayoutReady(()=>{this.reconcileLockedRegistry(),window.setTimeout(()=>void this.checkDueReminders(),6e3),this.registerInterval(window.setInterval(()=>void this.checkDueReminders(),5*60*1e3)),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(J,p=>new $s(p,this)),this.registerView(we,p=>new vs(p,this)),this.registerView(Ae,p=>new ss(p,this)),this.registerView(Re,p=>new Vs(p,this)),this.registerView(Ee,p=>new Ws(p,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",p=>{p&&p.view.getViewType()===J&&(this.lastActiveStashpadLeaf=p,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(we).length===0&&setTimeout(()=>{Fs(this.app)},0),this.notifyStashpadSelectionChanged())}));let e=()=>{let p=ne(),u=!!p&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===p,f=!!u&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",f),document.body.classList.toggle("stashpad-active",!!u)};this.register(wa(e)),this.registerEvent(this.app.workspace.on("active-leaf-change",e));let i=p=>{try{let u=Array.from(document.querySelectorAll("style")).filter(f=>(f.textContent??"").includes(".stashpad-"));for(let f of u){let C=f.id||"",m=C?`style[data-stashpad-source="${C}"]`:null;if(m&&p.head.querySelector(m))continue;let B=p.createElement("style");C?B.setAttribute("data-stashpad-source",C):B.setAttribute("data-stashpad-source","anon"),B.textContent=f.textContent??"",p.head.appendChild(B)}}catch(u){console.warn("[Stashpad] inject popout styles failed",u)}};this.registerEvent(this.app.workspace.on("window-open",p=>{let u=p?.doc??p?.win?.document??null;u&&i(u)})),this.registerEvent(this.app.workspace.on("file-menu",(p,u)=>{if(!(u instanceof M.TFolder))return;let f=u.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(f)&&p.addItem(C=>{C.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(f))})})),setTimeout(()=>{try{let p=this.app.workspace;typeof p.iterateAllLeaves=="function"&&p.iterateAllLeaves(u=>{let f=u?.view?.containerEl?.ownerDocument;f&&f!==document&&i(f)})}catch{}},200),e(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let s=window.visualViewport,n=()=>{let p=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),u=p&&p.isConnected?p.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${u}px`);let f=0;s&&(f=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${f}px`),document.body.classList.toggle("stashpad-keyboard-open",f>100)};n(),s&&(s.addEventListener("resize",n),s.addEventListener("scroll",n),this.register(()=>{s.removeEventListener("resize",n),s.removeEventListener("scroll",n)})),window.addEventListener("resize",n),this.register(()=>window.removeEventListener("resize",n)),requestAnimationFrame(n),setTimeout(n,250),setTimeout(n,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",p=>{p.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{ns(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Xs(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{Fs(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()}),this.addCommand({id:"stashpad-lock-encryption",name:"Lock encryption (forget password)",callback:()=>{if(!this.encryption.isConfigured()){new M.Notice("Encryption isn't set up.");return}this.encryption.lock(),new M.Notice("Encryption locked.")}});let a=p=>{let u=ne();u&&typeof u[p]=="function"&&u[p]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>a("toggleSplit")}),this.addCommand({id:"stashpad-fork-version",name:"Fork as a version (alternate draft in this sheet)",callback:()=>a("cmdForkVersion")}),this.addCommand({id:"stashpad-mark-version-final",name:"Mark version as final (sheet)",callback:()=>a("cmdMarkVersionFinal")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>a("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-lock-selection",name:"Encrypt (lock) selection (notes + children)",callback:()=>a("cmdLockSelection")}),this.addCommand({id:"stashpad-unlock-all",name:"Decrypt (unlock) locked notes in view",callback:()=>a("cmdUnlockAll")}),this.addCommand({id:"stashpad-unlock-all-vault",name:"Decrypt (unlock) ALL locked notes in the vault",callback:()=>void this.unlockAllInVault()}),this.addCommand({id:"stashpad-copy-notes",name:"Copy notes (note clipboard \u2014 paste to duplicate)",callback:()=>a("cmdCopyNotes")}),this.addCommand({id:"stashpad-cut-notes",name:"Cut notes (paste in list to move, in composer to extract text)",callback:()=>a("cmdCutNotes")}),this.addCommand({id:"stashpad-paste-notes",name:"Paste notes (from the note clipboard)",callback:()=>a("cmdPasteNotes")}),this.addCommand({id:"stashpad-move-to-archive",name:"Move selection to archive (encrypt)",callback:()=>a("cmdMoveToArchive")}),this.addCommand({id:"stashpad-encrypt-delete",name:"Encrypt & delete selection (to encrypted trash)",callback:()=>a("cmdEncryptDelete")}),this.addCommand({id:"stashpad-restore-trash",name:"Open encrypted trash (restore deleted)\u2026",callback:()=>this.openEncryptedTrash()}),this.addCommand({id:"stashpad-encrypt-existing-trash",name:"Encrypt existing Obsidian trash (backfill .trash into encrypted trash)",callback:()=>void this.encryptExistingTrash()}),this.addCommand({id:"stashpad-close-duplicate-tabs",name:"Close duplicate & orphaned Stashpad tabs (tidy up)",callback:()=>void this.closeDuplicateStashpadTabs()}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>a("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>a("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>a("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>a("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>a("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>a("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>a("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>a("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>a("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>a("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>a("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>a("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>a("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>a("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>a("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>a("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>a("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>a("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>a("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>a("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>a("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>a("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>a("cmdClone")}),this.addCommand({id:"stashpad-fork-note",name:"Fork into a separate note (copy under a chosen parent)",callback:()=>a("cmdForkNote")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>a("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>a("cmdToggleExpand")}),this.addCommand({id:"stashpad-expand-all",name:"Expand all (show every note's full body)",callback:()=>a("cmdExpandAll")}),this.addCommand({id:"stashpad-collapse-all",name:"Collapse all (clamp every note's body)",callback:()=>a("cmdCollapseAll")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>a("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>a("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>a("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>a("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>a("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new M.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let p=wt.report();console.log(p);try{await navigator.clipboard.writeText(p)}catch{}new M.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{wt.reset(),new M.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>a("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>a("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>a("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:p}=await Promise.resolve().then(()=>(Ft(),wi));new p(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:p=>{let u=this.importService.defaultDestination();return p?!!u:(u&&this.runImportLooseFiles(u),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:p=>{let u=this.importService.defaultDestination();return p?!!u:(u&&this.runFolderSlugPass(u),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:p=>{let u=this.importService.defaultDestination();return p?!!u:(u&&this.runFolderFrontmatterBackfill(u),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>a("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>a("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void ns(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void Xs(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void Fs(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:p=>{let u=this.app.workspace.getActiveFile(),f=!!u&&u.extension==="md"&&this.isStashpadNoteFile(u);return p||f&&u&&this.revealNoteInStashpad(u),f}});let l=Object.keys(vi);for(let p of l){let u=vi[p];this.addCommand({id:`stashpad-open-panels-${p}`,name:`Open Stashpad panel: ${u.label}`,callback:async()=>{await ns(this.app),this.app.workspace.getLeavesOfType(Ae)[0]?.view?.setActivePanel?.(p)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>a("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>a("cmdTogglePin")}),this.addCommand({id:"stashpad-list-pin",name:"Pin / unpin to top of list",callback:()=>a("cmdToggleListPin")}),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:()=>a("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>a("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>a("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>a("cmdExportStash")}),this.addCommand({id:"stashpad-export-okf",name:"Export selection as OKF bundle (.zip / .tar.gz / .stash)",callback:()=>a("cmdExportOkf")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>a("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:p=>{let u=ne(),f=u&&u.noteFolder;return f?(p||(new M.Notice(`Running integrity check on "${f}"\u2026`),this.runIntegrityCheckOnFolder(f).then(()=>{new M.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 M.Notice("Stashpad: rebuilding author registry\u2026");try{let p=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${p.total} author(s) \u2014 ${p.fromStubs} from stubs, ${p.fromNotes} from note links.`,kind:"success",category:"system"})}catch(p){new M.Notice(`Author registry rebuild failed: ${p.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new M.Notice("Stashpad: restoring author stubs\u2026");try{let p=await this.restoreMissingAuthorStubs();this.notifications.show({message:p.created>0?`Restored ${p.created} author stub(s) across ${p.folders} folder(s).`:`No missing author stubs \u2014 all present across ${p.folders} folder(s).`,kind:"success",category:"system"})}catch(p){new M.Notice(`Restore author stubs failed: ${p.message}`)}}}),this.addCommand({id:"stashpad-sync-authors",name:"Sync authors across all folders (multiplayer)",callback:()=>void this.syncAuthorsAcrossFolders()}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new M.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:p,fmChecked:u,fmWritten:f,slugsRenamed:C,authors:m,imported:B,attachmentsLinked:y,attachmentsRenamed:Q,attachmentsSkipped:E}=await this.rebootstrapAllFolders(),v=[];v.push(`rebootstrapped ${p.length} folder${p.length===1?"":"s"}`),B>0&&v.push(`imported ${B} loose file${B===1?"":"s"}`),y>0&&v.push(`linked attachments on ${y} note${y===1?"":"s"}`),Q>0&&v.push(`renamed ${Q} attachment${Q===1?"":"s"}`),f>0&&v.push(`updated ${f} note${f===1?"":"s"}' metadata`),C>0&&v.push(`renamed ${C} note${C===1?"":"s"}`),m>0&&v.push(`${m} author${m===1?"":"s"} in registry`),v.push(`(checked ${u} total)`),new M.Notice(`Stashpad: ${v.join(" \xB7 ")}`),E>0&&new M.Notice(`Stashpad: ${E} attachment${E===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(p){new M.Notice(`Stashpad: rebootstrap failed (${p.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:p=>{let u=this.app.workspace.getActiveFile();return!u||u.extension!=="md"?!1:(p||this.adoptNote(u),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ft(),wi)).then(({NotificationHistoryModal:p,LogModal:u})=>{new p(this.app,this.notifications,async()=>{let f=this.app.vault.adapter,C=this.pluginPrivatePath("log.jsonl");if(!await f.exists(C)){new M.Notice("No log yet \u2014 make some changes first.");return}let m=await f.read(C);new u(this.app,m,C).open()},this.settings.authorId||null,f=>this.lookupNoteAuthorIds(f)).open()})}});let A=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let p of A){let u=`stashpad-toggle-${String(p.key).replace(/[A-Z]/g,f=>`-${f.toLowerCase()}`)}`;this.addCommand({id:u,name:`Toggle: ${p.label}`,callback:async()=>{let f=!this.settings[p.key];this.settings[p.key]=f,await this.saveSettings(),new M.Notice(`${p.label}: ${f?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.openTabById(this.manifest.id),setTimeout(()=>{p?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let p of ys)this.addCommand({id:`stashpad-open-settings-${p.id}`,name:`Open Stashpad settings: ${p.label}`,callback:()=>{let u=this.app.setting;!u?.open||!u?.openTabById||(u.open(),u.openTabById(this.manifest.id))}});let d=()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.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:p}=await Promise.resolve().then(()=>(ki(),ls)),u=await p(this.app,this,this.settings);if(u.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(u.error==="no-home"){new M.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:f}=await Promise.resolve().then(()=>(ki(),ls));f(this.app,u)}catch(p){console.error("[stashpad] preview failed",p),new M.Notice(`Preview failed: ${p?.message??p}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:p,scanForJdNotes:u,JdBuildConfirmModal:f}=await Promise.resolve().then(()=>(ki(),ls));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}let m=u(this.app,this,this.settings);new f(this.app,this,this.settings,m.indexed.length,async()=>{try{let y=await p(this.app,this,this.settings);if(y.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(y.error==="dest-not-stashpad"){new M.Notice(`"${y.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),d();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new M.Notice(`Index built: ${y.created} created, ${y.updated} updated, ${y.skipped} skipped \u2192 ${y.destFolder}`,6e3)}catch(y){console.error("[stashpad] build failed",y),new M.Notice(`Build failed: ${y?.message??y}`,8e3)}}).open()}catch(p){console.error("[stashpad] build failed",p),new M.Notice(`Build failed: ${p?.message??p}`,8e3)}}});let h=p=>{if(p.extension!==re)return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),f=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),C=p.parent?.path||"",m=C.split("/").pop()??"";if(u&&m===u){if(f&&C.endsWith(`/${f}`))return;let B=C.slice(0,C.length-u.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(p,B);return}this.settings.autoImport&&this.importService.isArmed()&&(qe(p.path)||this.discoverStashpadFolders().includes(C)&&this.autoImportStash(p,C))};this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile&&h(p)})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile&&h(p)}));let g=p=>{if(p.extension!=="md")return;let u=p.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(u)&&setTimeout(()=>{this.fixOrphanParentForFile(p)},800)},I=p=>{if(p.extension!=="md")return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!u)return;let f=p.parent?.path?.replace(/\/+$/,"")??"";if((f.split("/").pop()??"")!==u)return;let m=f.slice(0,f.length-u.length).replace(/\/+$/,"");!m||!this.discoverStashpadFolders().includes(m)||setTimeout(()=>{this.adoptMarkdownDrop(p,m)},200)};this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile&&(g(p),I(p))})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile&&(g(p),I(p))})),this.registerEvent(this.app.vault.on("delete",p=>{if(!(p instanceof M.TFolder))return;let u=p.path.replace(/\/+$/,"");this.knownStashpadFolders.has(u)&&this.handleStashpadFolderDeleted(u)})),this.registerEvent(this.app.vault.on("rename",(p,u)=>{p instanceof M.TFile&&this.maybeReHomeOnCrossFolderMove(p,u)})),this.registerEvent(this.app.vault.on("rename",(p,u)=>{p instanceof M.TFile&&this.maybeArchiveOnMoveIn(p,u)})),this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile?this.importService.enqueue(p):p instanceof M.TFolder&&this.importService.enqueueFolder(p)})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile?this.importService.enqueue(p):p instanceof M.TFolder&&this.importService.enqueueFolder(p)})),this.registerEvent(this.app.vault.on("rename",(p,u)=>{p instanceof M.TFile&&this.maybeAdoptAuthorRename(p,u)})),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(Fo,"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 M.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(Fo)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Fo)}catch{}for(let e of this.app.workspace.getLeavesOfType(J))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,l=s[o]??0;if(a!==l)return a>l}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 l=`${n}/${i}-${t}.md`,A=o;if(o.path!==l)try{this.authorRenameInFlight.add(o.path),this.authorRenameInFlight.add(l),await this.app.fileManager.renameFile(o,l);let d=this.app.vault.getAbstractFileByPath(l);d&&(A=d)}catch(d){console.warn("[Stashpad] author file rename failed",d);continue}try{await this.refreshAuthorStub(A)}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):"",l=0;for(;await i.exists(`${e}/${s}`);)l+=1,s=`${o}-${l}${a}`;let A=`${e}/${s}`;await this.app.fileManager.renameFile(t,A);let d=this.app.vault.getAbstractFileByPath(A);d instanceof M.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(d)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[A]})}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,l=!n,A=!o;if(!a&&!l&&!A)return;let{newId:d}=await Promise.resolve().then(()=>(Ht(),es)),h,g=!1,I=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(h=d(),f.id=h)),l){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=F,g=!0)}A&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),I=!0))}),!h&&!g&&!I)return;let p=this.newLog(),u=h||i;u&&await p.append({type:"parent_change",id:u,payload:{from:null,to:F,reason:"orphan_auto_fix",path:t.path,addedId:!!h,addedParent:g,addedCreated:I}}),new M.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===F||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 l=typeof a.parent=="string"?a.parent.trim():"";l&&l!==F&&(a.parent=F)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:F,reason:"rehome_cross_folder_move",path:t.path}}),new M.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(Gt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await Xe(this.app,i);if(!s)return;let n=ne(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let A of n.collectExistingIds())o.add(A);else for(let A of this.app.vault.getMarkdownFiles()){if(!A.path.startsWith(e+"/"))continue;let d=this.app.metadataCache.getFileCache(A)?.frontmatter?.id;typeof d=="string"&&o.add(d)}let a=await Wt(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:F,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 l=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&l.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&l.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:l.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:cs(this.app,t.path,M.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 l of a){let A=i(l);A&&e.add(A)}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;for(let t of this.app.workspace.getLeavesOfType(K))t.view?.forceReconcileRender?.()},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let C of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(C)?.frontmatter?.id!==t)continue;let B=C.parent?.path;B&&e.add(B)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async C=>{if(C&&!await this.app.vault.adapter.exists(C))try{await this.app.vault.createFolder(C)}catch(m){let B=m?.message??"";if(!/already exists/i.test(B))throw m}},a=0,l=0,A=0,d=0,h=0,g=0,I=!!this.app.vault.getConfig?.("alwaysUpdateLinks"),p=new Set(this.okfActiveFolders());for(let C of e)try{if(i&&await o(`${C}/${i}`),s&&await o(`${C}/${s}`),this.settings.autoImport)try{let y=await this.importService.importLooseInto(C);d+=y.files+y.folders+y.stashes}catch(y){console.warn("Stashpad: loose sweep failed",C,y)}let m=await ii(this.app,C);a+=m.checked,l+=m.written,A+=await this.rebootstrapFolderSlugs(C);let B=await this.rebootstrapFolderAttachments(C,I);if(h+=B.renamed,g+=B.skipped,p.has(C.replace(/\/+$/,"")))try{await wo(this.app,C)}catch(y){console.warn("Stashpad: OKF rebuild during rebootstrap failed",C,y)}n.push(C)}catch(m){console.warn(`Stashpad: rebootstrap skipped ${C}`,m)}let u=0;try{u=(await this.rebuildAuthorRegistry()).total}catch(C){console.warn("Stashpad: rebootstrap author-registry rebuild failed",C)}let f=0;try{f=await this.convertAttachmentsToLinks()}catch(C){console.warn("Stashpad: attachment-link conversion failed",C)}return{touched:n,fmChecked:a,fmWritten:l,slugsRenamed:A,authors:u,imported:d,attachmentsLinked:f,attachmentsRenamed:h,attachmentsSkipped:g}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Yt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let l=de(a.basename);if(!(!l||l===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==l))try{let d=await this.app.vault.cachedRead(a),h=d.startsWith("---")?d.slice(d.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):d,g=Qt(h,s),I=yt(g,l);if(a.name===I)continue;let p=a.parent?`${a.parent.path}/${I}`:I;if(this.app.vault.getAbstractFileByPath(p))continue;await this.app.fileManager.renameFile(a,p),n+=1}catch(d){console.warn(`Stashpad: slug rebootstrap skipped ${a.path}`,d)}}return n}async rebootstrapFolderAttachments(t,e){let i=`${t.replace(/\/+$/,"")}/_attachments`,s=this.app.vault.getAbstractFileByPath(i);if(!(s instanceof M.TFolder))return{renamed:0,skipped:0};let n=s.children.filter(l=>l instanceof M.TFile),o=0,a=0;for(let l of n){let A=Zo(l.name);if(!A)continue;let d=ns(A.rest,A.stamp);if(l.name===d)continue;if(!e){a+=1;continue}let h=`${i}/${d}`;if(!this.app.vault.getAbstractFileByPath(h))try{await this.app.fileManager.renameFile(l,h),o+=1,await new Promise(g=>setTimeout(g,30))}catch(g){console.warn(`Stashpad: attachment rebootstrap skipped ${l.path}`,g)}}return{renamed:o,skipped:a}}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?.()!==K)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(le);for(let e of t){let i=e.view;i&&typeof i.render=="function"&&i.render()}}refreshAllStashpadViews(){for(let t of this.app.workspace.getLeavesOfType(K)){let e=t.view;e&&typeof e.render=="function"&&e.render()}}openFolderPicker(){let t=p=>{let f=p.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(K),i=this.discoverStashpadFolders(),s=ae(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let p of this.app.vault.getAllLoadedFiles())if(p.children){let u=p.path;u&&u!=="/"&&!u.startsWith(".")&&o.add(u)}let a=p=>{let u=p.split("/").filter(Boolean).pop()??"";return u?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(C=>(C??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(u):!1},l=new Set,A=[],d=[],h=new Set;for(let p of e){let u=t(p);if(h.has(u))continue;h.add(u),l.add(u);let f=u.split("/").pop()||u;A.push({kind:"reveal",folder:u,label:`Reveal "${f}" tab`,leaf:p,icon:this.isArchiveFolder(u)?"archive":"layout-grid"}),d.push({kind:"open-anyway",folder:u,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let p of i.filter(u=>!l.has(u))){let u=p.split("/").pop()||p;A.push({kind:"open",folder:p,label:`Open "${u}" in new tab`,icon:this.isArchiveFolder(p)?"archive":"layout-template"})}let g=this,I=new class extends M.SuggestModal{getSuggestions(p){let u=p.trim().toLowerCase(),f=u?u.split(/\s+/).filter(Boolean):[],C=Q=>{if(!f.length)return!0;let E=Q.toLowerCase();for(let v of f)if(!E.includes(v))return!1;return!0},m=u?A.filter(Q=>{let E="folder"in Q?Q.folder:"";return C(Q.label)||C(E)}):A.slice();if(u&&s&&n)for(let Q of i){if(Q.toLowerCase()===n.toLowerCase())continue;let E=Q.split("/").pop()??Q,v=`${Q} ${E}`;C(v)&&m.push({kind:"switch-current",folder:Q,label:`Switch this tab to "${E}"`,icon:"folder-input"})}let B=p.trim().replace(/^\/+|\/+$/g,"");if(B&&!a(B)){let Q=Array.from(o).find(v=>v.toLowerCase()===B.toLowerCase()),E=i.some(v=>v.toLowerCase()===B.toLowerCase());if(Q&&!E)m.push({kind:"convert",folder:Q,label:`Convert \u201C${pi(Q)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!Q){let v=pi(B);m.push({kind:"create",folder:B,label:`+ Create new Stashpad \u201C${v}\u201D`,icon:"folder-plus"})}}let y=d.filter(Q=>C(Q.label)||C("folder"in Q?Q.folder:""));return m.push(...y),g.encryption?.isConfigured?.()&&C("trash deleted encrypted")&&m.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),m}renderSuggestion(p,u){u.addClass("stashpad-suggest-item"),u.addClass("stashpad-ribbon-suggest-item"),p.kind==="create"&&u.addClass("stashpad-suggest-create");let f=u.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,M.setIcon)(f,p.icon);let C=u.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:p.label}),"folder"in p&&p.folder&&p.label!==p.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:p.folder})}async onChooseSuggestion(p){if(p.kind==="trash"){g.openEncryptedTrash();return}if(p.kind==="reveal"){g.app.workspace.revealLeaf(p.leaf);return}if(p.kind==="open"||p.kind==="open-anyway"){await g.activateViewForFolder(p.folder);return}if(p.kind==="switch-current"){let u=s;u&&typeof u.setFolderOverride=="function"&&(await u.setFolderOverride(p.folder),g.app.workspace.revealLeaf(u.leaf));return}if(p.kind==="create"){try{let u=pi(p.folder);await g.app.vault.adapter.exists(u)||await g.app.vault.createFolder(u),await g.activateViewForFolder(u)}catch(u){new M.Notice(`Stashpad: couldn't create folder (${u.message})`)}return}if(p.kind==="convert"){let{ConfirmModal:u}=await Promise.resolve().then(()=>(Ft(),wi)),f=p.folder,C=[`\u201C${f}\u201D already exists as a regular vault folder.`,"Converting adds a Home note + _imports / _exports subfolders, and imports the existing loose files and subfolders inside it as notes.","(Files already structured as notes, and reserved subfolders, are left alone.)"];new u(g.app,"Convert into a Stashpad?",C.join(` -`),"Convert & import",async m=>{if(m)try{await g.activateViewForFolder(f),await g.runImportLooseFiles(f)}catch(B){new M.Notice(`Stashpad: couldn't convert folder (${B.message})`)}}).open();return}}}(this.app);I.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"),I.open()}async openTinyWindow(){let t=ae(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new M.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:K,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(K);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:K,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(K),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 js(this.app);let t=this.app.workspace.getLeavesOfType(we)[0];t&&this.app.workspace.setActiveLeaf(t,{focus:!0})}async reconcileLockedRegistry(){let t=this.settings.lockedSubtrees??[],e=[];for(let n of t){let o=(n.folder??"").replace(/\/+$/,"");if(!(o==="_deleted"||o.startsWith("_deleted/")))try{await this.app.vault.adapter.exists(n.blob)&&e.push(n)}catch{e.push(n)}}let i=e.length!==t.length,s=new Set(e.map(n=>n.blob));for(let n of this.app.vault.getFiles()){if(n.extension!=="stashenc"||s.has(n.path))continue;let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o==="_deleted"||o.startsWith("_deleted/"))continue;let a=await Ya(this.app,n.path);a&&(e.push({folder:o,blob:n.path,parentId:a.parentId,title:a.title,count:a.count,created:a.created,rootId:a.rootId,prevSibling:a.prevSibling}),i=!0)}i&&(this.settings.lockedSubtrees=e,await this.saveSettings(),this.refreshAllStashpadViews?.())}lockedSubtreesFor(t,e){let i=t.replace(/\/+$/,""),s=[],n=new Set;for(let o of this.settings.lockedSubtrees??[])(o.folder??"").replace(/\/+$/,"")===i&&(o.parentId??F)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??F,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let a=o.parent?.path?.replace(/\/+$/,"")??"";a!==i||a==="_deleted"||a.startsWith("_deleted/")||e===F&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:F,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:e,remember:i})=>await this.encryption.unlock(e,i)?(t(!0),null):"Wrong password. Try again.",onCancel:()=>t(!1)}).open()}):(new M.Notice("Set up encryption first (Settings \u2192 Encryption)."),!1)}async lockNoteSubtree(t,e,i=null,s={}){if(!await this.ensureEncryptionUnlocked())return null;let n=this.encryption.getSessionKey();if(!n)return null;try{let o=this.settings.hideLockedTitles??!1,a=await $a(this.app,t,e,n,i,o,s.blobFolder),l=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(A=>A.blob!==a.blobPath),{folder:l,blob:a.blobPath,parentId:a.parentId,title:a.title,count:a.noteCount,created:a.created,rootId:a.rootId,prevSibling:i}],await this.saveSettings(),a.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Locked, but ${a.unpurged.length} file${a.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): +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:ds(this.app,t.path,M.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 l of a){let A=i(l);A&&e.add(A)}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;for(let t of this.app.workspace.getLeavesOfType(J))t.view?.forceReconcileRender?.()},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let C of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(C)?.frontmatter?.id!==t)continue;let B=C.parent?.path;B&&e.add(B)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async C=>{if(C&&!await this.app.vault.adapter.exists(C))try{await this.app.vault.createFolder(C)}catch(m){let B=m?.message??"";if(!/already exists/i.test(B))throw m}},a=0,l=0,A=0,d=0,h=0,g=0,I=!!this.app.vault.getConfig?.("alwaysUpdateLinks"),p=new Set(this.okfActiveFolders());for(let C of e)try{if(i&&await o(`${C}/${i}`),s&&await o(`${C}/${s}`),this.settings.autoImport)try{let y=await this.importService.importLooseInto(C);d+=y.files+y.folders+y.stashes}catch(y){console.warn("Stashpad: loose sweep failed",C,y)}let m=await ei(this.app,C);a+=m.checked,l+=m.written,A+=await this.rebootstrapFolderSlugs(C);let B=await this.rebootstrapFolderAttachments(C,I);if(h+=B.renamed,g+=B.skipped,p.has(C.replace(/\/+$/,"")))try{await wo(this.app,C)}catch(y){console.warn("Stashpad: OKF rebuild during rebootstrap failed",C,y)}n.push(C)}catch(m){console.warn(`Stashpad: rebootstrap skipped ${C}`,m)}let u=0;try{u=(await this.rebuildAuthorRegistry()).total}catch(C){console.warn("Stashpad: rebootstrap author-registry rebuild failed",C)}let f=0;try{f=await this.convertAttachmentsToLinks()}catch(C){console.warn("Stashpad: attachment-link conversion failed",C)}return{touched:n,fmChecked:a,fmWritten:l,slugsRenamed:A,authors:u,imported:d,attachmentsLinked:f,attachmentsRenamed:h,attachmentsSkipped:g}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Yt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let l=he(a.basename);if(!(!l||l===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==l))try{let d=await this.app.vault.cachedRead(a),h=d.startsWith("---")?d.slice(d.indexOf(` +---`,3)+4).replace(/^\r?\n/,""):d,g=Qt(h,s),I=yt(g,l);if(a.name===I)continue;let p=a.parent?`${a.parent.path}/${I}`:I;if(this.app.vault.getAbstractFileByPath(p))continue;await this.app.fileManager.renameFile(a,p),n+=1}catch(d){console.warn(`Stashpad: slug rebootstrap skipped ${a.path}`,d)}}return n}async rebootstrapFolderAttachments(t,e){let i=`${t.replace(/\/+$/,"")}/_attachments`,s=this.app.vault.getAbstractFileByPath(i);if(!(s instanceof M.TFolder))return{renamed:0,skipped:0};let n=s.children.filter(l=>l instanceof M.TFile),o=0,a=0;for(let l of n){let A=Zo(l.name);if(!A)continue;let d=os(A.rest,A.stamp);if(l.name===d)continue;if(!e){a+=1;continue}let h=`${i}/${d}`;if(!this.app.vault.getAbstractFileByPath(h))try{await this.app.fileManager.renameFile(l,h),o+=1,await new Promise(g=>setTimeout(g,30))}catch(g){console.warn(`Stashpad: attachment rebootstrap skipped ${l.path}`,g)}}return{renamed:o,skipped:a}}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?.()!==J)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(Ae);for(let e of t){let i=e.view;i&&typeof i.render=="function"&&i.render()}}refreshAllStashpadViews(){for(let t of this.app.workspace.getLeavesOfType(J)){let e=t.view;e&&typeof e.render=="function"&&e.render()}}openFolderPicker(){let t=p=>{let f=p.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(J),i=this.discoverStashpadFolders(),s=ne(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let p of this.app.vault.getAllLoadedFiles())if(p.children){let u=p.path;u&&u!=="/"&&!u.startsWith(".")&&o.add(u)}let a=p=>{let u=p.split("/").filter(Boolean).pop()??"";return u?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(C=>(C??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(u):!1},l=new Set,A=[],d=[],h=new Set;for(let p of e){let u=t(p);if(h.has(u))continue;h.add(u),l.add(u);let f=u.split("/").pop()||u;A.push({kind:"reveal",folder:u,label:`Reveal "${f}" tab`,leaf:p,icon:this.isArchiveFolder(u)?"archive":"layout-grid"}),d.push({kind:"open-anyway",folder:u,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let p of i.filter(u=>!l.has(u))){let u=p.split("/").pop()||p;A.push({kind:"open",folder:p,label:`Open "${u}" in new tab`,icon:this.isArchiveFolder(p)?"archive":"layout-template"})}let g=this,I=new class extends M.SuggestModal{getSuggestions(p){let u=p.trim().toLowerCase(),f=u?u.split(/\s+/).filter(Boolean):[],C=Q=>{if(!f.length)return!0;let E=Q.toLowerCase();for(let v of f)if(!E.includes(v))return!1;return!0},m=u?A.filter(Q=>{let E="folder"in Q?Q.folder:"";return C(Q.label)||C(E)}):A.slice();if(u&&s&&n)for(let Q of i){if(Q.toLowerCase()===n.toLowerCase())continue;let E=Q.split("/").pop()??Q,v=`${Q} ${E}`;C(v)&&m.push({kind:"switch-current",folder:Q,label:`Switch this tab to "${E}"`,icon:"folder-input"})}let B=p.trim().replace(/^\/+|\/+$/g,"");if(B&&!a(B)){let Q=Array.from(o).find(v=>v.toLowerCase()===B.toLowerCase()),E=i.some(v=>v.toLowerCase()===B.toLowerCase());if(Q&&!E)m.push({kind:"convert",folder:Q,label:`Convert \u201C${pi(Q)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!Q){let v=pi(B);m.push({kind:"create",folder:B,label:`+ Create new Stashpad \u201C${v}\u201D`,icon:"folder-plus"})}}let y=d.filter(Q=>C(Q.label)||C("folder"in Q?Q.folder:""));return m.push(...y),g.encryption?.isConfigured?.()&&C("trash deleted encrypted")&&m.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),m}renderSuggestion(p,u){u.addClass("stashpad-suggest-item"),u.addClass("stashpad-ribbon-suggest-item"),p.kind==="create"&&u.addClass("stashpad-suggest-create");let f=u.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,M.setIcon)(f,p.icon);let C=u.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:p.label}),"folder"in p&&p.folder&&p.label!==p.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:p.folder})}async onChooseSuggestion(p){if(p.kind==="trash"){g.openEncryptedTrash();return}if(p.kind==="reveal"){g.app.workspace.revealLeaf(p.leaf);return}if(p.kind==="open"||p.kind==="open-anyway"){await g.activateViewForFolder(p.folder);return}if(p.kind==="switch-current"){let u=s;u&&typeof u.setFolderOverride=="function"&&(await u.setFolderOverride(p.folder),g.app.workspace.revealLeaf(u.leaf));return}if(p.kind==="create"){try{let u=pi(p.folder);await g.app.vault.adapter.exists(u)||await g.app.vault.createFolder(u),await g.activateViewForFolder(u)}catch(u){new M.Notice(`Stashpad: couldn't create folder (${u.message})`)}return}if(p.kind==="convert"){let{ConfirmModal:u}=await Promise.resolve().then(()=>(Ft(),wi)),f=p.folder,C=[`\u201C${f}\u201D already exists as a regular vault folder.`,"Converting adds a Home note + _imports / _exports subfolders, and imports the existing loose files and subfolders inside it as notes.","(Files already structured as notes, and reserved subfolders, are left alone.)"];new u(g.app,"Convert into a Stashpad?",C.join(` +`),"Convert & import",async m=>{if(m)try{await g.activateViewForFolder(f),await g.runImportLooseFiles(f)}catch(B){new M.Notice(`Stashpad: couldn't convert folder (${B.message})`)}}).open();return}}}(this.app);I.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"),I.open()}async openTinyWindow(){let t=ne(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new M.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:J,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(J);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:J,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(J),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 Xs(this.app);let t=this.app.workspace.getLeavesOfType(Ee)[0];t&&this.app.workspace.setActiveLeaf(t,{focus:!0})}async reconcileLockedRegistry(){let t=this.settings.lockedSubtrees??[],e=[];for(let n of t){let o=(n.folder??"").replace(/\/+$/,"");if(!(o==="_deleted"||o.startsWith("_deleted/")))try{await this.app.vault.adapter.exists(n.blob)&&e.push(n)}catch{e.push(n)}}let i=e.length!==t.length,s=new Set(e.map(n=>n.blob));for(let n of this.app.vault.getFiles()){if(n.extension!=="stashenc"||s.has(n.path))continue;let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o==="_deleted"||o.startsWith("_deleted/"))continue;let a=await hr(this.app,n.path);a&&(e.push({folder:o,blob:n.path,parentId:a.parentId,title:a.title,count:a.count,created:a.created,rootId:a.rootId,prevSibling:a.prevSibling}),i=!0)}i&&(this.settings.lockedSubtrees=e,await this.saveSettings(),this.refreshAllStashpadViews?.())}lockedSubtreesFor(t,e){let i=t.replace(/\/+$/,""),s=[],n=new Set;for(let o of this.settings.lockedSubtrees??[])(o.folder??"").replace(/\/+$/,"")===i&&(o.parentId??F)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??F,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let a=o.parent?.path?.replace(/\/+$/,"")??"";a!==i||a==="_deleted"||a.startsWith("_deleted/")||e===F&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:F,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new vt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:e,remember:i})=>await this.encryption.unlock(e,i)?(t(!0),null):"Wrong password. Try again.",onCancel:()=>t(!1)}).open()}):(new M.Notice("Set up encryption first (Settings \u2192 Encryption)."),!1)}encryptionState(){let t=s=>{let n=s.replace(/\/[^/]*$/,"");return n==="_deleted"||n.startsWith("_deleted/")},e=!1,i=!1;for(let s of this.app.vault.getFiles())if(s.extension==="stashenc"&&(t(s.path)?i=!0:e=!0,e&&i))return{live:e,trash:i};for(let s of this.pendingEncBlobs)if(t(s)?i=!0:e=!0,e&&i)break;return{live:e,trash:i}}async encryptionStateStrict(){let t=this.encryptionState(),e=t.trash;if(!e)try{e=(await Qo(this.app)).length>0}catch{}if(!e)try{e=(await this.app.vault.adapter.list(Mt)).files.some(s=>s.endsWith(".stashenc"))}catch{}return{live:t.live,trash:e}}async lockNoteSubtree(t,e,i=null,s={}){if(!await this.ensureEncryptionUnlocked())return null;let n=this.encryption.getSessionKey();if(!n)return null;try{let o=this.settings.hideLockedTitles??!1,a=await gr(this.app,t,e,n,i,o,s.blobFolder);this.pendingEncBlobs.add(a.blobPath);let l=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(A=>A.blob!==a.blobPath),{folder:l,blob:a.blobPath,parentId:a.parentId,title:a.title,count:a.noteCount,created:a.created,rootId:a.rootId,prevSibling:i}],await this.saveSettings(),a.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Locked, but ${a.unpurged.length} file${a.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): ${a.unpurged.join(` -`)}`,0):s.silent||this.notifications.show({message:`Locked ${a.title?`\u201C${a.title}\u201D`:"a note"} (${a.noteCount} note${a.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),a}catch(o){return console.warn("[Stashpad] lock failed",o),new M.Notice(`Couldn't lock: ${o.message}`),null}}async unlockBundleCore(t,e,i){let s=(i??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,""),n=new Set;for(let o of this.app.vault.getMarkdownFiles())if((o.parent?.path?.replace(/\/+$/,"")??"")===s)try{let a=At(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}return Va(this.app,t,e,n,i)}async unlockBundleAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,"");try{let n=await this.unlockBundleCore(t,i,e.destFolder);return this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(o=>o.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${n.notesWritten} note${n.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:s}),!0}catch(n){return console.warn("[Stashpad] unlock failed",n),new M.Notice(`Couldn't unlock: ${n.message}`),!1}}async lockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=[];for(let d of this.app.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let h;try{h=At(await this.app.vault.read(d)).fm}catch{continue}let g=h.id;typeof g!="string"||g===F||(typeof h.parent=="string"?h.parent:F)!==F||i.push(g)}let s=new Set((this.settings.lockedSubtrees??[]).map(d=>d.rootId).filter(d=>!!d)),n=i.filter(d=>!s.has(d));if(n.length===0)return new M.Notice("Nothing to lock in this folder."),0;let a=(await new ti(this.app).load(e))[F]??[],l=n.length>3?new M.Notice("",0):null,A=0;for(let d=0;d<n.length;d++){let h=n[d];l?.setMessage(`\u{1F512} Encrypting ${d+1}/${n.length}\u2026`);let g=a.indexOf(h),I=g>0?a[g-1]:null;await this.lockNoteSubtree(e,h,I,{silent:!0})&&A++}return l?.hide(),A>0&&this.notifications.show({message:`Locked ${A} note${A===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),A}async unlockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>o.extension==="stashenc"&&(o.parent?.path?.replace(/\/+$/,"")??"")===e).map(o=>o.path);if(i.length===0)return new M.Notice("No locked notes in this folder."),0;let s=i.length>3?new M.Notice("",0):null,n=0;for(let o=0;o<i.length;o++){s?.setMessage(`\u{1F513} Decrypting ${o+1}/${i.length}\u2026`);try{await this.unlockBundleAt(i[o],{silent:!0})&&n++}catch(a){console.warn("[Stashpad] folder unlock skipped",i[o],a)}}return s?.hide(),n>0&&this.notifications.show({message:`Unlocked ${n} note${n===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),n}async unlockAllInVault(){if(!await this.ensureEncryptionUnlocked())return 0;let t=this.app.vault.getFiles().filter(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(a=>a.path);if(t.length===0)return new M.Notice("No locked notes anywhere in the vault."),0;let e=this.encryption.getSessionKey();if(!e)return 0;let i=t.length>3?new M.Notice("",0):null,s=0,n=[];for(let a=0;a<t.length;a++){i?.setMessage(`\u{1F513} Decrypting ${a+1}/${t.length}\u2026`);try{let l=await this.unlockBundleCore(t[a],e);s+=l.notesWritten,n.push(t[a])}catch(l){console.warn("[Stashpad] vault unlock skipped",t[a],l)}}if(n.length>0){let a=new Set(n);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(l=>!a.has(l.blob)),await this.saveSettings()}i?.hide();let o=t[0].replace(/\/[^/]*$/,"");return s>0&&this.notifications.show({message:`Unlocked ${s} note${s===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:o}),s}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),n=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),o=await Wa(this.app,t,e,i,s,n);return o.unpurged.length>0&&new M.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${o.unpurged.length} file${o.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): +`)}`,0):s.silent||this.notifications.show({message:`Locked ${a.title?`\u201C${a.title}\u201D`:"a note"} (${a.noteCount} note${a.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),a}catch(o){return console.warn("[Stashpad] lock failed",o),new M.Notice(`Couldn't lock: ${o.message}`),null}}async unlockBundleCore(t,e,i){let s=(i??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,""),n=new Set;for(let o of this.app.vault.getMarkdownFiles())if((o.parent?.path?.replace(/\/+$/,"")??"")===s)try{let a=ct(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}return Ir(this.app,t,e,n,i)}async unlockBundleAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,"");try{let n=await this.unlockBundleCore(t,i,e.destFolder);return this.pendingEncBlobs.delete(t),this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(o=>o.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${n.notesWritten} note${n.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:s}),!0}catch(n){return console.warn("[Stashpad] unlock failed",n),new M.Notice(`Couldn't unlock: ${n.message}`),!1}}async lockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=[];for(let d of this.app.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let h;try{h=ct(await this.app.vault.read(d)).fm}catch{continue}let g=h.id;typeof g!="string"||g===F||(typeof h.parent=="string"?h.parent:F)!==F||i.push(g)}let s=new Set((this.settings.lockedSubtrees??[]).map(d=>d.rootId).filter(d=>!!d)),n=i.filter(d=>!s.has(d));if(n.length===0)return new M.Notice("Nothing to lock in this folder."),0;let a=(await new _e(this.app).load(e))[F]??[],l=n.length>3?new M.Notice("",0):null,A=0;for(let d=0;d<n.length;d++){let h=n[d];l?.setMessage(`\u{1F512} Encrypting ${d+1}/${n.length}\u2026`);let g=a.indexOf(h),I=g>0?a[g-1]:null;await this.lockNoteSubtree(e,h,I,{silent:!0})&&A++}return l?.hide(),A>0&&this.notifications.show({message:`Locked ${A} note${A===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),A}async unlockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>o.extension==="stashenc"&&(o.parent?.path?.replace(/\/+$/,"")??"")===e).map(o=>o.path);if(i.length===0)return new M.Notice("No locked notes in this folder."),0;let s=i.length>3?new M.Notice("",0):null,n=0;for(let o=0;o<i.length;o++){s?.setMessage(`\u{1F513} Decrypting ${o+1}/${i.length}\u2026`);try{await this.unlockBundleAt(i[o],{silent:!0})&&n++}catch(a){console.warn("[Stashpad] folder unlock skipped",i[o],a)}}return s?.hide(),n>0&&this.notifications.show({message:`Unlocked ${n} note${n===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),n}async unlockAllInVault(){if(!await this.ensureEncryptionUnlocked())return 0;let t=this.app.vault.getFiles().filter(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(a=>a.path);if(t.length===0)return new M.Notice("No locked notes anywhere in the vault."),0;let e=this.encryption.getSessionKey();if(!e)return 0;let i=t.length>3?new M.Notice("",0):null,s=0,n=[];for(let a=0;a<t.length;a++){i?.setMessage(`\u{1F513} Decrypting ${a+1}/${t.length}\u2026`);try{let l=await this.unlockBundleCore(t[a],e);s+=l.notesWritten,n.push(t[a])}catch(l){console.warn("[Stashpad] vault unlock skipped",t[a],l)}}if(n.length>0){let a=new Set(n);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(l=>!a.has(l.blob)),await this.saveSettings()}i?.hide();let o=t[0].replace(/\/[^/]*$/,"");return s>0&&this.notifications.show({message:`Unlocked ${s} note${s===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:o}),s}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),n=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),o=await ur(this.app,t,e,i,s,n);return this.pendingEncBlobs.add(o.blobPath),o.unpurged.length>0&&new M.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${o.unpurged.length} file${o.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): ${o.unpurged.join(` -`)}`,0),o.blobPath}catch(s){return console.warn("[Stashpad] encrypt-delete failed",s),new M.Notice(`Couldn't encrypt-delete: ${s.message}`,0),null}}async restoreDeletedAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=await Ss(this.app,t);if(s?.kind==="rawtrash")try{let n=await ja(this.app,t,i);return e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Rt}/).`,kind:"success",category:"system",folder:""}),!0}catch(n){return console.warn("[Stashpad] trash-backfill restore failed",n),new M.Notice(`Couldn't restore: ${n.message}`,0),!1}try{let n=await oo(this.app,t,s,i),o=new Set;for(let l of this.app.vault.getMarkdownFiles())if((l.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let A=At(await this.app.vault.read(l)).fm.id;typeof A=="string"&&o.add(A)}catch{}let a=await Xa(this.app,t,i,o);return e.silent||this.notifications.show({message:`Restored ${a.notesWritten} note${a.notesWritten===1?"":"s"} to \u201C${a.restoredTo.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:a.restoredTo}),!0}catch(n){return console.warn("[Stashpad] restore-from-trash failed",n),new M.Notice(`Couldn't restore: ${n.message}`,0),!1}}async listDeletedTrash(){let t=await _a(this.app),e=[];for(let i of t)e.push({blob:i,meta:await Ss(this.app,i)});return e}async restoreAllTrash(){if(!await this.ensureEncryptionUnlocked())return 0;let t=await this.listDeletedTrash();if(t.length===0)return new M.Notice("Nothing to restore."),0;let e=t.length>3?new M.Notice("",0):null,i=0;for(let s=0;s<t.length;s++){e?.setMessage(`\u{1F513} Restoring ${s+1}/${t.length}\u2026`);try{await this.restoreDeletedAt(t[s].blob,{silent:!0})&&i++}catch(n){console.warn("[Stashpad] restore-all skipped",t[s].blob,n)}}return e?.hide(),i>0&&this.notifications.show({message:`Restored ${i} note${i===1?"":"s"} from encrypted trash.`,kind:"success",category:"system",folder:""}),i}async encryptExistingTrash(){if(!await this.ensureEncryptionUnlocked())return!1;let t=this.encryption.getSessionKey();if(!t)return!1;try{let e=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),i=await Za(this.app,t,new Date().toISOString(),e);return i?(i.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Encrypted the trash, but ${i.unpurged.length} file${i.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed): +`)}`,0),o.blobPath}catch(s){return console.warn("[Stashpad] encrypt-delete failed",s),new M.Notice(`Couldn't encrypt-delete: ${s.message}`,0),null}}async restoreDeletedAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=await js(this.app,t);if(s?.kind==="rawtrash")try{let n=await mr(this.app,t,i);return this.pendingEncBlobs.delete(t),e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Mt}/).`,kind:"success",category:"system",folder:""}),!0}catch(n){return console.warn("[Stashpad] trash-backfill restore failed",n),new M.Notice(`Couldn't restore: ${n.message}`,0),!1}try{let n=await mo(this.app,t,s,i),o=new Set;for(let l of this.app.vault.getMarkdownFiles())if((l.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let A=ct(await this.app.vault.read(l)).fm.id;typeof A=="string"&&o.add(A)}catch{}let a=await fr(this.app,t,i,o);return this.pendingEncBlobs.delete(t),e.silent||this.notifications.show({message:`Restored ${a.notesWritten} note${a.notesWritten===1?"":"s"} to \u201C${a.restoredTo.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:a.restoredTo}),!0}catch(n){return console.warn("[Stashpad] restore-from-trash failed",n),new M.Notice(`Couldn't restore: ${n.message}`,0),!1}}async purgeDeletedAt(t){try{return await Bo(this.app,t),this.pendingEncBlobs.delete(t),!0}catch(e){return console.warn("[Stashpad] purge-from-trash failed",t,e),new M.Notice(`Couldn't delete: ${e.message}`,0),!1}}async purgeAllLockedContent(){let t=s=>{let n=s.replace(/\/[^/]*$/,"");return n==="_deleted"||n.startsWith("_deleted/")},e=new Set;for(let s of this.app.vault.getFiles())s.extension==="stashenc"&&!t(s.path)&&e.add(s.path);for(let s of this.pendingEncBlobs)t(s)||e.add(s);let i=0;for(let s of e)try{await Bo(this.app,s),this.pendingEncBlobs.delete(s),i++}catch(n){console.warn("[Stashpad] purge locked content failed",s,n)}return this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(s=>!e.has(s.blob)),await this.saveSettings(),i}async listDeletedTrash(){let t=await Qo(this.app),e=[];for(let i of t)e.push({blob:i,meta:await js(this.app,i)});return e}async restoreAllTrash(){if(!await this.ensureEncryptionUnlocked())return 0;let t=await this.listDeletedTrash();if(t.length===0)return new M.Notice("Nothing to restore."),0;let e=t.length>3?new M.Notice("",0):null,i=0;for(let s=0;s<t.length;s++){e?.setMessage(`\u{1F513} Restoring ${s+1}/${t.length}\u2026`);try{await this.restoreDeletedAt(t[s].blob,{silent:!0})&&i++}catch(n){console.warn("[Stashpad] restore-all skipped",t[s].blob,n)}}return e?.hide(),i>0&&this.notifications.show({message:`Restored ${i} note${i===1?"":"s"} from encrypted trash.`,kind:"success",category:"system",folder:""}),i}async encryptExistingTrash(){if(!await this.ensureEncryptionUnlocked())return!1;let t=this.encryption.getSessionKey();if(!t)return!1;try{let e=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),i=await Cr(this.app,t,new Date().toISOString(),e);return i?(i.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Encrypted the trash, but ${i.unpurged.length} file${i.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed): ${i.unpurged.join(` -`)}`,0):this.notifications.show({message:`Encrypted ${i.fileCount} trash file${i.fileCount===1?"":"s"} into the encrypted trash. Restore from the trash tab puts them back in ${Rt}/.`,kind:"success",category:"system",folder:""}),!0):(new M.Notice(`Obsidian's vault trash (${Rt}/) is empty \u2014 nothing to encrypt. (Files in the system/OS trash can't be reached.)`,8e3),!1)}catch(e){return console.warn("[Stashpad] trash backfill failed",e),new M.Notice(`Couldn't encrypt the existing trash: ${e.message}`,0),!1}}openEncryptedTrash(t){if(!this.encryption.isConfigured()){new M.Notice("Set up encryption first (Settings \u2192 Encryption).");return}Br(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new M.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=await this.listDeletedTrash();if(t.length===0){new M.Notice("Encrypted trash is empty.");return}let e=t.map(({blob:i,meta:s})=>({blob:i,label:s?.title||i.split("/").pop()?.replace(/\.stashenc$/,"")||"Locked note",folder:s?.originalFolder||"(unknown)"}));new Ws(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)}async ensureOkfTemplate(){let t=await yr(this.app,this.settings.okfTemplatePath||void 0);return this.settings.okfTemplatePath!==t&&(this.settings.okfTemplatePath=t,await this.saveSettings()),t}okfTemplatePathOrDefault(){return this.settings.okfTemplatePath||yo}okfActiveFolders(){return this.settings.okfEnabled?Er(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}async rebuildOkfSuppressed(t){this.okfRebuildingFolders.add(t);try{return await wo(this.app,t)}finally{window.setTimeout(()=>{this.okfRebuildingFolders.delete(t);for(let e of this.app.workspace.getLeavesOfType(K)){let i=e.view;i?.noteFolder===t&&i.forceReconcileRender?.()}},600)}}onOkfFileEvent(t){if(!this.settings.okfEnabled||!t.toLowerCase().endsWith(".md"))return;let e=t.lastIndexOf("/"),i=(e>=0?t.slice(0,e):"").replace(/\/+$/,"");(e>=0?t.slice(e+1):t)!=="index.md"&&(/(^|\/)(_imports|_exports|_attachments|_deleted|\.stashpad)(\/|$)/.test(t)||this.okfActiveFolders().includes(i)&&this.scheduleOkfRebuild(i))}scheduleOkfRebuild(t){let e=this.okfRebuildTimers.get(t);e!=null&&window.clearTimeout(e),this.okfRebuildTimers.set(t,window.setTimeout(()=>{this.okfRebuildTimers.delete(t),this.okfActiveFolders().includes(t)&&this.rebuildOkfSuppressed(t).catch(i=>console.warn("[Stashpad] OKF auto-rebuild failed",t,i))},2500))}async rebuildAllOkf(){let t=this.okfActiveFolders(),e=0,i=0;for(let s of t){let n=await this.rebuildOkfSuppressed(s);e+=n.checked,i+=n.written}return{folders:t.length,checked:e,written:i}}async exportOkf(t,e,i,s){let n=t.replace(/\/+$/,""),o=[],a=[],l=[],A=new Set;for(let f of e){let C=await Ce(this.app,n,f);if(C){o.push({id:C.rootNote.id,file:C.rootNote.file}),l.push(C.rootNote.file),A.add(C.rootNote.id);for(let m of C.descendants)a.push({id:m.id,file:m.file}),l.push(m.file),A.add(m.id)}}if(!l.length)return[];let d=(i||"okf-export").replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim().slice(0,80)||"okf-export",h=new Date().toISOString().replace(/\D/g,"").slice(0,14),g=(this.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),I=`${n}/${g}`;for(let f of[n,I])try{await this.app.vault.adapter.exists(f)||await this.app.vault.adapter.mkdir(f)}catch{}let p=[],u=async(f,C)=>{let m=`${I}/${f}`;await this.app.vault.createBinary(m,C.buffer.slice(C.byteOffset,C.byteOffset+C.byteLength)),p.push(m)};if(s.zip||s.targz){let f=await wr(this.app,l,n,A);s.zip&&await u(`${d}-${h}.okf.zip`,await vr(f)),s.targz&&await u(`${d}-${h}.okf.tar.gz`,await Fr(f))}if(s.stash){let f=await ge(this.app,{rootNotes:o,allDescendants:a,sourceFolder:n});await u(`${d}-${h}.${oe}`,f)}return p}async idsInFolder(t){let e=t.replace(/\/+$/,""),i=new Set;for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===e)try{let n=At(await this.app.vault.read(s)).fm.id;typeof n=="string"&&i.add(n)}catch{}return i}async crossFolderPaste(t,e,i,s,n){let o=i.replace(/\/+$/,"");if(this.isArchiveFolder(o))return new M.Notice(`"${o.split("/").pop()}" auto-encrypts notes moved in, so cross-folder paste is disabled there. Use the "Move to archive" command \u2014 it checks the encryption key first.`),null;let a=[],l=[],A=[],d=[];for(let w of e){let D=await Ce(this.app,t,w);if(D){A.push(D.rootNote.id),a.push({id:D.rootNote.id,file:D.rootNote.file}),d.push(D.rootNote.file);for(let N of D.descendants)l.push({id:N.id,file:N.file}),d.push(N.file)}}if(!a.length)return null;let h=a.length+l.length,g=[],I=[];n==="cut"&&(g=await this.exclusiveAttachmentsOf(d),I=await this.snapshotPaths([...d.map(w=>w.path),...g.map(w=>w.path)]));let p=await ge(this.app,{rootNotes:a,allDescendants:l,sourceFolder:t}),u=await this.idsInFolder(o),f=new Set(this.filesUnder(o)),C=await Vt(this.app,p,o,u,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),m=this.filesUnder(o).filter(w=>!f.has(w)),B=await this.snapshotPaths(m),y=A.map(w=>C.idRemap[w]).filter(w=>!!w);if(n==="cut"){for(let w of d)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source note",w.path,D)}for(let w of g)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",w.path,D)}}let Q=async()=>{for(let w of[...m].reverse()){let D=this.app.vault.getAbstractFileByPath(w);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}};return{rootIds:y,noteCount:h,undo:n==="cut"?async()=>{await Q(),await this.restoreSnapshot(I)}:async()=>{await Q()},redo:n==="cut"?async()=>{await this.restoreSnapshot(B);for(let w of I){let D=this.app.vault.getAbstractFileByPath(w.path);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}}:async()=>{await this.restoreSnapshot(B)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let a=await Ce(this.app,t,o);a&&i.push(a.rootNote.file,...a.descendants.map(l=>l.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i),n=[];for(let o of[...i,...s])try{await this.app.fileManager.trashFile(o),n.push(o)}catch(a){console.warn("[Stashpad] trashSubtrees: couldn't trash",o.path,a)}return n}async exclusiveAttachmentsOf(t){let e=new Set(t.map(n=>n.path)),i=new Map;for(let n of t)for(let o of await Fs(this.app,n))i.set(o.path,o);let s=this.app.metadataCache.resolvedLinks??{};for(let n of Object.keys(s))if(!e.has(n))for(let o of Object.keys(s[n]??{}))i.delete(o);return[...i.values()]}async subtreeFilePaths(t,e){let i=[];for(let n of e){let o=await Ce(this.app,t,n);o&&i.push(o.rootNote.file,...o.descendants.map(a=>a.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i);return[...i.map(n=>n.path),...s.map(n=>n.path)]}async orderedSubtreeNodes(t,e){let i=[],s=new Set,n=o=>{let a=this.app.metadataCache.getFileCache(o)?.frontmatter?.position;return typeof a=="number"?a:Number.MAX_SAFE_INTEGER};for(let o of e){let a=await Ce(this.app,t,o);if(!a)continue;let l=new Map;for(let d of a.descendants){if(!d.parent)continue;let h=l.get(d.parent)??[];h.push({id:d.id,file:d.file,created:d.created}),l.set(d.parent,h)}for(let d of l.values())d.sort((h,g)=>n(h.file)-n(g.file)||h.created.localeCompare(g.created));let A=(d,h)=>{if(!s.has(d.id)){s.add(d.id),i.push({file:d.file,created:d.created,depth:h});for(let g of l.get(d.id)??[])A(g,h+1)}};A({id:a.rootNote.id,file:a.rootNote.file,created:a.rootNote.created},0)}return i}filesUnder(t){let e=t.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(i=>i.path.startsWith(e)).map(i=>i.path)}async snapshotPaths(t){let e=[];for(let i of t){let s=this.app.vault.getAbstractFileByPath(i);if(!s)continue;let n=!i.toLowerCase().endsWith(".md");try{n?e.push({path:i,binary:n,data:await this.app.vault.readBinary(s)}):e.push({path:i,binary:n,text:await this.app.vault.read(s)})}catch(o){console.warn("[Stashpad] snapshotPaths: couldn't read",i,o)}}return e}async restoreSnapshot(t){for(let e of t){let i=e.path.split("/").slice(0,-1).join("/");await this.ensureVaultFolder(i);let s=this.app.vault.getAbstractFileByPath(e.path);try{e.binary?s?await this.app.vault.adapter.writeBinary(e.path,e.data):await this.app.vault.createBinary(e.path,e.data):s?await this.app.vault.modify(s,e.text??""):await this.app.vault.create(e.path,e.text??"")}catch(n){console.warn("[Stashpad] restoreSnapshot: couldn't write",e.path,n)}}}async ensureVaultFolder(t){if(!t)return;let e="";for(let i of t.split("/"))if(e=e?`${e}/${i}`:i,!await this.app.vault.adapter.exists(e))try{await this.app.vault.createFolder(e)}catch{}}refreshOpenViewsForFolder(t){let e=t.replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(K)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,""),s=[];for(let A of e){let d=this.app.vault.getAbstractFileByPath(A);if(!(d instanceof M.TFile)||(d.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let h;try{h=At(await this.app.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===F||s.push({id:g,parent:typeof h.parent=="string"?h.parent:null})}if(s.length===0)return;let n=new Set(s.map(A=>A.id)),o=new Set((this.settings.lockedSubtrees??[]).map(A=>A.rootId).filter(A=>!!A)),a=s.filter(A=>!o.has(A.id)&&!(A.parent&&n.has(A.parent)));if(a.length===0)return;if(!await this.ensureEncryptionUnlocked()){new M.Notice(`\u26A0\uFE0F Archive folder "${i.split("/").pop()}": ${a.length} arriving note${a.length===1?"":"s"} NOT encrypted (vault is locked). Unlock encryption and lock them manually.`,0);return}let l=0;for(let A of a)await this.lockNoteSubtree(i,A.id,null,{silent:!0})&&l++;l>0&&this.notifications.show({message:`Archived (encrypted) ${l} note${l===1?"":"s"} moved into \u201C${i.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:i})}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return null;let i=this.app.workspace.getLeaf("tab");return await i.setViewState({type:K,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(i),i}navigateLeafTo(t,e,i){let s=t?.view;if(s?.navigateTo&&(!s.tree||s.tree.get(i))){s.navigateTo(i);return}this.navigateWhenReady(e,i)}async openFolderInStashpad(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=await this.findStashpadLeafForFolder(e);if(i){this.app.workspace.revealLeaf(i),this.app.workspace.setActiveLeaf(i,{focus:!0});return}await this.activateViewForFolder(e)}async findStashpadLeafForFolder(t){let e=t.replace(/\/+$/,""),i=this.app.workspace.getLeavesOfType(K),s=i.find(o=>!o.isDeferred&&(o.view?.noteFolder??"").replace(/\/+$/,"")===e);if(s)return s;let n=i.find(o=>o.isDeferred&&(o.getViewState()?.state?.folderOverride??"").replace(/\/+$/,"")===e);if(n){try{await n.loadIfDeferred?.()}catch{}return n}return null}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 M.Notice("That note isn't a Stashpad note.");return}await this.revealNoteByRef(e,i)}async revealNoteByRef(t,e){let i=t.replace(/\/+$/,""),s=await this.findStashpadLeafForFolder(i);if(s){this.app.workspace.revealLeaf(s),this.app.workspace.setActiveLeaf(s,{focus:!0}),this.navigateLeafTo(s,i,e);return}let n=await this.activateViewForFolder(i);this.navigateLeafTo(n,i,e)}async closeDuplicateStashpadTabs(){let t=this.app.workspace.getLeavesOfType(K),e=this.app.workspace.activeLeaf;for(let p of t)try{await p.loadIfDeferred?.()}catch{}let i=p=>p.getViewState()?.state??{},s=p=>{let u=i(p);return(p.isDeferred?u.folderOverride??"":p.view?.noteFolder??u.folderOverride??"").replace(/\/+$/,"")},n=p=>{let u=i(p);return(p.isDeferred?u.focusId:p.view?.focusId??u.focusId)||F},o=p=>{let u=p.view;return!!u&&u.getViewType?.()===K&&typeof u.navigateTo=="function"&&typeof u.noteFolder=="string"},a=new Map;for(let p of this.app.vault.getMarkdownFiles()){let u=(p.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(p)?.frontmatter?.id;typeof f=="string"&&f&&(a.get(u)??a.set(u,new Set).get(u)).add(f)}let l=0,A=[];for(let p of t){let u=s(p),f=n(p);if(u&&f&&f!==F){let C=!p.isDeferred&&!!p.view?.tree?.get?.(f),m=a.get(u)?.has(f)??!1;if(!C&&!m){p.detach(),l++;continue}}A.push(p)}let d=new Map;for(let p of A){let u=s(p);if(!u)continue;let f=u+" "+n(p);(d.get(f)??d.set(f,[]).get(f)).push(p)}let h=0;for(let p of d.values()){if(p.length<=1)continue;p.sort((f,C)=>{let m=B=>B===e?2:B.isDeferred?0:1;return m(C)-m(f)});let u=null;for(let f of p){try{await f.loadIfDeferred?.()}catch{}if(o(f)){u=f;break}}u||(u=p[0]);for(let f of p)f!==u&&(f.detach(),h++)}let g=this.app.workspace.getLeavesOfType(K).length,I=document.createDocumentFragment();return I.createEl("div",{text:h+l>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),I.createEl("div",{text:`\u2022 ${h} duplicate tab${h===1?"":"s"} closed`}),I.createEl("div",{text:`\u2022 ${l} orphaned tab${l===1?"":"s"} pruned (note no longer exists)`}),I.createEl("div",{text:`\u2022 ${g} Stashpad tab${g===1?"":"s"} remaining`}),new M.Notice(I,7e3),h+l}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(K).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:"",l=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],A=a.includes(e),d=l.some(p=>p.includes(e));if(!A&&!d)continue;let h=n.parent?.path??"",g=i.find(p=>h===p||h.startsWith(p+"/"));if(!g)continue;s.has(g)||s.set(g,{authored:0,contributed:0});let I=s.get(g);A&&I.authored++,d&&I.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return Ae(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!1;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(A=>A.path.startsWith(s+"/")&&this.parseAuthorFilePath(A.path)?.id===e))return!1;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),l=`${s}/${a}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(l)?!1:(await this.app.vault.create(l,this.buildAuthorStub({id:e,name:i,role:o?.role,department:o?.department},new Date().toISOString())),!0)}catch(A){return console.warn("[Stashpad] ensureAuthorStubFor failed",l,A),!1}}async seedKnownAuthorsInFolder(t){let e=0;for(let i of this.collectKnownAuthors())await this.ensureAuthorStubFor(t,i.id,i.name)&&e++;return e}async checkDueReminders(){let t=Date.now(),e=new Set(this.settings.notifiedDueKeys??[]),i=(this.settings.authorId??"").trim(),s=[];for(let o of this.app.vault.getMarkdownFiles()){if(o.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!a||a.due==null)continue;let l=typeof a.id=="string"?a.id:"";if(!l)continue;let A=String(a.due),d=typeof a.due=="number"?a.due:Date.parse(A);if(!Number.isFinite(d)||d>t)continue;let h=ke(a);if(h.length>0&&!(i&&h.some(I=>I.id===i)))continue;let g=`${l}@${A}`;e.has(g)||s.push({id:l,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:d,key:g})}if(s.length===0)return;this.settings.notifiedDueKeys=[...this.settings.notifiedDueKeys??[],...s.map(o=>o.key)].slice(-2e3),await this.saveSettings();let n=async o=>{try{let l=At(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(A=>A.trim()).find(A=>A.length>0);if(l)return l.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(s.length<=3)for(let o of s){let a=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${a}\u201D (${jt(o.dueMs,this.settings)})`,kind:"warning",category:"reminder",duration:0,folder:o.folder,affectedIds:[o.id],actions:[{label:"Open",onClick:()=>void this.revealNoteByRef(o.folder,o.id)}]})}else this.notifications.show({message:`\u23F0 ${s.length} tasks are due \u2014 open the Tasks panel to review.`,kind:"warning",category:"reminder",duration:0,folder:""})}async syncAuthorsAcrossFolders(){await this.rebuildAuthorRegistry();let t=this.collectKnownAuthors(),e=this.discoverStashpadFolders();if(!t.length||!e.length){new M.Notice("No authors or Stashpad folders to sync.");return}let i=e.length*t.length>8?new M.Notice("",0):null,s=0;for(let n of e){i?.setMessage(`Syncing authors \u2192 ${n.split("/").pop()}\u2026`);for(let o of t)await this.ensureAuthorStubFor(n,o.id,o.name)&&s++}i?.hide(),this.notifications.show({message:`Synced authors across ${e.length} folder${e.length===1?"":"s"} \u2014 ${s} new stub${s===1?"":"s"} (${t.length} author${t.length===1?"":"s"} known).`,kind:"success",category:"system",folder:""})}collectKnownAuthors(){let t=new Map,e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();e&&i&&t.set(e,i);for(let s of this.authorRegistry.all())t.has(s.id)||t.set(s.id,s.name);for(let s of this.app.vault.getMarkdownFiles()){if(!s.path.includes("/_authors/"))continue;let n=this.parseAuthorFilePath(s.path);if(!n)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter,l=((Array.isArray(o?.aliases)?o.aliases.find(A=>typeof A=="string")??"":typeof o?.aliases=="string"?o.aliases:"")||(typeof o?.name=="string"?o.name:"")||n.name).trim();t.has(n.id)||t.set(n.id,l),this.authorRegistry.record({id:n.id,name:l})}return[...t.entries()].map(([s,n])=>({id:s,name:n}))}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 l of o.contributors)typeof l=="string"&&a.push(l);for(let l of a){let A=this.parseAuthorRef(l);if(A)if(!e.has(A.id))e.set(A.id,{id:A.id,name:A.name,fromStub:!1}),i++;else{let d=e.get(A.id);!d.name&&A.name&&(d.name=A.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 l=this.parseAuthorFilePath(a.path);if(!l)continue;let A=this.app.metadataCache.getFileCache(a)?.frontmatter,h=((Array.isArray(A?.aliases)?A.aliases.find(u=>typeof u=="string")??"":typeof A?.aliases=="string"?A.aliases:"")||(typeof A?.name=="string"?A.name:"")||l.name).trim(),g=typeof A?.role=="string"?A.role:void 0,I=typeof A?.department=="string"?A.department:void 0,p=e.get(l.id);p||s++,e.set(l.id,{id:l.id,name:h||p?.name,role:g??p?.role,department:I??p?.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(` +`)}`,0):this.notifications.show({message:`Encrypted ${i.fileCount} trash file${i.fileCount===1?"":"s"} into the encrypted trash. Restore from the trash tab puts them back in ${Mt}/.`,kind:"success",category:"system",folder:""}),!0):(new M.Notice(`Obsidian's vault trash (${Mt}/) is empty \u2014 nothing to encrypt. (Files in the system/OS trash can't be reached.)`,8e3),!1)}catch(e){return console.warn("[Stashpad] trash backfill failed",e),new M.Notice(`Couldn't encrypt the existing trash: ${e.message}`,0),!1}}openEncryptedTrash(t){if(!this.encryption.isConfigured()){new M.Notice("Set up encryption first (Settings \u2192 Encryption).");return}dr(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new M.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=await this.listDeletedTrash();if(t.length===0){new M.Notice("Encrypted trash is empty.");return}let e=t.map(({blob:i,meta:s})=>({blob:i,label:s?.title||i.split("/").pop()?.replace(/\.stashenc$/,"")||"Locked note",folder:s?.originalFolder||"(unknown)"}));new zs(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)}async ensureOkfTemplate(){let t=await Qr(this.app,this.settings.okfTemplatePath||void 0);return this.settings.okfTemplatePath!==t&&(this.settings.okfTemplatePath=t,await this.saveSettings()),t}okfTemplatePathOrDefault(){return this.settings.okfTemplatePath||yo}okfActiveFolders(){return this.settings.okfEnabled?yr(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}async rebuildOkfSuppressed(t){this.okfRebuildingFolders.add(t);try{return await wo(this.app,t)}finally{window.setTimeout(()=>{this.okfRebuildingFolders.delete(t);for(let e of this.app.workspace.getLeavesOfType(J)){let i=e.view;i?.noteFolder===t&&i.forceReconcileRender?.()}},600)}}onOkfFileEvent(t){if(!this.settings.okfEnabled||!t.toLowerCase().endsWith(".md"))return;let e=t.lastIndexOf("/"),i=(e>=0?t.slice(0,e):"").replace(/\/+$/,"");(e>=0?t.slice(e+1):t)!=="index.md"&&(/(^|\/)(_imports|_exports|_attachments|_deleted|\.stashpad)(\/|$)/.test(t)||this.okfActiveFolders().includes(i)&&this.scheduleOkfRebuild(i))}scheduleOkfRebuild(t){let e=this.okfRebuildTimers.get(t);e!=null&&window.clearTimeout(e),this.okfRebuildTimers.set(t,window.setTimeout(()=>{this.okfRebuildTimers.delete(t),this.okfActiveFolders().includes(t)&&this.rebuildOkfSuppressed(t).catch(i=>console.warn("[Stashpad] OKF auto-rebuild failed",t,i))},2500))}async rebuildAllOkf(){let t=this.okfActiveFolders(),e=0,i=0;for(let s of t){let n=await this.rebuildOkfSuppressed(s);e+=n.checked,i+=n.written}return{folders:t.length,checked:e,written:i}}async exportOkf(t,e,i,s){let n=t.replace(/\/+$/,""),o=[],a=[],l=[],A=new Set;for(let f of e){let C=await Be(this.app,n,f);if(C){o.push({id:C.rootNote.id,file:C.rootNote.file}),l.push(C.rootNote.file),A.add(C.rootNote.id);for(let m of C.descendants)a.push({id:m.id,file:m.file}),l.push(m.file),A.add(m.id)}}if(!l.length)return[];let d=(i||"okf-export").replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim().slice(0,80)||"okf-export",h=new Date().toISOString().replace(/\D/g,"").slice(0,14),g=(this.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),I=`${n}/${g}`;for(let f of[n,I])try{await this.app.vault.adapter.exists(f)||await this.app.vault.adapter.mkdir(f)}catch{}let p=[],u=async(f,C)=>{let m=`${I}/${f}`;await this.app.vault.createBinary(m,C.buffer.slice(C.byteOffset,C.byteOffset+C.byteLength)),p.push(m)};if(s.zip||s.targz){let f=await Er(this.app,l,n,A);s.zip&&await u(`${d}-${h}.okf.zip`,await wr(f)),s.targz&&await u(`${d}-${h}.okf.tar.gz`,await vr(f))}if(s.stash){let f=await Ce(this.app,{rootNotes:o,allDescendants:a,sourceFolder:n});await u(`${d}-${h}.${re}`,f)}return p}async idsInFolder(t){let e=t.replace(/\/+$/,""),i=new Set;for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===e)try{let n=ct(await this.app.vault.read(s)).fm.id;typeof n=="string"&&i.add(n)}catch{}return i}async crossFolderPaste(t,e,i,s,n){let o=i.replace(/\/+$/,"");if(this.isArchiveFolder(o))return new M.Notice(`"${o.split("/").pop()}" auto-encrypts notes moved in, so cross-folder paste is disabled there. Use the "Move to archive" command \u2014 it checks the encryption key first.`),null;let a=[],l=[],A=[],d=[];for(let w of e){let D=await Be(this.app,t,w);if(D){A.push(D.rootNote.id),a.push({id:D.rootNote.id,file:D.rootNote.file}),d.push(D.rootNote.file);for(let N of D.descendants)l.push({id:N.id,file:N.file}),d.push(N.file)}}if(!a.length)return null;let h=a.length+l.length,g=[],I=[];n==="cut"&&(g=await this.exclusiveAttachmentsOf(d),I=await this.snapshotPaths([...d.map(w=>w.path),...g.map(w=>w.path)]));let p=await Ce(this.app,{rootNotes:a,allDescendants:l,sourceFolder:t}),u=await this.idsInFolder(o),f=new Set(this.filesUnder(o)),C=await Wt(this.app,p,o,u,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),m=this.filesUnder(o).filter(w=>!f.has(w)),B=await this.snapshotPaths(m),y=A.map(w=>C.idRemap[w]).filter(w=>!!w);if(n==="cut"){for(let w of d)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source note",w.path,D)}for(let w of g)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",w.path,D)}}let Q=async()=>{for(let w of[...m].reverse()){let D=this.app.vault.getAbstractFileByPath(w);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}};return{rootIds:y,noteCount:h,undo:n==="cut"?async()=>{await Q(),await this.restoreSnapshot(I)}:async()=>{await Q()},redo:n==="cut"?async()=>{await this.restoreSnapshot(B);for(let w of I){let D=this.app.vault.getAbstractFileByPath(w.path);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}}:async()=>{await this.restoreSnapshot(B)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let a=await Be(this.app,t,o);a&&i.push(a.rootNote.file,...a.descendants.map(l=>l.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i),n=[];for(let o of[...i,...s])try{await this.app.fileManager.trashFile(o),n.push(o)}catch(a){console.warn("[Stashpad] trashSubtrees: couldn't trash",o.path,a)}return n}async exclusiveAttachmentsOf(t){let e=new Set(t.map(n=>n.path)),i=new Map;for(let n of t)for(let o of await Ks(this.app,n))i.set(o.path,o);let s=this.app.metadataCache.resolvedLinks??{};for(let n of Object.keys(s))if(!e.has(n))for(let o of Object.keys(s[n]??{}))i.delete(o);return[...i.values()]}async subtreeFilePaths(t,e){let i=[];for(let n of e){let o=await Be(this.app,t,n);o&&i.push(o.rootNote.file,...o.descendants.map(a=>a.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i);return[...i.map(n=>n.path),...s.map(n=>n.path)]}async orderedSubtreeNodes(t,e){let i=[],s=new Set,n=o=>{let a=this.app.metadataCache.getFileCache(o)?.frontmatter?.position;return typeof a=="number"?a:Number.MAX_SAFE_INTEGER};for(let o of e){let a=await Be(this.app,t,o);if(!a)continue;let l=new Map;for(let d of a.descendants){if(!d.parent)continue;let h=l.get(d.parent)??[];h.push({id:d.id,file:d.file,created:d.created}),l.set(d.parent,h)}for(let d of l.values())d.sort((h,g)=>n(h.file)-n(g.file)||h.created.localeCompare(g.created));let A=(d,h)=>{if(!s.has(d.id)){s.add(d.id),i.push({file:d.file,created:d.created,depth:h});for(let g of l.get(d.id)??[])A(g,h+1)}};A({id:a.rootNote.id,file:a.rootNote.file,created:a.rootNote.created},0)}return i}filesUnder(t){let e=t.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(i=>i.path.startsWith(e)).map(i=>i.path)}async snapshotPaths(t){let e=[];for(let i of t){let s=this.app.vault.getAbstractFileByPath(i);if(!s)continue;let n=!i.toLowerCase().endsWith(".md");try{n?e.push({path:i,binary:n,data:await this.app.vault.readBinary(s)}):e.push({path:i,binary:n,text:await this.app.vault.read(s)})}catch(o){console.warn("[Stashpad] snapshotPaths: couldn't read",i,o)}}return e}async restoreSnapshot(t){for(let e of t){let i=e.path.split("/").slice(0,-1).join("/");await this.ensureVaultFolder(i);let s=this.app.vault.getAbstractFileByPath(e.path);try{e.binary?s?await this.app.vault.adapter.writeBinary(e.path,e.data):await this.app.vault.createBinary(e.path,e.data):s?await this.app.vault.modify(s,e.text??""):await this.app.vault.create(e.path,e.text??"")}catch(n){console.warn("[Stashpad] restoreSnapshot: couldn't write",e.path,n)}}}async ensureVaultFolder(t){if(!t)return;let e="";for(let i of t.split("/"))if(e=e?`${e}/${i}`:i,!await this.app.vault.adapter.exists(e))try{await this.app.vault.createFolder(e)}catch{}}refreshOpenViewsForFolder(t){let e=t.replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(J)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,""),s=[];for(let A of e){let d=this.app.vault.getAbstractFileByPath(A);if(!(d instanceof M.TFile)||(d.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let h;try{h=ct(await this.app.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===F||s.push({id:g,parent:typeof h.parent=="string"?h.parent:null})}if(s.length===0)return;let n=new Set(s.map(A=>A.id)),o=new Set((this.settings.lockedSubtrees??[]).map(A=>A.rootId).filter(A=>!!A)),a=s.filter(A=>!o.has(A.id)&&!(A.parent&&n.has(A.parent)));if(a.length===0)return;if(!await this.ensureEncryptionUnlocked()){new M.Notice(`\u26A0\uFE0F Archive folder "${i.split("/").pop()}": ${a.length} arriving note${a.length===1?"":"s"} NOT encrypted (vault is locked). Unlock encryption and lock them manually.`,0);return}let l=0;for(let A of a)await this.lockNoteSubtree(i,A.id,null,{silent:!0})&&l++;l>0&&this.notifications.show({message:`Archived (encrypted) ${l} note${l===1?"":"s"} moved into \u201C${i.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:i})}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return null;let i=this.app.workspace.getLeaf("tab");return await i.setViewState({type:J,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(i),i}navigateLeafTo(t,e,i){let s=t?.view;if(s?.navigateTo&&(!s.tree||s.tree.get(i))){s.navigateTo(i);return}this.navigateWhenReady(e,i)}async openFolderInStashpad(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=await this.findStashpadLeafForFolder(e);if(i){this.app.workspace.revealLeaf(i),this.app.workspace.setActiveLeaf(i,{focus:!0});return}await this.activateViewForFolder(e)}async findStashpadLeafForFolder(t){let e=t.replace(/\/+$/,""),i=this.app.workspace.getLeavesOfType(J),s=i.find(o=>!o.isDeferred&&(o.view?.noteFolder??"").replace(/\/+$/,"")===e);if(s)return s;let n=i.find(o=>o.isDeferred&&(o.getViewState()?.state?.folderOverride??"").replace(/\/+$/,"")===e);if(n){try{await n.loadIfDeferred?.()}catch{}return n}return null}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 M.Notice("That note isn't a Stashpad note.");return}await this.revealNoteByRef(e,i)}async revealNoteByRef(t,e){let i=t.replace(/\/+$/,""),s=await this.findStashpadLeafForFolder(i);if(s){this.app.workspace.revealLeaf(s),this.app.workspace.setActiveLeaf(s,{focus:!0}),this.navigateLeafTo(s,i,e);return}let n=await this.activateViewForFolder(i);this.navigateLeafTo(n,i,e)}async closeDuplicateStashpadTabs(){let t=this.app.workspace.getLeavesOfType(J),e=this.app.workspace.activeLeaf;for(let p of t)try{await p.loadIfDeferred?.()}catch{}let i=p=>p.getViewState()?.state??{},s=p=>{let u=i(p);return(p.isDeferred?u.folderOverride??"":p.view?.noteFolder??u.folderOverride??"").replace(/\/+$/,"")},n=p=>{let u=i(p);return(p.isDeferred?u.focusId:p.view?.focusId??u.focusId)||F},o=p=>{let u=p.view;return!!u&&u.getViewType?.()===J&&typeof u.navigateTo=="function"&&typeof u.noteFolder=="string"},a=new Map;for(let p of this.app.vault.getMarkdownFiles()){let u=(p.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(p)?.frontmatter?.id;typeof f=="string"&&f&&(a.get(u)??a.set(u,new Set).get(u)).add(f)}let l=0,A=[];for(let p of t){let u=s(p),f=n(p);if(u&&f&&f!==F){let C=!p.isDeferred&&!!p.view?.tree?.get?.(f),m=a.get(u)?.has(f)??!1;if(!C&&!m){p.detach(),l++;continue}}A.push(p)}let d=new Map;for(let p of A){let u=s(p);if(!u)continue;let f=u+" "+n(p);(d.get(f)??d.set(f,[]).get(f)).push(p)}let h=0;for(let p of d.values()){if(p.length<=1)continue;p.sort((f,C)=>{let m=B=>B===e?2:B.isDeferred?0:1;return m(C)-m(f)});let u=null;for(let f of p){try{await f.loadIfDeferred?.()}catch{}if(o(f)){u=f;break}}u||(u=p[0]);for(let f of p)f!==u&&(f.detach(),h++)}let g=this.app.workspace.getLeavesOfType(J).length,I=document.createDocumentFragment();return I.createEl("div",{text:h+l>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),I.createEl("div",{text:`\u2022 ${h} duplicate tab${h===1?"":"s"} closed`}),I.createEl("div",{text:`\u2022 ${l} orphaned tab${l===1?"":"s"} pruned (note no longer exists)`}),I.createEl("div",{text:`\u2022 ${g} Stashpad tab${g===1?"":"s"} remaining`}),new M.Notice(I,7e3),h+l}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(J).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:"",l=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],A=a.includes(e),d=l.some(p=>p.includes(e));if(!A&&!d)continue;let h=n.parent?.path??"",g=i.find(p=>h===p||h.startsWith(p+"/"));if(!g)continue;s.has(g)||s.set(g,{authored:0,contributed:0});let I=s.get(g);A&&I.authored++,d&&I.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return ce(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!1;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(A=>A.path.startsWith(s+"/")&&this.parseAuthorFilePath(A.path)?.id===e))return!1;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),l=`${s}/${a}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(l)?!1:(await this.app.vault.create(l,this.buildAuthorStub({id:e,name:i,role:o?.role,department:o?.department},new Date().toISOString())),!0)}catch(A){return console.warn("[Stashpad] ensureAuthorStubFor failed",l,A),!1}}async seedKnownAuthorsInFolder(t){let e=0;for(let i of this.collectKnownAuthors())await this.ensureAuthorStubFor(t,i.id,i.name)&&e++;return e}async checkDueReminders(){let t=Date.now(),e=new Set(this.settings.notifiedDueKeys??[]),i=(this.settings.authorId??"").trim(),s=[];for(let o of this.app.vault.getMarkdownFiles()){if(o.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!a||a.due==null)continue;let l=typeof a.id=="string"?a.id:"";if(!l)continue;let A=String(a.due),d=typeof a.due=="number"?a.due:Date.parse(A);if(!Number.isFinite(d)||d>t)continue;let h=Fe(a);if(h.length>0&&!(i&&h.some(I=>I.id===i)))continue;let g=`${l}@${A}`;e.has(g)||s.push({id:l,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:d,key:g})}if(s.length===0)return;this.settings.notifiedDueKeys=[...this.settings.notifiedDueKeys??[],...s.map(o=>o.key)].slice(-2e3),await this.saveSettings();let n=async o=>{try{let l=ct(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(A=>A.trim()).find(A=>A.length>0);if(l)return l.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(s.length<=3)for(let o of s){let a=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${a}\u201D (${_t(o.dueMs,this.settings)})`,kind:"warning",category:"reminder",duration:0,folder:o.folder,affectedIds:[o.id],actions:[{label:"Open",onClick:()=>void this.revealNoteByRef(o.folder,o.id)}]})}else this.notifications.show({message:`\u23F0 ${s.length} tasks are due \u2014 open the Tasks panel to review.`,kind:"warning",category:"reminder",duration:0,folder:""})}async syncAuthorsAcrossFolders(){await this.rebuildAuthorRegistry();let t=this.collectKnownAuthors(),e=this.discoverStashpadFolders();if(!t.length||!e.length){new M.Notice("No authors or Stashpad folders to sync.");return}let i=e.length*t.length>8?new M.Notice("",0):null,s=0;for(let n of e){i?.setMessage(`Syncing authors \u2192 ${n.split("/").pop()}\u2026`);for(let o of t)await this.ensureAuthorStubFor(n,o.id,o.name)&&s++}i?.hide(),this.notifications.show({message:`Synced authors across ${e.length} folder${e.length===1?"":"s"} \u2014 ${s} new stub${s===1?"":"s"} (${t.length} author${t.length===1?"":"s"} known).`,kind:"success",category:"system",folder:""})}collectKnownAuthors(){let t=new Map,e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();e&&i&&t.set(e,i);for(let s of this.authorRegistry.all())t.has(s.id)||t.set(s.id,s.name);for(let s of this.app.vault.getMarkdownFiles()){if(!s.path.includes("/_authors/"))continue;let n=this.parseAuthorFilePath(s.path);if(!n)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter,l=((Array.isArray(o?.aliases)?o.aliases.find(A=>typeof A=="string")??"":typeof o?.aliases=="string"?o.aliases:"")||(typeof o?.name=="string"?o.name:"")||n.name).trim();t.has(n.id)||t.set(n.id,l),this.authorRegistry.record({id:n.id,name:l})}return[...t.entries()].map(([s,n])=>({id:s,name:n}))}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 l of o.contributors)typeof l=="string"&&a.push(l);for(let l of a){let A=this.parseAuthorRef(l);if(A)if(!e.has(A.id))e.set(A.id,{id:A.id,name:A.name,fromStub:!1}),i++;else{let d=e.get(A.id);!d.name&&A.name&&(d.name=A.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 l=this.parseAuthorFilePath(a.path);if(!l)continue;let A=this.app.metadataCache.getFileCache(a)?.frontmatter,h=((Array.isArray(A?.aliases)?A.aliases.find(u=>typeof u=="string")??"":typeof A?.aliases=="string"?A.aliases:"")||(typeof A?.name=="string"?A.name:"")||l.name).trim(),g=typeof A?.role=="string"?A.role:void 0,I=typeof A?.department=="string"?A.department:void 0,p=e.get(l.id);p||s++,e.set(l.id,{id:l.id,name:h||p?.name,role:g??p?.role,department:I??p?.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 l of i){if(!l.path.startsWith(o+"/"))continue;let A=this.parseAuthorFilePath(l.path)?.id;A&&a.add(A)}for(let l of t){if(a.has(l.id))continue;let A=this.authorNameToSafe(l.name),d=`${o}/${A}-${l.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(d))continue;await this.app.vault.create(d,this.buildAuthorStub(l,l.firstSeen??new Date().toISOString())),s++}catch(h){console.warn("[Stashpad] restore author stub failed",d,h)}}}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+"/")||qe(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let l=a.attachments,A=Array.isArray(l),d=typeof l=="string"&&l.trim().length>0;if(!(!A&&!d||!(d?!e(l):l.some(g=>typeof g=="string"&&g.trim()&&!e(g)))))try{await this.app.fileManager.processFrontMatter(n,g=>{Array.isArray(g.attachments)?g.attachments=g.attachments.map(I=>typeof I=="string"&&I.trim()?Ot(I):I):typeof g.attachments=="string"&&g.attachments.trim()&&(g.attachments=[Ot(g.attachments)])}),t++}catch(g){console.warn("[Stashpad] attachment-link conversion failed",n.path,g)}}}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 M.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 ko(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(A){this.notifications.show({message:`Stashpad: import failed in \`${e}\` Error: ${A.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,A);return}let o=i+s+n,a=this.lastActiveStashpadLeaf?.view;o>0&&a?.noteFolder===t&&a?.tree&&(a.tree.rebuild(t),a.render?.());let l;if(o===0)l=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let A=[];i&&A.push(`${i} loose file${i===1?"":"s"}`),s&&A.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&A.push(`${n} .stash bundle${n===1?"":"s"}`),l=`Imported ${A.join(" + ")} in \`${e}\`.`}this.notifications.show({message:l,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 ii(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(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.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(l){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,l),!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={...me,...t,shortcuts:{...me.shortcuts,...t?.shortcuts??{}},mod:{...me.mod,...t?.mod??{}},bindings:vA(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,notifiedDueKeys:Array.isArray(t?.notifiedDueKeys)?t.notifiedDueKeys.filter(e=>typeof e=="string").slice(-2e3):[],drafts:FA(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Yt]},co(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)}}readActiveVersionsFile(){try{let t=window.localStorage.getItem(this.ACTIVE_VERSIONS_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadActiveVersions(t){let e=this.readActiveVersionsFile();return new Map(Object.entries(e[t]??{}))}saveActiveVersion(t,e,i){try{let s=this.readActiveVersionsFile();s[t]||(s[t]={}),s[t][e]=i,window.localStorage.setItem(this.ACTIVE_VERSIONS_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save active-version",s)}}async flushForkSiblingPrune(){let t=new Set(this.pendingForkDeletes);if(this.pendingForkDeletes.clear(),!!t.size)for(let e of this.app.vault.getMarkdownFiles()){let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.[Jt];if(Array.isArray(i)&&i.some(s=>t.has(Wi(s)??"")))try{await this.app.fileManager.processFrontMatter(e,s=>{let o=(Array.isArray(s[Jt])?s[Jt]:[]).filter(a=>!t.has(Wi(a)??""));o.length?s[Jt]=o:delete s[Jt]})}catch{}}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),co(this.settings),wt.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 M.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let h of i){let g=this.app.metadataCache.getFileCache(h)?.frontmatter,I=typeof g?.id=="string"?g.id.trim():"";I&&e.add(I)}let{newId:s}=await Promise.resolve().then(()=>(Tt(),ts)),n=()=>{for(let h=0;h<100;h++){let g=s();if(!e.has(g))return e.add(g),g}for(let h=8;h<=16;h+=2){let g=s(h);if(!e.has(g))return e.add(g),g}throw new Error("Could not generate a unique id")},o=[];for(let h of i){let g=h.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(g))continue;let I=this.app.metadataCache.getFileCache(h)?.frontmatter,p=typeof I?.id=="string"?I.id.trim():"",u=I?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof I?.created=="string"&&I.created.trim()!=="",m=!p,B=!f,y=!C;!m&&!B&&!y||o.push({file:h,addId:m,addParent:B,addCreated:y})}if(o.length===0){new M.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,l=0,A=this.newLog();for(let h of o)try{let g;await this.app.fileManager.processFrontMatter(h.file,u=>{if(h.addId&&(typeof u.id=="string"&&u.id.trim()||(g=n(),u.id=g)),h.addParent){let f=u.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(u.parent=F)}h.addCreated&&(typeof u.created=="string"&&u.created.trim()||(u.created=new Date(h.file.stat.ctime).toISOString()))});let I=this.app.metadataCache.getFileCache(h.file)?.frontmatter,p=g??I?.id??"";p&&await A.append({type:"parent_change",id:p,payload:{from:null,to:F,reason:"orphan_fix",path:h.file.path,addedId:h.addId,addedParent:h.addParent,addedCreated:h.addCreated}}),a++}catch(g){console.warn("Stashpad: orphan fix failed for",h.file.path,g),l++}let d=l?` (${l} failed \u2014 see console)`:"";new M.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${d}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Tt(),ts)),i=new Set;for(let A of this.app.vault.getMarkdownFiles()){if(A.path===t.path)continue;let d=this.app.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id.trim():"";h&&i.add(h)}let s=()=>{for(let A=0;A<50;A++){let d=e();if(!i.has(d))return d}for(let A=8;A<=16;A+=2){let d=e(A);if(!i.has(d))return d}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,A=>{let d=typeof A.id=="string"?A.id.trim():"";!d||/\s/.test(d)||i.has(d)?(A.id=s(),n.push("id")):o.push("id"),A.parent!==void 0&&A.parent!==null&&String(A.parent).trim()!==""?o.push("parent"):(A.parent=F,n.push("parent")),typeof A.created=="string"&&A.created.trim()!==""?o.push("created"):(A.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(A){new M.Notice(`Adopt failed: ${A.message}`);return}let a=!1;try{let A=this.app.metadataCache.getFileCache(t)?.frontmatter,d=typeof A?.id=="string"?A.id.trim():"";if(d&&t.basename&&!t.basename.endsWith(`-${d}`)){let h=`${t.parent?t.parent.path+"/":""}${t.basename}-${d}.md`;await this.app.vault.adapter.exists(h)||(await this.app.fileManager.renameFile(t,h),a=!0)}}catch(A){console.warn("Stashpad: adopt rename failed",A)}if(n.length===0&&!a){new M.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let l=[];n.length&&l.push(`added: ${n.join(", ")}`),a&&l.push("renamed with id"),new M.Notice(`Adopted into Stashpad \u2014 ${l.join("; ")}.`);try{let A=this.newLog(),d=this.app.metadataCache.getFileCache(t)?.frontmatter,h=d?.id??"";h&&await A.append({type:"create",id:h,payload:{path:t.path,parent:d?.parent??F,source:"adopt",added:n}})}catch{}}};$i.DEBUG_BUFFER_MAX=300;var An=$i;function vA(c,r,t){let e=Ao();for(let i of je){let s=r&&typeof r[i.id]=="string"?r[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(c&&typeof c=="object")for(let i of je){let s=c[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 je){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(c){let r={};if(!c||typeof c!="object")return r;for(let[t,e]of Object.entries(c))if(typeof e=="string")r[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){r[t]=i;break}}return r}var ko=class extends M.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)}}; +${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 ei(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(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.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(l){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,l),!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={...ge,...t,shortcuts:{...ge.shortcuts,...t?.shortcuts??{}},mod:{...ge.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,notifiedDueKeys:Array.isArray(t?.notifiedDueKeys)?t.notifiedDueKeys.filter(e=>typeof e=="string").slice(-2e3):[],drafts:vA(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Yt]},$n(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)}}readActiveVersionsFile(){try{let t=window.localStorage.getItem(this.ACTIVE_VERSIONS_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadActiveVersions(t){let e=this.readActiveVersionsFile();return new Map(Object.entries(e[t]??{}))}saveActiveVersion(t,e,i){try{let s=this.readActiveVersionsFile();s[t]||(s[t]={}),s[t][e]=i,window.localStorage.setItem(this.ACTIVE_VERSIONS_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save active-version",s)}}async flushForkSiblingPrune(){let t=new Set(this.pendingForkDeletes);if(this.pendingForkDeletes.clear(),!!t.size)for(let e of this.app.vault.getMarkdownFiles()){let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.[Jt];if(Array.isArray(i)&&i.some(s=>t.has(Xi(s)??"")))try{await this.app.fileManager.processFrontMatter(e,s=>{let o=(Array.isArray(s[Jt])?s[Jt]:[]).filter(a=>!t.has(Xi(a)??""));o.length?s[Jt]=o:delete s[Jt]})}catch{}}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),$n(this.settings),wt.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 M.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let h of i){let g=this.app.metadataCache.getFileCache(h)?.frontmatter,I=typeof g?.id=="string"?g.id.trim():"";I&&e.add(I)}let{newId:s}=await Promise.resolve().then(()=>(Ht(),es)),n=()=>{for(let h=0;h<100;h++){let g=s();if(!e.has(g))return e.add(g),g}for(let h=8;h<=16;h+=2){let g=s(h);if(!e.has(g))return e.add(g),g}throw new Error("Could not generate a unique id")},o=[];for(let h of i){let g=h.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(g))continue;let I=this.app.metadataCache.getFileCache(h)?.frontmatter,p=typeof I?.id=="string"?I.id.trim():"",u=I?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof I?.created=="string"&&I.created.trim()!=="",m=!p,B=!f,y=!C;!m&&!B&&!y||o.push({file:h,addId:m,addParent:B,addCreated:y})}if(o.length===0){new M.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,l=0,A=this.newLog();for(let h of o)try{let g;await this.app.fileManager.processFrontMatter(h.file,u=>{if(h.addId&&(typeof u.id=="string"&&u.id.trim()||(g=n(),u.id=g)),h.addParent){let f=u.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(u.parent=F)}h.addCreated&&(typeof u.created=="string"&&u.created.trim()||(u.created=new Date(h.file.stat.ctime).toISOString()))});let I=this.app.metadataCache.getFileCache(h.file)?.frontmatter,p=g??I?.id??"";p&&await A.append({type:"parent_change",id:p,payload:{from:null,to:F,reason:"orphan_fix",path:h.file.path,addedId:h.addId,addedParent:h.addParent,addedCreated:h.addCreated}}),a++}catch(g){console.warn("Stashpad: orphan fix failed for",h.file.path,g),l++}let d=l?` (${l} failed \u2014 see console)`:"";new M.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${d}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Ht(),es)),i=new Set;for(let A of this.app.vault.getMarkdownFiles()){if(A.path===t.path)continue;let d=this.app.metadataCache.getFileCache(A)?.frontmatter,h=typeof d?.id=="string"?d.id.trim():"";h&&i.add(h)}let s=()=>{for(let A=0;A<50;A++){let d=e();if(!i.has(d))return d}for(let A=8;A<=16;A+=2){let d=e(A);if(!i.has(d))return d}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,A=>{let d=typeof A.id=="string"?A.id.trim():"";!d||/\s/.test(d)||i.has(d)?(A.id=s(),n.push("id")):o.push("id"),A.parent!==void 0&&A.parent!==null&&String(A.parent).trim()!==""?o.push("parent"):(A.parent=F,n.push("parent")),typeof A.created=="string"&&A.created.trim()!==""?o.push("created"):(A.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(A){new M.Notice(`Adopt failed: ${A.message}`);return}let a=!1;try{let A=this.app.metadataCache.getFileCache(t)?.frontmatter,d=typeof A?.id=="string"?A.id.trim():"";if(d&&t.basename&&!t.basename.endsWith(`-${d}`)){let h=`${t.parent?t.parent.path+"/":""}${t.basename}-${d}.md`;await this.app.vault.adapter.exists(h)||(await this.app.fileManager.renameFile(t,h),a=!0)}}catch(A){console.warn("Stashpad: adopt rename failed",A)}if(n.length===0&&!a){new M.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let l=[];n.length&&l.push(`added: ${n.join(", ")}`),a&&l.push("renamed with id"),new M.Notice(`Adopted into Stashpad \u2014 ${l.join("; ")}.`);try{let A=this.newLog(),d=this.app.metadataCache.getFileCache(t)?.frontmatter,h=d?.id??"";h&&await A.append({type:"create",id:h,payload:{path:t.path,parent:d?.parent??F,source:"adopt",added:n}})}catch{}}};Vi.DEBUG_BUFFER_MAX=300;var An=Vi;function wA(c,r,t){let e=Yn();for(let i of Ze){let s=r&&typeof r[i.id]=="string"?r[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(c&&typeof c=="object")for(let i of Ze){let s=c[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 Ze){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(c){let r={};if(!c||typeof c!="object")return r;for(let[t,e]of Object.entries(c))if(typeof e=="string")r[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){r[t]=i;break}}return r}var ko=class extends M.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: hash-wasm/dist/index.esm.js: diff --git a/manifest.json b/manifest.json index 8fad142..4620fb6 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.111.0", + "version": "0.112.11", "minAppVersion": "1.13.0", "description": "A chat-style, nested-notes workspace: rapid capture, outliner navigation, fast search, tasks, and per-folder templates, with one-click Open Knowledge Format (OKF) export for LLMs and agents.", "author": "Human", diff --git a/package.json b/package.json index 4a0f4c7..0503e1b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.111.0", + "version": "0.112.11", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.112.11.md b/release-notes/0.112.11.md new file mode 100644 index 0000000..13ee29f --- /dev/null +++ b/release-notes/0.112.11.md @@ -0,0 +1,26 @@ +# 0.112.11 — Friendlier "Remove encryption" + settings reliability + +## Removing encryption is now simple and unblockable +- **No password retyping.** Removing encryption only asks you to type the confirmation + phrase — not your password. So if you've **lost the password**, you can still remove + encryption and start fresh. +- **Locked notes:** if anything is still encrypted (locked), removal offers to either + **decrypt everything** (back to normal notes) or, if you've lost the password, + **permanently delete the locked content** — then proceeds. +- **Encrypted trash:** a clear choice to **Decrypt** it back to your folders or + **Discard** it (with a second confirmation). Discarding now actually deletes the trash + files rather than leaving unreadable leftovers. +- The "is anything still encrypted?" check is now near-instant instead of scanning the + whole vault. + +## Encrypted trash tab +- **Permanent delete** of individual items (with a "can't be restored" warning), + **multi-select** (click, ⌘/Ctrl-click, Shift-range), bulk **Restore/Delete selected**, + and **⌘/Ctrl+A** to select all. + +## Settings reliability +- Fixed a bug where the **settings tab could render blank** (it stopped on a button + that used an API not present on all builds), and another where it **didn't refresh** + after actions like removing encryption. +- Settings sections are now listed **alphabetically**. +- Hardened rendering so a single misbehaving control can no longer blank the whole tab. diff --git a/scripts/obs-dev.mjs b/scripts/obs-dev.mjs index 68ad156..8c744c4 100755 --- a/scripts/obs-dev.mjs +++ b/scripts/obs-dev.mjs @@ -17,7 +17,7 @@ // Node 18+ (global fetch / WebSocket). macOS paths. import { spawn } from "node:child_process"; -import { mkdirSync, writeFileSync, readFileSync, existsSync } from "node:fs"; +import { mkdirSync, writeFileSync, readFileSync, existsSync, readdirSync, copyFileSync } from "node:fs"; import { fileURLToPath } from "node:url"; import { dirname, resolve, join } from "node:path"; import { execSync } from "node:child_process"; @@ -110,6 +110,30 @@ function seedConfig() { writeFileSync(cfgPath, JSON.stringify(cfg)); } +// Obsidian auto-updates by writing a newer `obsidian-<ver>.asar` into the +// user-data-dir (NOT the .app bundle), and loads the newest asar present there. +// The dev profile is isolated, so it never receives those updates and runs the +// bundled (older, stable) version — which can render/behave differently from the +// user's main app (e.g. the 1.13 declarative-settings API is absent on stable, so +// dev tests silently exercise a different code path). Mirror the main profile's +// newest asar into the dev profile so the dev instance matches the real app. +const MAIN_OBSIDIAN_DIR = join(process.env.HOME, "Library", "Application Support", "obsidian"); +function syncInsiderAsar() { + try { + if (!existsSync(MAIN_OBSIDIAN_DIR)) return; + const verOf = (f) => (f.match(/(\d+)\.(\d+)\.(\d+)/) || []).slice(1).map(Number); + const cmp = (a, b) => { for (let i = 0; i < 3; i++) { const d = (verOf(a)[i] ?? 0) - (verOf(b)[i] ?? 0); if (d) return d; } return 0; }; + const asars = readdirSync(MAIN_OBSIDIAN_DIR).filter((f) => /^obsidian-.*\.asar$/.test(f)).sort(cmp); + if (!asars.length) return; // main app on the bundled version too — nothing to mirror + const newest = asars[asars.length - 1]; + const dst = join(USER_DATA_DIR, newest); + if (!existsSync(dst)) { + copyFileSync(join(MAIN_OBSIDIAN_DIR, newest), dst); + console.log(`synced ${newest} into the dev profile (matches your main Obsidian version)`); + } + } catch (e) { console.warn("asar sync skipped:", e.message); } +} + async function start() { if (await portReady()) { const v = await verifyVault(); @@ -117,6 +141,7 @@ async function start() { return; } seedConfig(); + syncInsiderAsar(); console.log(`launching dedicated Obsidian (vault: ${VAULT_NAME}, port :${PORT}, isolated user-data-dir)…`); const child = spawn(OBSIDIAN_BIN, [`--remote-debugging-port=${PORT}`, `--user-data-dir=${USER_DATA_DIR}`], { detached: true, stdio: "ignore", diff --git a/scripts/seed-demo.mjs b/scripts/seed-demo.mjs new file mode 100644 index 0000000..f1b143b --- /dev/null +++ b/scripts/seed-demo.mjs @@ -0,0 +1,92 @@ +/* Seed a rich, nested demo note-folder for website screenshots. + * node scripts/seed-demo.mjs "/abs/path/to/vault" "My Stash" [--force] + * Filenames are human-readable (drives Stashpad's breadcrumb/header titles); + * the canonical identity is the frontmatter `id`. --force replaces the folder + * (only ever the demo folder it generates — never touches sibling notes). + */ +import { mkdir, writeFile, access, rm } from "node:fs/promises"; +import { join } from "node:path"; + +const vault = process.argv[2]; +const folder = process.argv[3] || "My Stash"; +const force = process.argv.includes("--force"); +if (!vault) { console.error("usage: seed-demo.mjs <vaultPath> [folder] [--force]"); process.exit(1); } + +const dir = join(vault, folder); +let exists = false; +try { await access(dir); exists = true; } catch {} +if (exists && !force) { console.error(`REFUSED: ${dir} exists (use --force to regenerate)`); process.exit(1); } +if (exists && force) await rm(dir, { recursive: true }); +await mkdir(dir, { recursive: true }); + +let t = Date.parse("2026-06-12T09:00:00"); +const stamp = () => { const d = new Date(t); t += 60_000; return d.toISOString().slice(0, 19); }; + +const notes = []; +const byId = new Map(); +// id, parent, name(=filename/title), body, extra +const add = (id, parent, name, body, extra = {}) => { + const n = { id, parent, name, created: stamp(), body: body.trim(), extra }; + notes.push(n); byId.set(id, n); +}; + +await writeFile(join(dir, `Home.md`), + `---\nid: __root__\nparent: __root__\ncreated: ${stamp()}\nattachments: []\n---\n# My Stash\nEverything I'm thinking about, one stack at a time.\n`); + +// ── 1. Reading list ────────────────────────────────────────────────────── +add("read", "__root__", "Reading list", `📚 **Reading list** — what I'm working through and the bits worth keeping.`); +add("read-ah", "read", "Atomic Habits", `📕 **Atomic Habits** — James Clear. The core move: don't set goals, design systems. You don't rise to the level of your goals — you fall to the level of your systems.`); +add("read-ah-hs", "read-ah", "Habit stacking", `**Habit stacking** to try this week: "After I pour my morning coffee, I will write three lines in my stash." Anchor the new habit to one I already never skip.`); +add("read-ah-2", "read-ah", "The two-minute rule", `**The 2-minute rule:** scale any new habit down until it takes two minutes. "Read before bed" → "read one page." Make it so easy you can't say no.`); +add("read-tfs", "read", "Thinking Fast and Slow", `📗 **Thinking, Fast and Slow** — Kahneman. System 1 is fast, intuitive, wrong a lot. System 2 is slow, deliberate, lazy. Most "intuition" is System 1 pattern-matching wearing a confident face.`); +add("read-pp", "read", "The Pragmatic Programmer", `📘 **The Pragmatic Programmer** — Hunt & Thomas. DRY isn't about code, it's about knowledge. Two snippets can look identical and not be a violation if they encode different decisions.`); + +// ── 2. Japan trip ──────────────────────────────────────────────────────── +add("jp", "__root__", "Japan trip — March", `✈️ **Japan trip — March** 🌸 Nine days, Tokyo → Kyoto → back. Blossom forecast says peak around the 28th. Fingers crossed.`); +add("jp-tok", "jp", "Tokyo", `**Tokyo** (5 nights, Airbnb in Shimokitazawa). Base in the west, day-trip out. Grab a Suica card at the airport and top it up before anything else.`); +add("jp-tok-d1", "jp-tok", "Day 1 — arrival", `**Day 1** — recover from the flight slowly. Shimokitazawa vintage shops in the morning, Shibuya crossing at dusk, conveyor-belt sushi when we can't keep our eyes open.`); +add("jp-tok-d2", "jp-tok", "Day 2 — teamLab", `**Day 2** — teamLab Planets (book tickets NOW, they sell out), then Tsukiji outer market for lunch. Evening: tiny bars in Golden Gai.`); +add("jp-kyo", "jp", "Kyoto", `**Kyoto** (3 nights). Slower pace. Fushimi Inari at sunrise to beat the crowds, Arashiyama bamboo grove, an afternoon doing absolutely nothing in a tea house.`); +add("jp-pack", "jp", "Packing list", `**Packing** — pack light, you'll buy stuff. Comfortable walking shoes (20k steps/day), a foldable tote, portable battery, and cash — Japan still loves cash.`); +add("jp-budget", "jp", "Budget", `**Budget** — flights booked. Aim for ¥12k/day for food + transit per person. Splurge once on a proper kaiseki dinner in Kyoto; balance it with conbini breakfasts.`); + +// ── 3. Recipes ─────────────────────────────────────────────────────────── +add("rec", "__root__", "Recipes", `🍳 **Recipes** — the ones that actually made it into rotation.`); +add("rec-ramen", "rec", "Weeknight miso ramen", `**Weeknight miso ramen** (20 min). Soften garlic + ginger in sesame oil, whisk in 2 tbsp miso + a splash of soy, add stock. Noodles, soft egg, whatever greens are wilting in the drawer. Done.`); +add("rec-sd", "rec", "Sourdough method", `**Sourdough — my method.** 500g flour, 350g water, 100g active starter, 10g salt. Autolyse 1h, 4 stretch-and-folds, bulk till 50% risen, shape, cold-proof overnight, bake in a dutch oven at 250°C.`); +add("rec-chx", "rec", "Sheet-pan harissa chicken", `**Sheet-pan harissa chicken.** Thighs + chickpeas + red onion tossed in harissa, honey, lemon. 220°C for 35 min. Finish with yogurt and mint. Feeds 4, dirties one pan.`); + +// ── 4. Rust ────────────────────────────────────────────────────────────── +add("rust", "__root__", "Rust — learning notes", `🦀 **Rust — learning notes.** Slowly fighting the borrow checker less and understanding it more.`); +add("rust-own", "rust", "Ownership", `**Ownership.** Every value has exactly one owner; when the owner goes out of scope, the value is dropped. Move semantics by default — assigning transfers ownership, it doesn't copy.`); +add("rust-bor", "rust", "Borrowing", `**Borrowing.** Either one mutable reference *or* any number of immutable ones — never both at once. That's the whole game: data races become compile errors.`); +add("rust-life", "rust", "Lifetimes", `**Lifetimes, finally clicking.** An annotation doesn't change how long anything lives — it *describes* a relationship the compiler can't infer. \`'a\` means "lives at least as long as 'a."`); +add("rust-err", "rust", "Error handling", `**Error handling.** No exceptions — \`Result<T, E>\` and the \`?\` operator. \`?\` early-returns the error, otherwise unwraps the Ok. \`thiserror\` for libraries, \`anyhow\` for apps.`); + +// ── 5. Ideas inbox ─────────────────────────────────────────────────────── +add("idea", "__root__", "Ideas inbox", `💡 **Ideas inbox** — capture now, judge later. Most won't survive the week, and that's fine.`); +add("idea-out", "idea", "Why outliners beat documents", `**Blog post: why outliners beat documents.** A document forces one order. An outliner lets structure emerge — write the thoughts, then drag them into shape. Working title: "Structure is a verb."`); +add("idea-plant", "idea", "Plant-care reminders app", `**App idea: plant-care reminders** that account for season + light. Not "water every Tuesday" but "this fern, this window, this month." Probably already exists. Capture anyway.`); + +// ── 6. This week (tasks) ───────────────────────────────────────────────── +add("week", "__root__", "This week", `🎯 **This week** — the short list. If it's not here, it's not happening before Sunday.`); +add("week-invoice", "week", "Send invoice to Meridian", `Send the invoice to Meridian for the May work.`, { task: true, due: "2026-06-20T17:00:00" }); +add("week-dentist", "week", "Book dentist cleaning", `Book the dentist cleaning — it's been a year.`, { task: true, due: "2026-06-23T09:00:00" }); +add("week-passport", "week", "Renew passport", `Renew the passport before it expires (need it for Japan!).`, { task: true, due: "2026-06-25T12:00:00" }); +add("week-itin", "week", "Draft itinerary email", `Draft the Japan itinerary email for the group.`, { task: true, completed: true, due: "2026-06-18T20:00:00" }); + +// ── 7. Home projects ───────────────────────────────────────────────────── +add("home", "__root__", "Home projects", `🏠 **Home projects** — the slow-burn list.`); +add("home-shelf", "home", "Garage shelving", `**Garage shelving.** 2×4 frame, plywood shelves, lag-bolted into the studs. Measure twice: the door swing eats 80cm on the left wall.`); +add("home-faucet", "home", "Fix leaky faucet", `**Fix the leaky bathroom faucet.** Almost certainly a worn cartridge — match the brand first. Shut off the supply valves *before* getting cocky.`, { task: true, due: "2026-06-28T10:00:00" }); + +for (const n of notes) { + const fm = [`id: ${n.id}`, `parent: ${n.parent}`, `created: ${n.created}`, `attachments: []`]; + if (n.extra.task) fm.push(`task: true`); + if (n.extra.completed) fm.push(`completed: true`); + if (n.extra.due) fm.push(`due: ${n.extra.due}`); + const parentName = n.parent === "__root__" ? "Home" : byId.get(n.parent)?.name || "Home"; + fm.push(`parentLink: "[[${folder}/${parentName}]]"`); + await writeFile(join(dir, `${n.name}.md`), `---\n${fm.join("\n")}\n---\n${n.body}\n`); +} +console.log(JSON.stringify({ folder: dir, count: notes.length + 1 }, null, 2)); diff --git a/src/encryption-ops.ts b/src/encryption-ops.ts index 87358e1..5b033b2 100644 --- a/src/encryption-ops.ts +++ b/src/encryption-ops.ts @@ -313,24 +313,13 @@ export async function deletedRestoreDest(app: App, blobPath: string, meta: Delet return blobDir; } -/** Is ANY `.stashenc` blob on disk? Walks the ADAPTER (not vault.getFiles) — - * adapter-written blobs can be invisible to the vault index for a while, and - * this backs the "Remove encryption" hard guard, which must never miss one. - * Skips `.obsidian/` only. */ -export async function anyStashencOnDisk(app: App): Promise<boolean> { - const queue = [""]; - while (queue.length) { - const dir = queue.shift()!; - let listing; - try { listing = await app.vault.adapter.list(dir || "/"); } catch { continue; } - if (listing.files.some((f) => f.endsWith(`.${STASHENC_EXT}`))) return true; - for (const f of listing.folders) { - if (f === ".obsidian" || f.endsWith("/.obsidian")) continue; - queue.push(f); - } - } - return false; -} +// 0.112.2: `anyStashencOnDisk()` (a full recursive adapter walk) was removed — +// it took minutes on big vaults and its premise was wrong. Empirically (Claude +// Dev Vault, pendingEncBlobs empty): `vault.getFiles()` DOES return +// `_deleted/*.stashenc` (it's a normal, fully-indexed folder), so the old +// comment "`_deleted/` blobs aren't indexed" was stale. The only location +// `getFiles()` misses is the `.trash/` DOT-folder, which `plugin.encryptionState` +// + `encryptionStateStrict` now handle directly. Use those instead. /** Encrypt-delete a subtree into `_deleted/` (recoverable, encrypted), then * permanently delete the plaintext. Mirrors lockSubtree but the blob lives in the @@ -411,6 +400,14 @@ export async function readDeletedMeta(app: App, blobPath: string): Promise<Delet catch { return null; } } +/** Permanently delete an encrypted-trash item: the `.stashenc` blob AND its + * `.stashmeta` sidecar. No decrypt, no restore — the content is GONE forever. + * Callers MUST confirm first (it's irreversible). 0.112.3. */ +export async function purgeDeletedBlob(app: App, blobPath: string): Promise<void> { + await app.vault.adapter.remove(blobPath); + try { await app.vault.adapter.remove(sidecarPath(blobPath)); } catch { /* sidecar may not exist */ } +} + // ------- v2 backfill: encrypt Obsidian's pre-existing plaintext trash ------- /** Obsidian's in-vault trash folder ("Deleted files" → "Move to vault trash"). */ diff --git a/src/encryption-service.ts b/src/encryption-service.ts index f60f66f..8a827a0 100644 --- a/src/encryption-service.ts +++ b/src/encryption-service.ts @@ -112,6 +112,23 @@ export class EncryptionService { isRemembered(): boolean { try { return !!this.secretStore()?.getSecret(this.keychainId()); } catch { return false; } } + /** The password saved in this device's keychain, or null. Lets flows that + * need the password (e.g. Remove encryption) pull it automatically instead + * of forcing the user to retype it. Falls back to the legacy entry. */ + rememberedPassword(): string | null { + const ss = this.secretStore(); + if (!ss) return null; + try { const v = ss.getSecret(this.keychainId()); if (v) return v; } catch { /* fall through */ } + try { return ss.getSecret(LEGACY_KEYCHAIN_ID) || null; } catch { return null; } + } + /** True if the keychain holds a password that actually verifies against the + * current key — so a flow can treat "keychain present" as proof of access + * without prompting. */ + async verifyWithKeychain(): Promise<boolean> { + const pw = this.rememberedPassword(); + if (!pw) return false; + try { return await this.verifyPassword(pw); } catch { return false; } + } private async remember(password: string): Promise<void> { try { await this.secretStore()?.setSecret(this.keychainId(), password); } catch (e) { console.warn("[Stashpad] couldn't save password to keychain", e); } diff --git a/src/folder-panel-view.ts b/src/folder-panel-view.ts index 67bfde6..86f71d7 100644 --- a/src/folder-panel-view.ts +++ b/src/folder-panel-view.ts @@ -72,8 +72,10 @@ export class StashpadFolderPanelView extends ItemView { he.onmousedown = (e) => { if (e.button === 0) { e.preventDefault(); this.plugin.openFolderPicker(); } }; const newBtn = head.createEl("button", { cls: "stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-newfolder" }); setIcon(newBtn, "folder-plus"); - newBtn.setAttr("aria-label", "New Stashpad folder"); - newBtn.onmousedown = (e) => { if (e.button === 0) { e.preventDefault(); e.stopPropagation(); void this.createNewFolderFlow(); } }; + newBtn.setAttr("aria-label", "New Stashpad folder (folder switcher)"); + // 0.112.3: open the folder switcher (which already has a "Create" entry) + // rather than a bespoke prompt — one place to create + switch folders. + newBtn.onmousedown = (e) => { if (e.button === 0) { e.preventDefault(); e.stopPropagation(); this.plugin.openFolderPicker(); } }; if (this.plugin.encryption?.isConfigured?.()) { const trashBtn = head.createEl("button", { cls: "stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-trash" }); setIcon(trashBtn, "trash-2"); @@ -83,23 +85,6 @@ export class StashpadFolderPanelView extends ItemView { this.renderFolders(folderSection.createDiv({ cls: "stashpad-folderpanel-list" })); } - /** Prompt for a name, create a new Stashpad folder, then open it. Wired to the - * "+" button in the Folders heading. 0.111.0. */ - private async createNewFolderFlow(): Promise<void> { - const raw = await new NewFolderPromptModal(this.app).prompt(); - const cleaned = (raw ?? "").trim().replace(/^\/+|\/+$/g, ""); - if (!cleaned) return; // cancelled or empty - try { - await this.plugin.createNewStashpad(cleaned); - await this.plugin.waitForStashpadFolder(cleaned, 2000); - await this.plugin.activateViewForFolder(cleaned); - this.scheduleRender(); - new Notice(`Created Stashpad "${cleaned.split("/").pop()}".`); - } catch (e) { - new Notice(`Couldn't create folder: ${(e as Error).message}`); - } - } - private clampFrac(f: number): number { if (!Number.isFinite(f)) return 0.5; return Math.max(0.15, Math.min(0.85, f)); @@ -769,51 +754,3 @@ export async function openFolderPanelView(app: App): Promise<void> { await leaf.setViewState({ type: STASHPAD_FOLDER_PANEL_VIEW_TYPE, active: true }); app.workspace.revealLeaf(leaf); } - -/** Minimal single-line name prompt for "New Stashpad folder". Resolves the - * entered name, or null if cancelled (Esc / Cancel / empty). 0.111.0. */ -class NewFolderPromptModal extends Modal { - private value = ""; - private resolved = false; - private resolve: ((v: string | null) => void) | null = null; - - prompt(): Promise<string | null> { - return new Promise((resolve) => { this.resolve = resolve; this.open(); }); - } - - onOpen(): void { - this.titleEl.setText("New Stashpad folder"); - const { contentEl } = this; - contentEl.createEl("p", { - cls: "setting-item-description", - text: "Vault-relative folder path. It's created (with intermediates) and seeded with a Home note, then opened.", - }); - const input = contentEl.createEl("input", { type: "text", cls: "stashpad-newfolder-input" }); - input.placeholder = "my-stashpad"; - input.setCssStyles({ width: "100%", marginBottom: "12px" }); - input.addEventListener("input", () => { this.value = input.value; }); - input.addEventListener("keydown", (e) => { - if (e.key === "Enter") { e.preventDefault(); this.finish(input.value); } - else if (e.key === "Escape") { e.preventDefault(); this.finish(null); } - }); - const btns = contentEl.createDiv({ cls: "modal-button-container" }); - const create = btns.createEl("button", { text: "Create", cls: "mod-cta" }); - create.onclick = () => this.finish(this.value); - const cancel = btns.createEl("button", { text: "Cancel" }); - cancel.onclick = () => this.finish(null); - window.setTimeout(() => input.focus(), 0); - } - - private finish(v: string | null): void { - if (this.resolved) return; - this.resolved = true; - this.resolve?.(v); - this.close(); - } - - onClose(): void { - this.contentEl.empty(); - // Closed via the X / click-out without an explicit choice → treat as cancel. - if (!this.resolved) { this.resolved = true; this.resolve?.(null); } - } -} diff --git a/src/main.ts b/src/main.ts index 647fd7e..5556682 100644 --- a/src/main.ts +++ b/src/main.ts @@ -8,7 +8,7 @@ import { STASHPAD_TRASH_VIEW_TYPE } from "./types"; import { StashpadPanelsView, openStashpadPanelsView, PANEL_REGISTRY, type PanelId } from "./panels-view"; import { StashpadFolderPanelView, openFolderPanelView } from "./folder-panel-view"; import { EncryptionService, defaultEncryptionConfig } from "./encryption-service"; -import { lockSubtree, unlockBundle, readLockedMeta, type LockResult, deleteEncryptSubtree, restoreDeleted, listDeletedBlobs, readDeletedMeta, deletedRestoreDest, backfillTrashEncrypt, restoreRawTrash, OBSIDIAN_TRASH_DIR, type DeletedMeta, collectSubtree } from "./encryption-ops"; +import { lockSubtree, unlockBundle, readLockedMeta, type LockResult, deleteEncryptSubtree, restoreDeleted, listDeletedBlobs, readDeletedMeta, deletedRestoreDest, backfillTrashEncrypt, restoreRawTrash, purgeDeletedBlob, OBSIDIAN_TRASH_DIR, type DeletedMeta, collectSubtree } from "./encryption-ops"; import { EncryptionPasswordModal } from "./modals"; import { DEFAULT_SETTINGS, StashpadSettings, StashpadSettingTab, setSettings, SETTINGS_TABS, @@ -79,6 +79,11 @@ export default class StashpadPlugin extends Plugin { * wikilink rewrites Obsidian does when slug-renames move files — never * bump `modified` (or add the local user as a contributor). */ rebootstrapInProgress = false; + /** 0.112.0: paths of `.stashenc` blobs written via the adapter THIS session + * that the vault's in-memory index may not have picked up yet. Backs the fast + * encryption-state check so the removal guard never has to do a full recursive + * adapter walk. Pruned by the create watcher (once indexed) and delete watcher. */ + private pendingEncBlobs = new Set<string>(); /** 0.86.6: while `Date.now() < this`, a Stashpad view's activation * auto-focus skips grabbing the composer. Set by the folder panel before it * reveals/opens a leaf so tapping a pinned note on mobile doesn't pop the @@ -760,6 +765,11 @@ export default class StashpadPlugin extends Plugin { // has settled so folder discovery + the "already has my stub" check // are accurate (avoids creating a duplicate before the cache lists // the existing one). New folders are seeded at creation time instead. + // 0.112.0: keep the fast encryption-state index honest — drop a pending blob + // once the vault indexes it (then getFiles() covers it), and reflect external + // or synced deletes so a stale pending entry can't falsely report "locked". + this.registerEvent(this.app.vault.on("create", (f) => { if (f.path.endsWith(".stashenc")) this.pendingEncBlobs.delete(f.path); })); + this.registerEvent(this.app.vault.on("delete", (f) => { if (f.path.endsWith(".stashenc")) this.pendingEncBlobs.delete(f.path); })); this.app.workspace.onLayoutReady(() => { // Vault is fully indexed now — safe to reconcile locked placeholders // (drop entries whose blob is truly gone, add cross-device blobs). @@ -3130,6 +3140,60 @@ export default class StashpadPlugin extends Plugin { }); } + /** 0.112.0: FAST encryption-state check — replaces a full recursive adapter + * walk that made "Remove encryption" take minutes on big vaults. Reads + * Obsidian's in-memory file index (instant) plus this session's + * `pendingEncBlobs` (adapter writes not yet indexed). Splits LIVE locked + * content (notes/folders — irrecoverable if the key is erased) from TRASH + * (`_deleted/` — recoverable until the key goes). Short-circuits as soon as it + * knows both. + * + * 0.112.2: empirically verified (Claude Dev Vault, pendingEncBlobs empty) + * that `vault.getFiles()` DOES return `_deleted/*.stashenc` — it's a normal, + * fully-indexed folder — so trash detection here is reliable across sessions, + * NOT dependent on `pendingEncBlobs`. The only location `getFiles()` misses is + * the `.trash/` DOT-folder; for any IRREVERSIBLE decision use + * `encryptionStateStrict()`, which adapter-confirms `_deleted/` + `.trash/`. */ + encryptionState(): { live: boolean; trash: boolean } { + const isTrash = (p: string): boolean => { + const dir = p.replace(/\/[^/]*$/, ""); + return dir === "_deleted" || dir.startsWith("_deleted/"); + }; + let live = false, trash = false; + for (const f of this.app.vault.getFiles()) { + if (f.extension !== "stashenc") continue; + if (isTrash(f.path)) trash = true; else live = true; + if (live && trash) return { live, trash }; + } + for (const p of this.pendingEncBlobs) { + if (isTrash(p)) trash = true; else live = true; + if (live && trash) break; + } + return { live, trash }; + } + + /** Authoritative-but-cheap variant for the IRREVERSIBLE "Remove encryption" + * moment. Starts from the fast in-memory check, then confirms TRASH via two + * adapter folder listings: `_deleted/` (covers an index lag) and Obsidian's + * vault-local trash `.trash/` — a DOT-folder that `vault.getFiles()` never + * returns, so a `.stashenc` the user trashed there would otherwise be erased + * silently. Two listings, not a full vault walk. Live blobs only ever live in + * normal (indexed) Stashpad folders, so live detection stays on the fast path. */ + async encryptionStateStrict(): Promise<{ live: boolean; trash: boolean }> { + const s = this.encryptionState(); + let trash = s.trash; + if (!trash) { + try { trash = (await listDeletedBlobs(this.app)).length > 0; } catch { /* ignore */ } + } + if (!trash) { + try { + const t = await this.app.vault.adapter.list(OBSIDIAN_TRASH_DIR); + trash = t.files.some((f) => f.endsWith(".stashenc")); + } catch { /* no .trash dir — fine */ } + } + return { live: s.live, trash }; + } + async lockNoteSubtree(folder: string, rootId: StashpadId, prevSibling: StashpadId | null = null, opts: { silent?: boolean; blobFolder?: string } = {}): Promise<LockResult | null> { if (!(await this.ensureEncryptionUnlocked())) return null; const dek = this.encryption.getSessionKey(); @@ -3137,6 +3201,7 @@ export default class StashpadPlugin extends Plugin { try { const hideTitle = this.settings.hideLockedTitles ?? false; const r = await lockSubtree(this.app, folder, rootId, dek, prevSibling, hideTitle, opts.blobFolder); + this.pendingEncBlobs.add(r.blobPath); // fast-state index: cover the pre-vault-index window // Record a placeholder registry entry so the list shows a 🔒 stub where // the note was. The blob may live in a different folder than the note's // source (archive) — register it under the blob's actual folder. @@ -3188,6 +3253,9 @@ export default class StashpadPlugin extends Plugin { const folder = (opts.destFolder ?? blobPath.replace(/\/[^/]*$/, "")).replace(/\/+$/, ""); try { const r = await this.unlockBundleCore(blobPath, dek, opts.destFolder); + // Blob is removed via raw adapter (no vault 'delete' event) — prune the + // fast-index pending entry directly so it can't falsely report "locked". + this.pendingEncBlobs.delete(blobPath); this.settings.lockedSubtrees = (this.settings.lockedSubtrees ?? []).filter((e) => e.blob !== blobPath); await this.saveSettings(); if (!opts.silent) this.notifications.show({ message: `Unlocked ${r.notesWritten} note${r.notesWritten === 1 ? "" : "s"}.`, kind: "success", category: "system", folder }); @@ -3317,6 +3385,7 @@ export default class StashpadPlugin extends Plugin { // the general hide-locked-titles setting is off. const hideTitle = (this.settings.hideLockedTitles ?? false) || (this.settings.encryptTrashFilenames ?? false); const r = await deleteEncryptSubtree(this.app, folder, rootId, dek, deletedAt, hideTitle); + this.pendingEncBlobs.add(r.blobPath); // fast-state index if (r.unpurged.length > 0) { new Notice(`⚠️ Sent to encrypted trash, but ${r.unpurged.length} file${r.unpurged.length === 1 ? " is" : "s are"} still in plaintext (couldn't be removed or changed during the delete):\n${r.unpurged.join("\n")}`, 0); } @@ -3339,6 +3408,7 @@ export default class StashpadPlugin extends Plugin { if (meta?.kind === "rawtrash") { try { const r = await restoreRawTrash(this.app, blobPath, dek); + this.pendingEncBlobs.delete(blobPath); if (!opts.silent) this.notifications.show({ message: `Restored ${r.filesWritten} file${r.filesWritten === 1 ? "" : "s"} to Obsidian's trash (${OBSIDIAN_TRASH_DIR}/).`, kind: "success", category: "system", folder: "" }); return true; } catch (e) { @@ -3364,6 +3434,7 @@ export default class StashpadPlugin extends Plugin { } catch { /* unreadable — skip */ } } const r = await restoreDeleted(this.app, blobPath, dek, existing); + this.pendingEncBlobs.delete(blobPath); if (!opts.silent) this.notifications.show({ message: `Restored ${r.notesWritten} note${r.notesWritten === 1 ? "" : "s"} to “${r.restoredTo.split("/").pop()}”.`, kind: "success", category: "system", folder: r.restoredTo }); return true; } catch (e) { @@ -3373,6 +3444,39 @@ export default class StashpadPlugin extends Plugin { } } + /** Permanently delete one encrypted-trash item (blob + sidecar). Irreversible + * — no decrypt. The caller MUST confirm first. Returns true on success. */ + async purgeDeletedAt(blobPath: string): Promise<boolean> { + try { + await purgeDeletedBlob(this.app, blobPath); + this.pendingEncBlobs.delete(blobPath); + return true; + } catch (e) { + console.warn("[Stashpad] purge-from-trash failed", blobPath, e); + new Notice(`Couldn't delete: ${(e as Error).message}`, 0); + return false; + } + } + + /** Permanently delete EVERY live locked `.stashenc` bundle (+ sidecar) WITHOUT + * decrypting — the notes inside are gone for good. Backs "Remove encryption → + * Delete locked content" for when the password is lost. Excludes `_deleted/` + * trash (that's handled separately). Caller MUST confirm. Returns the count. */ + async purgeAllLockedContent(): Promise<number> { + const isTrash = (p: string): boolean => { const d = p.replace(/\/[^/]*$/, ""); return d === "_deleted" || d.startsWith("_deleted/"); }; + const blobs = new Set<string>(); + for (const f of this.app.vault.getFiles()) if (f.extension === "stashenc" && !isTrash(f.path)) blobs.add(f.path); + for (const p of this.pendingEncBlobs) if (!isTrash(p)) blobs.add(p); + let n = 0; + for (const b of blobs) { + try { await purgeDeletedBlob(this.app, b); this.pendingEncBlobs.delete(b); n++; } + catch (e) { console.warn("[Stashpad] purge locked content failed", b, e); } + } + this.settings.lockedSubtrees = (this.settings.lockedSubtrees ?? []).filter((e) => !blobs.has(e.blob)); + await this.saveSettings(); + return n; + } + /** List the encrypted-trash contents (blob path + sidecar metadata). */ async listDeletedTrash(): Promise<Array<{ blob: string; meta: DeletedMeta | null }>> { const blobs = await listDeletedBlobs(this.app); diff --git a/src/modals.ts b/src/modals.ts index 31ac715..55e2aa3 100644 --- a/src/modals.ts +++ b/src/modals.ts @@ -1409,6 +1409,7 @@ export class ConfirmModal extends Modal { private message: string, private confirmText: string, private onChoose: (confirmed: boolean) => void, + private cancelText: string = "Cancel", ) { super(app); } onOpen(): void { this.modalEl?.addClass("stashpad-compact-modal"); // 0.76.18 @@ -1423,7 +1424,7 @@ export class ConfirmModal extends Modal { block.createDiv({ cls: "stashpad-confirm-line", text: line }); } const row = this.contentEl.createDiv({ cls: "stashpad-modal-btns" }); - const cancel = row.createEl("button", { text: "Cancel" }); + const cancel = row.createEl("button", { text: this.cancelText }); cancel.onclick = () => { this.didChoose = true; this.close(); this.onChoose(false); }; const ok = row.createEl("button", { cls: "mod-cta", text: this.confirmText }); ok.onclick = () => { this.didChoose = true; this.close(); this.onChoose(true); }; diff --git a/src/settings.ts b/src/settings.ts index c4ddcda..934f504 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -9,14 +9,13 @@ import { FolderSuggest } from "./folder-suggest"; import type StashpadPlugin from "./main"; import { RESERVED_FRONTMATTER, type ViewMode } from "./types"; import { type SplitMode } from "./view-helpers"; -import { LogModal, ColorPickerModal, NotificationHistoryModal, EncryptionPasswordModal, TypeToConfirmModal } from "./modals"; +import { LogModal, ColorPickerModal, NotificationHistoryModal, EncryptionPasswordModal, TypeToConfirmModal, ConfirmModal } from "./modals"; import { CATEGORY_LABELS, type NotificationCategory } from "./notifications"; import { startHotkeyRecording, prettifyChord } from "./hotkey-recorder"; import { DEFAULT_STOPWORDS } from "./slug-service"; import { newId } from "./id-service"; import { formatDateTime } from "./format"; import { type EncryptionConfig, defaultEncryptionConfig } from "./encryption-service"; -import { anyStashencOnDisk } from "./encryption-ops"; import { getActiveView } from "./active-view"; export interface ShortcutMap { @@ -597,7 +596,7 @@ export type SettingsTabId = | "movingNotes" | "deleting" | "composerCopy" | "windowsTabs" | "notifications" | "encryption" | "authorship" | "templates" | "jdindex" | "okf" | "maintenance" | "diagnostics" | "misc" | "hotkeys"; -export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = [ +export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = ([ { id: "foldersStorage", label: "Folders & storage" }, { id: "importExport", label: "Import & export" }, { id: "noteTitles", label: "Note titles" }, @@ -617,7 +616,9 @@ export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = [ { id: "diagnostics", label: "Diagnostics" }, { id: "misc", label: "Misc" }, { id: "hotkeys", label: "Hotkeys" }, -]; +// 0.112.9: sections shown alphabetically by label. Display order only — the +// `id`-keyed itemsForTab dispatch is unaffected, and new tabs auto-sort in. +] as Array<{ id: SettingsTabId; label: string }>).sort((a, b) => a.label.localeCompare(b.label)); /** 0.94.0: a declarative sub-page that renders one of Stashpad's settings tabs * via the existing imperative `renderTabContent`. Used by @@ -670,8 +671,19 @@ export class StashpadSettingTab extends PluginSettingTab { * (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. */ + /** 0.112.11: IMPERATIVE fallback ONLY. On 1.13+ Obsidian ignores display() + * whenever getSettingDefinitions() returns items — it renders declaratively + * via the base `update()` (a navigable page list + native search). So this + * runs only on pre-1.13 (no declarative API). It must NOT call super.display() + * — on 1.13 that renders nothing (the source of the earlier blank tab) and on + * pre-1.13 it's a no-op. Just render every tab's items inline. + * + * CRITICAL: do NOT override `update()`. The base SettingTab.update() IS the + * 1.13 declarative renderer + search indexer; overriding it (as 0.112.8 did, + * based on stale-Obsidian testing where update() didn't exist) blanks the tab + * and forces this imperative fallback. The `this.update?.()` refresh calls + * resolve to the base update() on 1.13 (re-render) and no-op on pre-1.13. */ display(): void { - if (SettingPage) { super.display(); return; } const { containerEl } = this; containerEl.empty(); for (const t of SETTINGS_TABS) { @@ -861,7 +873,13 @@ export class StashpadSettingTab extends PluginSettingTab { build: (s: Setting) => void, aliases?: string[], ): SettingDefinitionItem { - return { name, desc, aliases, render: (s: Setting) => { s.setName(name).setDesc(desc); build(s); } }; + // 0.112.5: try/catch so a single throwing control (e.g. a missing Obsidian + // API on an older build) degrades to a labelled row instead of aborting the + // ENTIRE declarative settings render and blanking every later section. + return { name, desc, aliases, render: (s: Setting) => { + s.setName(name).setDesc(desc); + try { build(s); } catch (e) { console.error(`[Stashpad] settings control "${name}" failed to render:`, e); } + } }; } /** 0.94.3: a declarative item whose render builds a whole MULTI-element @@ -881,7 +899,7 @@ export class StashpadSettingTab extends PluginSettingTab { host.empty(); host.removeClass("setting-item"); host.addClass("stashpad-settings-section"); - render(host); + try { render(host); } catch (e) { console.error(`[Stashpad] settings section "${name}" failed to render:`, e); } }, }; } @@ -1279,37 +1297,113 @@ export class StashpadSettingTab extends PluginSettingTab { } if (enc.amIMember()) { - new Setting(host).setName("Remove encryption").setDesc("Erases the key from this vault. Refused while any locked notes exist — decrypt everything first (locked notes have NO plaintext copy; losing the key loses them forever).").addButton((b) => { - b.setButtonText("Remove…").onClick(async () => { - // 0.98.23: HARD GUARD — locked blobs are the ONLY copy of their notes - // (lock permanently deletes the plaintext). Erasing the key with blobs - // still on disk = permanent data loss. Refuse until everything is - // decrypted; offer the vault-wide unlock as the way out. - // 0.98.42: scan the ADAPTER, not vault.getFiles — blobs are written - // via the adapter and can be invisible to the vault index for a - // while (and `_deleted/` / `.trash` blobs aren't indexed at all). - if (await anyStashencOnDisk(this.app)) { - new Notice(`Can't remove encryption: locked/encrypted-deleted notes still exist and would be lost forever. Run "Decrypt (unlock) ALL locked notes in the vault" and empty the encrypted trash first.`, 10000); - return; - } - new TypeToConfirmModal(this.app, { - title: "Remove encryption?", - body: "This erases the encryption key for this vault. Nothing is currently encrypted (locked notes are checked), so no content is lost — but you'll need to set a new password to encrypt later, and anything you had exported encrypted with this key stays locked to its passphrase.", - phrase: "REMOVE ENCRYPTION", - confirmText: "Remove encryption", - requirePassword: (pw) => enc.verifyPassword(pw), - onConfirm: async () => { - // Re-check at confirm time — a lock could have happened while the - // modal sat open (another device syncing, another window). - if (await anyStashencOnDisk(this.app)) { - new Notice("Locked notes appeared while this dialog was open — removal cancelled. Decrypt everything first.", 10000); + new Setting(host).setName("Remove encryption").setDesc("Erases the key for this vault so you can start fresh. If anything is still encrypted, you'll be offered to decrypt it (needs your password) or — if you've lost the password — permanently delete it. Then just type the confirmation phrase; no password needed.").addButton((b) => { + const runRemoval = async (): Promise<void> => { + // 0.112.0: authoritative-but-cheap state check (in-memory index + two + // folder listings of `_deleted/` and `.trash/`) instead of the old full + // recursive adapter walk that took minutes. + const state = await this.plugin.encryptionStateStrict(); + if (state.live) { + // 0.112.7: live locked content has no plaintext copy. Offer to either + // DECRYPT everything (needs the password) or DELETE it forever (for a + // lost password), then re-enter the removal flow. Mirrors the trash. + const deleteAllLocked = (): void => { + new ConfirmModal(this.app, "Delete all locked content forever?", + "This PERMANENTLY destroys every locked note and folder — there is NO decrypted copy and NO recovery. Only do this if you've lost the password and want to start fresh.", + "Delete locked content forever", + async (del) => { + if (!del) return; + const n = await this.plugin.purgeAllLockedContent(); + new Notice(`Deleted ${n} locked item${n === 1 ? "" : "s"}.`); + void runRemoval(); + }).open(); + }; + const decryptAll = async (): Promise<void> => { + await this.plugin.unlockAllInVault(); // prompts for the password if locked + if ((await this.plugin.encryptionStateStrict()).live) { + new Notice("Some notes are still locked (decryption was cancelled or failed) — removal cancelled.", 10000); return; } - await enc.clear(); new Notice("Encryption removed."); this.update?.(); - }, - }).open(); - }); - b.setDestructive(); + void runRemoval(); + }; + new ConfirmModal(this.app, "Encrypted notes are still locked", + "Some notes or folders are still encrypted (locked) and have no plaintext copy. Before removing encryption:\n\n• Decrypt everything — unlock them back to normal notes (needs your password).\n• Delete locked content — permanently destroy them (only if you've lost the password).", + "Decrypt everything", + (decrypt) => { if (decrypt) void decryptAll(); else deleteAllLocked(); }, + "Delete locked content").open(); + return; + } + // No password required to remove encryption. By the time we get here + // there is nothing recoverable to protect: live locked content already + // HARD-REFUSES removal (you must decrypt it first), and the trash has + // been explicitly decrypted or discarded. So the "REMOVE ENCRYPTION" + // phrase is the only gate — critically, this lets a user who has LOST + // the password (keychain empty/zeroed) still start fresh. + // trashConsented: the user already chose to decrypt or discard the + // encrypted trash; the confirm-time re-check uses it to abort only if + // NEW encrypted content appears mid-dialog. + const proceedToConfirm = (extraWarn: string, trashConsented: boolean): void => { + new TypeToConfirmModal(this.app, { + title: "Remove encryption?", + body: `This erases the encryption key for this vault. No locked notes/folders exist, so your live content is safe.${extraWarn} You'll need to set a new password to encrypt again later, and anything previously exported with this key stays locked to its passphrase.`, + phrase: "REMOVE ENCRYPTION", + confirmText: "Remove encryption", + onConfirm: async () => { + // Re-check authoritatively at confirm time — a lock or encrypt- + // delete could have synced in while the modal sat open. + const now = await this.plugin.encryptionStateStrict(); + if (now.live) { + new Notice("Locked notes appeared while this dialog was open — removal cancelled. Decrypt everything first.", 10000); + return; + } + if (now.trash && !trashConsented) { + new Notice("Encrypted trash appeared while this dialog was open — removal cancelled. Re-open Remove encryption to handle it.", 10000); + return; + } + // Discard path: actually DELETE the encrypted-trash blobs now, so + // removal doesn't leave orphaned, forever-unreadable files behind. + // (Decrypt path already emptied `_deleted/`, so this is a no-op there.) + const leftover = await this.plugin.listDeletedTrash(); + for (const it of leftover) await this.plugin.purgeDeletedAt(it.blob); + await enc.clear(); new Notice("Encryption removed."); this.update?.(); + }, + }).open(); + }; + + if (state.trash) { + // Encrypted trash exists but no live locked content. Removing the key + // makes the trash permanently unreadable. Fork: Decrypt Trash (CTA, + // recommended — restores them to their folders) vs Discard trash + // (→ a second Cancel/Confirm step before anything is lost). Esc on + // this modal routes to the Discard confirm, which is cancelable. + const decryptThenRemove = async (): Promise<void> => { + const n = await this.plugin.restoreAllTrash(); + // Authoritative re-check — restore removes blobs via raw adapter + // (no vault event), so confirm `_deleted/` is actually empty. + if ((await this.plugin.encryptionStateStrict()).trash) { + new Notice("Some encrypted-trash items couldn't be decrypted — removal cancelled. Check the trash tab and try again.", 10000); + return; + } + proceedToConfirm(n > 0 ? ` (${n} trash item${n === 1 ? "" : "s"} were decrypted back to their folders.)` : "", true); + }; + const confirmDiscard = (): void => { + new ConfirmModal(this.app, "Discard encrypted trash?", + "The encrypted-trash items will be PERMANENTLY lost the moment the key is erased — there is no recovery. Continue?", + "Confirm", + (discard) => { if (discard) proceedToConfirm(" ⚠️ The encrypted trash is being permanently discarded.", true); }).open(); + }; + new ConfirmModal(this.app, "Encrypted notes in the trash", + "There are encrypted, deleted notes in the trash. Removing encryption makes them PERMANENTLY unreadable.\n\n• Decrypt Trash — restore them to their original folders first (recommended).\n• Discard trash — let them be permanently erased with the key.", + "Decrypt Trash", + (decrypt) => { if (decrypt) void decryptThenRemove(); else confirmDiscard(); }, + "Discard trash").open(); + return; + } + // Nothing encrypted at all → clean removal. + proceedToConfirm("", false); + }; + b.setButtonText("Remove…").onClick(() => void runRemoval()); + b.buttonEl.addClass("mod-warning"); }); } @@ -1324,7 +1418,7 @@ export class StashpadSettingTab extends PluginSettingTab { new EncryptionPasswordModal(this.app, { mode: "setup", offerKeychain: false, kdfProbe, title: "Change shared password", intro: "Everyone who unlocks with the shared password will need the new one. Re-share it securely after changing.", onSubmit: async ({ next }) => { if (!next) return "Enter a password."; try { await enc.setSharedPassword(next); } catch (e) { return (e as Error).message; } new Notice("Shared password updated."); this.update?.(); return null; } }).open(); })) - .addButton((b) => { b.setButtonText("Turn off").onClick(async () => { await enc.removeSharedPassword(); new Notice("Shared password turned off."); this.update?.(); }); b.setDestructive(); }); + .addButton((b) => { b.setButtonText("Turn off").onClick(async () => { await enc.removeSharedPassword(); new Notice("Shared password turned off."); this.update?.(); }); b.buttonEl.addClass("mod-warning"); }); } else { new Setting(host).setName("Shared password").setDesc("OFF — set one passphrase that everyone types to unlock (the simplest way to share). Anyone who knows it can unlock; turning it off later doesn't claw back copies already synced elsewhere.") .addButton((b) => b.setButtonText("Set shared password…").onClick(() => { @@ -1354,7 +1448,7 @@ export class StashpadSettingTab extends PluginSettingTab { await enc.removeMember(m.id); new Notice(`Removed ${m.label}. (Not full revocation without rotating the key.)`); this.update?.(); - }); b.setDestructive(); }); + }); b.buttonEl.addClass("mod-warning"); }); } } const reqs = enc.pendingJoinRequests(); diff --git a/src/trash-view.ts b/src/trash-view.ts index f6cbbe0..b83e766 100644 --- a/src/trash-view.ts +++ b/src/trash-view.ts @@ -1,6 +1,7 @@ import { ItemView, WorkspaceLeaf, moment, setIcon } from "obsidian"; import type StashpadPlugin from "./main"; import { STASHPAD_TRASH_VIEW_TYPE } from "./types"; +import { ConfirmModal } from "./modals"; // Obsidian types `moment` as the namespace (not callable); cast to a callable. const momentFn = moment as unknown as (...args: unknown[]) => { fromNow: () => string }; @@ -24,6 +25,18 @@ export class StashpadTrashView extends ItemView { // re-reads the store. Debounced via a microtask guard. this.registerEvent(this.app.vault.on("create", (f) => { if (f.path.startsWith("_deleted/")) this.scheduleRender(); })); this.registerEvent(this.app.vault.on("delete", (f) => { if (f.path.startsWith("_deleted/")) this.scheduleRender(); })); + // 0.112.4: Mod+A selects every trash item — but only while THIS tab is the + // active leaf, and not while typing in a field. + this.registerDomEvent(document, "keydown", (e) => { + if (this.app.workspace.activeLeaf !== this.leaf) return; + const tgt = e.target as HTMLElement | null; + if (tgt && (tgt.tagName === "INPUT" || tgt.tagName === "TEXTAREA" || tgt.isContentEditable)) return; + if ((e.metaKey || e.ctrlKey) && !e.altKey && (e.key === "a" || e.key === "A")) { + if (this.order.length === 0) return; + e.preventDefault(); + this.selectAll(); + } + }); await this.render(); } @@ -38,6 +51,11 @@ export class StashpadTrashView extends ItemView { * each await (render is async + called from buttons/events — two in flight * would each empty-then-append, duplicating rows). */ private renderGen = 0; + /** 0.112.3: multi-select state. `selected` holds blob paths; `order` is the + * flat render order (for shift-range); `anchorIdx` is the last clicked row. */ + private selected = new Set<string>(); + private order: string[] = []; + private anchorIdx: number | null = null; async render(): Promise<void> { const gen = ++this.renderGen; @@ -65,7 +83,27 @@ export class StashpadTrashView extends ItemView { const restoreAll = header.createEl("button", { cls: "stashpad-trash-restore", text: "Restore all" }); setIcon(restoreAll.createSpan({ cls: "stashpad-btn-icon" }), "rotate-ccw"); - restoreAll.onclick = async () => { restoreAll.disabled = true; await this.plugin.restoreAllTrash(); await this.render(); }; + restoreAll.onclick = async () => { restoreAll.disabled = true; await this.plugin.restoreAllTrash(); this.clearSelection(); await this.render(); }; + + // Drop any selected paths that no longer exist (restored/purged elsewhere). + const present = new Set(items.map((it) => it.blob)); + for (const b of [...this.selected]) if (!present.has(b)) this.selected.delete(b); + + // Selection action bar (only when something is selected). + if (this.selected.size > 0) { + const bar = root.createDiv({ cls: "stashpad-trash-selbar" }); + bar.createSpan({ cls: "stashpad-trash-selcount", text: `${this.selected.size} selected` }); + const restoreSel = bar.createEl("button", { cls: "stashpad-trash-restore", text: "Restore selected" }); + restoreSel.onclick = async () => { + restoreSel.disabled = true; + for (const b of [...this.selected]) await this.plugin.restoreDeletedAt(b, { silent: true }); + this.clearSelection(); await this.render(); + }; + const delSel = bar.createEl("button", { cls: "stashpad-trash-delete mod-warning", text: "Delete selected" }); + delSel.onclick = () => this.confirmPurge([...this.selected]); + const clear = bar.createEl("button", { cls: "stashpad-trash-iconbtn", text: "Clear" }); + clear.onclick = () => { this.clearSelection(); void this.render(); }; + } // Group by origin folder; obscured-title notes (no readable origin on disk) // go under "Hidden" so we don't reveal where they came from. @@ -76,6 +114,9 @@ export class StashpadTrashView extends ItemView { } const keys = [...groups.keys()].sort((a, b) => (a === " hidden" ? 1 : b === " hidden" ? -1 : a.localeCompare(b))); + // Rebuild the flat render order for shift-range selection. + this.order = []; + for (const key of keys) { const hidden = key === " hidden"; const group = root.createDiv({ cls: "stashpad-trash-group" }); @@ -85,7 +126,15 @@ export class StashpadTrashView extends ItemView { head.createSpan({ cls: "stashpad-trash-group-count", text: String(groups.get(key)!.length) }); for (const it of groups.get(key)!) { + const idx = this.order.length; + this.order.push(it.blob); const row = group.createDiv({ cls: "stashpad-trash-row" }); + if (this.selected.has(it.blob)) row.addClass("is-selected"); + // Click the row body to (multi-)select; cmd/ctrl toggles, shift ranges. + row.addEventListener("click", (e) => { + if ((e.target as HTMLElement).closest("button")) return; // let buttons act + this.onRowClick(idx, it.blob, e); + }); const main = row.createDiv({ cls: "stashpad-trash-row-main" }); main.createSpan({ cls: "stashpad-trash-title", text: hidden ? "Locked note" : (it.meta?.title || "Locked note") }); const when = it.meta?.deletedAt ? `deleted ${momentFn(it.meta.deletedAt).fromNow()}` : "deleted"; @@ -94,10 +143,55 @@ export class StashpadTrashView extends ItemView { const btn = row.createEl("button", { cls: "stashpad-trash-restore", text: "Restore" }); setIcon(btn.createSpan({ cls: "stashpad-btn-icon" }), "rotate-ccw"); btn.onclick = async () => { btn.disabled = true; const ok = await this.plugin.restoreDeletedAt(it.blob); if (ok) await this.render(); else btn.disabled = false; }; + const del = row.createEl("button", { cls: "stashpad-trash-delete", attr: { "aria-label": "Delete permanently" } }); + setIcon(del, "trash-2"); + del.onclick = () => this.confirmPurge([it.blob]); } } } + private clearSelection(): void { this.selected.clear(); this.anchorIdx = null; } + + /** Select every trash item (Mod+A). No-op when the list is empty. */ + private selectAll(): void { + if (this.order.length === 0) return; + for (const b of this.order) this.selected.add(b); + this.anchorIdx = this.order.length - 1; + void this.render(); + } + + /** Selection click with cmd/ctrl (toggle), shift (range), plain (single). */ + private onRowClick(idx: number, blob: string, e: MouseEvent): void { + if (e.shiftKey && this.anchorIdx !== null) { + const [a, b] = this.anchorIdx < idx ? [this.anchorIdx, idx] : [idx, this.anchorIdx]; + this.selected.clear(); + for (let i = a; i <= b; i++) this.selected.add(this.order[i]); + } else if (e.metaKey || e.ctrlKey) { + if (this.selected.has(blob)) this.selected.delete(blob); else this.selected.add(blob); + this.anchorIdx = idx; + } else { + if (this.selected.size === 1 && this.selected.has(blob)) this.selected.clear(); + else { this.selected.clear(); this.selected.add(blob); } + this.anchorIdx = idx; + } + void this.render(); + } + + /** Confirm + permanently delete trash blobs (irreversible — no decrypt). */ + private confirmPurge(blobs: string[]): void { + if (blobs.length === 0) return; + const n = blobs.length; + new ConfirmModal(this.app, n === 1 ? "Delete permanently?" : `Delete ${n} items permanently?`, + `${n === 1 ? "This encrypted item" : `These ${n} encrypted items`} will be PERMANENTLY deleted and CANNOT be restored — there is no decrypted copy. Continue?`, + "Delete forever", + async (ok) => { + if (!ok) return; + for (const b of blobs) await this.plugin.purgeDeletedAt(b); + this.clearSelection(); + await this.render(); + }).open(); + } + async onClose(): Promise<void> { this.contentEl.empty(); } } diff --git a/styles.css b/styles.css index 8e1fe92..0a2a6ab 100644 --- a/styles.css +++ b/styles.css @@ -2435,6 +2435,23 @@ .stashpad-trash-sub { font-size: var(--font-ui-smaller); color: var(--text-muted); } .stashpad-trash-restore { flex: 0 0 auto; display: inline-flex; align-items: center; gap: 4px; font-size: var(--font-ui-smaller); padding: 3px 10px; cursor: pointer; --icon-size: 13px; } .stashpad-trash-restore .svg-icon { width: var(--icon-size); height: var(--icon-size); } +/* 0.112.3: multi-select + permanent-delete in the encrypted-trash tab. */ +.stashpad-trash-row { cursor: pointer; } +.stashpad-trash-row.is-selected { background: var(--background-modifier-hover); box-shadow: inset 0 0 0 1px var(--interactive-accent); } +.stashpad-trash-delete { + flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; + padding: 3px 8px; cursor: pointer; --icon-size: 14px; + background: transparent; border: none; box-shadow: none; color: var(--text-faint); +} +.stashpad-trash-delete:hover { color: var(--text-error); background: var(--background-modifier-error-hover); } +.stashpad-trash-delete .svg-icon { width: var(--icon-size); height: var(--icon-size); } +.stashpad-trash-selbar { + display: flex; align-items: center; gap: 8px; flex-wrap: wrap; + padding: 6px 8px; margin-bottom: 8px; border-radius: 6px; + background: var(--background-modifier-hover); +} +.stashpad-trash-selcount { flex: 1 1 auto; font-size: var(--font-ui-smaller); color: var(--text-muted); } +.stashpad-trash-delete.mod-warning { color: var(--text-on-accent); background: var(--text-error); padding: 3px 10px; border-radius: 4px; font-size: var(--font-ui-smaller); } /* 0.98.24: mobile ⋮ menu button on locked stubs (desktop uses right-click). */ .stashpad-locked-menu { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center;