diff --git a/main.js b/main.js index 1992ace..b06151f 100644 --- a/main.js +++ b/main.js @@ -1,149 +1,149 @@ -"use strict";var yn=Object.defineProperty;var el=Object.getOwnPropertyDescriptor;var il=Object.getOwnPropertyNames;var sl=Object.prototype.hasOwnProperty;var Jt=(A,a)=>()=>(A&&(a=A(A=0)),a);var fi=(A,a)=>{for(var t in a)yn(A,t,{get:a[t],enumerable:!0})},nl=(A,a,t,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let i of il(a))!sl.call(A,i)&&i!==t&&yn(A,i,{get:()=>a[i],enumerable:!(e=el(a,i))||e.enumerable});return A};var ol=A=>nl(yn({},"__esModule",{value:!0}),A);function Fn(A){return Array.isArray(A)?A.filter(a=>typeof a=="string"):typeof A=="string"?A.split(/[,\s]+/).filter(Boolean):[]}function Ye(A,a){let t=a.replace(/^#/,"");return Fn(A?.tags).some(e=>e.replace(/^#/,"")===t)}function kn(A,a){let t=a.replace(/^#/,""),e=Fn(A.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),A.tags=e}function Sn(A,a){let t=a.replace(/^#/,""),e=Fn(A.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?A.tags=e:delete A.tags}function $e(A){return A.split("/").some(a=>wi.has(a))}function zo(A){return A.split("/").some(a=>a==="_archive"||a===".archive")}function $t(A){let a=(A??"").trim();return!a||/^\[\[.*\]\]$/.test(a)?a:`[[${a}]]`}function be(A){let a=(A??"").trim(),t=a.match(/^\[\[(.*)\]\]$/);return t&&(a=t[1]),a.split("|")[0].split("#")[0].split("^")[0].trim()}function Wo(A){let a=A.match(/\.([^./]+)$/);return!!a&&ll.has(a[1].toLowerCase())}function Xo(A,a){if(!Array.isArray(a))return!1;for(let t of a){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(A))return!0}catch{}else if(A===e||A.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function os(A,a){let t=A.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=a.toLowerCase();return t.every(i=>e.includes(i))}function fe(A){if(typeof A!="string")return null;let a=A.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=a.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function De(A){let a=A?.assignedTo,t=Array.isArray(a)?a:a!=null?[a]:[],e=[];for(let i of t){let s=fe(i);s&&e.push(s)}return e}var K,pe,ge,Se,Je,Oe,k,ue,wi,ll,rt=Jt(()=>{"use strict";K="stashpad-view",pe="stashpad-panels",ge="stashpad-folder-panel",Se="stashpad-detail",Je="stashpad-trash",Oe="stashpad-aggregate",k="__root__";ue=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","listPinned","listPinnedAt","imported","okfParent","okfChildren"],wi=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ll=new Set(["edtz"])});function Ei(A,a){let t=A.replace(/\r\n/g,` -`);if(a==="lines")return t.split(` -`).map(n=>n.trim()).filter(Boolean);if(a==="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(` +"use strict";var vn=Object.defineProperty;var sl=Object.getOwnPropertyDescriptor;var nl=Object.getOwnPropertyNames;var ol=Object.prototype.hasOwnProperty;var Jt=(A,r)=>()=>(A&&(r=A(A=0)),r);var Ii=(A,r)=>{for(var t in r)vn(A,t,{get:r[t],enumerable:!0})},al=(A,r,t,e)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of nl(r))!ol.call(A,i)&&i!==t&&vn(A,i,{get:()=>r[i],enumerable:!(e=sl(r,i))||e.enumerable});return A};var rl=A=>al(vn({},"__esModule",{value:!0}),A);function Dn(A){return Array.isArray(A)?A.filter(r=>typeof r=="string"):typeof A=="string"?A.split(/[,\s]+/).filter(Boolean):[]}function Ye(A,r){let t=r.replace(/^#/,"");return Dn(A?.tags).some(e=>e.replace(/^#/,"")===t)}function xn(A,r){let t=r.replace(/^#/,""),e=Dn(A.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),A.tags=e}function Nn(A,r){let t=r.replace(/^#/,""),e=Dn(A.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?A.tags=e:delete A.tags}function $e(A){return A.split("/").some(r=>Qi.has(r))}function jo(A){return A.split("/").some(r=>r==="_archive"||r===".archive")}function $t(A){let r=(A??"").trim();return!r||/^\[\[.*\]\]$/.test(r)?r:`[[${r}]]`}function be(A){let r=(A??"").trim(),t=r.match(/^\[\[(.*)\]\]$/);return t&&(r=t[1]),r.split("|")[0].split("#")[0].split("^")[0].trim()}function _o(A){let r=A.match(/\.([^./]+)$/);return!!r&&Al.has(r[1].toLowerCase())}function ta(A,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(A))return!0}catch{}else if(A===e||A.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function as(A,r){let t=A.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=r.toLowerCase();return t.every(i=>e.includes(i))}function fe(A){if(typeof A!="string")return null;let r=A.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 De(A){let r=A?.assignedTo,t=Array.isArray(r)?r:r!=null?[r]:[],e=[];for(let i of t){let s=fe(i);s&&e.push(s)}return e}var q,pe,ge,Se,Je,Oe,k,ue,Qi,Al,at=Jt(()=>{"use strict";q="stashpad-view",pe="stashpad-panels",ge="stashpad-folder-panel",Se="stashpad-detail",Je="stashpad-trash",Oe="stashpad-aggregate",k="__root__";ue=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","listPinned","listPinnedAt","imported","okfParent","okfChildren"],Qi=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);Al=new Set(["edtz"])});function vi(A,r){let t=A.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 Ft(A,a,t){A.empty();try{(0,tr.setIcon)(A,a)}catch{}let e=A.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(A.empty(),A.createSpan({cls:"stashpad-icon-fallback",text:t}))}function er(A){if(A instanceof Element&&A.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let a=new Set([document]);A instanceof Element&&A.ownerDocument&&a.add(A.ownerDocument);for(let t of a)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}function ir(A){let a=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(A))!=null;)a.push({lang:e[3].trim(),code:e[4]});return a}function vi(A){return A.split("/").map(a=>a.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function sr(A,a,t){let e=new Set(a),i=A.filter(n=>!e.has(n)),s=A.findIndex(n=>e.has(n));if(s<0)return A.slice();switch(t){case"top":return[...a,...i];case"bottom":return[...i,...a];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...a),o}case"down":{let n=(()=>{let c=-1;return A.forEach((d,h)=>{e.has(d)&&(c=h)}),c})(),o=0;for(let c=0;c0){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:cl(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):a}var tr,Qi,xe,Ne,Fi=Jt(()=>{"use strict";tr=require("obsidian"),Qi={lines:"Each line",paragraphs:"Paragraphs (blank line)",headings:"Headings"};xe="__stashpad:tagged__",Ne="__stashpad:untagged__"});function Al(A,a){return A>12?A>=24?0:A:a==="am"?A===12?0:A:A===12?12:A+12}function as(A,a){A.addClass("stashpad-when-pop-time");let t=a.seedPeriod,e=A.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(a.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(a.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let r=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});r.type="button";let l=()=>{o.toggleClass("is-active",t==="am"),r.toggleClass("is-active",t==="pm")};l(),o.addEventListener("mousedown",B=>B.preventDefault()),r.addEventListener("mousedown",B=>B.preventDefault()),o.addEventListener("click",B=>{B.preventDefault(),t="am",l()}),r.addEventListener("click",B=>{B.preventDefault(),t="pm",l()});let c=i;i.addEventListener("focus",()=>{c=i,i.select()}),s.addEventListener("focus",()=>{c=s,s.select()});let d=()=>{let w=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",w),r.toggleClass("is-disabled",w),o.disabled=w,r.disabled=w},h=B=>{let w=B.value.replace(/\D/g,"").slice(0,2);if(w===""){B.value="",B===i&&d();return}let y=parseInt(w,10);B===i?y>24&&(y=24):y>59&&(y=59),B.value=String(y),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,w=parseInt(s.value||"0",10)||0,y=B>12;a.onFinalize({hours24:Al(B,t),minutes:w,raw:{hh:B,mm:w,period:t,is24:y}}),a.close()};a.setOnEnter?.(g);let u=[i,s,o,r],p=(B,w)=>{let y=u.indexOf(B);if(y===-1)return;let Q=(y+w+u.length)%u.length;u[Q].focus()},f=B=>{B.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),g()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),a.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),p(B,w.shiftKey?-1:1))})},I=A.createDiv({cls:"stashpad-when-time-pad"}),m=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],C=null;for(let B of m){let w=I.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",B==="backspace"?(0,or.setIcon)(w,"delete"):B==="insert"?(w.setText("OK"),C=w):w.setText(B),B==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{if(y.preventDefault(),B==="insert"){g();return}if(B==="backspace"){c.value=c.value.slice(0,-1),h(c),c.focus();return}let Q=c.selectionStart===0&&c.selectionEnd===c.value.length&&c.value.length>0,v=2,E=Q||c.value.length>=v?B:c.value+B;c.value=E,h(c),c.focus(),c.setSelectionRange(c.value.length,c.value.length),c===i&&c.value.length>=v&&(s.focus(),s.select())})}C&&u.push(C);for(let B of u)f(B);i.focus(),i.select()}function rr(A){let{hh:a,mm:t,period:e,is24:i}=A.raw;return i?`${a}:${String(t).padStart(2,"0")}`:`${a}:${String(t).padStart(2,"0")}${e}`}var or,Dn=Jt(()=>{"use strict";or=require("obsidian")});function lr(A){let a=Math.floor(4294967296/A)*A,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=a);return e%A}function xn(A=5){let a=[];for(let t=0;t=1&&s.every(r=>/^[a-zA-Z]+$/.test(r))&&(i=Math.min(i,s.length*11)),dl.has(A.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 hl(A){let a=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Ve(A){let a="stashpad-",t=hl(A),e=64-a.length-1-t.length,i=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${a}${i}-${t}`}var ar,dl,ls=Jt(()=>{"use strict";ar="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((A,a,t)=>t.indexOf(A)===a);dl=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 cs={};fi(cs,{newId:()=>W});function W(A=6){let a="",t=new Uint8Array(A);crypto.getRandomValues(t);for(let e=0;e{"use strict";cr="abcdefghijkmnpqrstuvwxyz23456789"});var Pi={};fi(Pi,{BreadcrumbLevelsModal:()=>xi,ColorPickerModal:()=>Pe,ConfirmDeleteModal:()=>We,ConfirmModal:()=>it,CustomColorModal:()=>As,DueDatePickerModal:()=>Ze,EncryptionPasswordModal:()=>ct,ExportStashModal:()=>Xe,ImportDupChoiceModal:()=>Mi,ImportLogModal:()=>Mn,LogModal:()=>ze,NotificationHistoryModal:()=>Ni,OkfExportModal:()=>Ti,SplitNoteModal:()=>Si,StashPasswordModal:()=>bi,TypeToConfirmModal:()=>Di,buildAssigneePicker:()=>Ar});function Ar(A,a){let t=[...a.initial],e=a.knownAuthors,i=A.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"}}),r=n.createDiv({cls:"stashpad-assign-suggest"});r.setCssStyles({display:"none"});let l=()=>a.onChange([...t]),c=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let g of t){let u=s.createSpan({cls:"stashpad-assign-chip"});u.createSpan({cls:"stashpad-assign-chip-name",text:g.name});let p=u.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});p.title=`Remove ${g.name}`,p.onclick=()=>{t=t.filter(f=>f.id!==g.id),l(),c()}}},d=g=>{g.name.trim()&&(t.some(u=>u.id===g.id)||t.push(g),o.value="",r.setCssStyles({display:"none"}),l(),c(),o.focus())},h=()=>{let g=o.value.trim();r.empty();let u=new Set(t.map(I=>I.id)),f=e.filter(I=>!u.has(I.id)&&os(g,I.name)).slice(0,6).map(I=>({label:I.name,onPick:()=>d(I)}));if(g&&!e.some(I=>I.name.toLowerCase()===g.toLowerCase())&&f.push({label:`Create \u201C${g}\u201D`,onPick:()=>d({id:W(6),name:g})}),f.length===0){r.setCssStyles({display:"none"});return}r.setCssStyles({display:""});for(let I of f){let m=r.createDiv({cls:"stashpad-assign-suggest-item",text:I.label});m.onmousedown=C=>{C.preventDefault(),I.onPick()}}};o.addEventListener("input",h),o.addEventListener("focus",h),o.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let u=r.querySelector(".stashpad-assign-suggest-item");u&&u.dispatchEvent(new MouseEvent("mousedown"))}else g.key==="Escape"&&r.style.display!=="none"&&(g.stopPropagation(),r.setCssStyles({display:"none"}))}),o.addEventListener("blur",()=>{window.setTimeout(()=>{r.setCssStyles({display:"none"})},120)}),c()}var q,pl,Me,ze,We,Si,Xe,bi,ct,Di,As,ki,Pe,it,xi,Ze,Te,Ni,Mn,Mi,Ti,kt=Jt(()=>{"use strict";q=require("obsidian");Fi();Dn();rt();ls();Gt();pl=q.moment,Me=class Me 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 r=t.createEl("button",{cls:"mod-warning",text:"Clear log"});r.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(Me.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 r=t.createEl("option",{text:`${n} (${o})`});r.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(Me.PAGE),this.renderFooter()},t>Me.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 it(this.app,"Clear log?","A timestamped copy will be saved alongside the active log before it's truncated.","Export & clear",async t=>{if(!(!t||!await this.exportCopy())){try{await this.app.vault.adapter.write(this.jsonlPath,"")}catch(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 r=document.createElement("span");return r.className="stashpad-log-msg",r.textContent=this.describe(t),e.appendChild(r),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()}};Me.PAGE=100;ze=Me,We=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"}),r=o.createEl("input",{type:"checkbox"});r.checked=e,r.onchange=()=>{e=r.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()}},Si=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 Ft(A,r,t){A.empty();try{(0,ia.setIcon)(A,r)}catch{}let e=A.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(A.empty(),A.createSpan({cls:"stashpad-icon-fallback",text:t}))}function sa(A){if(A instanceof Element&&A.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let r=new Set([document]);A instanceof Element&&A.ownerDocument&&r.add(A.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 na(A){let r=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(A))!=null;)r.push({lang:e[3].trim(),code:e[4]});return r}function Fi(A){return A.split("/").map(r=>r.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function oa(A,r,t){let e=new Set(r),i=A.filter(n=>!e.has(n)),s=A.findIndex(n=>e.has(n));if(s<0)return A.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 c=-1;return A.forEach((d,h)=>{e.has(d)&&(c=h)}),c})(),o=0;for(let c=0;c0){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:dl(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 ia,Ei,xe,Ne,ki=Jt(()=>{"use strict";ia=require("obsidian"),Ei={lines:"Each line",paragraphs:"Paragraphs (blank line)",headings:"Headings"};xe="__stashpad:tagged__",Ne="__stashpad:untagged__"});function hl(A,r){return A>12?A>=24?0:A:r==="am"?A===12?0:A:A===12?12:A+12}function As(A,r){A.addClass("stashpad-when-pop-time");let t=r.seedPeriod,e=A.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 c=i;i.addEventListener("focus",()=>{c=i,i.select()}),s.addEventListener("focus",()=>{c=s,s.select()});let d=()=>{let w=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",w),a.toggleClass("is-disabled",w),o.disabled=w,a.disabled=w},h=B=>{let w=B.value.replace(/\D/g,"").slice(0,2);if(w===""){B.value="",B===i&&d();return}let y=parseInt(w,10);B===i?y>24&&(y=24):y>59&&(y=59),B.value=String(y),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,w=parseInt(s.value||"0",10)||0,y=B>12;r.onFinalize({hours24:hl(B,t),minutes:w,raw:{hh:B,mm:w,period:t,is24:y}}),r.close()};r.setOnEnter?.(g);let u=[i,s,o,a],p=(B,w)=>{let y=u.indexOf(B);if(y===-1)return;let Q=(y+w+u.length)%u.length;u[Q].focus()},f=B=>{B.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),g()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),r.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),p(B,w.shiftKey?-1:1))})},I=A.createDiv({cls:"stashpad-when-time-pad"}),m=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],C=null;for(let B of m){let w=I.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",B==="backspace"?(0,ra.setIcon)(w,"delete"):B==="insert"?(w.setText("OK"),C=w):w.setText(B),B==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{if(y.preventDefault(),B==="insert"){g();return}if(B==="backspace"){c.value=c.value.slice(0,-1),h(c),c.focus();return}let Q=c.selectionStart===0&&c.selectionEnd===c.value.length&&c.value.length>0,v=2,E=Q||c.value.length>=v?B:c.value+B;c.value=E,h(c),c.focus(),c.setSelectionRange(c.value.length,c.value.length),c===i&&c.value.length>=v&&(s.focus(),s.select())})}C&&u.push(C);for(let B of u)f(B);i.focus(),i.select()}function la(A){let{hh:r,mm:t,period:e,is24:i}=A.raw;return i?`${r}:${String(t).padStart(2,"0")}`:`${r}:${String(t).padStart(2,"0")}${e}`}var ra,Tn=Jt(()=>{"use strict";ra=require("obsidian")});function Aa(A){let r=Math.floor(4294967296/A)*A,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=r);return e%A}function Pn(A=5){let r=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),pl.has(A.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 gl(A){let r=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Ve(A){let r="stashpad-",t=gl(A),e=64-r.length-1-t.length,i=A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${r}${i}-${t}`}var ca,pl,ds=Jt(()=>{"use strict";ca="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((A,r,t)=>t.indexOf(A)===r);pl=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 hs={};Ii(hs,{newId:()=>W});function W(A=6){let r="",t=new Uint8Array(A);crypto.getRandomValues(t);for(let e=0;e{"use strict";da="abcdefghijkmnpqrstuvwxyz23456789"});var Hi={};Ii(Hi,{BreadcrumbLevelsModal:()=>Ni,ColorPickerModal:()=>Pe,ConfirmDeleteModal:()=>We,ConfirmModal:()=>it,CustomColorModal:()=>ps,DueDatePickerModal:()=>Ze,EncryptionPasswordModal:()=>ct,ExportStashModal:()=>Xe,ImportDupChoiceModal:()=>Ti,ImportLogModal:()=>Un,LogModal:()=>ze,NotificationHistoryModal:()=>Mi,OkfExportModal:()=>Pi,SplitNoteModal:()=>bi,StashPasswordModal:()=>Di,TypeToConfirmModal:()=>xi,buildAssigneePicker:()=>ha});function ha(A,r){let t=[...r.initial],e=r.knownAuthors,i=A.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]),c=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let g of t){let u=s.createSpan({cls:"stashpad-assign-chip"});u.createSpan({cls:"stashpad-assign-chip-name",text:g.name});let p=u.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});p.title=`Remove ${g.name}`,p.onclick=()=>{t=t.filter(f=>f.id!==g.id),l(),c()}}},d=g=>{g.name.trim()&&(t.some(u=>u.id===g.id)||t.push(g),o.value="",a.setCssStyles({display:"none"}),l(),c(),o.focus())},h=()=>{let g=o.value.trim();a.empty();let u=new Set(t.map(I=>I.id)),f=e.filter(I=>!u.has(I.id)&&as(g,I.name)).slice(0,6).map(I=>({label:I.name,onPick:()=>d(I)}));if(g&&!e.some(I=>I.name.toLowerCase()===g.toLowerCase())&&f.push({label:`Create \u201C${g}\u201D`,onPick:()=>d({id:W(6),name:g})}),f.length===0){a.setCssStyles({display:"none"});return}a.setCssStyles({display:""});for(let I of f){let m=a.createDiv({cls:"stashpad-assign-suggest-item",text:I.label});m.onmousedown=C=>{C.preventDefault(),I.onPick()}}};o.addEventListener("input",h),o.addEventListener("focus",h),o.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let u=a.querySelector(".stashpad-assign-suggest-item");u&&u.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)}),c()}var K,ul,Me,ze,We,bi,Xe,Di,ct,xi,ps,Si,Pe,it,Ni,Ze,Te,Mi,Un,Ti,Pi,kt=Jt(()=>{"use strict";K=require("obsidian");ki();Tn();at();ds();Gt();ul=K.moment,Me=class Me extends K.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(Me.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(Me.PAGE),this.renderFooter()},t>Me.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 K.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,K.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 K.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new K.Notice(`Export failed: ${t.message}`),null}}clearLog(){new it(this.app,"Clear log?","A timestamped copy will be saved alongside the active log before it's truncated.","Export & clear",async t=>{if(!(!t||!await this.exportCopy())){try{await this.app.vault.adapter.write(this.jsonlPath,"")}catch(i){new K.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 K.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,K.moment)(t.ts).isValid()?(0,K.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()}};Me.PAGE=100;ze=Me,We=class extends K.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()}},bi=class extends K.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 r=Ei(this.body,o),l=t.createEl("button",{cls:"stashpad-split-quick-btn",text:`${Qi[o]} (${r.length})`});l.disabled=r.length<2,l.onmousedown=c=>c.preventDefault(),l.onclick=()=>{let c=Ei(this.body,o);if(c.length<2){new q.Notice("That delimiter wouldn't split this note.");return}this.close(),this.onSplitMany(c)}});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 r=Math.min(e.scrollHeight,i*s+16);e.setCssStyles({height:`${Math.max(r,i*n+16)}px`})};requestAnimationFrame(()=>{o();let r=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(r,r)}),e.addEventListener("input",o)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},Xe=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 r=n.createEl("label",{text:"Encrypt with a password"});r.htmlFor=o.id;let l=s.createDiv({cls:"stashpad-export-pw-area"});l.setCssStyles({display:"none"});let c=[],d=L=>{let z=l.createDiv({cls:"stashpad-export-pw-row"}),J=z.createEl("input",{type:"password"});J.addClass("stashpad-export-name"),J.placeholder=L;let O=z.createEl("button",{cls:"stashpad-export-copy"}),st=()=>{let lt=J.value.length===0;O.setText(lt?"Paste":"Copy"),O.toggleClass("is-paste",lt),O.setAttr("aria-label",`${lt?"Paste into":"Copy"} ${L.toLowerCase()}`)};return O.onclick=async lt=>{if(lt.preventDefault(),J.value.length===0)try{let tt=(await navigator.clipboard?.readText())?.trim();if(!tt){new q.Notice("Clipboard is empty.");return}J.value=tt,J.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(J.value).then(()=>new q.Notice("Passphrase copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},st(),c.push(st),J},h=d("Password"),g=d("Confirm password"),u=l.createDiv({cls:"stashpad-export-strength"}),p=u.createDiv({cls:"stashpad-strength-bar"}),f=[0,1,2,3].map(()=>p.createDiv({cls:"stashpad-strength-seg"})),I=u.createEl("span",{cls:"stashpad-strength-label"}),m=l.createDiv({cls:"stashpad-export-genrow"}),C=m.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),B=m.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=l.createEl("div",{cls:"stashpad-export-pw-hint"}),y=l.createEl("div",{cls:"stashpad-export-pw-suite"});y.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(L=>{y.toggleClass("is-weak",!L),y.setText(L?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run on this device, so this export will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>{y.setText("Encryption: AES-256-GCM with a password-derived key.")}):y.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let Q=this.app.secretStorage,v=l.createDiv({cls:"stashpad-export-remember"}),E=v.createEl("input",{type:"checkbox"});E.id="stashpad-export-remember-cb";let S=v.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});S.htmlFor=E.id;let D=l.createDiv({cls:"stashpad-export-remember-note"});D.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."),D.setCssStyles({display:"none"}),E.onchange=()=>{D.setCssStyles({display:E.checked?"":"none"})},Q||v.setCssStyles({display:"none"});let H=()=>{let L=e.value.trim()||this.defaultBaseName;return o.checked?`${L}-encrypted`:L},U=()=>i.setText(`Saves as: ${H()}-.stash`);e.oninput=U;let N=this.contentEl.createDiv({cls:"stashpad-export-footer"}),b=N.createEl("button",{text:"Cancel"});b.onclick=()=>this.close();let T=N.createEl("button",{cls:"mod-cta",text:"Export"}),P=()=>{let L=Nn(h.value);u.style.visibility=h.value?"visible":"hidden",f.forEach((z,J)=>z.toggleClass("is-on",h.value!==""&&J<=L.level)),p.dataset.level=String(L.level),I.setText(L.label)},R=()=>{let L=o.checked;l.setCssStyles({display:L?"":"none"});let z=!0;L&&(h.value?h.value!==g.value?(w.setText("Passwords don't match."),w.addClass("is-error"),z=!1):(w.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),w.removeClass("is-error")):(w.setText("Enter a password to encrypt this export."),w.removeClass("is-error"),z=!1)),P(),c.forEach(J=>J()),T.disabled=!z,T.toggleClass("is-disabled",!z),U()},Z=!1,$=L=>{Z=L,h.type=g.type=L?"text":"password",B.setText(L?"Hide":"Show")};B.onclick=L=>{L.preventDefault(),$(!Z)},C.onclick=L=>{L.preventDefault(),h.value=g.value=xn(),$(!1),new q.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),R()},o.onchange=R,h.oninput=R,g.oninput=R,R();let V=()=>this.commit(H(),o.checked?h.value:null,o.checked&&E.checked);T.onclick=V,this.scope.register([],"Enter",L=>{L.preventDefault(),T.disabled||V()}),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()}},bi=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()}},ct=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=f=>{let I=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),m=I.createEl("input",{type:"password"});m.addClass("stashpad-export-name","stashpad-encryption-field"),m.placeholder=f;let C=I.createEl("button",{cls:"stashpad-export-copy"}),B=()=>{let w=m.value.length===0;C.setText(w?"Paste":"Copy"),C.toggleClass("is-paste",w),C.setAttr("aria-label",`${w?"Paste into":"Copy"} ${f.toLowerCase()}`)};return C.onclick=async w=>{if(w.preventDefault(),m.value.length===0)try{let y=(await navigator.clipboard?.readText())?.trim();if(!y){new q.Notice("Clipboard is empty.");return}m.value=y,m.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(m.value).then(()=>new q.Notice("Copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},m.addEventListener("input",B),B(),e.push(B),m},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 f=this.contentEl.createDiv({cls:"stashpad-export-strength"}),I=f.createDiv({cls:"stashpad-strength-bar"}),m=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),C=f.createEl("span",{cls:"stashpad-strength-label"}),B=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),w=()=>{let E=n.value,S=Nn(E);m.forEach((D,H)=>D.toggleClass("is-on",H0&&E.length<6?" \u2014 use at least 6":""}`),B.toggleClass("is-weak",E.length>0&&E.length<6)};n.addEventListener("input",w),w();let y=this.contentEl.createDiv({cls:"stashpad-export-genrow"});y.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=E=>{E.preventDefault();let S=xn(5);n.value=S,o&&(o.value=S),w(),e.forEach(D=>D()),new q.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(S).catch(()=>{})};let Q=y.createEl("button",{cls:"stashpad-export-show",text:"Show"});Q.onclick=E=>{E.preventDefault();let S=n.type==="password";n.type=S?"text":"password",o&&(o.type=S?"text":"password"),Q.setText(S?"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(E=>{v.toggleClass("is-weak",!E),v.setText(E?"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 r=null,l=this.app.secretStorage;if(this.opts.offerKeychain&&l){let f=this.contentEl.createDiv({cls:"stashpad-export-remember"});r=f.createEl("input",{type:"checkbox"}),r.id="stashpad-enc-remember";let I=f.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});I.htmlFor=r.id;let m=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});m.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."),m.setCssStyles({display:"none"}),r.onchange=()=>{m.setCssStyles({display:r.checked?"":"none"})}}let c=this.contentEl.createEl("div",{cls:"stashpad-export-error"});c.setCssStyles({display:"none"});let d=f=>{c.setText(f),c.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"}),u=!1,p=async()=>{if(u)return;let f=s?.value??void 0,I=n?.value??void 0;if((t==="unlock"||t==="change")&&!f){d("Enter your current password.");return}if(t==="setup"||t==="change"){if(!I){d("Enter a password.");return}if(I.length<6){d("Use at least 6 characters.");return}if(I!==o?.value){d("Passwords don't match.");return}}u=!0,g.disabled=!0,c.setCssStyles({display:"none"});let m=g.textContent;g.setText("Working\u2026");try{let C=await this.opts.onSubmit({current:f,next:I,remember:!!r?.checked});if(C){d(C),u=!1,g.disabled=!1,g.setText(m??"OK");return}this.succeeded=!0,this.close()}catch(C){d(`Failed: ${C.message}`),u=!1,g.disabled=!1,g.setText(m??"OK")}};g.onclick=()=>void p(),this.scope.register([],"Enter",f=>{f.preventDefault(),p()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},Di=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(),r=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",r),t?.addEventListener("input",r),r();let l=!1,c=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,r();return}this.close(),await this.opts.onConfirm()}};n.onclick=()=>void c(),this.scope.register([],"Enter",d=>{d.preventDefault(),c()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},As=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"}),r=o.createEl("button",{text:"Cancel"});r.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 c=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});c.title="Apply and save this color so it appears as a tile next time.",c.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",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()}},ki=class ki 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=[...ki.DEFAULT_PALETTE,...this.customPalette];for(let r of i){let l=t.createDiv({cls:"stashpad-color-tile"});l.style.background=r,l.title=r;let c=!ki.DEFAULT_PALETTE.some(h=>h.toLowerCase()===r.toLowerCase()),d=this.items.length;if(l.onclick=()=>this.activate(d),c&&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(r)}}this.items.push({kind:c?"custom":"preset",color:r,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(r=>this.currentColor===null?r.kind==="none":this.currentColor?r.color!==null&&r.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=o>=0?o:0,this.refreshActive(),this.scope.register([],"ArrowRight",r=>{r.preventDefault(),this.moveFocus(1)}),this.scope.register([],"ArrowLeft",r=>{r.preventDefault(),this.moveFocus(-1)}),this.scope.register([],"ArrowDown",r=>{r.preventDefault(),this.moveFocus(this.columns())}),this.scope.register([],"ArrowUp",r=>{r.preventDefault(),this.moveFocus(-this.columns())}),this.scope.register([],"Enter",r=>{r.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 As(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 r=o.el.getBoundingClientRect();if(Math.abs(r.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))}},xi=class extends q.Modal{constructor(t,e,i,s={}){super(t);this.levels=e;this.onPick=i;this.opts=s}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.modalEl?.addClass("stashpad-breadcrumb-modal"),this.contentEl.empty(),this.titleEl.setText("Jump to level");let t=this.contentEl.createDiv({cls:"stashpad-bc-levels"});for(let e of this.levels){let i=t.createDiv({cls:"stashpad-bc-level-row"});if(e.isCurrent&&i.addClass("is-current"),i.createSpan({cls:"stashpad-bc-level-num",text:String(e.level)}),i.createSpan({cls:"stashpad-bc-level-label",text:e.label}),!e.isCurrent){i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=()=>{this.close(),this.onPick(e.id)};i.onclick=s,i.onkeydown=n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),s())}}this.opts.onContext&&(i.oncontextmenu=s=>{s.preventDefault(),this.opts.onContext(e.id,s,i,()=>this.close())},this.opts.attachLongPress?.(i,()=>this.opts.onContext(e.id,null,i,()=>this.close())))}}onClose(){this.contentEl.empty()}};Ze=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 C=Date.parse(this.current);Number.isNaN(C)||(t=new Date(C))}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"}),r=s.createSpan({cls:"stashpad-due-clear",attr:{"aria-label":"Clear date"}});(0,q.setIcon)(r,"x"),r.onclick=()=>{o.value="",o.focus()};let l=i.createDiv({cls:"stashpad-due-field"}),c=l.createSpan({cls:"stashpad-due-field-icon"});(0,q.setIcon)(c,"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{}},c.onclick=()=>this.openTimeNumpad(c,d),t&&(o.value=this.toDateValue(t),d.value=this.toTimeValue(t)),this.renderAssignSection(e);let g=e.createDiv({cls:"stashpad-due-grid"}),u=(C,B)=>{let w=g.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:C});w.onclick=()=>{let y=B();o.value=this.toDateValue(y),d.value||(d.value=this.toTimeValue(y))}},p=C=>(C.setHours(9,0,0,0),C);u("Today",()=>p(this.startOfTodayLocal())),u("Tomorrow",()=>{let C=this.startOfTodayLocal();return C.setDate(C.getDate()+1),p(C)}),u("Next week",()=>{let C=this.startOfTodayLocal();return C.setDate(C.getDate()+7),p(C)});let f=g.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});f.onclick=()=>{o.value="",d.value="",o.focus()};let I=g.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});I.onclick=()=>{this.didChoose=!0,this.close()};let m=g.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});m.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[C,B,w]=o.value.split("-").map(E=>parseInt(E,10)),y=9,Q=0;if(d.value){let[E,S]=d.value.split(":").map(D=>parseInt(D,10));y=E,Q=S}let v=new Date(C,B-1,w,y,Q,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){Ar(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[u,p]=e.value.split(":").map(f=>parseInt(f,10));Number.isFinite(u)&&(i=u),Number.isFinite(p)&&(s=p)}else{let u=new Date;i=u.getHours(),s=u.getMinutes()}let n=i>=12?"pm":"am",o=i===0?12:i>12?i-12:i,r=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});r.setCssStyles({position:"fixed",zIndex:"9999"});let l=null,c=()=>{r.remove(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",h,!0),this.tinyClosePopover===c&&(this.tinyClosePopover=null)},d=u=>{!r.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&c()},h=u=>{u.key==="Escape"?(u.preventDefault(),u.stopPropagation(),c()):u.key==="Enter"&&l&&(u.preventDefault(),u.stopPropagation(),l())};this.tinyClosePopover=c,as(r,{seedH:o,seedM:s,seedPeriod:n,close:c,setOnEnter:u=>{l=u},onFinalize:u=>{e.value=`${String(u.hours24).padStart(2,"0")}:${String(u.minutes).padStart(2,"0")}`}});let g=t.getBoundingClientRect();r.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}`}},Te=class Te 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 it(this.app,"Clear notification history?",`This will permanently remove all ${this.records.length} stored notifications from the history. The current toasts on screen are unaffected. This can't be undone.`,"Clear history",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 r=t.createEl("option",{text:`${n} (${o})`});r.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(Te.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let c=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let d of e.actionLabels){let h=c.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(Te.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Te.PAGE),this.renderFooter()},t>Te.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Te.PAGE=100;Ni=Te,Mn=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()}},Mi=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()}},Ti=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,c)=>{let d=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),h=d.createEl("input",{type:"checkbox"});return h.checked=c,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 r=o.createEl("button",{cls:"mod-cta",text:"Export"});r.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 St(A,a=Vt){let t=a instanceof Set?a:new Set(a.map(o=>o.toLowerCase())),e=(A.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 r=n?`${n}-${o}`:o;if(r.length>50)break;n=r}return n||"Untitled"}function bt(A,a){return`${A}-${a}.md`}function me(A){let a=A.match(/-([a-z0-9]{4,12})$/);return a?a[1]:null}function ps(A,a){let t=A.lastIndexOf(".");return t>0?`${A.slice(0,t)}-${a}${A.slice(t)}`:`${A}-${a}`}function dr(A){let a=A.match(/^([0-9a-z]{7,9})-(.+)$/);if(!a)return null;let t=parseInt(a[1],36);return!Number.isFinite(t)||t<142e10||t>Date.now()+864e5?null:{stamp:a[1],rest:a[2]}}var Vt,je=Jt(()=>{"use strict";Vt=["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 fs={};fi(fs,{JdBuildConfirmModal:()=>Ui,buildJdIndexNotes:()=>Pn,buildJdIndexPreview:()=>gs,buildJdPreviewNotice:()=>us,scanForJdNotes:()=>_e});function Tn(A,a){if(/^\d+-\d+$/.test(A))return null;if(A.includes(".")){let e=A.split(".").slice(0,-1).join(".");return a.has(e)?e:Tn(e,a)}if(/^\d+$/.test(A)){let t=parseInt(A,10);for(let e of a){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function _e(A,a,t){let e=A.vault.getMarkdownFiles(),i=ul(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(a.discoverStashpadFolders()),o=u=>s?!1:Array.from(n).some(p=>u===p||u.startsWith(p+"/")),r=[],l=[],c=[];for(let u of i){let p=u.parent?.path?.replace(/\/+$/,"")??"";if(o(p)){c.push(u);continue}let f=u.basename.match(hr);f?r.push({prefix:f[1],segments:f[1].split("."),title:f[2],file:u,folder:null}):l.push(u)}let d=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",h=u=>{let p=u.path.replace(/\/+$/,"");if(!(d&&p&&p!==d&&!p.startsWith(d+"/"))){if(p&&!o(p)){let f=u.name.match(hr);f&&r.push({prefix:f[1],segments:f[1].split("."),title:f[2],file:null,folder:u})}}for(let f of u.children)f instanceof ut.TFolder&&h(f)};h(A.vault.getRoot());let g=t.jdIndexSort??"natural";return r.sort((u,p)=>fl(u,p,g)),{indexed:r,nonIndex:l,skippedStashpadNotes:c}}async function gs(A,a,t){let e=Hn(t.jdIndexStashpadFolder??"");if(!e)return{..._e(A,a,t),previewPath:null,error:"no-dest"};let i=_e(A,a,t),s=gl(A,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Il(i.indexed,i.nonIndex,i.skippedStashpadNotes),r=(await A.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),l=r?`${r[0]}${n}`:n;return await A.vault.modify(s,l),{...i,previewPath:s.path}}function gl(A,a){let t=A.vault.getAbstractFileByPath(a);if(!(t instanceof ut.TFolder))return null;for(let e of t.children){if(!(e instanceof ut.TFile)||e.extension!=="md")continue;if((A.metadataCache.getFileCache(e)?.frontmatter??{}).id===k)return e}return null}async function Pn(A,a,t){let e=Hn(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(a.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let s=_e(A,a,t),n=new Map;for(let I of s.indexed)n.set(I.prefix,I);for(let I of s.indexed)if(I.prefix.includes("."))for(let m=1;m{l.push(I);for(let m of r.get(I)??[])c(m)};for(let I of o)c(I);let d=new Map,h=A.vault.getAbstractFileByPath(e);if(h instanceof ut.TFolder)for(let I of h.children){if(!(I instanceof ut.TFile)||I.extension!=="md")continue;let m=A.metadataCache.getFileCache(I)?.frontmatter??{};typeof m.jdPrefix=="string"&&d.set(m.jdPrefix,I)}let g=new Map,u=0,p=0,f=0;for(let I of l){let m=n.get(I)??null,C=Tn(I,new Set(n.keys())),B=C?g.get(C)??k:k,w=m?`${I} ${m.title}`:I,y=m?.file?`[[${m.file.basename}]]`:"",Q=y?`${y} +`),this.lineCursorIdx=Math.max(1,Math.min(this.lines.length-1,Math.floor(this.lines.length/2))),this.lines.length<2&&(this.mode="cursor")}onOpen(){this.titleEl.setText("Split note"),this.modalEl.addClass("stashpad-split-modal"),this.render(),this.scope.register([],"Tab",t=>{this.lines.length<2||(t.preventDefault(),this.mode=this.mode==="line"?"cursor":"line",this.render())}),this.scope.register([],"Enter",t=>{this.mode==="line"&&(t.preventDefault(),this.commitLine())}),this.scope.register(["Mod"],"Enter",t=>{this.mode==="cursor"&&(t.preventDefault(),this.commitCursor())}),this.scope.register([],"ArrowUp",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.max(1,this.lineCursorIdx-1),this.render())}),this.scope.register([],"ArrowDown",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.min(this.lines.length-1,this.lineCursorIdx+1),this.render())})}commitLine(){let t=this.lineCursorIdx;this.close(),this.onSplitAtLine(t)}commitCursor(){let t=this.cursorTextarea;if(!t)return;let e=t.selectionStart;if(e<=0||e>=t.value.length){new K.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=vi(this.body,o),l=t.createEl("button",{cls:"stashpad-split-quick-btn",text:`${Ei[o]} (${a.length})`});l.disabled=a.length<2,l.onmousedown=c=>c.preventDefault(),l.onclick=()=>{let c=vi(this.body,o);if(c.length<2){new K.Notice("That delimiter wouldn't split this note.");return}this.close(),this.onSplitMany(c)}});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"});K.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=K.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()}},Xe=class extends K.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 c=[],d=L=>{let z=l.createDiv({cls:"stashpad-export-pw-row"}),J=z.createEl("input",{type:"password"});J.addClass("stashpad-export-name"),J.placeholder=L;let O=z.createEl("button",{cls:"stashpad-export-copy"}),st=()=>{let lt=J.value.length===0;O.setText(lt?"Paste":"Copy"),O.toggleClass("is-paste",lt),O.setAttr("aria-label",`${lt?"Paste into":"Copy"} ${L.toLowerCase()}`)};return O.onclick=async lt=>{if(lt.preventDefault(),J.value.length===0)try{let tt=(await navigator.clipboard?.readText())?.trim();if(!tt){new K.Notice("Clipboard is empty.");return}J.value=tt,J.dispatchEvent(new Event("input")),new K.Notice("Pasted from clipboard.")}catch{new K.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(J.value).then(()=>new K.Notice("Passphrase copied to clipboard."),()=>new K.Notice("Couldn't access the clipboard."))},st(),c.push(st),J},h=d("Password"),g=d("Confirm password"),u=l.createDiv({cls:"stashpad-export-strength"}),p=u.createDiv({cls:"stashpad-strength-bar"}),f=[0,1,2,3].map(()=>p.createDiv({cls:"stashpad-strength-seg"})),I=u.createEl("span",{cls:"stashpad-strength-label"}),m=l.createDiv({cls:"stashpad-export-genrow"}),C=m.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),B=m.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=l.createEl("div",{cls:"stashpad-export-pw-hint"}),y=l.createEl("div",{cls:"stashpad-export-pw-suite"});y.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(L=>{y.toggleClass("is-weak",!L),y.setText(L?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run on this device, so this export will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>{y.setText("Encryption: AES-256-GCM with a password-derived key.")}):y.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let Q=this.app.secretStorage,v=l.createDiv({cls:"stashpad-export-remember"}),E=v.createEl("input",{type:"checkbox"});E.id="stashpad-export-remember-cb";let S=v.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});S.htmlFor=E.id;let D=l.createDiv({cls:"stashpad-export-remember-note"});D.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."),D.setCssStyles({display:"none"}),E.onchange=()=>{D.setCssStyles({display:E.checked?"":"none"})},Q||v.setCssStyles({display:"none"});let H=()=>{let L=e.value.trim()||this.defaultBaseName;return o.checked?`${L}-encrypted`:L},U=()=>i.setText(`Saves as: ${H()}-.stash`);e.oninput=U;let N=this.contentEl.createDiv({cls:"stashpad-export-footer"}),b=N.createEl("button",{text:"Cancel"});b.onclick=()=>this.close();let T=N.createEl("button",{cls:"mod-cta",text:"Export"}),P=()=>{let L=Hn(h.value);u.style.visibility=h.value?"visible":"hidden",f.forEach((z,J)=>z.toggleClass("is-on",h.value!==""&&J<=L.level)),p.dataset.level=String(L.level),I.setText(L.label)},R=()=>{let L=o.checked;l.setCssStyles({display:L?"":"none"});let z=!0;L&&(h.value?h.value!==g.value?(w.setText("Passwords don't match."),w.addClass("is-error"),z=!1):(w.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),w.removeClass("is-error")):(w.setText("Enter a password to encrypt this export."),w.removeClass("is-error"),z=!1)),P(),c.forEach(J=>J()),T.disabled=!z,T.toggleClass("is-disabled",!z),U()},Z=!1,$=L=>{Z=L,h.type=g.type=L?"text":"password",B.setText(L?"Hide":"Show")};B.onclick=L=>{L.preventDefault(),$(!Z)},C.onclick=L=>{L.preventDefault(),h.value=g.value=Pn(),$(!1),new K.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),R()},o.onchange=R,h.oninput=R,g.oninput=R,R();let V=()=>this.commit(H(),o.checked?h.value:null,o.checked&&E.checked);T.onclick=V,this.scope.register([],"Enter",L=>{L.preventDefault(),T.disabled||V()}),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()}},Di=class extends K.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()}},ct=class extends K.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=f=>{let I=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),m=I.createEl("input",{type:"password"});m.addClass("stashpad-export-name","stashpad-encryption-field"),m.placeholder=f;let C=I.createEl("button",{cls:"stashpad-export-copy"}),B=()=>{let w=m.value.length===0;C.setText(w?"Paste":"Copy"),C.toggleClass("is-paste",w),C.setAttr("aria-label",`${w?"Paste into":"Copy"} ${f.toLowerCase()}`)};return C.onclick=async w=>{if(w.preventDefault(),m.value.length===0)try{let y=(await navigator.clipboard?.readText())?.trim();if(!y){new K.Notice("Clipboard is empty.");return}m.value=y,m.dispatchEvent(new Event("input")),new K.Notice("Pasted from clipboard.")}catch{new K.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(m.value).then(()=>new K.Notice("Copied to clipboard."),()=>new K.Notice("Couldn't access the clipboard."))},m.addEventListener("input",B),B(),e.push(B),m},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 f=this.contentEl.createDiv({cls:"stashpad-export-strength"}),I=f.createDiv({cls:"stashpad-strength-bar"}),m=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),C=f.createEl("span",{cls:"stashpad-strength-label"}),B=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),w=()=>{let E=n.value,S=Hn(E);m.forEach((D,H)=>D.toggleClass("is-on",H0&&E.length<6?" \u2014 use at least 6":""}`),B.toggleClass("is-weak",E.length>0&&E.length<6)};n.addEventListener("input",w),w();let y=this.contentEl.createDiv({cls:"stashpad-export-genrow"});y.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=E=>{E.preventDefault();let S=Pn(5);n.value=S,o&&(o.value=S),w(),e.forEach(D=>D()),new K.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(S).catch(()=>{})};let Q=y.createEl("button",{cls:"stashpad-export-show",text:"Show"});Q.onclick=E=>{E.preventDefault();let S=n.type==="password";n.type=S?"text":"password",o&&(o.type=S?"text":"password"),Q.setText(S?"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(E=>{v.toggleClass("is-weak",!E),v.setText(E?"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 f=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=f.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let I=f.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});I.htmlFor=a.id;let m=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});m.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."),m.setCssStyles({display:"none"}),a.onchange=()=>{m.setCssStyles({display:a.checked?"":"none"})}}let c=this.contentEl.createEl("div",{cls:"stashpad-export-error"});c.setCssStyles({display:"none"});let d=f=>{c.setText(f),c.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"}),u=!1,p=async()=>{if(u)return;let f=s?.value??void 0,I=n?.value??void 0;if((t==="unlock"||t==="change")&&!f){d("Enter your current password.");return}if(t==="setup"||t==="change"){if(!I){d("Enter a password.");return}if(I.length<6){d("Use at least 6 characters.");return}if(I!==o?.value){d("Passwords don't match.");return}}u=!0,g.disabled=!0,c.setCssStyles({display:"none"});let m=g.textContent;g.setText("Working\u2026");try{let C=await this.opts.onSubmit({current:f,next:I,remember:!!a?.checked});if(C){d(C),u=!1,g.disabled=!1,g.setText(m??"OK");return}this.succeeded=!0,this.close()}catch(C){d(`Failed: ${C.message}`),u=!1,g.disabled=!1,g.setText(m??"OK")}};g.onclick=()=>void p(),this.scope.register([],"Enter",f=>{f.preventDefault(),p()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},xi=class extends K.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,c=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 c(),this.scope.register([],"Enter",d=>{d.preventDefault(),c()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},ps=class extends K.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 c=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});c.title="Apply and save this color so it appears as a tile next time.",c.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",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()}},Si=class Si extends K.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=[...Si.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 c=!Si.DEFAULT_PALETTE.some(h=>h.toLowerCase()===a.toLowerCase()),d=this.items.length;if(l.onclick=()=>this.activate(d),c&&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:c?"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 ps(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))}},Ni=class extends K.Modal{constructor(t,e,i,s={}){super(t);this.levels=e;this.onPick=i;this.opts=s}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.modalEl?.addClass("stashpad-breadcrumb-modal"),this.contentEl.empty(),this.titleEl.setText("Jump to level");let t=this.contentEl.createDiv({cls:"stashpad-bc-levels"});for(let e of this.levels){let i=t.createDiv({cls:"stashpad-bc-level-row"});if(e.isCurrent&&i.addClass("is-current"),i.createSpan({cls:"stashpad-bc-level-num",text:String(e.level)}),i.createSpan({cls:"stashpad-bc-level-label",text:e.label}),!e.isCurrent){i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=()=>{this.close(),this.onPick(e.id)};i.onclick=s,i.onkeydown=n=>{(n.key==="Enter"||n.key===" ")&&(n.preventDefault(),s())}}this.opts.onContext&&(i.oncontextmenu=s=>{s.preventDefault(),this.opts.onContext(e.id,s,i,()=>this.close())},this.opts.attachLongPress?.(i,()=>this.opts.onContext(e.id,null,i,()=>this.close())))}}onClose(){this.contentEl.empty()}};Ze=class extends K.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 C=Date.parse(this.current);Number.isNaN(C)||(t=new Date(C))}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,K.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,K.setIcon)(a,"x"),a.onclick=()=>{o.value="",o.focus()};let l=i.createDiv({cls:"stashpad-due-field"}),c=l.createSpan({cls:"stashpad-due-field-icon"});(0,K.setIcon)(c,"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,K.setIcon)(h,"x"),h.onclick=()=>{d.value="",d.focus()},n.onclick=()=>{try{o.showPicker?.()}catch{}},c.onclick=()=>this.openTimeNumpad(c,d),t&&(o.value=this.toDateValue(t),d.value=this.toTimeValue(t)),this.renderAssignSection(e);let g=e.createDiv({cls:"stashpad-due-grid"}),u=(C,B)=>{let w=g.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:C});w.onclick=()=>{let y=B();o.value=this.toDateValue(y),d.value||(d.value=this.toTimeValue(y))}},p=C=>(C.setHours(9,0,0,0),C);u("Today",()=>p(this.startOfTodayLocal())),u("Tomorrow",()=>{let C=this.startOfTodayLocal();return C.setDate(C.getDate()+1),p(C)}),u("Next week",()=>{let C=this.startOfTodayLocal();return C.setDate(C.getDate()+7),p(C)});let f=g.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});f.onclick=()=>{o.value="",d.value="",o.focus()};let I=g.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});I.onclick=()=>{this.didChoose=!0,this.close()};let m=g.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});m.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[C,B,w]=o.value.split("-").map(E=>parseInt(E,10)),y=9,Q=0;if(d.value){let[E,S]=d.value.split(":").map(D=>parseInt(D,10));y=E,Q=S}let v=new Date(C,B-1,w,y,Q,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){ha(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[u,p]=e.value.split(":").map(f=>parseInt(f,10));Number.isFinite(u)&&(i=u),Number.isFinite(p)&&(s=p)}else{let u=new Date;i=u.getHours(),s=u.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,c=()=>{a.remove(),document.removeEventListener("mousedown",d,!0),document.removeEventListener("keydown",h,!0),this.tinyClosePopover===c&&(this.tinyClosePopover=null)},d=u=>{!a.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&c()},h=u=>{u.key==="Escape"?(u.preventDefault(),u.stopPropagation(),c()):u.key==="Enter"&&l&&(u.preventDefault(),u.stopPropagation(),l())};this.tinyClosePopover=c,As(a,{seedH:o,seedM:s,seedPeriod:n,close:c,setOnEnter:u=>{l=u},onFinalize:u=>{e.value=`${String(u.hours24).padStart(2,"0")}:${String(u.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}`}},Te=class Te extends K.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 it(this.app,"Clear notification history?",`This will permanently remove all ${this.records.length} stored notifications from the history. The current toasts on screen are unaffected. This can't be undone.`,"Clear history",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(Te.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let c=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let d of e.actionLabels){let h=c.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(Te.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Te.PAGE),this.renderFooter()},t>Te.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Te.PAGE=100;Mi=Te,Un=class extends K.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,K.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()}},Ti=class extends K.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()}},Pi=class extends K.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,c)=>{let d=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),h=d.createEl("input",{type:"checkbox"});return h.checked=c,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 K.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 St(A,r=Vt){let t=r instanceof Set?r:new Set(r.map(o=>o.toLowerCase())),e=(A.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['β€˜-β€›ΚΌ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function bt(A,r){return`${A}-${r}.md`}function me(A){let r=A.match(/-([a-z0-9]{4,12})$/);return r?r[1]:null}function fs(A,r){let t=A.lastIndexOf(".");return t>0?`${A.slice(0,t)}-${r}${A.slice(t)}`:`${A}-${r}`}function pa(A){let r=A.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 Vt,je=Jt(()=>{"use strict";Vt=["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 Cs={};Ii(Cs,{JdBuildConfirmModal:()=>Ri,buildJdIndexNotes:()=>Gn,buildJdIndexPreview:()=>Is,buildJdPreviewNotice:()=>ms,scanForJdNotes:()=>_e});function Rn(A,r){if(/^\d+-\d+$/.test(A))return null;if(A.includes(".")){let e=A.split(".").slice(0,-1).join(".");return r.has(e)?e:Rn(e,r)}if(/^\d+$/.test(A)){let t=parseInt(A,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(A,r,t){let e=A.vault.getMarkdownFiles(),i=Il(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(r.discoverStashpadFolders()),o=u=>s?!1:Array.from(n).some(p=>u===p||u.startsWith(p+"/")),a=[],l=[],c=[];for(let u of i){let p=u.parent?.path?.replace(/\/+$/,"")??"";if(o(p)){c.push(u);continue}let f=u.basename.match(ga);f?a.push({prefix:f[1],segments:f[1].split("."),title:f[2],file:u,folder:null}):l.push(u)}let d=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",h=u=>{let p=u.path.replace(/\/+$/,"");if(!(d&&p&&p!==d&&!p.startsWith(d+"/"))){if(p&&!o(p)){let f=u.name.match(ga);f&&a.push({prefix:f[1],segments:f[1].split("."),title:f[2],file:null,folder:u})}}for(let f of u.children)f instanceof ut.TFolder&&h(f)};h(A.vault.getRoot());let g=t.jdIndexSort??"natural";return a.sort((u,p)=>ml(u,p,g)),{indexed:a,nonIndex:l,skippedStashpadNotes:c}}async function Is(A,r,t){let e=Ln(t.jdIndexStashpadFolder??"");if(!e)return{..._e(A,r,t),previewPath:null,error:"no-dest"};let i=_e(A,r,t),s=fl(A,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Cl(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await A.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),l=a?`${a[0]}${n}`:n;return await A.vault.modify(s,l),{...i,previewPath:s.path}}function fl(A,r){let t=A.vault.getAbstractFileByPath(r);if(!(t instanceof ut.TFolder))return null;for(let e of t.children){if(!(e instanceof ut.TFile)||e.extension!=="md")continue;if((A.metadataCache.getFileCache(e)?.frontmatter??{}).id===k)return e}return null}async function Gn(A,r,t){let e=Ln(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(A,r,t),n=new Map;for(let I of s.indexed)n.set(I.prefix,I);for(let I of s.indexed)if(I.prefix.includes("."))for(let m=1;m{l.push(I);for(let m of a.get(I)??[])c(m)};for(let I of o)c(I);let d=new Map,h=A.vault.getAbstractFileByPath(e);if(h instanceof ut.TFolder)for(let I of h.children){if(!(I instanceof ut.TFile)||I.extension!=="md")continue;let m=A.metadataCache.getFileCache(I)?.frontmatter??{};typeof m.jdPrefix=="string"&&d.set(m.jdPrefix,I)}let g=new Map,u=0,p=0,f=0;for(let I of l){let m=n.get(I)??null,C=Rn(I,new Set(n.keys())),B=C?g.get(C)??k:k,w=m?`${I} ${m.title}`:I,y=m?.file?`[[${m.file.basename}]]`:"",Q=y?`${y} `:`${w} `,v=d.get(I);if(v){try{let E=null;await A.fileManager.processFrontMatter(v,U=>{U.jdPrefix=I,B&&(U.parent=B),(!U.id||typeof U.id!="string")&&(U.id=W()),U.created||(U.created=new Date().toISOString()),U.attachments||(U.attachments=[]),E=U.id});let D=(await A.vault.read(v)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),H=D?`${D[0]}${Q}`:Q;await A.vault.modify(v,H),E&&g.set(I,E),p++}catch(E){console.error("[stashpad] buildJdIndexNotes: update failed",E),f++}continue}try{let E=W();g.set(I,E);let S=St(w,t.slugStopWords),D=bt(S,E),H=`${e}/${D}`,U=["---",`id: ${E}`,`parent: ${B}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${I}"`,"---",""].join(` -`);await A.vault.create(H,U+Q),u++}catch(E){console.error("[stashpad] buildJdIndexNotes: create failed for",I,E),f++}}return{created:u,updated:p,skipped:f,destFolder:e}}function Hn(A){return(A||"").trim().replace(/^\/+|\/+$/g,"")}function ul(A,a){if((a.jdIndexScope??"vault")==="vault")return A;let t=Hn(a.jdIndexScopeFolder??"");return t?A.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):A}function fl(A,a,t){if(t==="created"){let e=A.file?.stat?.ctime??0,i=a.file?.stat?.ctime??0;if(e!==i)return e-i}return gr(A.segments,a.segments)}function pr(A,a){let t=A.match(/^(\d+)-(\d+)$/),e=a.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:A.split("."),s=e?[e[1]]:a.split(".");return gr(i,s)}function gr(A,a){let t=Math.min(A.length,a.length);for(let e=0;e{s.set(o,r);for(let l of e.get(o)??[])n(l,r+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function Il(A,a,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),A.length===0){let s=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(s)}else{let s=new Map;for(let c of A)s.set(c.prefix,c);for(let c of A)if(c.prefix.includes("."))for(let d=1;d{let d=s.get(c),h=r.get(c)??0,g=" ".repeat(h),u=i(h),p=d?.folder?` ${d.title} _(folder)_`:(d?.file,"");d?.file?e.push(`${g}- ${u} [[${d.file.basename}|${d.prefix} ${d.title}]]`):d?.folder?e.push(`${g}- ${u} ${d.prefix}${p}`):e.push(`${g}- ${u} ${c}`);for(let f of o.get(c)??[])l(f)};for(let c of n)l(c)}if(a.length>0){e.push(""),e.push(`# Non-indexed (${a.length})`),e.push(""),e.push("_These notes don't match the JD-prefix convention. Rename them to ` ` and re-run to include them._"),e.push("");for(let s of a)e.push(`- # [[${s.basename}]] \xB7 \`${s.path}\``)}if(t.length>0){let s=new Map;for(let o of t){let r=o.parent?.path?.replace(/\/+$/,"")??"";s.set(r,(s.get(r)??0)+1)}let n=Array.from(s.entries()).sort((o,r)=>o[0].localeCompare(r[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,r]of n)e.push(`- # All ${r} file${r===1?"":"s"} in \`${o||"(vault root)"}\``)}return e.join(` +`);await A.vault.create(H,U+Q),u++}catch(E){console.error("[stashpad] buildJdIndexNotes: create failed for",I,E),f++}}return{created:u,updated:p,skipped:f,destFolder:e}}function Ln(A){return(A||"").trim().replace(/^\/+|\/+$/g,"")}function Il(A,r){if((r.jdIndexScope??"vault")==="vault")return A;let t=Ln(r.jdIndexScopeFolder??"");return t?A.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):A}function ml(A,r,t){if(t==="created"){let e=A.file?.stat?.ctime??0,i=r.file?.stat?.ctime??0;if(e!==i)return e-i}return fa(A.segments,r.segments)}function ua(A,r){let t=A.match(/^(\d+)-(\d+)$/),e=r.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:A.split("."),s=e?[e[1]]:r.split(".");return fa(i,s)}function fa(A,r){let t=Math.min(A.length,r.length);for(let e=0;e<t;e++){let i=A[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 A.length-r.length}function Ia(A){let r=new Set(A.keys()),t=new Map,e=new Map;for(let o of r){let a=Rn(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(ua);for(let o of e.values())o.sort(ua);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 Cl(A,r,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),A.length===0){let s=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(s)}else{let s=new Map;for(let c of A)s.set(c.prefix,c);for(let c of A)if(c.prefix.includes("."))for(let d=1;d<c.segments.length;d++){let h=c.segments.slice(0,d).join(".");s.has(h)||s.set(h,null)}let{roots:n,childrenOf:o,depthOf:a}=Ia(s),l=c=>{let d=s.get(c),h=a.get(c)??0,g=" ".repeat(h),u=i(h),p=d?.folder?` ${d.title} _(folder)_`:(d?.file,"");d?.file?e.push(`${g}- ${u} [[${d.file.basename}|${d.prefix} ${d.title}]]`):d?.folder?e.push(`${g}- ${u} ${d.prefix}${p}`):e.push(`${g}- ${u} ${c}`);for(let f of o.get(c)??[])l(f)};for(let c of n)l(c)}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 us(A,a){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:`${a.indexed.length} indexed`}),i.createEl("li",{text:`${a.nonIndex.length+a.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.setCssStyles({padding:"2px 10px",fontSize:"var(--font-ui-smaller)"});let n;return s.onclick=async o=>{if(o.stopPropagation(),a.previewPath){let r=A.vault.getAbstractFileByPath(a.previewPath);r instanceof ut.TFile&&await A.workspace.getLeaf("tab").openFile(r)}n?.hide()},n=new ut.Notice(t,0),n}var ut,hr,Ui,Ri=Jt(()=>{"use strict";ut=require("obsidian");Gt();je();rt();hr=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ui=class extends ut.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"),r=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;i?(o.appendText(`Stashpad is about to create ${r} (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 ${r}. 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 ut.Setting(t);(i||s)&&l.addButton(c=>{c.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),c.setCta(),c.onClick(async()=>{try{let d=await gs(this.app,this.plugin,this.settings);if(d.error==="no-dest"){new ut.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(d.error==="no-home"){new ut.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,us(this.app,d),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(d){new ut.Notice(`Preview failed: ${d?.message??d}`,8e3)}})}),l.addButton(c=>{c.setButtonText(i?"Build anyway":"Build"),!i&&!s&&c.setCta(),c.onClick(async()=>{this.close(),await this.onBuild()})}),l.addButton(c=>{c.setButtonText("Cancel"),c.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});function mc(A,a){return Ic(A,a||{},0,0)}function Cc(A,a){return hc(A,{i:2},a&&a.out,a&&a.dictionary)}function Js(A,a){if(a){for(var t=new At(A.length),e=0;e<A.length;++e)t[e]=A.charCodeAt(e);return t}if(ea)return ea.encode(A);for(var i=A.length,s=new At(A.length+(A.length>>1)),n=0,o=function(c){s[n++]=c},e=0;e<i;++e){if(n+5>s.length){var r=new At(n+8+(i-e<<1));r.set(s),s=r}var l=A.charCodeAt(e);l<128||a?o(l):l<2048?(o(192|l>>6),o(128|l&63)):l>55295&&l<57344?(l=65536+(l&1047552)|A.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 Zi(s,0,n)}function vo(A,a){if(a){for(var t="",e=0;e<A.length;e+=16384)t+=String.fromCharCode.apply(null,A.subarray(e,e+16384));return t}else{if(yo)return yo.decode(A);var i=yc(A),s=i.s,t=i.r;return t.length&&Ct(8),s}}function da(A,a){a||(a={});var t={},e=[];Aa(A,"",t,a);var i=0,s=0;for(var n in t){var o=t[n],r=o[0],l=o[1],c=l.level==0?0:8,d=Js(n),h=d.length,g=l.comment,u=g&&Js(g),p=u&&u.length,f=wo(l.extra);h>65535&&Ct(11);var I=c?mc(r,l):r,m=I.length,C=fc();C.p(r),e.push(ca(l,{size:r.length,crc:C.d(),c:I,f:d,m:u,u:h!=n.length||u&&g.length!=p,o:i,compression:c})),i+=30+h+f+m,s+=76+2*(h+f)+(p||0)+m}for(var B=new At(s+22),w=i,y=s-i,Q=0;Q<e.length;++Q){var d=e[Q];ia(B,d.o,d,d.f,d.u,d.c.length);var v=30+d.f.length+wo(d.extra);B.set(d.c,d.o+v),ia(B,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+v+(d.m?d.m.length:0)}return vc(B,i,e.length,y,w),B}function ha(A,a){for(var t={},e=A.length-22;Pt(A,e)!=101010256;--e)(!e||A.length-e>65558)&&Ct(13);var i=jt(A,e+8);if(!i)return{};var s=Pt(A,e+16),n=Pt(A,e-20)==117853008;if(n){var o=Pt(A,e-12);n=Pt(A,o)==101075792,n&&(i=Pt(A,o+32),s=Pt(A,o+48))}for(var r=a&&a.filter,l=0;l<i;++l){var c=Qc(A,s,n),d=c[0],h=c[1],g=c[2],u=c[3],p=c[4],f=c[5],I=wc(A,f);s=p,(!r||r({name:u,size:h,originalSize:g,compression:d}))&&(d?d==8?t[u]=Cc(A.subarray(I,I+h),{out:new At(g)}):Ct(14,"unknown compression type "+d):t[u]=Zi(A,I,I+h))}return t}var At,Nt,Qo,Os,Ys,Io,sa,na,oa,mo,ra,rc,jr,Co,Ae,_,_t,Qe,_,_,_,_,Xi,_,ac,lc,cc,Ac,po,Kt,go,Eo,Zi,dc,Ct,hc,de,zi,uo,Bo,_r,Wi,aa,ta,pc,la,gc,uc,fc,Ic,ca,jt,Pt,fo,ft,Aa,ea,yo,Bc,yc,wc,Qc,Ec,wo,ia,vc,pa=Jt(()=>{At=Uint8Array,Nt=Uint16Array,Qo=Int32Array,Os=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]),Ys=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]),Io=new At([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),sa=function(A,a){for(var t=new Nt(31),e=0;e<31;++e)t[e]=a+=1<<A[e-1];for(var i=new Qo(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}},na=sa(Os,2),oa=na.b,mo=na.r;oa[28]=258,mo[258]=28;ra=sa(Ys,0),rc=ra.b,jr=ra.r,Co=new Nt(32768);for(_=0;_<32768;++_)Ae=(_&43690)>>1|(_&21845)<<1,Ae=(Ae&52428)>>2|(Ae&13107)<<2,Ae=(Ae&61680)>>4|(Ae&3855)<<4,Co[_]=((Ae&65280)>>8|(Ae&255)<<8)>>1;_t=function(A,a,t){for(var e=A.length,i=0,s=new Nt(a);i<e;++i)A[i]&&++s[A[i]-1];var n=new Nt(a);for(i=1;i<a;++i)n[i]=n[i-1]+s[i-1]<<1;var o;if(t){o=new Nt(1<<a);var r=15-a;for(i=0;i<e;++i)if(A[i])for(var l=i<<4|A[i],c=a-A[i],d=n[A[i]-1]++<<c,h=d|(1<<c)-1;d<=h;++d)o[Co[d]>>r]=l}else for(o=new Nt(e),i=0;i<e;++i)A[i]&&(o[i]=Co[n[A[i]-1]++]>>15-A[i]);return o},Qe=new At(288);for(_=0;_<144;++_)Qe[_]=8;for(_=144;_<256;++_)Qe[_]=9;for(_=256;_<280;++_)Qe[_]=7;for(_=280;_<288;++_)Qe[_]=8;Xi=new At(32);for(_=0;_<32;++_)Xi[_]=5;ac=_t(Qe,9,0),lc=_t(Qe,9,1),cc=_t(Xi,5,0),Ac=_t(Xi,5,1),po=function(A){for(var a=A[0],t=1;t<A.length;++t)A[t]>a&&(a=A[t]);return a},Kt=function(A,a,t){var e=a/8|0;return(A[e]|A[e+1]<<8)>>(a&7)&t},go=function(A,a){var t=a/8|0;return(A[t]|A[t+1]<<8|A[t+2]<<16)>>(a&7)},Eo=function(A){return(A+7)/8|0},Zi=function(A,a,t){return(a==null||a<0)&&(a=0),(t==null||t>A.length)&&(t=A.length),new At(A.subarray(a,t))},dc=["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(A,a,t){var e=new Error(a||dc[A]);if(e.code=A,Error.captureStackTrace&&Error.captureStackTrace(e,Ct),!t)throw e;return e},hc=function(A,a,t,e){var i=A.length,s=e?e.length:0;if(!i||a.f&&!a.l)return t||new At(0);var n=!t,o=n||a.i!=2,r=a.i;n&&(t=new At(i*3));var l=function(ht){var Mt=t.length;if(ht>Mt){var nt=new At(Math.max(Mt*2,ht));nt.set(t),t=nt}},c=a.f||0,d=a.p||0,h=a.b||0,g=a.l,u=a.d,p=a.m,f=a.n,I=i*8;do{if(!g){c=Kt(A,d,1);var m=Kt(A,d+1,3);if(d+=3,m)if(m==1)g=lc,u=Ac,p=9,f=5;else if(m==2){var y=Kt(A,d,31)+257,Q=Kt(A,d+10,15)+4,v=y+Kt(A,d+5,31)+1;d+=14;for(var E=new At(v),S=new At(19),D=0;D<Q;++D)S[Io[D]]=Kt(A,d+D*3,7);d+=Q*3;for(var H=po(S),U=(1<<H)-1,N=_t(S,H,1),D=0;D<v;){var b=N[Kt(A,d,U)];d+=b&15;var C=b>>4;if(C<16)E[D++]=C;else{var T=0,P=0;for(C==16?(P=3+Kt(A,d,3),d+=2,T=E[D-1]):C==17?(P=3+Kt(A,d,7),d+=3):C==18&&(P=11+Kt(A,d,127),d+=7);P--;)E[D++]=T}}var R=E.subarray(0,y),Z=E.subarray(y);p=po(R),f=po(Z),g=_t(R,p,1),u=_t(Z,f,1)}else Ct(1);else{var C=Eo(d)+4,B=A[C-4]|A[C-3]<<8,w=C+B;if(w>i){r&&Ct(0);break}o&&l(h+B),t.set(A.subarray(C,w),h),a.b=h+=B,a.p=d=w*8,a.f=c;continue}if(d>I){r&&Ct(0);break}}o&&l(h+131072);for(var $=(1<<p)-1,V=(1<<f)-1,L=d;;L=d){var T=g[go(A,d)&$],z=T>>4;if(d+=T&15,d>I){r&&Ct(0);break}if(T||Ct(2),z<256)t[h++]=z;else if(z==256){L=d,g=null;break}else{var J=z-254;if(z>264){var D=z-257,O=Os[D];J=Kt(A,d,(1<<O)-1)+oa[D],d+=O}var st=u[go(A,d)&V],lt=st>>4;st||Ct(3),d+=st&15;var Z=rc[lt];if(lt>3){var O=Ys[lt];Z+=go(A,d)&(1<<O)-1,d+=O}if(d>I){r&&Ct(0);break}o&&l(h+131072);var tt=h+J;if(h<Z){var j=s-Z,yt=Math.min(Z,tt);for(j+h<0&&Ct(3);h<yt;++h)t[h]=e[j+h]}for(;h<tt;++h)t[h]=t[h-Z]}}a.l=g,a.p=L,a.b=h,a.f=c,g&&(c=1,a.m=p,a.d=u,a.n=f)}while(!c);return h!=t.length&&n?Zi(t,0,h):t.subarray(0,h)},de=function(A,a,t){t<<=a&7;var e=a/8|0;A[e]|=t,A[e+1]|=t>>8},zi=function(A,a,t){t<<=a&7;var e=a/8|0;A[e]|=t,A[e+1]|=t>>8,A[e+2]|=t>>16},uo=function(A,a){for(var t=[],e=0;e<A.length;++e)A[e]&&t.push({s:e,f:A[e]});var i=t.length,s=t.slice();if(!i)return{t:la,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(w,y){return w.f-y.f}),t.push({s:-1,f:25001});var o=t[0],r=t[1],l=0,c=1,d=2;for(t[0]={s:-1,f:o.f+r.f,l:o,r};c!=i-1;)o=t[t[l].f<t[d].f?l++:d++],r=t[l!=c&&t[l].f<t[d].f?l++:d++],t[c++]={s:-1,f:o.f+r.f,l:o,r};for(var h=s[0].s,e=1;e<i;++e)s[e].s>h&&(h=s[e].s);var g=new Nt(h+1),u=Bo(t[c-1],g,0);if(u>a){var e=0,p=0,f=u-a,I=1<<f;for(s.sort(function(y,Q){return g[Q.s]-g[y.s]||y.f-Q.f});e<i;++e){var m=s[e].s;if(g[m]>a)p+=I-(1<<u-g[m]),g[m]=a;else break}for(p>>=f;p>0;){var C=s[e].s;g[C]<a?p-=1<<a-g[C]++-1:++e}for(;e>=0&&p;--e){var B=s[e].s;g[B]==a&&(--g[B],++p)}u=a}return{t:new At(g),l:u}},Bo=function(A,a,t){return A.s==-1?Math.max(Bo(A.l,a,t+1),Bo(A.r,a,t+1)):a[A.s]=t},_r=function(A){for(var a=A.length;a&&!A[--a];);for(var t=new Nt(++a),e=0,i=A[0],s=1,n=function(r){t[e++]=r},o=1;o<=a;++o)if(A[o]==i&&o!=a)++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=A[o]}return{c:t.subarray(0,e),n:a}},Wi=function(A,a){for(var t=0,e=0;e<a.length;++e)t+=A[e]*a[e];return t},aa=function(A,a,t){var e=t.length,i=Eo(a+2);A[i]=e&255,A[i+1]=e>>8,A[i+2]=A[i]^255,A[i+3]=A[i+1]^255;for(var s=0;s<e;++s)A[i+s+4]=t[s];return(i+4+e)*8},ta=function(A,a,t,e,i,s,n,o,r,l,c){de(a,c++,t),++i[256];for(var d=uo(i,15),h=d.t,g=d.l,u=uo(s,15),p=u.t,f=u.l,I=_r(h),m=I.c,C=I.n,B=_r(p),w=B.c,y=B.n,Q=new Nt(19),v=0;v<m.length;++v)++Q[m[v]&31];for(var v=0;v<w.length;++v)++Q[w[v]&31];for(var E=uo(Q,7),S=E.t,D=E.l,H=19;H>4&&!S[Io[H-1]];--H);var U=l+5<<3,N=Wi(i,Qe)+Wi(s,Xi)+n,b=Wi(i,h)+Wi(s,p)+n+14+3*H+Wi(Q,S)+2*Q[16]+3*Q[17]+7*Q[18];if(r>=0&&U<=N&&U<=b)return aa(a,c,A.subarray(r,r+l));var T,P,R,Z;if(de(a,c,1+(b<N)),c+=2,b<N){T=_t(h,g,0),P=h,R=_t(p,f,0),Z=p;var $=_t(S,D,0);de(a,c,C-257),de(a,c+5,y-1),de(a,c+10,H-4),c+=14;for(var v=0;v<H;++v)de(a,c+3*v,S[Io[v]]);c+=3*H;for(var V=[m,w],L=0;L<2;++L)for(var z=V[L],v=0;v<z.length;++v){var J=z[v]&31;de(a,c,$[J]),c+=S[J],J>15&&(de(a,c,z[v]>>5&127),c+=z[v]>>12)}}else T=ac,P=Qe,R=cc,Z=Xi;for(var v=0;v<o;++v){var O=e[v];if(O>255){var J=O>>18&31;zi(a,c,T[J+257]),c+=P[J+257],J>7&&(de(a,c,O>>23&31),c+=Os[J]);var st=O&31;zi(a,c,R[st]),c+=Z[st],st>3&&(zi(a,c,O>>5&8191),c+=Ys[st])}else zi(a,c,T[O]),c+=P[O]}return zi(a,c,T[256]),c+P[256]},pc=new Qo([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),la=new At(0),gc=function(A,a,t,e,i,s){var n=s.z||A.length,o=new At(e+n+5*(1+Math.ceil(n/7e3))+i),r=o.subarray(e,o.length-i),l=s.l,c=(s.r||0)&7;if(a){c&&(r[0]=s.r>>3);for(var d=pc[a-1],h=d>>13,g=d&8191,u=(1<<t)-1,p=s.p||new Nt(32768),f=s.h||new Nt(u+1),I=Math.ceil(t/3),m=2*I,C=function(wt){return(A[wt]^A[wt+1]<<I^A[wt+2]<<m)&u},B=new Qo(25e3),w=new Nt(288),y=new Nt(32),Q=0,v=0,E=s.i||0,S=0,D=s.w||0,H=0;E+2<n;++E){var U=C(E),N=E&32767,b=f[U];if(p[N]=b,f[U]=N,D<=E){var T=n-E;if((Q>7e3||S>24576)&&(T>423||!l)){c=ta(A,r,0,B,w,y,v,S,H,E-H,c),S=Q=v=0,H=E;for(var P=0;P<286;++P)w[P]=0;for(var P=0;P<30;++P)y[P]=0}var R=2,Z=0,$=g,V=N-b&32767;if(T>2&&U==C(E-V))for(var L=Math.min(h,T)-1,z=Math.min(32767,E),J=Math.min(258,T);V<=z&&--$&&N!=b;){if(A[E+R]==A[E+R-V]){for(var O=0;O<J&&A[E+O]==A[E+O-V];++O);if(O>R){if(R=O,Z=V,O>L)break;for(var st=Math.min(V,O-2),lt=0,P=0;P<st;++P){var tt=E-V+P&32767,j=p[tt],yt=tt-j&32767;yt>lt&&(lt=yt,b=tt)}}}N=b,b=p[N],V+=N-b&32767}if(Z){B[S++]=268435456|mo[R]<<18|jr[Z];var ht=mo[R]&31,Mt=jr[Z]&31;v+=Os[ht]+Ys[Mt],++w[257+ht],++y[Mt],D=E+R,++Q}else B[S++]=A[E],++w[A[E]]}}for(E=Math.max(E,D);E<n;++E)B[S++]=A[E],++w[A[E]];c=ta(A,r,l,B,w,y,v,S,H,E-H,c),l||(s.r=c&7|r[c/8|0]<<3,c-=7,s.h=f,s.p=p,s.i=E,s.w=D)}else{for(var E=s.w||0;E<n+l;E+=65535){var nt=E+65535;nt>=n&&(r[c/8|0]=l,nt=n),c=aa(r,c+1,A.subarray(E,nt))}s.i=n}return Zi(o,0,e+Eo(c)+i)},uc=function(){for(var A=new Int32Array(256),a=0;a<256;++a){for(var t=a,e=9;--e;)t=(t&1&&-306674912)^t>>>1;A[a]=t}return A}(),fc=function(){var A=-1;return{p:function(a){for(var t=A,e=0;e<a.length;++e)t=uc[t&255^a[e]]^t>>>8;A=t},d:function(){return~A}}},Ic=function(A,a,t,e,i){if(!i&&(i={l:1},a.dictionary)){var s=a.dictionary.subarray(-32768),n=new At(s.length+A.length);n.set(s),n.set(A,s.length),A=n,i.w=s.length}return gc(A,a.level==null?6:a.level,a.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(A.length)))*1.5):20:12+a.mem,t,e,i)},ca=function(A,a){var t={};for(var e in A)t[e]=A[e];for(var e in a)t[e]=a[e];return t},jt=function(A,a){return A[a]|A[a+1]<<8},Pt=function(A,a){return(A[a]|A[a+1]<<8|A[a+2]<<16|A[a+3]<<24)>>>0},fo=function(A,a){return Pt(A,a)+Pt(A,a+4)*4294967296},ft=function(A,a,t){for(;t;++a)A[a]=t,t>>>=8};Aa=function(A,a,t,e){for(var i in A){var s=A[i],n=a+i,o=e;Array.isArray(s)&&(o=ca(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[n]=[s,o]:(t[n+="/"]=[new At(0),o],Aa(s,n,t,e))}},ea=typeof TextEncoder<"u"&&new TextEncoder,yo=typeof TextDecoder<"u"&&new TextDecoder,Bc=0;try{yo.decode(la,{stream:!0}),Bc=1}catch{}yc=function(A){for(var a="",t=0;;){var e=A[t++],i=(e>127)+(e>223)+(e>239);if(t+i>A.length)return{s:a,r:Zi(A,t-1)};i?i==3?(e=((e&15)<<18|(A[t++]&63)<<12|(A[t++]&63)<<6|A[t++]&63)-65536,a+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?a+=String.fromCharCode((e&31)<<6|A[t++]&63):a+=String.fromCharCode((e&15)<<12|(A[t++]&63)<<6|A[t++]&63):a+=String.fromCharCode(e)}};wc=function(A,a){return a+30+jt(A,a+26)+jt(A,a+28)},Qc=function(A,a,t){var e=jt(A,a+28),i=jt(A,a+30),s=vo(A.subarray(a+46,a+46+e),!(jt(A,a+8)&2048)),n=a+46+e,o=Ec(A,n,i,t,Pt(A,a+20),Pt(A,a+24),Pt(A,a+42)),r=o[0],l=o[1],c=o[2];return[jt(A,a+10),r,l,s,n+i+jt(A,a+32),c]},Ec=function(A,a,t,e,i,s,n){var o=i==4294967295,r=s==4294967295,l=n==4294967295,c=a+t,d=o+r+l;if(e&&d){for(;a+4<c;a+=4+jt(A,a+2))if(jt(A,a)==1)return[o?fo(A,a+4+8*r):i,r?fo(A,a+4):s,l?fo(A,a+4+8*(r+o)):n,1];e<2&&Ct(13)}return[i,s,n,0]},wo=function(A){var a=0;if(A)for(var t in A){var e=A[t].length;e>65535&&Ct(9),a+=e+4}return a},ia=function(A,a,t,e,i,s,n,o){var r=e.length,l=t.extra,c=o&&o.length,d=wo(l);ft(A,a,n!=null?33639248:67324752),a+=4,n!=null&&(A[a++]=20,A[a++]=t.os),A[a]=20,a+=2,A[a++]=t.flag<<1|(s<0&&8),A[a++]=i&&8,A[a++]=t.compression&255,A[a++]=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),ft(A,a,g<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),a+=4,s!=-1&&(ft(A,a,t.crc),ft(A,a+4,s<0?-s-2:s),ft(A,a+8,t.size)),ft(A,a+12,r),ft(A,a+14,d),a+=16,n!=null&&(ft(A,a,c),ft(A,a+6,t.attrs),ft(A,a+10,n),a+=14),A.set(e,a),a+=r,d)for(var u in l){var p=l[u],f=p.length;ft(A,a,+u),ft(A,a+2,f),A.set(p,a+4),a+=4+f}return c&&(A.set(o,a),a+=c),a},vc=function(A,a,t,e,i){ft(A,a,101010256),ft(A,a+8,t),ft(A,a+10,t),ft(A,a+12,e),ft(A,a+16,i)}});var ga={};fi(ga,{bytesToStr:()=>$s,unzipFiles:()=>hi,zipFiles:()=>di});function Fc(A){return typeof A=="string"?Js(A):A instanceof Uint8Array?A:new Uint8Array(A)}function di(A,a=6){let t={};for(let e of A)t[e.name]=[Fc(e.data),{level:a}];return Promise.resolve(da(t,{level:a}))}function $s(A){return vo(A)}function hi(A){let a=A instanceof Uint8Array?A:new Uint8Array(A);return Promise.resolve(ha(a))}var Vs=Jt(()=>{"use strict";pa()});var zc={};fi(zc,{default:()=>Cn});module.exports=ol(zc);var M=require("obsidian");var Ii="sheet-group",ne="sheet-order",Ke="sheet-final",Ko="sheet-label",mi="sheet-origin",Ci="forked-from",Ot="fork-siblings",Qn="forked-at",En=[Ii,ne,Ke,Ko,mi,Ci,Ot,Qn];function Yt(A){if(!A)return null;let a=A[Ii];return typeof a=="string"&&a.trim()?a:null}function wn(A){let a=A?.[ne];return typeof a=="number"?a:null}function Bi(A){return Yt(A)!==null&&wn(A)!==null}function yi(A){return A?.[Ke]===!0}function Jo(A){return A?.[mi]===!0}function rl(A){let a=A?.[Ci];return typeof a=="string"&&a.trim()?a:null}function ns(A){return typeof A!="string"?null:A.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].split("#")[0].trim()||null}function Oo(A){return ns(rl(A))}function al(A){let a=A?.[Ko];return typeof a=="string"&&a.trim()?a:null}function Yo(){let A=Date.now().toString(36),a=Math.floor(Math.random()*1e6).toString(36);return`s-${A}-${a}`}function It(A,a){return a.file?A.metadataCache.getFileCache(a.file)?.frontmatter:null}function vn(A,a){return a.slice().sort((t,e)=>{let i=wn(It(A,t)),s=wn(It(A,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 $o(A,a){if(a.length===0)return null;let t=vn(A,a);return t.find(e=>yi(It(A,e)))??t[0]}function Vo(A,a,t){let e=al(It(A,a));return e||t}rt();var Et=require("obsidian");var at=require("obsidian");rt();function rs(A){let a=(A.dateDisplayTimezone||"").trim();return a?{timeZone:a}:{}}function oe(A,a){try{return new Intl.DateTimeFormat(void 0,a).format(new Date(A))}catch{let{timeZone:t,...e}=a;return new Intl.DateTimeFormat(void 0,e).format(new Date(A))}}function re(A,a){let t=rs(a);switch(a.dateDisplayFormat??"locale"){case"iso":return _o(A,a,!0);case"us":return oe(A,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return oe(A,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return oe(A,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return oe(A,{...t,dateStyle:"medium",timeStyle:"short"})}}function Zo(A,a){let t=rs(a);switch(a.dateDisplayFormat??"locale"){case"iso":return _o(A,a,!1);case"us":return oe(A,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return oe(A,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return oe(A,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(A).getFullYear()===e.getFullYear();return oe(A,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function jo(A,a){let t=rs(a),e=a.dateDisplayFormat==="iso"||a.dateDisplayFormat==="eu";return oe(A,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function _o(A,a,t){let e=rs(a),i=new Intl.DateTimeFormat("en-CA",{...e,year:"numeric",month:"2-digit",day:"2-digit",...t?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:{}}).formatToParts(new Date(A)),s=o=>i.find(r=>r.type===o)?.value??"",n=`${s("year")}-${s("month")}-${s("day")}`;return t?`${n} ${s("hour")}:${s("minute")}`:n}function Ie(A,a,t){let e=A.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(a>99?"99+":String(a))}var Hi={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},ds=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 pe}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,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 r=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,at.setIcon)(r.createSpan({cls:"stashpad-panels-global-btn-icon"}),"bell"),r.createSpan({cls:"stashpad-panels-global-btn-text",text:"Notifications"}),r.onclick=()=>this.openNotificationsFromPanel();let l=t.createDiv({cls:"stashpad-panels-bar"});for(let d of Object.keys(Hi)){let h=Hi[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 c=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(c):this.activePanel==="shared"?this.renderSharedPanel(c):this.activePanel==="tasks"&&this.renderTasksPanel(c)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new 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 r=this.plugin.listPinnedNotes();if(r.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"){r.forEach((g,u)=>this.renderPinnedRow(e,g,u));return}let c=new Map;r.forEach((g,u)=>{let p=c.get(g.folder);p||(p=[],c.set(g.folder,p)),p.push({pin:g,idx:u})});let d=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,h=Array.from(c.keys());d&&c.has(d)&&(h.splice(h.indexOf(d),1),h.unshift(d));for(let g of h){let u=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:u});let f=c.get(g)??[];for(let{pin:I,idx:m}of f)this.renderPinnedRow(e,I,m)}}renderPinnedRow(t,e,i){let s=this.findFileFor(e);if(!s)return;let n=this.app.metadataCache.getFileCache(s)?.frontmatter??{},o=this.titleFromFile(s),r=typeof n.color=="string"?n.color:null,l=n.completed===!0,c=this.childrenOf(e.folder,e.id).length,d=c>0,h=this.expanded.has(`${e.folder}|${e.id}`),g=t.createDiv({cls:"stashpad-pinned-row"});r&&g.addClass("has-color"),l&&g.addClass("is-completed"),g.draggable=!0,g.dataset.pinIdx=String(i),g.addEventListener("dragstart",m=>{m.dataTransfer?.setData("text/plain",String(i)),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),g.addClass("is-dragging")}),g.addEventListener("dragend",()=>g.removeClass("is-dragging")),g.addEventListener("dragover",m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="move");let C=g.getBoundingClientRect(),B=m.clientY-C.top<C.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",m=>{m.preventDefault(),g.removeClass("drop-before"),g.removeClass("drop-after");let C=parseInt(m.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===i)return;let B=g.getBoundingClientRect(),w=m.clientY-B.top<B.height/2;this.reorderPin(C,w?i:i+1)});let u=g.createSpan({cls:"stashpad-pinned-toggle"});d&&(Ie(u,c,h),u.onclick=m=>{m.stopPropagation();let C=`${e.folder}|${e.id}`;this.expanded.has(C)?this.expanded.delete(C):this.expanded.add(C),this.render()});let p=g.createSpan({cls:"stashpad-pinned-icon"});(0,at.setIcon)(p,d?"folder-tree":"file-text"),r&&(p.style.color=r);let f=g.createSpan({cls:"stashpad-pinned-label",text:o});f.onclick=()=>this.openPinFromPanel(e);let I=e.folder.split("/").pop()||e.folder;if(g.createSpan({cls:"stashpad-pinned-folder",text:I}),g.oncontextmenu=m=>{m.preventDefault();let C=new at.Menu;C.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),C.showAtMouseEvent(m)},d&&h){let m=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(m,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)),r=n[o-1],l=n[o],c;!r&&!l?c=Date.now():r?l?c=(r.pinnedAt+l.pinnedAt)/2:c=r.pinnedAt+1e3:c=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=c})}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 r=this.app.metadataCache.getFileCache(o)?.frontmatter??{},l=typeof r.id=="string"?r.id:null;if(!l)continue;let c=typeof r.color=="string"?r.color:null,d=r.completed===!0,h=this.childrenOf(e,l).length,g=h>0,u=this.expanded.has(`${e}|${l}`),p=t.createDiv({cls:"stashpad-pinned-subrow"});d&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let f=p.createSpan({cls:"stashpad-pinned-toggle"});g&&(Ie(f,h,u),f.onclick=C=>{C.stopPropagation();let B=`${e}|${l}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,at.setIcon)(I,"file-text"),c&&(I.style.color=c);let m=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});m.onclick=()=>this.openPinFromPanel({folder:e,id:l}),g&&u&&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 r=o.parent;if(r===e||e===k&&(r==null||r===k)){if(o.id===k)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,r=this.app.metadataCache.getFileCache(n)?.frontmatter,l=o?.created??"",c=r?.created??"";return l.localeCompare(c)}),i}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new at.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(kt(),Pi));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(k)}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"}),r=(d,h,g)=>{let u=o.createEl("button",{cls:"stashpad-shared-chip",text:d});return h&&u.addClass("is-active"),u.onclick=g,u};if(r("All",this.sharedAuthorFilter==="all",()=>{this.sharedAuthorFilter="all",this.render()}),r("Mine",this.sharedAuthorFilter==="mine",()=>{this.sharedAuthorFilter="mine",this.render()}),r("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[u,p]of n){let f=d.createEl("option",{text:p});f.value=u}let g=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;d.value=g,d.onchange=()=>{let u=d.value;u==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=u,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 c=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(c.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let d of c){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 u=h.createSpan({cls:"stashpad-pinned-label",text:d.title});u.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 r=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(r))continue;let l=this.app.metadataCache.getFileCache(o)?.frontmatter??{};l.id===k&&s.set(r,this.extractAuthorId(l.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let r=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(r)||r.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let l=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof l.id!="string"||l.id===k)continue;let c=this.extractAuthorId(l.author),d=Array.isArray(l.contributors)?l.contributors.filter(C=>typeof C=="string"):[],h=s.get(r)??null;if(!(d.length>0||h===t&&(c!==null&&c!==t)))continue;let I=this.titleFromFile(o),m=typeof l.color=="string"?l.color:null;n.push({file:o,folder:r,id:l.id,title:I,color:m,authorId:c,authorDisplay:this.extractAuthorDisplay(l.author)||(c??""),contributorCount:d.length})}return n.sort((o,r)=>{let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},c=this.app.metadataCache.getFileCache(r.file)?.frontmatter??{},d=l.modified??l.created??"";return(c.modified??c.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=b=>!!s&&b.assignedTo.some(T=>T.id===s),o=b=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let P=T.slice(7);return b.assignedTo.some(R=>R.id===P)}switch(T){case"mine":return n(b);case"others":return b.assignedTo.length>0&&!n(b);case"byme":return!!s&&b.assignedBy?.id===s;case"unassigned":return b.assignedTo.length===0;default:return!0}},r=new Map;for(let b of i){for(let T of b.assignedTo)T.id!==s&&r.set(T.id,T.name);b.assignedBy&&b.assignedBy.id!==s&&r.set(b.assignedBy.id,b.assignedBy.name)}let l=[...r.entries()].map(([b,T])=>({id:b,name:T})).sort((b,T)=>b.name.localeCompare(T.name)),c=e.createDiv({cls:"stashpad-task-assign-bar"});c.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let d=c.createEl("select",{cls:"stashpad-task-assign-select"}),h=b=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return b.startsWith("person:")?r.get(b.slice(7))??"Person":T[b]??b},g=b=>{let T=d.createEl("option",{text:h(b),value:b});this.taskAssignFilter===b&&(T.selected=!0)};for(let b of["all","mine","others","byme","unassigned"])g(b);if(l.length>0){let b=d.createEl("optgroup");b.setAttr("label","By person");for(let T of l){let P=b.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(P.selected=!0)}}d.onchange=()=>{this.taskAssignFilter=d.value,this.render()};let u=[...new Set(i.map(b=>b.folder))].sort((b,T)=>b.localeCompare(T));this.taskFolderFilter!=="all"&&!u.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 f=p.createEl("select",{cls:"stashpad-task-assign-select"}),I=f.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(I.selected=!0);for(let b of u){let T=f.createEl("option",{text:b.split("/").pop()||b,value:b});this.taskFolderFilter===b&&(T.selected=!0)}f.onchange=()=>{this.taskFolderFilter=f.value,this.render()};let m=b=>this.taskFolderFilter==="all"||b.folder===this.taskFolderFilter,C=i.filter(b=>o(b)&&m(b));if(C.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 w=B.getTime(),y=w+24*60*60*1e3,Q={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let b of C){if(b.completed){Q.completed.push(b);continue}if(b.due==null){Q.nodate.push(b);continue}b.due<w?Q.overdue.push(b):b.due<y?Q.today.push(b):Q.upcoming.push(b)}let v=(b,T)=>b.due==null&&T.due==null?b.title.localeCompare(T.title):b.due==null?1:T.due==null?-1:b.due-T.due,E=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],S=e.createDiv({cls:"stashpad-task-filters"}),D=C.length,H=(b,T,P)=>{let R=S.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===b&&R.addClass("is-active"),R.createSpan({cls:"stashpad-task-filter-label",text:T}),R.createSpan({cls:"stashpad-task-filter-count",text:String(P)}),R.onclick=()=>{this.taskFilter=b,this.render()}};H("all","All",D),H("overdue","Overdue",Q.overdue.length),H("today","Today",Q.today.length),H("upcoming","Upcoming",Q.upcoming.length),H("nodate","No date",Q.nodate.length),H("completed","Done",Q.completed.length);let U=this.taskFilter==="all"?E:E.filter(b=>b.key===this.taskFilter),N=!1;for(let b of U){let T=Q[b.key];if(T.length!==0){if(N=!0,T.sort(b.key==="completed"?(P,R)=>v(R,P):v),this.taskFilter==="all"){let P=e.createDiv({cls:`stashpad-task-section-header is-${b.key}`});(0,at.setIcon)(P.createSpan({cls:"stashpad-task-section-icon"}),b.icon),P.createSpan({cls:"stashpad-task-section-name",text:b.label}),P.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let P of T)this.renderTaskRow(e,P,b.key==="today")}}if(!N&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${U[0]?.label??this.taskFilter}".`);return}N||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=r=>{r.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 r=s.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,i)});e.due<Date.now()&&!e.completed&&r.addClass("is-overdue")}else e.dueRaw&&s.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let r=(this.plugin.settings.authorId??"").trim(),l=s.createSpan({cls:"stashpad-task-assignees"});for(let c of e.assignedTo){let d=l.createSpan({cls:"stashpad-task-assignee"});r&&c.id===r&&d.addClass("is-me"),d.setText(this.initials(c.name)),d.title=r&&c.id===r?`${c.name} (you)`:c.name}}s.oncontextmenu=r=>{r.preventDefault();let l=new at.Menu;l.addItem(c=>c.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),l.showAtMouseEvent(r)}}formatDueShort(t,e){return e?jo(t,this.plugin.settings):Zo(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??{},r=typeof o.id=="string"?o.id:null;if(!r||r===k)continue;let l=o.completed===!0,c=Ye(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)}!c&&!l&&h==null&&!d||i.push({file:s,folder:n,id:r,title:this.titleFromFile(s),task:c,completed:l,due:h,dueRaw:d,color:typeof o.color=="string"?o.color:null,assignedTo:De(o),assignedBy:fe(o.assignedBy)})}return i}};async function hs(A){let a=A.workspace.getLeavesOfType(pe);if(a.length>0){A.workspace.revealLeaf(a[0]);return}let t=A.workspace.getLeftLeaf(!1);if(!t){new at.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:pe,active:!0}),A.workspace.revealLeaf(t)}var qr=require("obsidian");rt();var x=require("obsidian");Ri();var Is=require("obsidian");rt();var ti=class extends Is.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),i=o=>e.every(r=>o.toLowerCase().includes(r)),s=[],n=o=>{if(!(o.path!=="/"&&wi.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let r of o.children)r instanceof Is.TFolder&&n(r)}};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();kt();var He=require("obsidian"),Un={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."}},ml={info:4e3,success:4e3,warning:6e3,error:1e4},fr=5e3,ms=class{constructor(a){this.app=a;this.history=[];this.nextId=1;this.historyLimit=fr;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(a){this.defaultAuthorId=a||null}show(a){let t=a.kind??"info",e=a.category??"system",i={id:this.nextId++,ts:Date.now(),message:a.message,kind:t,category:e,authorId:a.authorId??this.defaultAuthorId??void 0,affectedIds:a.affectedIds?a.affectedIds.slice():[],affectedPaths:a.affectedPaths?a.affectedPaths.slice():[],affectedAuthorIds:a.affectedAuthorIds?a.affectedAuthorIds.slice():[],folder:a.folder,actionLabels:(a.actions??[]).map(o=>o.label)};if(this.pushHistory(i),this.muted.has(e))return null;let s=this.buildContent(a,t),n=a.duration??ml[t];return new He.Notice(s,n)}onChange(a){return this.changeListeners.add(a),()=>this.changeListeners.delete(a)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(a,t){t?this.muted.add(a):this.muted.delete(a)}isMuted(a){return this.muted.has(a)}loadMutedFromList(a){this.muted=new Set(a)}mutedList(){return Array.from(this.muted)}loadHistory(a){let t=this.applyLimit(a.slice());this.history=t;let e=0;for(let i of t)i.id>e&&(e=i.id);this.nextId=Math.max(this.nextId,e+1),this.emit()}setHistoryLimit(a){this.historyLimit=Number.isFinite(a)?a:fr,this.history=this.applyLimit(this.history),this.emit()}applyLimit(a){return this.historyLimit<=0||a.length<=this.historyLimit?a:a.slice(a.length-this.historyLimit)}pushHistory(a){this.history.push(a),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let a of this.changeListeners)try{a()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(a,t){let e=document.createDocumentFragment(),i=document.createElement("div");i.className=`stashpad-notice stashpad-notice-${t}`;let s=document.createElement("div");s.className="stashpad-notice-message";let n=a.message.split(/(`[^`\n]+`)/);for(let o of n)if(o.length>1&&o.startsWith("`")&&o.endsWith("`")){let r=document.createElement("code");r.textContent=o.slice(1,-1),s.appendChild(r)}else o.length>0&&s.appendChild(document.createTextNode(o));if(i.appendChild(s),a.actions&&a.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let r of a.actions){let l=document.createElement("button");l.className="stashpad-notice-action",l.textContent=r.label,l.addEventListener("click",c=>{if(c.stopPropagation(),Promise.resolve().then(()=>r.onClick()).catch(d=>console.warn("[Stashpad] notification action failed",d)),!r.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(A,a,t){let e=A.vault.getAbstractFileByPath(a);if(!(e instanceof He.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=A.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;A.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=He.Platform.isMacOS?"Finder":He.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,r=A.vault.adapter?.getFullPath?.(a);r&&n?.showItemInFolder&&n.showItemInFolder(r)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var Ir=require("obsidian"),Rn=Ir.Platform.isMacOS;function Gi(A){if(!A)return"(none)";let a=A.replace(/\bMod\b/g,Rn?"Cmd":"Ctrl");return Rn&&(a=a.replace(/\bAlt\b/g,"Option")),a}function mr(A,a,t={allowSingleKey:!0}){let e=A.placeholder,i=A.value;A.placeholder="Press a key\u2026 (Backspace to cancel)",A.value="",A.classList.add("is-recording");let s=!1,n=()=>{A.placeholder=e,A.classList.remove("is-recording"),s||(A.value=i),A.removeEventListener("keydown",o,!0),A.removeEventListener("blur",r)},o=l=>{if(l.key==="Control"||l.key==="Shift"||l.key==="Alt"||l.key==="Meta"||l.key==="OS")return;let c=!!l.code&&(/^Key[A-Z]$/.test(l.code)||/^Digit\d$/.test(l.code));if((l.key==="Dead"||l.key==="Process"||l.key==="Unidentified")&&!c)return;if(l.preventDefault(),l.stopPropagation(),l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.shiftKey){n();return}let d=[];Rn?(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=Cl(l.key,l.code);if(!h||d.length===0&&!t.allowSingleKey)return;d.push(h);let g=d.join("+");s=!0,n(),a(g)},r=()=>n();return A.addEventListener("keydown",o,!0),A.addEventListener("blur",r),n}function Cl(A,a){if(!A)return"";if(a){let t=/^Key([A-Z])$/.exec(a);if(t)return t[1];let e=/^Digit(\d)$/.exec(a);if(e)return e[1]}return A.length===1?A.toUpperCase():A}je();Gt();function Ue(A,a,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(c){try{l(e.next(c))}catch(d){n(d)}}function r(c){try{l(e.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):i(c.value).then(o,r)}l((e=e.apply(A,a||[])).next())})}var ot=class{constructor(){this.mutex=Promise.resolve()}lock(){let a=()=>{};return this.mutex=this.mutex.then(()=>new Promise(a)),new Promise(t=>{a=t})}dispatch(a){return Ue(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(a())}finally{t()}})}},Gn;function Bl(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Jn=Bl(),Ln=(Gn=Jn.Buffer)!==null&&Gn!==void 0?Gn:null,yl=Jn.TextEncoder?new Jn.TextEncoder:null;function Er(A,a){return(A&15)+(A>>6|A>>3&8)<<4|(a&15)+(a>>6|a>>3&8)}function vr(A,a){let t=a.length>>1;for(let e=0;e<t;e++){let i=e<<1;A[e]=Er(a.charCodeAt(i),a.charCodeAt(i+1))}}function wl(A,a){if(A.length!==a.length*2)return!1;for(let t=0;t<a.length;t++){let e=t<<1;if(a[t]!==Er(A.charCodeAt(e),A.charCodeAt(e+1)))return!1}return!0}var Cr=87,Br=48;function On(A,a,t){let e=0;for(let i=0;i<t;i++){let s=a[i]>>>4;A[e++]=s>9?s+Cr:s+Br,s=a[i]&15,A[e++]=s>9?s+Cr:s+Br}return String.fromCharCode.apply(null,A)}var le=Ln!==null?A=>{if(typeof A=="string"){let a=Ln.from(A,"utf8");return new Uint8Array(a.buffer,a.byteOffset,a.length)}if(Ln.isBuffer(A))return new Uint8Array(A.buffer,A.byteOffset,A.length);if(ArrayBuffer.isView(A))return new Uint8Array(A.buffer,A.byteOffset,A.byteLength);throw new Error("Invalid data type!")}:A=>{if(typeof A=="string")return yl.encode(A);if(ArrayBuffer.isView(A))return new Uint8Array(A.buffer,A.byteOffset,A.byteLength);throw new Error("Invalid data type!")},Lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",qi=new Uint8Array(256);for(let A=0;A<Lt.length;A++)qi[Lt.charCodeAt(A)]=A;function yr(A,a=!0){let t=A.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(A[n]<<16&16711680)+(A[n+1]<<8&65280)+(A[n+2]&255),r=Lt.charAt(o>>18&63)+Lt.charAt(o>>12&63)+Lt.charAt(o>>6&63)+Lt.charAt(o&63);i.push(r)}if(e===1){let n=A[t-1],o=Lt.charAt(n>>2),r=Lt.charAt(n<<4&63);i.push(`${o}${r}`),a&&i.push("==")}else if(e===2){let n=(A[t-2]<<8)+A[t-1],o=Lt.charAt(n>>10),r=Lt.charAt(n>>4&63),l=Lt.charAt(n<<2&63);i.push(`${o}${r}${l}`),a&&i.push("=")}return i.join("")}function Ql(A){let a=Math.floor(A.length*.75),t=A.length;return A[t-1]==="="&&(a-=1,A[t-2]==="="&&(a-=1)),a}function El(A){let a=Ql(A),t=A.length,e=new Uint8Array(a),i=0;for(let s=0;s<t;s+=4){let n=qi[A.charCodeAt(s)],o=qi[A.charCodeAt(s+1)],r=qi[A.charCodeAt(s+2)],l=qi[A.charCodeAt(s+3)];e[i]=n<<2|o>>4,i+=1,e[i]=(o&15)<<4|r>>2,i+=1,e[i]=(r&3)<<6|l&63,i+=1}return e}var Bs=16*1024,Li=4,vl=new ot,qn=new Map;function Fr(A,a){return Ue(this,void 0,void 0,function*(){let t=null,e=null,i=!1;if(typeof WebAssembly>"u")throw new Error("WebAssembly is not supported in this environment!");let s=(y,Q=0)=>{e.set(y,Q)},n=()=>e,o=()=>t.exports,r=y=>{t.exports.Hash_SetMemorySize(y);let Q=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,Q,y)},l=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),c=vl.dispatch(()=>Ue(this,void 0,void 0,function*(){if(!qn.has(A.name)){let Q=El(A.data),v=WebAssembly.compile(Q);qn.set(A.name,v)}let y=yield qn.get(A.name);t=yield WebAssembly.instantiate(y,{})})),d=()=>Ue(this,void 0,void 0,function*(){t||(yield c);let y=t.exports.Hash_GetBuffer(),Q=t.exports.memory.buffer;e=new Uint8Array(Q,y,Bs)}),h=(y=null)=>{i=!0,t.exports.Hash_Init(y)},g=y=>{let Q=0;for(;Q<y.length;){let v=y.subarray(Q,Q+Bs);Q+=v.length,e.set(v),t.exports.Hash_Update(v.length)}},u=y=>{if(!i)throw new Error("update() called before init()");let Q=le(y);g(Q)},p=new Uint8Array(a*2),f=(y,Q=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(Q),y==="binary"?e.slice(0,a):On(p,e,a)},I=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),Q=l(),v=t.exports.memory.buffer,E=new Uint8Array(v,y,Q),S=new Uint8Array(Li+Q);return vr(S,A.hash),S.set(E,Li),S},m=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let Q=t.exports.Hash_GetState(),v=l(),E=Li+v,S=t.exports.memory.buffer;if(y.length!==E)throw new Error(`Bad state length (expected ${E} bytes, got ${y.length})`);if(!wl(A.hash,y.subarray(0,Li)))throw new Error("This state was written by an incompatible hash implementation");let D=y.subarray(Li);new Uint8Array(S,Q,v).set(D),i=!0},C=y=>typeof y=="string"?y.length<Bs/4:y.byteLength<Bs,B=C;switch(A.name){case"argon2":case"scrypt":B=()=>!0;break;case"blake2b":case"blake2s":B=(y,Q)=>Q<=512&&C(y);break;case"blake3":B=(y,Q)=>Q===0&&C(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":B=()=>!1;break}let w=(y,Q=null,v=null)=>{if(!B(y,Q))return h(Q),u(y),f("hex",v);let E=le(y);return e.set(E),t.exports.Hash_Calculate(E.length,Q,v),On(p,e,a)};return yield d(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:r,init:h,update:u,digest:f,save:I,load:m,calculate:w,hashLength:a}})}var EA=new ot;var Fl="argon2",kl="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",bl={name:Fl,data:kl,hash:Sl},Dl="blake2b",xl="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=",Nl="c6f286e6",Ml={name:Dl,data:xl,hash:Nl},vA=new ot;function wr(A){return!Number.isInteger(A)||A<8||A>512||A%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function Tl(A,a){return A|a<<16}function Yn(A=512,a=null){if(wr(A))return Promise.reject(wr(A));let t=null,e=A;if(a!==null){if(t=le(a),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=Tl(A,t.length)}let i=A/8;return Fr(Ml,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 Pl(A,a,t){let e=[`m=${a.memorySize}`,`t=${a.iterations}`,`p=${a.parallelism}`].join(",");return`$argon2${a.hashType}$v=19$${e}$${yr(A,!1)}$${yr(t,!1)}`}var Qr=new DataView(new ArrayBuffer(4));function ae(A){return Qr.setInt32(0,A,!0),new Uint8Array(Qr.buffer)}function Kn(A,a,t){return Ue(this,void 0,void 0,function*(){if(t<=64){let r=yield Yn(t*8);return r.update(ae(t)),r.update(a),r.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);A.init(),A.update(ae(t)),A.update(a);let s=A.digest("binary");i.set(s.subarray(0,32),0);for(let r=1;r<e;r++)A.init(),A.update(s),s=A.digest("binary"),i.set(s.subarray(0,32),r*32);let n=t-32*e,o;return n===64?(o=A,o.init()):o=yield Yn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function Hl(A){switch(A){case"d":return 0;case"i":return 1;default:return 2}}function Ul(A){return Ue(this,void 0,void 0,function*(){var a;let{parallelism:t,iterations:e,hashLength:i}=A,s=le(A.password),n=le(A.salt),o=19,r=Hl(A.hashType),{memorySize:l}=A,c=le((a=A.secret)!==null&&a!==void 0?a:""),[d,h]=yield Promise.all([Fr(bl,1024),Yn(512)]);d.setMemorySize(l*1024+1024);let g=new Uint8Array(24),u=new DataView(g.buffer);u.setInt32(0,t,!0),u.setInt32(4,i,!0),u.setInt32(8,l,!0),u.setInt32(12,e,!0),u.setInt32(16,o,!0),u.setInt32(20,r,!0),d.writeMemory(g,l*1024),h.init(),h.update(g),h.update(ae(s.length)),h.update(s),h.update(ae(n.length)),h.update(n),h.update(ae(c.length)),h.update(c),h.update(ae(0));let f=Math.floor(l/(t*4))*4,I=new Uint8Array(72),m=h.digest("binary");I.set(m);for(let w=0;w<t;w++){I.set(ae(0),64),I.set(ae(w),68);let y=w*f,Q=yield Kn(h,I,1024);d.writeMemory(Q,y*1024),y+=1,I.set(ae(1),64),Q=yield Kn(h,I,1024),d.writeMemory(Q,y*1024)}let C=new Uint8Array(1024);vr(C,d.calculate(new Uint8Array([]),l));let B=yield Kn(h,C,i);if(A.outputType==="hex"){let w=new Uint8Array(i*2);return On(w,B,i)}return A.outputType==="encoded"?Pl(n,A,B):B})}var Rl=A=>{var a;if(!A||typeof A!="object")throw new Error("Invalid options parameter. It requires an object.");if(!A.password)throw new Error("Password must be specified");if(A.password=le(A.password),A.password.length<1)throw new Error("Password must be specified");if(!A.salt)throw new Error("Salt must be specified");if(A.salt=le(A.salt),A.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(A.secret=le((a=A.secret)!==null&&a!==void 0?a:""),!Number.isInteger(A.iterations)||A.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(A.parallelism)||A.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(A.hashLength)||A.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(A.memorySize))throw new Error("Memory size should be specified.");if(A.memorySize<8*A.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(A.outputType===void 0&&(A.outputType="hex"),!["hex","binary","encoded"].includes(A.outputType))throw new Error(`Insupported output type ${A.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function $n(A){return Ue(this,void 0,void 0,function*(){return Rl(A),Ul(Object.assign(Object.assign({},A),{hashType:"id"}))})}var FA=new ot;var kA=new ot;var SA=new ot;var bA=new ot;var DA=new Uint8Array(8);var xA=new ot;var NA=new ot;var MA=new ot;var TA=new ot;var PA=new ot;var HA=new ot;var UA=new ot;var RA=new ot;var GA=new ot;var LA=new ot;var qA=new ot;var KA=new Uint8Array(8);var JA=new ot;var OA=new Uint8Array(8);var YA=new ot;var $A=new Uint8Array(8);var VA=new ot;var zA=new ot;var WA=new ot;kt();var qt=new Uint8Array([83,84,65,83,72,69,78,67]),Wn=2,Xn=1,Zn=2,br=3,Gl=32,ei=12,Vn=32,Ll=6e5,ql=47104,Kl=3,Jl=1,pt=A=>A;function xt(A){if(A.length<qt.length+1)return!1;for(let a=0;a<qt.length;a++)if(A[a]!==qt[a])return!1;return!0}function kr(A,a,t){A[a]=t>>>24&255,A[a+1]=t>>>16&255,A[a+2]=t>>>8&255,A[a+3]=t&255}function Sr(A,a){return A[a]*16777216+(A[a+1]<<16)+(A[a+2]<<8)+A[a+3]}async function zn(A,a,t){if(t.id===Zn)return await $n({password:A,salt:a,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Vn,outputType:"binary"});if(t.id===Xn){let e=await crypto.subtle.importKey("raw",pt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:pt(a),iterations:t.a,hash:"SHA-256"},e,Vn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function ys(A){return crypto.subtle.importKey("raw",pt(A),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var jn={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function Wt(A,a){let t=crypto.getRandomValues(new Uint8Array(Gl)),e=crypto.getRandomValues(new Uint8Array(ei)),i,s,n;try{i={id:Zn,a:ql,b:Kl,c:Jl},n=await zn(a,t,i),s="argon2id"}catch(d){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",d),i={id:Xn,a:Ll,b:0,c:0},n=await zn(a,t,i),s="pbkdf2"}let o=Dr(i,t,e),r=await ys(n),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(e),additionalData:pt(o)},r,pt(A))),c=new Uint8Array(o.length+l.length);return c.set(o,0),c.set(l,o.length),{data:c,kdf:s}}var Ki=null;async function Ji(){if(Ki!==null)return Ki;try{await $n({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Ki=!0}catch{Ki=!1}return Ki}function Dr(A,a,t){let e=new Uint8Array(qt.length+1+1+4+4+1+1+a.length+t.length),i=0;return e.set(qt,i),i+=qt.length,e[i++]=Wn,e[i++]=A.id,kr(e,i,A.a),i+=4,kr(e,i,A.b),i+=4,e[i++]=A.c,e[i++]=a.length,e.set(a,i),i+=a.length,e.set(t,i),i+=t.length,e}async function zt(A,a){if(!xt(A))throw new Error("Not an encrypted Stashpad file.");let t=A[qt.length];if(t===1)return Ol(A,a);if(t!==Wn)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=qt.length+1,i={id:A[e++],a:0,b:0,c:0};if(i.a=Sr(A,e),e+=4,i.b=Sr(A,e),e+=4,i.c=A[e++],i.id===Zn){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===Xn&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=A[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=A.slice(e,e+s);e+=s;let o=A.slice(e,e+ei);e+=ei;let r=A.slice(0,e),l=A.slice(e),c=await zn(a,n,i),d=await ys(c),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(o),additionalData:pt(r)},d,pt(l));return new Uint8Array(h)}async function Ol(A,a){let t=qt.length+1,e=A.slice(t,t+16);t+=16;let i=A.slice(t,t+12);t+=12;let s=A.slice(t),n=await crypto.subtle.importKey("raw",pt(new TextEncoder().encode(a)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:pt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),r=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(i)},o,pt(s));return new Uint8Array(r)}async function Ce(A,a){if(a.length!==Vn)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(ei)),i=Dr({id:br,a:0,b:0,c:0},new Uint8Array(0),t),s=await ys(a),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(t),additionalData:pt(i)},s,pt(A))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function Qt(A,a){if(!xt(A))throw new Error("Not an encrypted Stashpad file.");let t=A[qt.length];if(t!==Wn)throw new Error(`Unsupported encrypted version (${t}).`);let e=qt.length+1;if(A[e++]!==br)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=A[e++];e+=s;let n=A.slice(e,e+ei);e+=ei;let o=A.slice(0,e),r=A.slice(e),l=await ys(a),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(n),additionalData:pt(o)},l,pt(r));return new Uint8Array(c)}async function ii(A,a,t={}){if(!xt(a))return a;if(t.secretId){let i=A.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await zt(a,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new bi(A,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await zt(a,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Gt();var ws={name:"ECDH",namedCurve:"P-256"},Yl="stashpad-vault-dek-wrap",$l=new TextEncoder;function _n(A){let a="";for(let t=0;t<A.length;t++)a+=String.fromCharCode(A[t]);return btoa(a)}function to(A){let a=atob(A),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}async function xr(){let A=await crypto.subtle.generateKey(ws,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",A.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",A.privateKey))}}function Nr(A){return crypto.subtle.importKey("spki",A,ws,!1,[])}function Vl(A){return crypto.subtle.importKey("pkcs8",A,ws,!1,["deriveBits"])}async function Mr(A,a){let t=await crypto.subtle.deriveBits({name:"ECDH",public:a},A,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:$l.encode(Yl)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Qs(A,a,t){let e=await crypto.subtle.generateKey(ws,!0,["deriveBits"]),i=await Mr(e.privateKey,await Nr(a)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,A)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:_n(o),iv:_n(s),ct:_n(n)}}async function Tr(A,a){let t=await Mr(await Vl(a),await Nr(to(A.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:to(A.iv)},t,to(A.ct)))}var Pr=".stashpad/keys.json",zl=".stashpad",Oi="_keys";function eo(A){return{v:2,keyId:A,identities:[],slots:[],joinRequests:[]}}var Es=class{constructor(a){this.app=a}get a(){return this.app.vault.adapter}validate(a){let t=a;return!!t&&t.v===2&&typeof t.keyId=="string"&&Array.isArray(t.identities)&&Array.isArray(t.slots)&&Array.isArray(t.joinRequests)}async readValid(a){try{if(!await this.a.exists(a))return null;let t=JSON.parse(await this.a.read(a));return this.validate(t)?t:null}catch{return null}}async load(){let a=await this.readValid(Pr);if(a)return a;try{let e=((await this.a.list(Oi)).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(a){try{await this.a.exists(a)||await this.a.mkdir(a)}catch{}}async save(a){let t=JSON.stringify(a,null,2);await this.ensureDir(zl),await this.a.write(Pr,t),await this.ensureDir(Oi);for(let e=4;e>=1;e--){let i=`${Oi}/keys-${e}.json`,s=`${Oi}/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(`${Oi}/keys-1.json`,t)}catch{}}};var Re="stashpad-vault-encryption";function Yi(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function Ge(A){let a="";for(let t=0;t<A.length;t++)a+=String.fromCharCode(A[t]);return btoa(a)}function Xt(A){let a=atob(A),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}var Hr=32,vs=class{constructor(a,t,e,i=()=>0){this.app=a;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.folderSessionKeys=new Map;this.idleTimer=null;this.kf=null;this.keyfiles=new Es(a)}argonProbe(){return Ji()}async init(){await this.refresh()}async refresh(){this.kf=await this.keyfiles.load()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}appTag(){return(this.app.appId||"default").toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,20)||"default"}keychainId(){return`${Re}-${this.appTag()}`}legacyAppIdKeychainId(){let a=this.app.appId||"default";return`${Re}-${a}`}isRemembered(){try{let a=this.secretStore();return!!(a?.getSecret(this.keychainId())||a?.getSecret(this.legacyAppIdKeychainId()))}catch{return!1}}rememberedPassword(){let a=this.secretStore();if(!a)return null;try{let t=a.getSecret(this.keychainId());if(t)return t}catch{}try{let t=a.getSecret(this.legacyAppIdKeychainId());if(t)return t}catch{}try{return a.getSecret(Re)||null}catch{return null}}async verifyWithKeychain(){let a=this.rememberedPassword();if(!a)return!1;try{return await this.verifyPassword(a)}catch{return!1}}async remember(a){try{await this.secretStore()?.setSecret(this.keychainId(),a)}catch(t){console.warn("[Stashpad] couldn't save password to keychain",t)}}async forgetKeychain(){let a=this.secretStore();if(a)try{a.removeSecret?await a.removeSecret(this.keychainId()):await a.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 a=this.secretStore(),t=null;try{t=a?.getSecret(this.keychainId())??null}catch{t=null}if(t)return this.unlock(t);let e=null;try{e=a?.getSecret(Re)??null}catch{e=null}if(!e)return!1;let i=await this.unlock(e);if(i){await this.remember(e);try{a?.removeSecret?await a.removeSecret(Re):await a?.setSecret(Re,"")}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 a=this.load().identityId;return a?this.kf?.slots.find(t=>t.recipientId===a)??null:null}accessState(){let a=this.load();return!this.kf&&a.wrappedKey?"member":this.kf?this.hasIdentity()&&this.mySlot()?"member":a.identityId&&this.kf.joinRequests.some(t=>t.id===a.identityId)?"pending":"outsider":"none"}amIMember(){return this.accessState()==="member"}async setup(a,t=!1,e){if(await this.refresh(),this.isConfigured())throw new Error("Encryption is already set up in this vault.");if(!a)throw new Error("Password required.");let i=crypto.getRandomValues(new Uint8Array(Hr)),s=await this.mintIdentity(a,e),n=eo(W(8));n.identities.push(this.identityRecord(s)),n.slots.push(await Qs(i,Xt(s.pub),s.id)),await this.keyfiles.save(n),this.kf=n,this.sessionKey=i,t&&await this.remember(a),this.armIdle()}async unlock(a,t=!1){await this.refresh();let e=this.load();if(!this.kf&&e.wrappedKey){let s;try{s=await zt(Xt(e.wrappedKey),a)}catch{return!1}let n=await this.mintIdentity(a,e.identityLabel??void 0),o=eo(W(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await Qs(s,Xt(n.pub),n.id)),await this.keyfiles.save(o),this.kf=o,this.sessionKey=s,t&&await this.remember(a),this.armIdle(),!0}let i=this.hasIdentity()?this.mySlot():null;if(i)try{let s=await zt(Xt(e.identityPrivWrapped),a);try{let n=await Tr(i,s);return s.fill(0),this.sessionKey=n,t&&await this.remember(a),this.armIdle(),!0}catch{s.fill(0)}}catch{}for(let s of(this.kf?.passwordSlots??[]).filter(n=>!n.label.startsWith("[deprecated]")))try{let n=await zt(Xt(s.wrapped),a);return this.sessionKey=n,t&&await this.remember(a),this.armIdle(),!0}catch{}return!1}hasSharedPassword(){return(this.kf?.passwordSlots??[]).some(a=>!a.label.startsWith("[deprecated]"))}async setSharedPassword(a,t=!1){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(!a)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let e=(this.kf.passwordSlots??[]).filter(o=>!o.label.startsWith("[deprecated]")),i=this.rememberedPassword();if(i&&e[0])try{await this.secretStore()?.setSecret(`${this.keychainId()}-d-${e[0].id}`,i)}catch{}let s=await Wt(this.sessionKey,a),n=(this.kf.passwordSlots??[]).map(o=>o.label.startsWith("[deprecated]")?o:{...o,label:`[deprecated] ${o.label}`});this.kf.passwordSlots=[{id:W(8),label:"Shared password",wrapped:Ge(s.data),kdf:s.kdf,createdAt:new Date().toISOString()},...n],await this.keyfiles.save(this.kf),(t||this.isRemembered())&&await this.remember(a)}async removeSharedPassword(){await this.refresh(),!(!this.kf||!this.kf.passwordSlots?.length)&&(this.kf.passwordSlots=[],await this.keyfiles.save(this.kf))}owningFolder(a){let t=this.kf?.folderKeys;if(!t)return null;let e=this.cleanFolder(a);for(;e;){if(t[e])return e;let i=e.lastIndexOf("/");if(i<0)break;e=e.slice(0,i)}return null}hasOwnFolderKey(a){return!!this.kf?.folderKeys?.[this.cleanFolder(a)]}folderKeyEntry(a){let t=this.owningFolder(a);return t?this.kf.folderKeys[t]??null:null}hasFolderKey(a){return this.owningFolder(a)!==null}folderPathByKeyId(a){for(let[t,e]of Object.entries(this.kf?.folderKeys??{}))if(e.keyId===a)return t;return null}folderActiveSlots(a){return a.passwordSlots.filter(t=>!t.label.startsWith("[deprecated]"))}isFolderUnlocked(a){let t=this.owningFolder(a);return t?this.folderSessionKeys.has(t):this.isUnlocked()}getFolderKey(a){let t=this.owningFolder(a);if(!t)return this.getSessionKey();let e=this.folderSessionKeys.get(t);return e?(this.armIdle(),e.slice()):null}async setupFolderKey(a,t,e,i=!1){if(!t)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Set up vault encryption first.");let s=this.cleanFolder(a);if(this.kf.folderKeys?.[s])throw new Error("This folder already has its own key.");let n=this.owningFolder(s);if(n&&n!==s)throw new Error(`A parent folder (\u201C${n.split("/").pop()}\u201D) already has its own password; this folder inherits it.`);let o=crypto.getRandomValues(new Uint8Array(Hr)),r=await Wt(o,t),l=W(8),c={keyId:l,folderPath:s,label:e,kcId:this.folderKcId(e,l),passwordSlots:[{id:W(8),label:"Folder password",wrapped:Ge(r.data),kdf:r.kdf,createdAt:new Date().toISOString()}],createdAt:new Date().toISOString()};this.kf.folderKeys={...this.kf.folderKeys??{},[s]:c},await this.keyfiles.save(this.kf),this.folderSessionKeys.set(s,o),i&&await this.rememberFolder(this.folderKcIdFor(c),t),this.armIdle()}async unlockFolder(a,t,e=!1){await this.refresh();let i=this.cleanFolder(a),s=this.folderKeyEntry(i);if(!s)return!1;for(let n of this.folderActiveSlots(s))try{let o=await zt(Xt(n.wrapped),t);this.folderSessionKeys.set(s.folderPath,o);let r=this.folderKcIdFor(s);return(e||this.isFolderRemembered(r))&&await this.rememberFolder(r,t),this.armIdle(),!0}catch{}return!1}async tryAutoUnlockFolder(a){let t=this.folderKeyEntry(a);if(!t||this.isFolderUnlocked(a))return this.isFolderUnlocked(a);let e=this.rememberedFolderPassword(this.folderKcIdFor(t));return e?this.unlockFolder(a,e):!1}async changeFolderPassword(a,t,e=!1){if(!t)throw new Error("Password required.");let i=this.cleanFolder(a);await this.refresh();let s=this.folderKeyEntry(i);if(!s||!this.kf)throw new Error("This folder has no key.");let n=s.folderPath,o=this.folderSessionKeys.get(n);if(!o)throw new Error("Unlock this folder first.");let r=s.passwordSlots.filter(u=>!u.label.startsWith("[deprecated]")),l=this.folderKcIdFor(s),c=this.rememberedFolderPassword(l);if(c&&r[0])try{await this.secretStore()?.setSecret(`${l}-d-${r[0].id}`,c)}catch{}let d=await Wt(o,t),h=s.passwordSlots.map(u=>u.label.startsWith("[deprecated]")?u:{...u,label:`[deprecated] ${u.label}`}),g={...s,kcId:s.kcId??this.folderKcId(s.label,s.keyId),passwordSlots:[{id:W(8),label:"Folder password",wrapped:Ge(d.data),kdf:d.kdf,createdAt:new Date().toISOString()},...h]};this.kf.folderKeys={...this.kf.folderKeys??{},[n]:g},await this.keyfiles.save(this.kf),(e||this.isFolderRemembered(l))&&await this.rememberFolder(this.folderKcIdFor(g),t)}async commitFolderRotation(a,t,e,i,s,n=!1){if(!t)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let o=this.cleanFolder(a),r=this.folderKeyEntry(o),l=r?.folderPath??o,c=r?.keyId??W(8),d=r?this.folderKcIdFor(r):null,h=(r?.passwordSlots??[]).filter(C=>!C.label.startsWith("[deprecated]")),g=d?this.rememberedFolderPassword(d):null;if(g&&h[0])try{await this.secretStore()?.setSecret(`${d}-d-${h[0].id}`,g)}catch{}let u=await Wt(e,t),p=(r?.passwordSlots??[]).map(C=>C.label.startsWith("[deprecated]")?C:{...C,label:`[deprecated] ${C.label}`}),f=s??r?.label??`rotated - ${o.split("/").pop()||o}`,I={keyId:c,folderPath:l,label:f,kcId:this.folderKcId(f,c),rotId:i,passwordSlots:[{id:W(8),label:"Folder password",wrapped:Ge(u.data),kdf:u.kdf,createdAt:new Date().toISOString()},...p],createdAt:r?.createdAt??new Date().toISOString()};this.kf.folderKeys={...this.kf.folderKeys??{},[l]:I},await this.keyfiles.save(this.kf);let m=this.folderSessionKeys.get(l);m&&m!==e&&m.fill(0),this.folderSessionKeys.set(l,e.slice()),(n||d&&this.isFolderRemembered(d))&&await this.rememberFolder(this.folderKcIdFor(I),t)}folderKcId(a,t){return(`sp-${(a||"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}`.slice(0,44)+`-${t.slice(0,6)}`).replace(/-+/g,"-")}folderKcIdFor(a){return a.kcId||`${Re}-f-${a.keyId}`}isFolderRemembered(a){try{return!!this.secretStore()?.getSecret(a)}catch{return!1}}rememberedFolderPassword(a){try{return this.secretStore()?.getSecret(a)||null}catch{return null}}async rememberFolder(a,t){try{await this.secretStore()?.setSecret(a,t)}catch(e){console.warn("[Stashpad] couldn't save folder password to keychain",e)}}async forgetFolderKeychain(a){let t=this.folderKeyEntry(a);if(!t)return;let e=this.secretStore();if(!e)return;let i=this.folderKcIdFor(t);try{e.removeSecret?await e.removeSecret(i):await e.setSecret(i,"")}catch(s){console.warn("[Stashpad] couldn't clear folder keychain",s)}}async verifyPassword(a){let t=this.load();try{if(t.identityPrivWrapped)return(await zt(Xt(t.identityPrivWrapped),a)).fill(0),!0;if(t.wrappedKey)return(await zt(Xt(t.wrappedKey),a)).fill(0),!0}catch{}return!1}async changePassword(a,t,e=!1){let i=this.load();if(!t)throw new Error("New password required.");if(!i.identityPrivWrapped&&!await this.unlock(a,!1))return!1;let s=this.load(),n;try{n=await zt(Xt(s.identityPrivWrapped),a)}catch{return!1}let o=await Wt(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:Ge(o.data),identityPrivKdf:o.kdf}),(e||this.isRemembered())&&await this.remember(t),this.armIdle(),!0}async requestAccess(a,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??a,pub:this.load().identityPub}:await this.mintIdentity(t,a);a&&i.label!==a&&(await this.save({...this.load(),identityLabel:a}),i.label=a);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||this.isRemembered())&&await this.remember(t)}pendingJoinRequests(){return this.kf?.joinRequests??[]}members(){return this.kf?.identities??[]}myIdentityId(){return this.load().identityId}async approveJoinRequest(a,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===a);return e?(this.kf.slots=[...this.kf.slots.filter(i=>i.recipientId!==e.id),await Qs(this.sessionKey,Xt(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!==a),await this.keyfiles.save(this.kf),!0):!1}async removeMember(a){await this.refresh(),this.kf&&(this.kf.slots=this.kf.slots.filter(t=>t.recipientId!==a),this.kf.identities=this.kf.identities.filter(t=>t.id!==a),this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==a),await this.keyfiles.save(this.kf))}async denyJoinRequest(a){await this.refresh(),this.kf&&(this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==a),await this.keyfiles.save(this.kf))}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null;for(let a of this.folderSessionKeys.values())a.fill(0);this.folderSessionKeys.clear(),this.clearIdle()}lockFolder(a){let t=this.owningFolder(a)??this.cleanFolder(a),e=this.folderSessionKeys.get(t);e&&(e.fill(0),this.folderSessionKeys.delete(t))}cleanFolder(a){return(a||"").replace(/\/+$/,"")}async clear(){this.lock(),await this.forgetKeychain();try{let a=this.app.vault.adapter;for(let t of[".stashpad/keys.json"])try{await a.exists(t)&&await a.remove(t)}catch{}try{let t=await a.list("_keys");for(let e of t.files||[])if(/\/keys-\d+\.json$/.test(e))try{await a.remove(e)}catch{}}catch{}}catch{}this.kf=null,await this.save(Yi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(a,t){let e=await xr(),i=await Wt(e.privKeyPkcs8,a);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??W(8),o=t??s.identityLabel??"This device",r=Ge(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:r,identityPrivWrapped:Ge(i.data),identityPrivKdf:i.kdf}),{id:n,label:o,pub:r}}identityRecord(a){return{id:a.id,label:a.label,pubKey:a.pub,addedAt:new Date().toISOString()}}armIdle(){this.clearIdle();let a=this.idleMinutes();a>0&&(this.idleTimer=window.setTimeout(()=>this.lock(),a*6e4))}clearIdle(){this.idleTimer!=null&&(window.clearTimeout(this.idleTimer),this.idleTimer=null)}dispose(){this.lock()}};var $i=null,Fs=new Set;function ks(A){if($i!==A){$i=A;for(let a of Fs)a()}}function ce(){return $i}function Ur(A){if($i===A){$i=null;for(let a of Fs)a()}}function Rr(A){return Fs.add(A),()=>Fs.delete(A)}function Wl(){return x.Platform.isMacOS?"Finder":x.Platform.isWin?"File Explorer":"file manager"}var si=[{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 no(){let A={};for(let a of si)A[a.id]={primary:a.defaultPrimary,secondary:a.defaultSecondary??"",preferRight:!1,useBoth:!!a.defaultUseBoth};return A}var Xl=!1,Zl=!1,Be={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:Yi(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],folderEncPrefs:{},folderIcons:{},folderSwitcherIncludePinned:!1,importExcludePrefixes:"_",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:no()},Gr=JSON.parse(JSON.stringify(Be)),so=new Set;function X(){return Gr}function oo(A){Gr=A;for(let a of so)a()}function Lr(A){return so.add(A),()=>so.delete(A)}function Ds(A){try{let a=A.internalPlugins?.plugins?.templates;if(!a?.enabled)return null;let t=a.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var Ss=[{id:"foldersStorage",label:"\u{1F4C1} Folders & Storage"},{id:"importExport",label:"\u{1F504} Import & Export"},{id:"noteTitles",label:"\u{1F3F7}\uFE0F Note Titles"},{id:"datesTime",label:"\u{1F552} Dates & Time"},{id:"listDisplay",label:"\u{1F4CB} List & Display"},{id:"movingNotes",label:"\u2195\uFE0F Moving Notes"},{id:"deleting",label:"\u{1F5D1}\uFE0F Deleting"},{id:"composerCopy",label:"\u270D\uFE0F Composer & Copying"},{id:"windowsTabs",label:"\u{1FA9F} Windows & Tabs"},{id:"notifications",label:"\u{1F514} Notifications"},{id:"encryption",label:"\u{1F512} Encryption"},{id:"authorship",label:"\u2712\uFE0F Authorship"},{id:"templates",label:"\u{1F4C4} Templates"},{id:"jdindex",label:"\u{1F522} JD Index"},{id:"okf",label:"\u{1F4DA} Open Knowledge Format (OKF)"},{id:"maintenance",label:"\u{1F6E0}\uFE0F Maintenance"},{id:"diagnostics",label:"\u{1FA7A} Diagnostics"},{id:"misc",label:"\u2699\uFE0F Misc"},{id:"hotkeys",label:"\u2328\uFE0F Hotkeys"}].sort((A,a)=>{let t=e=>e.replace(/^[^\p{L}\p{N}]+/u,"");return t(A.label).localeCompare(t(a.label))}),io=null;function jl(A,a){return io||(io=class extends x.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new io(A,a)}var bs=class extends x.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.pfeSelected=null;this.iconPickFolder=null}display(){let{containerEl:t}=this;t.empty();for(let e of Ss){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 Ss.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>jl(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 ze(this.app,n,s).open()})),["log","history","diagnostics"])]}notificationsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(Un);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=Un[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async r=>{let l=!r;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 Ni(this.app,this.plugin.notifications,async n=>{let o=this.app.vault.adapter,r=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(r)){new x.Notice("No log yet \u2014 make some changes first.");return}let l=await o.read(r);new ze(this.app,l,r).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(r){console.error(`[Stashpad] settings section "${t}" failed to render:`,r)}}}}headingDef(t,e){return this.sectionDef(t,e??"",i=>{let s=new x.Setting(i).setName(t).setHeading();e&&s.setDesc(e)},[t.toLowerCase()])}folderKeyLabel(t){let e=new Date,i=r=>String(r).padStart(2,"0"),s=`${e.getFullYear()}${i(e.getMonth()+1)}${i(e.getDate())}-${i(e.getHours())}${i(e.getMinutes())}`,n=(this.plugin.settings.authorName||"").trim(),o=n?n.split(/\s+/).map(r=>r[0]).join(""):(this.plugin.settings.authorId||"anon").slice(0,4);return`${s} - ${t.split("/").pop()||t} - ${o}`}promptSetFolderPassword(t){new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Set password for \u201C${t.split("/").pop()}\u201D`,intro:"A separate password just for this folder. Share it with collaborators out-of-band (a password manager, Signal, in person). There is NO recovery if it's lost.",onSubmit:async({next:e,remember:i})=>{if(!e)return"Enter a password.";try{await this.plugin.encryption.setupFolderKey(t,e,this.folderKeyLabel(t),i)}catch(s){return s.message}return new x.Notice("Folder password set \u2014 share it securely."),this.update?.(),null}}).open()}promptChangeFolderPassword(t){new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Change password for \u201C${t.split("/").pop()}\u201D`,intro:"Re-wraps this folder's key under a new password. The OLD password stops working on THIS device right away (un-synced copies elsewhere keep working until they sync). To truly cut off someone who left, you'll want \u201CRotate key\u201D (re-encrypts everything) \u2014 coming soon.",onSubmit:async({next:e,remember:i})=>{if(!e)return"Enter a password.";try{await this.plugin.encryption.changeFolderPassword(t,e,i)}catch(s){return s.message}return new x.Notice("Folder password changed."),this.update?.(),null}}).open()}promptRotateFolderKey(t){let e=t.split("/").pop()||t;new it(this.app,`Rotate key for \u201C${e}\u201D?`,`This RE-ENCRYPTS every locked note in \u201C${e}\u201D under a brand-new key, then retires the old password so it can no longer decrypt them \u2014 even copies a collaborator synced earlier. Use this when someone should LOSE access (e.g. they left the org). Large folders can take a while. Everyone who should keep access will need the new password.`,"Rotate key",i=>{i&&new ct(this.app,{mode:"setup",offerKeychain:!0,title:`New password for \u201C${e}\u201D`,intro:"The new password to use after rotating. Share it only with people who should keep access.",onSubmit:async({next:s,remember:n})=>s?await this.plugin.rotateFolderKey(t,s,n)<0?"Rotation failed \u2014 see the notice.":(this.update?.(),null):"Enter a password."}).open()}).open()}promptUnlockFolder(t){new ct(this.app,{mode:"unlock",offerKeychain:!0,title:`Unlock \u201C${t.split("/").pop()}\u201D`,intro:"Enter this folder's password.",onSubmit:async({current:e,remember:i})=>await this.plugin.encryption.unlockFolder(t,e,i)?(new x.Notice("Folder unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()}encryptionOrOnboard(){return this.plugin.encryption?.isConfigured?.()?!0:(new x.Notice("That setting needs vault encryption, which isn't set up yet \u2014 let's set it up first.",6e3),new ct(this.app,{mode:"setup",offerKeychain:!0,title:"Set up encryption",intro:"One password protects what you encrypt in this vault. It's stored only on this device \u2014 there is NO recovery if you lose it.",onSubmit:async({next:t,remember:e})=>{if(!t)return"Enter a password.";try{await this.plugin.encryption.setup(t,e,this.plugin.settings.authorName||"This device")}catch(i){return i.message}return new x.Notice("Encryption set up \u2014 now switch on the setting you wanted."),this.update?.(),null}}).open(),!1)}renderPerFolderEncryption(t){if(!this.plugin.encryption.isConfigured()){t.createEl("p",{cls:"setting-item-description"}).setText("Set up vault encryption above first. Per-folder passwords layer on top: a folder with its own password uses a separate key; folders without one use the vault password.");return}t.createEl("p",{cls:"setting-item-description stashpad-enc-warning"}).setText("\u26A0\uFE0F Encryption has no recovery \u2014 if you lose a password, anything encrypted under it (notes, archived items, and encrypted-trash items) is gone for good. Locking / archiving / secure-deleting permanently removes the plaintext; the encrypted copy is the only one left. A plaintext archive only de-indexes notes from search \u2014 it does NOT encrypt them.");let i=this.plugin.discoverStashpadFolders();if(i.length===0){t.createEl("p",{cls:"setting-item-description"}).setText("No Stashpad folders found yet.");return}(!this.pfeSelected||!i.includes(this.pfeSelected))&&(this.pfeSelected=i[0]),new x.Setting(t).setName("Folder").setDesc("Pick a folder to configure its password, archive, and trash options. Everything below applies to the selected folder only.").addDropdown(n=>{for(let o of i)n.addOption(o,o);n.setValue(this.pfeSelected),n.onChange(o=>{this.pfeSelected=o,this.update?.()})});let s=t.createDiv({cls:"stashpad-folderenc-panel"});this.renderFolderEncPanel(s,this.pfeSelected)}renderFolderEncPanel(t,e){let i=this.plugin.encryption,s=i.hasOwnFolderKey(e),n=i.folderKeyEntry(e)?.folderPath??null,o=!!n&&!s,r=i.isFolderUnlocked(e),l=(this.plugin.settings.folderEncPrefs??{})[e]??{},c=s?r?"Has its own password \xB7 unlocked":"Has its own password \xB7 locked":o?`Inherits \u201C${n.split("/").pop()||n}\u201D's password \xB7 ${r?"unlocked":"locked"}`:"Uses the vault password",d=new x.Setting(t).setName("Password").setDesc(c);o?d.addButton(p=>p.setButtonText("Manage on parent folder").onClick(()=>{this.pfeSelected=n,this.update?.()})):s?r?(d.addButton(p=>p.setButtonText("Lock (forget password)").onClick(()=>{this.plugin.encryption.lockFolder(e),new x.Notice("Folder locked \u2014 you'll re-enter its password next time."),this.update?.()})),d.addButton(p=>p.setButtonText("Change password\u2026").onClick(()=>this.promptChangeFolderPassword(e))),d.addButton(p=>{p.setButtonText("Rotate key\u2026").onClick(()=>this.promptRotateFolderKey(e)),p.buttonEl.addClass("mod-warning")})):d.addButton(p=>p.setButtonText("Unlock\u2026").setCta().onClick(()=>this.promptUnlockFolder(e))):d.addButton(p=>p.setButtonText("Set folder password\u2026").setCta().onClick(()=>this.promptSetFolderPassword(e)));let h=async p=>{this.plugin.settings.folderEncPrefs={...this.plugin.settings.folderEncPrefs??{},[e]:{...(this.plugin.settings.folderEncPrefs??{})[e]??{},...p}},await this.plugin.saveSettings()};new x.Setting(t).setName("Archive").setDesc("De-indexes this folder from cross-folder search; notes moved in get auto-encrypted (when \u201CEncrypt archived notes\u201D is on below).").addToggle(p=>p.setValue(!!l.archive).onChange(async f=>{await h({archive:f,...f&&l.archiveEncryptContent===void 0?{archiveEncryptContent:!0}:{}});let I=new Set((this.plugin.settings.archiveFolders??[]).map(m=>m.replace(/\/+$/,"")));f?I.add(e):I.delete(e),this.plugin.settings.archiveFolders=[...I],!f&&(this.plugin.settings.defaultArchiveFolder??"")===e&&(this.plugin.settings.defaultArchiveFolder=void 0),await this.plugin.saveSettings(),this.plugin.refreshFolderPanels(),this.update?.()})),new x.Setting(t).setName("Trash handling").setDesc("Where notes deleted from this folder go.").addDropdown(p=>p.addOption("","Use global default").addOption("stashpad","Stashpad encrypted trash").addOption("obsidian","Obsidian native trash").setValue(l.trashHandling??"").onChange(f=>h({trashHandling:f||void 0})));let g=(p,f,I,m)=>{new x.Setting(t).setName(p).addToggle(C=>C.setValue(!!l[f]).onChange(async B=>{let w={};w[f]=B,B||(w[I]=!1),await h(w),m&&await m(B),this.update?.()})),new x.Setting(t).setName(`\u21B3 ${p} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(C=>{C.setValue(!!l[I]),C.setDisabled(!l[f]),C.onChange(B=>{let w={};w[I]=B,h(w)})})};g("Encrypt this folder's notes","encryptContent","encryptFilenames",async p=>{p?await this.plugin.lockFolder(e):await this.plugin.unlockFolder(e);let f=(this.plugin.settings.lockedSubtrees??[]).some(I=>(I.folder||"").replace(/\/+$/,"")===e);await h({encryptContent:f,...f?{}:{encryptFilenames:!1}})}),g("Encrypt archived notes","archiveEncryptContent","archiveEncryptFilenames"),g("Encrypt trashed notes","trashEncryptContent","trashEncryptFilenames");let u=this.plugin.discoverStashpadFolders().filter(p=>p!==e&&p.startsWith(e+"/")).sort();if(u.length){new x.Setting(t).setName("Subfolders").setDesc(`${u.length} subfolder${u.length===1?"":"s"} \u2014 they use \u201C${e.split("/").pop()}\u201D's password. Encrypt each individually.`).setHeading();for(let p of u){let f=(this.plugin.settings.folderEncPrefs??{})[p]??{},I=async B=>{this.plugin.settings.folderEncPrefs={...this.plugin.settings.folderEncPrefs??{},[p]:{...(this.plugin.settings.folderEncPrefs??{})[p]??{},...B}},await this.plugin.saveSettings()},m=(this.plugin.settings.lockedSubtrees??[]).some(B=>(B.folder||"").replace(/\/+$/,"")===p),C=p.slice(e.length+1);new x.Setting(t).setName(C).addToggle(B=>B.setValue(m).onChange(async w=>{w?await this.plugin.lockFolder(p):await this.plugin.unlockFolder(p);let y=(this.plugin.settings.lockedSubtrees??[]).some(Q=>(Q.folder||"").replace(/\/+$/,"")===p);await I({encryptContent:y,...y?{}:{encryptFilenames:!1}}),this.update?.()})),new x.Setting(t).setName(`\u21B3 ${C} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(B=>{B.setValue(!!f.encryptFilenames),B.setDisabled(!m),B.onChange(w=>void I({encryptFilenames:w}))})}}}buildGeneralCategories(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,r,l)=>this.renderDef(s,n,c=>c.addToggle(d=>d.setValue(o()).onChange(async h=>{r(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 ti(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let r=(o||"").trim().replace(/^\/+|\/+$/g,"")||Be.folder,l=r.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(`"${r}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=r,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.foldersStorage.push(e("Include pinned notes in the folder switcher","When on, the folder switcher / creator (the folder button and the \u201COpen or switch Stashpad folder\u201D command) also lists your pinned notes, so you can jump straight to one. Off keeps the picker focused on folders.",()=>this.plugin.settings.folderSwitcherIncludePinned,s=>{this.plugin.settings.folderSwitcherIncludePinned=s},["pinned","switcher","folder","picker","jump"])),i.foldersStorage.push(this.renderDef("Folder tab icon","Give a folder its own Lucide icon (e.g. rocket, star, book-open) shown on its tab, the folder switcher, and its folder-panel row. Pick a folder, then enter an icon id (browse at lucide.dev). Blank = the default icon. Set per folder.",s=>{let n=this.plugin.discoverStashpadFolders();if(n.length===0){s.setDesc("No Stashpad folders found yet.");return}(!this.iconPickFolder||!n.includes(this.iconPickFolder))&&(this.iconPickFolder=n[0]);let o=null,r=s.controlEl.createSpan({cls:"stashpad-folder-icon-preview"}),l=c=>{r.empty();let d=c.trim();d&&(0,x.setIcon)(r,d)};s.addDropdown(c=>{for(let d of n)c.addOption(d,d.split("/").pop()||d);c.setValue(this.iconPickFolder),c.onChange(d=>{this.iconPickFolder=d;let h=this.plugin.getFolderIcon(d)??"";o?.setValue(h),l(h)})}),s.addText(c=>{o=c,c.setPlaceholder("list-tree"),c.setValue(this.plugin.getFolderIcon(this.iconPickFolder)??""),c.onChange(async d=>{l(d),await this.plugin.setFolderIcon(this.iconPickFolder,d)})}),l(this.plugin.getFolderIcon(this.iconPickFolder)??"")},["icon","folder","tab","lucide","emoji","switcher"])),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,"")||Be.exportFolder,await t()})),["export","stash","subfolder"])),i.importExport.push(this.renderDef("Exclude subfolders by prefix","Comma-separated name prefixes (default \u201C_\u201D). A subfolder whose name starts with any of these \u2014 at any depth \u2014 is NOT surfaced as a Stashpad folder or imported (it stays local). To encrypt such a folder, right-click it in Obsidian's file explorer \u2192 \u201C\u{1F512} Encrypt with Stashpad\u201D.",s=>s.addText(n=>n.setValue(this.plugin.settings.importExcludePrefixes??"_").setPlaceholder("_").onChange(async o=>{this.plugin.settings.importExcludePrefixes=o,await t()})),["import","exclude","prefix","subfolder","underscore","ignore"])),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{await this.plugin.runRebootstrapWithUI()}catch{}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 r=>{this.plugin.settings.useTemplatesFormat=r,await t()}));let n=Ds(this.app);s.descEl.createDiv({cls:"stashpad-settings-note"}).setText(n?`Templates plugin: date = "${n.dateFormat}", time = "${n.timeFormat}"`:"Templates plugin not enabled.")},["templates","date","time","format"]));{let s=null,n=()=>{s&&s.setText(`Sample: ${re(Date.now(),this.plugin.settings)}`)};i.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(r=>{r.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),r.addOption("long","Locale, long (Thursday, March 5\u2026)"),r.addOption("iso","ISO (2026-03-05 09:00)"),r.addOption("us","US (3/5/2026, 9:00 AM)"),r.addOption("eu","EU (5/3/2026, 09:00)"),r.setValue(this.plugin.settings.dateDisplayFormat??"locale"),r.onChange(async 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(r=>{r.setPlaceholder("(system timezone)"),r.setValue(this.plugin.settings.dateDisplayTimezone??""),r.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 r=o.settingEl;r.empty(),r.removeClass("setting-item"),s=r.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:Vt).join(` -`);s.addTextArea(r=>{r.setValue(o),n=r.inputEl,n.rows=6,n.setCssStyles({fontFamily:"var(--font-monospace)"}),r.onChange(async l=>{this.plugin.settings.slugStopWords=(l||"").split(/\r?\n/).map(c=>c.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(r=>r.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Vt],n&&(n.value=Vt.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 r=s.createDiv({cls:"stashpad-folder-list"});for(let l of n)this.renderFolderScopeRow(r,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(r=>{r.setPlaceholder("my-stashpad"),o=r.inputEl}).addButton(r=>r.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(c){new x.Notice(`Couldn't create: ${c.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",r=t.accessState();t.refresh().then(()=>{t.accessState()!==r&&this.update?.()});let l=r;if(l==="none"){new x.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(h=>h.setButtonText("Set up password\u2026").setCta().onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:g,remember:u})=>{if(!g)return"Enter a password.";try{await t.setup(g,u,o())}catch(p){return p.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(h=>h.setButtonText("Unlock with shared password\u2026").setCta().onClick(()=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(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(h=>h.setButtonText("Request access\u2026").onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:g,remember:u})=>{if(!g)return"Choose a password for this device.";try{await t.requestAccess(o(),g,u)}catch(p){return p.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(h=>h.setButtonText("Try unlock now").setCta().onClick(()=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(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(h=>h.setButtonText("Cancel request").onClick(async()=>{let g=t.myIdentityId();g&&await t.denyJoinRequest(g),new x.Notice("Access request cancelled."),this.update?.()}));return}let c=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"}${c?` \xB7 ${c}`:""}${d}`),t.isUnlocked()?new x.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(h=>h.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(h=>h.setButtonText("Unlock\u2026").setCta().onClick(()=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),Zl&&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(h=>h.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(h=>h.setButtonText("Change\u2026").onClick(()=>{new ct(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:g,next:u,remember:p})=>await t.changePassword(g,u,p)?(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(h=>{let g=async()=>{let u=await this.plugin.encryptionStateStrict();if(u.live){let f=()=>{new it(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 C=await this.plugin.purgeAllLockedContent();new x.Notice(`Deleted ${C} locked item${C===1?"":"s"}.`),g()}).open()},I=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}g()};new it(this.app,"Encrypted notes are still locked",`Some notes or folders are still encrypted (locked) and have no plaintext copy. Before removing encryption: +`}function ms(A,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=A.vault.getAbstractFileByPath(r.previewPath);a instanceof ut.TFile&&await A.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new ut.Notice(t,0),n}var ut,ga,Ri,Gi=Jt(()=>{"use strict";ut=require("obsidian");Gt();je();at();ga=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ri=class extends ut.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 ut.Setting(t);(i||s)&&l.addButton(c=>{c.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),c.setCta(),c.onClick(async()=>{try{let d=await Is(this.app,this.plugin,this.settings);if(d.error==="no-dest"){new ut.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(d.error==="no-home"){new ut.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,ms(this.app,d),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(d){new ut.Notice(`Preview failed: ${d?.message??d}`,8e3)}})}),l.addButton(c=>{c.setButtonText(i?"Build anyway":"Build"),!i&&!s&&c.setCta(),c.onClick(async()=>{this.close(),await this.onBuild()})}),l.addButton(c=>{c.setButtonText("Cancel"),c.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});function Bc(A,r){return Cc(A,r||{},0,0)}function yc(A,r){return gc(A,{i:2},r&&r.out,r&&r.dictionary)}function Vs(A,r){if(r){for(var t=new At(A.length),e=0;e<A.length;++e)t[e]=A.charCodeAt(e);return t}if(sr)return sr.encode(A);for(var i=A.length,s=new At(A.length+(A.length>>1)),n=0,o=function(c){s[n++]=c},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=A.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)|A.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 bo(A,r){if(r){for(var t="",e=0;e<A.length;e+=16384)t+=String.fromCharCode.apply(null,A.subarray(e,e+16384));return t}else{if(vo)return vo.decode(A);var i=Qc(A),s=i.s,t=i.r;return t.length&&Ct(8),s}}function pr(A,r){r||(r={});var t={},e=[];hr(A,"",t,r);var i=0,s=0;for(var n in t){var o=t[n],a=o[0],l=o[1],c=l.level==0?0:8,d=Vs(n),h=d.length,g=l.comment,u=g&&Vs(g),p=u&&u.length,f=Fo(l.extra);h>65535&&Ct(11);var I=c?Bc(a,l):a,m=I.length,C=mc();C.p(a),e.push(dr(l,{size:a.length,crc:C.d(),c:I,f:d,m:u,u:h!=n.length||u&&g.length!=p,o:i,compression:c})),i+=30+h+f+m,s+=76+2*(h+f)+(p||0)+m}for(var B=new At(s+22),w=i,y=s-i,Q=0;Q<e.length;++Q){var d=e[Q];nr(B,d.o,d,d.f,d.u,d.c.length);var v=30+d.f.length+Fo(d.extra);B.set(d.c,d.o+v),nr(B,i,d,d.f,d.u,d.c.length,d.o,d.m),i+=16+v+(d.m?d.m.length:0)}return kc(B,i,e.length,y,w),B}function gr(A,r){for(var t={},e=A.length-22;Pt(A,e)!=101010256;--e)(!e||A.length-e>65558)&&Ct(13);var i=jt(A,e+8);if(!i)return{};var s=Pt(A,e+16),n=Pt(A,e-20)==117853008;if(n){var o=Pt(A,e-12);n=Pt(A,o)==101075792,n&&(i=Pt(A,o+32),s=Pt(A,o+48))}for(var a=r&&r.filter,l=0;l<i;++l){var c=vc(A,s,n),d=c[0],h=c[1],g=c[2],u=c[3],p=c[4],f=c[5],I=Ec(A,f);s=p,(!a||a({name:u,size:h,originalSize:g,compression:d}))&&(d?d==8?t[u]=yc(A.subarray(I,I+h),{out:new At(g)}):Ct(14,"unknown compression type "+d):t[u]=ji(A,I,I+h))}return t}var At,Nt,ko,zs,Ws,yo,or,ar,rr,wo,lr,lc,tr,Qo,Ae,_,_t,Qe,_,_,_,_,Zi,_,cc,Ac,dc,hc,Io,qt,mo,So,ji,pc,Ct,gc,de,Wi,Co,Eo,er,Xi,cr,ir,uc,Ar,fc,Ic,mc,Cc,dr,jt,Pt,Bo,ft,hr,sr,vo,wc,Qc,Ec,vc,Fc,Fo,nr,kc,ur=Jt(()=>{At=Uint8Array,Nt=Uint16Array,ko=Int32Array,zs=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]),Ws=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]),yo=new At([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),or=function(A,r){for(var t=new Nt(31),e=0;e<31;++e)t[e]=r+=1<<A[e-1];for(var i=new ko(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}},ar=or(zs,2),rr=ar.b,wo=ar.r;rr[28]=258,wo[258]=28;lr=or(Ws,0),lc=lr.b,tr=lr.r,Qo=new Nt(32768);for(_=0;_<32768;++_)Ae=(_&43690)>>1|(_&21845)<<1,Ae=(Ae&52428)>>2|(Ae&13107)<<2,Ae=(Ae&61680)>>4|(Ae&3855)<<4,Qo[_]=((Ae&65280)>>8|(Ae&255)<<8)>>1;_t=function(A,r,t){for(var e=A.length,i=0,s=new Nt(r);i<e;++i)A[i]&&++s[A[i]-1];var n=new Nt(r);for(i=1;i<r;++i)n[i]=n[i-1]+s[i-1]<<1;var o;if(t){o=new Nt(1<<r);var a=15-r;for(i=0;i<e;++i)if(A[i])for(var l=i<<4|A[i],c=r-A[i],d=n[A[i]-1]++<<c,h=d|(1<<c)-1;d<=h;++d)o[Qo[d]>>a]=l}else for(o=new Nt(e),i=0;i<e;++i)A[i]&&(o[i]=Qo[n[A[i]-1]++]>>15-A[i]);return o},Qe=new At(288);for(_=0;_<144;++_)Qe[_]=8;for(_=144;_<256;++_)Qe[_]=9;for(_=256;_<280;++_)Qe[_]=7;for(_=280;_<288;++_)Qe[_]=8;Zi=new At(32);for(_=0;_<32;++_)Zi[_]=5;cc=_t(Qe,9,0),Ac=_t(Qe,9,1),dc=_t(Zi,5,0),hc=_t(Zi,5,1),Io=function(A){for(var r=A[0],t=1;t<A.length;++t)A[t]>r&&(r=A[t]);return r},qt=function(A,r,t){var e=r/8|0;return(A[e]|A[e+1]<<8)>>(r&7)&t},mo=function(A,r){var t=r/8|0;return(A[t]|A[t+1]<<8|A[t+2]<<16)>>(r&7)},So=function(A){return(A+7)/8|0},ji=function(A,r,t){return(r==null||r<0)&&(r=0),(t==null||t>A.length)&&(t=A.length),new At(A.subarray(r,t))},pc=["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(A,r,t){var e=new Error(r||pc[A]);if(e.code=A,Error.captureStackTrace&&Error.captureStackTrace(e,Ct),!t)throw e;return e},gc=function(A,r,t,e){var i=A.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(ht){var Mt=t.length;if(ht>Mt){var nt=new At(Math.max(Mt*2,ht));nt.set(t),t=nt}},c=r.f||0,d=r.p||0,h=r.b||0,g=r.l,u=r.d,p=r.m,f=r.n,I=i*8;do{if(!g){c=qt(A,d,1);var m=qt(A,d+1,3);if(d+=3,m)if(m==1)g=Ac,u=hc,p=9,f=5;else if(m==2){var y=qt(A,d,31)+257,Q=qt(A,d+10,15)+4,v=y+qt(A,d+5,31)+1;d+=14;for(var E=new At(v),S=new At(19),D=0;D<Q;++D)S[yo[D]]=qt(A,d+D*3,7);d+=Q*3;for(var H=Io(S),U=(1<<H)-1,N=_t(S,H,1),D=0;D<v;){var b=N[qt(A,d,U)];d+=b&15;var C=b>>4;if(C<16)E[D++]=C;else{var T=0,P=0;for(C==16?(P=3+qt(A,d,3),d+=2,T=E[D-1]):C==17?(P=3+qt(A,d,7),d+=3):C==18&&(P=11+qt(A,d,127),d+=7);P--;)E[D++]=T}}var R=E.subarray(0,y),Z=E.subarray(y);p=Io(R),f=Io(Z),g=_t(R,p,1),u=_t(Z,f,1)}else Ct(1);else{var C=So(d)+4,B=A[C-4]|A[C-3]<<8,w=C+B;if(w>i){a&&Ct(0);break}o&&l(h+B),t.set(A.subarray(C,w),h),r.b=h+=B,r.p=d=w*8,r.f=c;continue}if(d>I){a&&Ct(0);break}}o&&l(h+131072);for(var $=(1<<p)-1,V=(1<<f)-1,L=d;;L=d){var T=g[mo(A,d)&$],z=T>>4;if(d+=T&15,d>I){a&&Ct(0);break}if(T||Ct(2),z<256)t[h++]=z;else if(z==256){L=d,g=null;break}else{var J=z-254;if(z>264){var D=z-257,O=zs[D];J=qt(A,d,(1<<O)-1)+rr[D],d+=O}var st=u[mo(A,d)&V],lt=st>>4;st||Ct(3),d+=st&15;var Z=lc[lt];if(lt>3){var O=Ws[lt];Z+=mo(A,d)&(1<<O)-1,d+=O}if(d>I){a&&Ct(0);break}o&&l(h+131072);var tt=h+J;if(h<Z){var j=s-Z,yt=Math.min(Z,tt);for(j+h<0&&Ct(3);h<yt;++h)t[h]=e[j+h]}for(;h<tt;++h)t[h]=t[h-Z]}}r.l=g,r.p=L,r.b=h,r.f=c,g&&(c=1,r.m=p,r.d=u,r.n=f)}while(!c);return h!=t.length&&n?ji(t,0,h):t.subarray(0,h)},de=function(A,r,t){t<<=r&7;var e=r/8|0;A[e]|=t,A[e+1]|=t>>8},Wi=function(A,r,t){t<<=r&7;var e=r/8|0;A[e]|=t,A[e+1]|=t>>8,A[e+2]|=t>>16},Co=function(A,r){for(var t=[],e=0;e<A.length;++e)A[e]&&t.push({s:e,f:A[e]});var i=t.length,s=t.slice();if(!i)return{t:Ar,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(w,y){return w.f-y.f}),t.push({s:-1,f:25001});var o=t[0],a=t[1],l=0,c=1,d=2;for(t[0]={s:-1,f:o.f+a.f,l:o,r:a};c!=i-1;)o=t[t[l].f<t[d].f?l++:d++],a=t[l!=c&&t[l].f<t[d].f?l++:d++],t[c++]={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 Nt(h+1),u=Eo(t[c-1],g,0);if(u>r){var e=0,p=0,f=u-r,I=1<<f;for(s.sort(function(y,Q){return g[Q.s]-g[y.s]||y.f-Q.f});e<i;++e){var m=s[e].s;if(g[m]>r)p+=I-(1<<u-g[m]),g[m]=r;else break}for(p>>=f;p>0;){var C=s[e].s;g[C]<r?p-=1<<r-g[C]++-1:++e}for(;e>=0&&p;--e){var B=s[e].s;g[B]==r&&(--g[B],++p)}u=r}return{t:new At(g),l:u}},Eo=function(A,r,t){return A.s==-1?Math.max(Eo(A.l,r,t+1),Eo(A.r,r,t+1)):r[A.s]=t},er=function(A){for(var r=A.length;r&&!A[--r];);for(var t=new Nt(++r),e=0,i=A[0],s=1,n=function(a){t[e++]=a},o=1;o<=r;++o)if(A[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=A[o]}return{c:t.subarray(0,e),n:r}},Xi=function(A,r){for(var t=0,e=0;e<r.length;++e)t+=A[e]*r[e];return t},cr=function(A,r,t){var e=t.length,i=So(r+2);A[i]=e&255,A[i+1]=e>>8,A[i+2]=A[i]^255,A[i+3]=A[i+1]^255;for(var s=0;s<e;++s)A[i+s+4]=t[s];return(i+4+e)*8},ir=function(A,r,t,e,i,s,n,o,a,l,c){de(r,c++,t),++i[256];for(var d=Co(i,15),h=d.t,g=d.l,u=Co(s,15),p=u.t,f=u.l,I=er(h),m=I.c,C=I.n,B=er(p),w=B.c,y=B.n,Q=new Nt(19),v=0;v<m.length;++v)++Q[m[v]&31];for(var v=0;v<w.length;++v)++Q[w[v]&31];for(var E=Co(Q,7),S=E.t,D=E.l,H=19;H>4&&!S[yo[H-1]];--H);var U=l+5<<3,N=Xi(i,Qe)+Xi(s,Zi)+n,b=Xi(i,h)+Xi(s,p)+n+14+3*H+Xi(Q,S)+2*Q[16]+3*Q[17]+7*Q[18];if(a>=0&&U<=N&&U<=b)return cr(r,c,A.subarray(a,a+l));var T,P,R,Z;if(de(r,c,1+(b<N)),c+=2,b<N){T=_t(h,g,0),P=h,R=_t(p,f,0),Z=p;var $=_t(S,D,0);de(r,c,C-257),de(r,c+5,y-1),de(r,c+10,H-4),c+=14;for(var v=0;v<H;++v)de(r,c+3*v,S[yo[v]]);c+=3*H;for(var V=[m,w],L=0;L<2;++L)for(var z=V[L],v=0;v<z.length;++v){var J=z[v]&31;de(r,c,$[J]),c+=S[J],J>15&&(de(r,c,z[v]>>5&127),c+=z[v]>>12)}}else T=cc,P=Qe,R=dc,Z=Zi;for(var v=0;v<o;++v){var O=e[v];if(O>255){var J=O>>18&31;Wi(r,c,T[J+257]),c+=P[J+257],J>7&&(de(r,c,O>>23&31),c+=zs[J]);var st=O&31;Wi(r,c,R[st]),c+=Z[st],st>3&&(Wi(r,c,O>>5&8191),c+=Ws[st])}else Wi(r,c,T[O]),c+=P[O]}return Wi(r,c,T[256]),c+P[256]},uc=new ko([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),Ar=new At(0),fc=function(A,r,t,e,i,s){var n=s.z||A.length,o=new At(e+n+5*(1+Math.ceil(n/7e3))+i),a=o.subarray(e,o.length-i),l=s.l,c=(s.r||0)&7;if(r){c&&(a[0]=s.r>>3);for(var d=uc[r-1],h=d>>13,g=d&8191,u=(1<<t)-1,p=s.p||new Nt(32768),f=s.h||new Nt(u+1),I=Math.ceil(t/3),m=2*I,C=function(wt){return(A[wt]^A[wt+1]<<I^A[wt+2]<<m)&u},B=new ko(25e3),w=new Nt(288),y=new Nt(32),Q=0,v=0,E=s.i||0,S=0,D=s.w||0,H=0;E+2<n;++E){var U=C(E),N=E&32767,b=f[U];if(p[N]=b,f[U]=N,D<=E){var T=n-E;if((Q>7e3||S>24576)&&(T>423||!l)){c=ir(A,a,0,B,w,y,v,S,H,E-H,c),S=Q=v=0,H=E;for(var P=0;P<286;++P)w[P]=0;for(var P=0;P<30;++P)y[P]=0}var R=2,Z=0,$=g,V=N-b&32767;if(T>2&&U==C(E-V))for(var L=Math.min(h,T)-1,z=Math.min(32767,E),J=Math.min(258,T);V<=z&&--$&&N!=b;){if(A[E+R]==A[E+R-V]){for(var O=0;O<J&&A[E+O]==A[E+O-V];++O);if(O>R){if(R=O,Z=V,O>L)break;for(var st=Math.min(V,O-2),lt=0,P=0;P<st;++P){var tt=E-V+P&32767,j=p[tt],yt=tt-j&32767;yt>lt&&(lt=yt,b=tt)}}}N=b,b=p[N],V+=N-b&32767}if(Z){B[S++]=268435456|wo[R]<<18|tr[Z];var ht=wo[R]&31,Mt=tr[Z]&31;v+=zs[ht]+Ws[Mt],++w[257+ht],++y[Mt],D=E+R,++Q}else B[S++]=A[E],++w[A[E]]}}for(E=Math.max(E,D);E<n;++E)B[S++]=A[E],++w[A[E]];c=ir(A,a,l,B,w,y,v,S,H,E-H,c),l||(s.r=c&7|a[c/8|0]<<3,c-=7,s.h=f,s.p=p,s.i=E,s.w=D)}else{for(var E=s.w||0;E<n+l;E+=65535){var nt=E+65535;nt>=n&&(a[c/8|0]=l,nt=n),c=cr(a,c+1,A.subarray(E,nt))}s.i=n}return ji(o,0,e+So(c)+i)},Ic=function(){for(var A=new Int32Array(256),r=0;r<256;++r){for(var t=r,e=9;--e;)t=(t&1&&-306674912)^t>>>1;A[r]=t}return A}(),mc=function(){var A=-1;return{p:function(r){for(var t=A,e=0;e<r.length;++e)t=Ic[t&255^r[e]]^t>>>8;A=t},d:function(){return~A}}},Cc=function(A,r,t,e,i){if(!i&&(i={l:1},r.dictionary)){var s=r.dictionary.subarray(-32768),n=new At(s.length+A.length);n.set(s),n.set(A,s.length),A=n,i.w=s.length}return fc(A,r.level==null?6:r.level,r.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(A.length)))*1.5):20:12+r.mem,t,e,i)},dr=function(A,r){var t={};for(var e in A)t[e]=A[e];for(var e in r)t[e]=r[e];return t},jt=function(A,r){return A[r]|A[r+1]<<8},Pt=function(A,r){return(A[r]|A[r+1]<<8|A[r+2]<<16|A[r+3]<<24)>>>0},Bo=function(A,r){return Pt(A,r)+Pt(A,r+4)*4294967296},ft=function(A,r,t){for(;t;++r)A[r]=t,t>>>=8};hr=function(A,r,t,e){for(var i in A){var s=A[i],n=r+i,o=e;Array.isArray(s)&&(o=dr(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[n]=[s,o]:(t[n+="/"]=[new At(0),o],hr(s,n,t,e))}},sr=typeof TextEncoder<"u"&&new TextEncoder,vo=typeof TextDecoder<"u"&&new TextDecoder,wc=0;try{vo.decode(Ar,{stream:!0}),wc=1}catch{}Qc=function(A){for(var r="",t=0;;){var e=A[t++],i=(e>127)+(e>223)+(e>239);if(t+i>A.length)return{s:r,r:ji(A,t-1)};i?i==3?(e=((e&15)<<18|(A[t++]&63)<<12|(A[t++]&63)<<6|A[t++]&63)-65536,r+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?r+=String.fromCharCode((e&31)<<6|A[t++]&63):r+=String.fromCharCode((e&15)<<12|(A[t++]&63)<<6|A[t++]&63):r+=String.fromCharCode(e)}};Ec=function(A,r){return r+30+jt(A,r+26)+jt(A,r+28)},vc=function(A,r,t){var e=jt(A,r+28),i=jt(A,r+30),s=bo(A.subarray(r+46,r+46+e),!(jt(A,r+8)&2048)),n=r+46+e,o=Fc(A,n,i,t,Pt(A,r+20),Pt(A,r+24),Pt(A,r+42)),a=o[0],l=o[1],c=o[2];return[jt(A,r+10),a,l,s,n+i+jt(A,r+32),c]},Fc=function(A,r,t,e,i,s,n){var o=i==4294967295,a=s==4294967295,l=n==4294967295,c=r+t,d=o+a+l;if(e&&d){for(;r+4<c;r+=4+jt(A,r+2))if(jt(A,r)==1)return[o?Bo(A,r+4+8*a):i,a?Bo(A,r+4):s,l?Bo(A,r+4+8*(a+o)):n,1];e<2&&Ct(13)}return[i,s,n,0]},Fo=function(A){var r=0;if(A)for(var t in A){var e=A[t].length;e>65535&&Ct(9),r+=e+4}return r},nr=function(A,r,t,e,i,s,n,o){var a=e.length,l=t.extra,c=o&&o.length,d=Fo(l);ft(A,r,n!=null?33639248:67324752),r+=4,n!=null&&(A[r++]=20,A[r++]=t.os),A[r]=20,r+=2,A[r++]=t.flag<<1|(s<0&&8),A[r++]=i&&8,A[r++]=t.compression&255,A[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),ft(A,r,g<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),r+=4,s!=-1&&(ft(A,r,t.crc),ft(A,r+4,s<0?-s-2:s),ft(A,r+8,t.size)),ft(A,r+12,a),ft(A,r+14,d),r+=16,n!=null&&(ft(A,r,c),ft(A,r+6,t.attrs),ft(A,r+10,n),r+=14),A.set(e,r),r+=a,d)for(var u in l){var p=l[u],f=p.length;ft(A,r,+u),ft(A,r+2,f),A.set(p,r+4),r+=4+f}return c&&(A.set(o,r),r+=c),r},kc=function(A,r,t,e,i){ft(A,r,101010256),ft(A,r+8,t),ft(A,r+10,t),ft(A,r+12,e),ft(A,r+16,i)}});var fr={};Ii(fr,{bytesToStr:()=>Xs,unzipFiles:()=>pi,zipFiles:()=>hi});function Sc(A){return typeof A=="string"?Vs(A):A instanceof Uint8Array?A:new Uint8Array(A)}function hi(A,r=6){let t={};for(let e of A)t[e.name]=[Sc(e.data),{level:r}];return Promise.resolve(pr(t,{level:r}))}function Xs(A){return bo(A)}function pi(A){let r=A instanceof Uint8Array?A:new Uint8Array(A);return Promise.resolve(gr(r))}var Zs=Jt(()=>{"use strict";ur()});var Xc={};Ii(Xc,{default:()=>Qn});module.exports=rl(Xc);var M=require("obsidian");var mi="sheet-group",ne="sheet-order",qe="sheet-final",$o="sheet-label",Ci="sheet-origin",Bi="forked-from",Ot="fork-siblings",kn="forked-at",Sn=[mi,ne,qe,$o,Ci,Bi,Ot,kn];function Yt(A){if(!A)return null;let r=A[mi];return typeof r=="string"&&r.trim()?r:null}function Fn(A){let r=A?.[ne];return typeof r=="number"?r:null}function yi(A){return Yt(A)!==null&&Fn(A)!==null}function wi(A){return A?.[qe]===!0}function Vo(A){return A?.[Ci]===!0}function ll(A){let r=A?.[Bi];return typeof r=="string"&&r.trim()?r:null}function os(A){return typeof A!="string"?null:A.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].split("#")[0].trim()||null}function zo(A){return os(ll(A))}function cl(A){let r=A?.[$o];return typeof r=="string"&&r.trim()?r:null}function Wo(){let A=Date.now().toString(36),r=Math.floor(Math.random()*1e6).toString(36);return`s-${A}-${r}`}function It(A,r){return r.file?A.metadataCache.getFileCache(r.file)?.frontmatter:null}function bn(A,r){return r.slice().sort((t,e)=>{let i=Fn(It(A,t)),s=Fn(It(A,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(A,r){if(r.length===0)return null;let t=bn(A,r);return t.find(e=>wi(It(A,e)))??t[0]}function Zo(A,r,t){let e=cl(It(A,r));return e||t}at();var Et=require("obsidian");var rt=require("obsidian");at();function rs(A){let r=(A.dateDisplayTimezone||"").trim();return r?{timeZone:r}:{}}function oe(A,r){try{return new Intl.DateTimeFormat(void 0,r).format(new Date(A))}catch{let{timeZone:t,...e}=r;return new Intl.DateTimeFormat(void 0,e).format(new Date(A))}}function ae(A,r){let t=rs(r);switch(r.dateDisplayFormat??"locale"){case"iso":return ea(A,r,!0);case"us":return oe(A,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return oe(A,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return oe(A,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return oe(A,{...t,dateStyle:"medium",timeStyle:"short"})}}function ls(A,r){let t=rs(r);switch(r.dateDisplayFormat??"locale"){case"iso":return ea(A,r,!1);case"us":return oe(A,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return oe(A,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return oe(A,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(A).getFullYear()===e.getFullYear();return oe(A,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function cs(A,r){let t=rs(r),e=r.dateDisplayFormat==="iso"||r.dateDisplayFormat==="eu";return oe(A,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function ea(A,r,t){let e=rs(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(A)),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 Ie(A,r,t){let e=A.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(r>99?"99+":String(r))}var Ui={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},gs=class extends rt.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 pe}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()===q&&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,rt.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,rt.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,rt.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,rt.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(Ui)){let h=Ui[d],g=l.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,rt.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 c=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(c):this.activePanel==="shared"?this.renderSharedPanel(c):this.activePanel==="tasks"&&this.renderTasksPanel(c)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new rt.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,rt.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,rt.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,u)=>this.renderPinnedRow(e,g,u));return}let c=new Map;a.forEach((g,u)=>{let p=c.get(g.folder);p||(p=[],c.set(g.folder,p)),p.push({pin:g,idx:u})});let d=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,h=Array.from(c.keys());d&&c.has(d)&&(h.splice(h.indexOf(d),1),h.unshift(d));for(let g of h){let u=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:u});let f=c.get(g)??[];for(let{pin:I,idx:m}of f)this.renderPinnedRow(e,I,m)}}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,c=this.childrenOf(e.folder,e.id).length,d=c>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",m=>{m.dataTransfer?.setData("text/plain",String(i)),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),g.addClass("is-dragging")}),g.addEventListener("dragend",()=>g.removeClass("is-dragging")),g.addEventListener("dragover",m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="move");let C=g.getBoundingClientRect(),B=m.clientY-C.top<C.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",m=>{m.preventDefault(),g.removeClass("drop-before"),g.removeClass("drop-after");let C=parseInt(m.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===i)return;let B=g.getBoundingClientRect(),w=m.clientY-B.top<B.height/2;this.reorderPin(C,w?i:i+1)});let u=g.createSpan({cls:"stashpad-pinned-toggle"});d&&(Ie(u,c,h),u.onclick=m=>{m.stopPropagation();let C=`${e.folder}|${e.id}`;this.expanded.has(C)?this.expanded.delete(C):this.expanded.add(C),this.render()});let p=g.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(p,d?"folder-tree":"file-text"),a&&(p.style.color=a);let f=g.createSpan({cls:"stashpad-pinned-label",text:o});f.onclick=()=>this.openPinFromPanel(e);let I=e.folder.split("/").pop()||e.folder;if(g.createSpan({cls:"stashpad-pinned-folder",text:I}),g.oncontextmenu=m=>{m.preventDefault();let C=new rt.Menu;C.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),C.showAtMouseEvent(m)},d&&h){let m=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(m,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],c;!a&&!l?c=Date.now():a?l?c=(a.pinnedAt+l.pinnedAt)/2:c=a.pinnedAt+1e3:c=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=c})}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 c=typeof a.color=="string"?a.color:null,d=a.completed===!0,h=this.childrenOf(e,l).length,g=h>0,u=this.expanded.has(`${e}|${l}`),p=t.createDiv({cls:"stashpad-pinned-subrow"});d&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let f=p.createSpan({cls:"stashpad-pinned-toggle"});g&&(Ie(f,h,u),f.onclick=C=>{C.stopPropagation();let B=`${e}|${l}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(I,"file-text"),c&&(I.style.color=c);let m=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});m.onclick=()=>this.openPinFromPanel({folder:e,id:l}),g&&u&&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===k&&(a==null||a===k)){if(o.id===k)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??"",c=a?.created??"";return l.localeCompare(c)}),i}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new rt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(kt(),Hi));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(k)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===q)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(q);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()===q?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 u=o.createEl("button",{cls:"stashpad-shared-chip",text:d});return h&&u.addClass("is-active"),u.onclick=g,u};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[u,p]of n){let f=d.createEl("option",{text:p});f.value=u}let g=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;d.value=g,d.onchange=()=>{let u=d.value;u==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=u,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 c=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(c.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let d of c){let h=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),g=h.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(g,"users"),d.color&&(g.style.color=d.color);let u=h.createSpan({cls:"stashpad-pinned-label",text:d.title});u.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===k&&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===k)continue;let c=this.extractAuthorId(l.author),d=Array.isArray(l.contributors)?l.contributors.filter(C=>typeof C=="string"):[],h=s.get(a)??null;if(!(d.length>0||h===t&&(c!==null&&c!==t)))continue;let I=this.titleFromFile(o),m=typeof l.color=="string"?l.color:null;n.push({file:o,folder:a,id:l.id,title:I,color:m,authorId:c,authorDisplay:this.extractAuthorDisplay(l.author)||(c??""),contributorCount:d.length})}return n.sort((o,a)=>{let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},c=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},d=l.modified??l.created??"";return(c.modified??c.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=b=>!!s&&b.assignedTo.some(T=>T.id===s),o=b=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let P=T.slice(7);return b.assignedTo.some(R=>R.id===P)}switch(T){case"mine":return n(b);case"others":return b.assignedTo.length>0&&!n(b);case"byme":return!!s&&b.assignedBy?.id===s;case"unassigned":return b.assignedTo.length===0;default:return!0}},a=new Map;for(let b of i){for(let T of b.assignedTo)T.id!==s&&a.set(T.id,T.name);b.assignedBy&&b.assignedBy.id!==s&&a.set(b.assignedBy.id,b.assignedBy.name)}let l=[...a.entries()].map(([b,T])=>({id:b,name:T})).sort((b,T)=>b.name.localeCompare(T.name)),c=e.createDiv({cls:"stashpad-task-assign-bar"});c.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let d=c.createEl("select",{cls:"stashpad-task-assign-select"}),h=b=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return b.startsWith("person:")?a.get(b.slice(7))??"Person":T[b]??b},g=b=>{let T=d.createEl("option",{text:h(b),value:b});this.taskAssignFilter===b&&(T.selected=!0)};for(let b of["all","mine","others","byme","unassigned"])g(b);if(l.length>0){let b=d.createEl("optgroup");b.setAttr("label","By person");for(let T of l){let P=b.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(P.selected=!0)}}d.onchange=()=>{this.taskAssignFilter=d.value,this.render()};let u=[...new Set(i.map(b=>b.folder))].sort((b,T)=>b.localeCompare(T));this.taskFolderFilter!=="all"&&!u.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 f=p.createEl("select",{cls:"stashpad-task-assign-select"}),I=f.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(I.selected=!0);for(let b of u){let T=f.createEl("option",{text:b.split("/").pop()||b,value:b});this.taskFolderFilter===b&&(T.selected=!0)}f.onchange=()=>{this.taskFolderFilter=f.value,this.render()};let m=b=>this.taskFolderFilter==="all"||b.folder===this.taskFolderFilter,C=i.filter(b=>o(b)&&m(b));if(C.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 w=B.getTime(),y=w+24*60*60*1e3,Q={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let b of C){if(b.completed){Q.completed.push(b);continue}if(b.due==null){Q.nodate.push(b);continue}b.due<w?Q.overdue.push(b):b.due<y?Q.today.push(b):Q.upcoming.push(b)}let v=(b,T)=>b.due==null&&T.due==null?b.title.localeCompare(T.title):b.due==null?1:T.due==null?-1:b.due-T.due,E=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],S=e.createDiv({cls:"stashpad-task-filters"}),D=C.length,H=(b,T,P)=>{let R=S.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===b&&R.addClass("is-active"),R.createSpan({cls:"stashpad-task-filter-label",text:T}),R.createSpan({cls:"stashpad-task-filter-count",text:String(P)}),R.onclick=()=>{this.taskFilter=b,this.render()}};H("all","All",D),H("overdue","Overdue",Q.overdue.length),H("today","Today",Q.today.length),H("upcoming","Upcoming",Q.upcoming.length),H("nodate","No date",Q.nodate.length),H("completed","Done",Q.completed.length);let U=this.taskFilter==="all"?E:E.filter(b=>b.key===this.taskFilter),N=!1;for(let b of U){let T=Q[b.key];if(T.length!==0){if(N=!0,T.sort(b.key==="completed"?(P,R)=>v(R,P):v),this.taskFilter==="all"){let P=e.createDiv({cls:`stashpad-task-section-header is-${b.key}`});(0,rt.setIcon)(P.createSpan({cls:"stashpad-task-section-icon"}),b.icon),P.createSpan({cls:"stashpad-task-section-name",text:b.label}),P.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let P of T)this.renderTaskRow(e,P,b.key==="today")}}if(!N&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${U[0]?.label??this.taskFilter}".`);return}N||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,rt.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 c of e.assignedTo){let d=l.createSpan({cls:"stashpad-task-assignee"});a&&c.id===a&&d.addClass("is-me"),d.setText(this.initials(c.name)),d.title=a&&c.id===a?`${c.name} (you)`:c.name}}s.oncontextmenu=a=>{a.preventDefault();let l=new rt.Menu;l.addItem(c=>c.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),l.showAtMouseEvent(a)}}formatDueShort(t,e){return e?cs(t,this.plugin.settings):ls(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 rt.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===k)continue;let l=o.completed===!0,c=Ye(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)}!c&&!l&&h==null&&!d||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:c,completed:l,due:h,dueRaw:d,color:typeof o.color=="string"?o.color:null,assignedTo:De(o),assignedBy:fe(o.assignedBy)})}return i}};async function us(A){let r=A.workspace.getLeavesOfType(pe);if(r.length>0){A.workspace.revealLeaf(r[0]);return}let t=A.workspace.getLeftLeaf(!1);if(!t){new rt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:pe,active:!0}),A.workspace.revealLeaf(t)}var Ja=require("obsidian");at();var x=require("obsidian");Gi();var Bs=require("obsidian");at();var ti=class extends Bs.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!=="/"&&Qi.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof Bs.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()}};var ei=require("obsidian"),ys=class A extends ei.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}static norm(t){return t.replace(/^lucide-/,"")}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),i=new Set,s=[];for(let a of(0,ei.getIconIds)()){let l=A.norm(a);i.has(l)||(i.add(l),s.push(l))}let n=a=>e.every(l=>a.toLowerCase().includes(l));return(e.length?s.filter(n):s).sort().slice(0,50)}renderSuggestion(t,e){e.addClass("stashpad-icon-suggest-item");let i=e.createSpan({cls:"stashpad-icon-suggest-icon"});(0,ei.setIcon)(i,t),e.createSpan({cls:"stashpad-icon-suggest-label",text:t})}selectSuggestion(t){this.setValue(t),this.inputEl.dispatchEvent(new Event("input",{bubbles:!0})),this.close()}};at();kt();var He=require("obsidian"),Kn={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."}},Bl={info:4e3,success:4e3,warning:6e3,error:1e4},ma=5e3,ws=class{constructor(r){this.app=r;this.history=[];this.nextId=1;this.historyLimit=ma;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??Bl[t];return new He.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:ma,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",c=>{if(c.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 Qs(A,r,t){let e=A.vault.getAbstractFileByPath(r);if(!(e instanceof He.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=A.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;A.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=He.Platform.isMacOS?"Finder":He.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=A.vault.adapter?.getFullPath?.(r);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var Ca=require("obsidian"),qn=Ca.Platform.isMacOS;function Li(A){if(!A)return"(none)";let r=A.replace(/\bMod\b/g,qn?"Cmd":"Ctrl");return qn&&(r=r.replace(/\bAlt\b/g,"Option")),r}function Ba(A,r,t={allowSingleKey:!0}){let e=A.placeholder,i=A.value;A.placeholder="Press a key\u2026 (Backspace to cancel)",A.value="",A.classList.add("is-recording");let s=!1,n=()=>{A.placeholder=e,A.classList.remove("is-recording"),s||(A.value=i),A.removeEventListener("keydown",o,!0),A.removeEventListener("blur",a)},o=l=>{if(l.key==="Control"||l.key==="Shift"||l.key==="Alt"||l.key==="Meta"||l.key==="OS")return;let c=!!l.code&&(/^Key[A-Z]$/.test(l.code)||/^Digit\d$/.test(l.code));if((l.key==="Dead"||l.key==="Process"||l.key==="Unidentified")&&!c)return;if(l.preventDefault(),l.stopPropagation(),l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&!l.shiftKey){n();return}let d=[];qn?(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=yl(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 A.addEventListener("keydown",o,!0),A.addEventListener("blur",a),n}function yl(A,r){if(!A)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 A.length===1?A.toUpperCase():A}je();Gt();function Ue(A,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(c){try{l(e.next(c))}catch(d){n(d)}}function a(c){try{l(e.throw(c))}catch(d){n(d)}}function l(c){c.done?s(c.value):i(c.value).then(o,a)}l((e=e.apply(A,r||[])).next())})}var ot=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 Ue(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(r())}finally{t()}})}},Jn;function wl(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Vn=wl(),On=(Jn=Vn.Buffer)!==null&&Jn!==void 0?Jn:null,Ql=Vn.TextEncoder?new Vn.TextEncoder:null;function Fa(A,r){return(A&15)+(A>>6|A>>3&8)<<4|(r&15)+(r>>6|r>>3&8)}function ka(A,r){let t=r.length>>1;for(let e=0;e<t;e++){let i=e<<1;A[e]=Fa(r.charCodeAt(i),r.charCodeAt(i+1))}}function El(A,r){if(A.length!==r.length*2)return!1;for(let t=0;t<r.length;t++){let e=t<<1;if(r[t]!==Fa(A.charCodeAt(e),A.charCodeAt(e+1)))return!1}return!0}var ya=87,wa=48;function zn(A,r,t){let e=0;for(let i=0;i<t;i++){let s=r[i]>>>4;A[e++]=s>9?s+ya:s+wa,s=r[i]&15,A[e++]=s>9?s+ya:s+wa}return String.fromCharCode.apply(null,A)}var le=On!==null?A=>{if(typeof A=="string"){let r=On.from(A,"utf8");return new Uint8Array(r.buffer,r.byteOffset,r.length)}if(On.isBuffer(A))return new Uint8Array(A.buffer,A.byteOffset,A.length);if(ArrayBuffer.isView(A))return new Uint8Array(A.buffer,A.byteOffset,A.byteLength);throw new Error("Invalid data type!")}:A=>{if(typeof A=="string")return Ql.encode(A);if(ArrayBuffer.isView(A))return new Uint8Array(A.buffer,A.byteOffset,A.byteLength);throw new Error("Invalid data type!")},Lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",qi=new Uint8Array(256);for(let A=0;A<Lt.length;A++)qi[Lt.charCodeAt(A)]=A;function Qa(A,r=!0){let t=A.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(A[n]<<16&16711680)+(A[n+1]<<8&65280)+(A[n+2]&255),a=Lt.charAt(o>>18&63)+Lt.charAt(o>>12&63)+Lt.charAt(o>>6&63)+Lt.charAt(o&63);i.push(a)}if(e===1){let n=A[t-1],o=Lt.charAt(n>>2),a=Lt.charAt(n<<4&63);i.push(`${o}${a}`),r&&i.push("==")}else if(e===2){let n=(A[t-2]<<8)+A[t-1],o=Lt.charAt(n>>10),a=Lt.charAt(n>>4&63),l=Lt.charAt(n<<2&63);i.push(`${o}${a}${l}`),r&&i.push("=")}return i.join("")}function vl(A){let r=Math.floor(A.length*.75),t=A.length;return A[t-1]==="="&&(r-=1,A[t-2]==="="&&(r-=1)),r}function Fl(A){let r=vl(A),t=A.length,e=new Uint8Array(r),i=0;for(let s=0;s<t;s+=4){let n=qi[A.charCodeAt(s)],o=qi[A.charCodeAt(s+1)],a=qi[A.charCodeAt(s+2)],l=qi[A.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 Es=16*1024,Ki=4,kl=new ot,Yn=new Map;function Sa(A,r){return Ue(this,void 0,void 0,function*(){let t=null,e=null,i=!1;if(typeof WebAssembly>"u")throw new Error("WebAssembly is not supported in this environment!");let s=(y,Q=0)=>{e.set(y,Q)},n=()=>e,o=()=>t.exports,a=y=>{t.exports.Hash_SetMemorySize(y);let Q=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,Q,y)},l=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),c=kl.dispatch(()=>Ue(this,void 0,void 0,function*(){if(!Yn.has(A.name)){let Q=Fl(A.data),v=WebAssembly.compile(Q);Yn.set(A.name,v)}let y=yield Yn.get(A.name);t=yield WebAssembly.instantiate(y,{})})),d=()=>Ue(this,void 0,void 0,function*(){t||(yield c);let y=t.exports.Hash_GetBuffer(),Q=t.exports.memory.buffer;e=new Uint8Array(Q,y,Es)}),h=(y=null)=>{i=!0,t.exports.Hash_Init(y)},g=y=>{let Q=0;for(;Q<y.length;){let v=y.subarray(Q,Q+Es);Q+=v.length,e.set(v),t.exports.Hash_Update(v.length)}},u=y=>{if(!i)throw new Error("update() called before init()");let Q=le(y);g(Q)},p=new Uint8Array(r*2),f=(y,Q=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(Q),y==="binary"?e.slice(0,r):zn(p,e,r)},I=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),Q=l(),v=t.exports.memory.buffer,E=new Uint8Array(v,y,Q),S=new Uint8Array(Ki+Q);return ka(S,A.hash),S.set(E,Ki),S},m=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let Q=t.exports.Hash_GetState(),v=l(),E=Ki+v,S=t.exports.memory.buffer;if(y.length!==E)throw new Error(`Bad state length (expected ${E} bytes, got ${y.length})`);if(!El(A.hash,y.subarray(0,Ki)))throw new Error("This state was written by an incompatible hash implementation");let D=y.subarray(Ki);new Uint8Array(S,Q,v).set(D),i=!0},C=y=>typeof y=="string"?y.length<Es/4:y.byteLength<Es,B=C;switch(A.name){case"argon2":case"scrypt":B=()=>!0;break;case"blake2b":case"blake2s":B=(y,Q)=>Q<=512&&C(y);break;case"blake3":B=(y,Q)=>Q===0&&C(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":B=()=>!1;break}let w=(y,Q=null,v=null)=>{if(!B(y,Q))return h(Q),u(y),f("hex",v);let E=le(y);return e.set(E),t.exports.Hash_Calculate(E.length,Q,v),zn(p,e,r)};return yield d(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:h,update:u,digest:f,save:I,load:m,calculate:w,hashLength:r}})}var SA=new ot;var Sl="argon2",bl="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",Dl="e4cdc523",xl={name:Sl,data:bl,hash:Dl},Nl="blake2b",Ml="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=",Tl="c6f286e6",Pl={name:Nl,data:Ml,hash:Tl},bA=new ot;function Ea(A){return!Number.isInteger(A)||A<8||A>512||A%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function Hl(A,r){return A|r<<16}function Wn(A=512,r=null){if(Ea(A))return Promise.reject(Ea(A));let t=null,e=A;if(r!==null){if(t=le(r),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=Hl(A,t.length)}let i=A/8;return Sa(Pl,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 Ul(A,r,t){let e=[`m=${r.memorySize}`,`t=${r.iterations}`,`p=${r.parallelism}`].join(",");return`$argon2${r.hashType}$v=19$${e}$${Qa(A,!1)}$${Qa(t,!1)}`}var va=new DataView(new ArrayBuffer(4));function re(A){return va.setInt32(0,A,!0),new Uint8Array(va.buffer)}function $n(A,r,t){return Ue(this,void 0,void 0,function*(){if(t<=64){let a=yield Wn(t*8);return a.update(re(t)),a.update(r),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);A.init(),A.update(re(t)),A.update(r);let s=A.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)A.init(),A.update(s),s=A.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=A,o.init()):o=yield Wn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function Rl(A){switch(A){case"d":return 0;case"i":return 1;default:return 2}}function Gl(A){return Ue(this,void 0,void 0,function*(){var r;let{parallelism:t,iterations:e,hashLength:i}=A,s=le(A.password),n=le(A.salt),o=19,a=Rl(A.hashType),{memorySize:l}=A,c=le((r=A.secret)!==null&&r!==void 0?r:""),[d,h]=yield Promise.all([Sa(xl,1024),Wn(512)]);d.setMemorySize(l*1024+1024);let g=new Uint8Array(24),u=new DataView(g.buffer);u.setInt32(0,t,!0),u.setInt32(4,i,!0),u.setInt32(8,l,!0),u.setInt32(12,e,!0),u.setInt32(16,o,!0),u.setInt32(20,a,!0),d.writeMemory(g,l*1024),h.init(),h.update(g),h.update(re(s.length)),h.update(s),h.update(re(n.length)),h.update(n),h.update(re(c.length)),h.update(c),h.update(re(0));let f=Math.floor(l/(t*4))*4,I=new Uint8Array(72),m=h.digest("binary");I.set(m);for(let w=0;w<t;w++){I.set(re(0),64),I.set(re(w),68);let y=w*f,Q=yield $n(h,I,1024);d.writeMemory(Q,y*1024),y+=1,I.set(re(1),64),Q=yield $n(h,I,1024),d.writeMemory(Q,y*1024)}let C=new Uint8Array(1024);ka(C,d.calculate(new Uint8Array([]),l));let B=yield $n(h,C,i);if(A.outputType==="hex"){let w=new Uint8Array(i*2);return zn(w,B,i)}return A.outputType==="encoded"?Ul(n,A,B):B})}var Ll=A=>{var r;if(!A||typeof A!="object")throw new Error("Invalid options parameter. It requires an object.");if(!A.password)throw new Error("Password must be specified");if(A.password=le(A.password),A.password.length<1)throw new Error("Password must be specified");if(!A.salt)throw new Error("Salt must be specified");if(A.salt=le(A.salt),A.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(A.secret=le((r=A.secret)!==null&&r!==void 0?r:""),!Number.isInteger(A.iterations)||A.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(A.parallelism)||A.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(A.hashLength)||A.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(A.memorySize))throw new Error("Memory size should be specified.");if(A.memorySize<8*A.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(A.outputType===void 0&&(A.outputType="hex"),!["hex","binary","encoded"].includes(A.outputType))throw new Error(`Insupported output type ${A.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Xn(A){return Ue(this,void 0,void 0,function*(){return Ll(A),Gl(Object.assign(Object.assign({},A),{hashType:"id"}))})}var DA=new ot;var xA=new ot;var NA=new ot;var MA=new ot;var TA=new Uint8Array(8);var PA=new ot;var HA=new ot;var UA=new ot;var RA=new ot;var GA=new ot;var LA=new ot;var KA=new ot;var qA=new ot;var JA=new ot;var OA=new ot;var YA=new ot;var $A=new Uint8Array(8);var VA=new ot;var zA=new Uint8Array(8);var WA=new ot;var XA=new Uint8Array(8);var ZA=new ot;var jA=new ot;var _A=new ot;kt();var Kt=new Uint8Array([83,84,65,83,72,69,78,67]),_n=2,to=1,eo=2,xa=3,Kl=32,ii=12,Zn=32,ql=6e5,Jl=47104,Ol=3,Yl=1,pt=A=>A;function xt(A){if(A.length<Kt.length+1)return!1;for(let r=0;r<Kt.length;r++)if(A[r]!==Kt[r])return!1;return!0}function ba(A,r,t){A[r]=t>>>24&255,A[r+1]=t>>>16&255,A[r+2]=t>>>8&255,A[r+3]=t&255}function Da(A,r){return A[r]*16777216+(A[r+1]<<16)+(A[r+2]<<8)+A[r+3]}async function jn(A,r,t){if(t.id===eo)return await Xn({password:A,salt:r,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Zn,outputType:"binary"});if(t.id===to){let e=await crypto.subtle.importKey("raw",pt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:pt(r),iterations:t.a,hash:"SHA-256"},e,Zn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function vs(A){return crypto.subtle.importKey("raw",pt(A),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var io={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function Wt(A,r){let t=crypto.getRandomValues(new Uint8Array(Kl)),e=crypto.getRandomValues(new Uint8Array(ii)),i,s,n;try{i={id:eo,a:Jl,b:Ol,c:Yl},n=await jn(r,t,i),s="argon2id"}catch(d){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",d),i={id:to,a:ql,b:0,c:0},n=await jn(r,t,i),s="pbkdf2"}let o=Na(i,t,e),a=await vs(n),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(e),additionalData:pt(o)},a,pt(A))),c=new Uint8Array(o.length+l.length);return c.set(o,0),c.set(l,o.length),{data:c,kdf:s}}var Ji=null;async function Oi(){if(Ji!==null)return Ji;try{await Xn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Ji=!0}catch{Ji=!1}return Ji}function Na(A,r,t){let e=new Uint8Array(Kt.length+1+1+4+4+1+1+r.length+t.length),i=0;return e.set(Kt,i),i+=Kt.length,e[i++]=_n,e[i++]=A.id,ba(e,i,A.a),i+=4,ba(e,i,A.b),i+=4,e[i++]=A.c,e[i++]=r.length,e.set(r,i),i+=r.length,e.set(t,i),i+=t.length,e}async function zt(A,r){if(!xt(A))throw new Error("Not an encrypted Stashpad file.");let t=A[Kt.length];if(t===1)return $l(A,r);if(t!==_n)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Kt.length+1,i={id:A[e++],a:0,b:0,c:0};if(i.a=Da(A,e),e+=4,i.b=Da(A,e),e+=4,i.c=A[e++],i.id===eo){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===to&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=A[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=A.slice(e,e+s);e+=s;let o=A.slice(e,e+ii);e+=ii;let a=A.slice(0,e),l=A.slice(e),c=await jn(r,n,i),d=await vs(c),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(o),additionalData:pt(a)},d,pt(l));return new Uint8Array(h)}async function $l(A,r){let t=Kt.length+1,e=A.slice(t,t+16);t+=16;let i=A.slice(t,t+12);t+=12;let s=A.slice(t),n=await crypto.subtle.importKey("raw",pt(new TextEncoder().encode(r)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:pt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(i)},o,pt(s));return new Uint8Array(a)}async function Ce(A,r){if(r.length!==Zn)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(ii)),i=Na({id:xa,a:0,b:0,c:0},new Uint8Array(0),t),s=await vs(r),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(t),additionalData:pt(i)},s,pt(A))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function Qt(A,r){if(!xt(A))throw new Error("Not an encrypted Stashpad file.");let t=A[Kt.length];if(t!==_n)throw new Error(`Unsupported encrypted version (${t}).`);let e=Kt.length+1;if(A[e++]!==xa)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=A[e++];e+=s;let n=A.slice(e,e+ii);e+=ii;let o=A.slice(0,e),a=A.slice(e),l=await vs(r),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(n),additionalData:pt(o)},l,pt(a));return new Uint8Array(c)}async function si(A,r,t={}){if(!xt(r))return r;if(t.secretId){let i=A.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await zt(r,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new Di(A,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await zt(r,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Gt();var Fs={name:"ECDH",namedCurve:"P-256"},Vl="stashpad-vault-dek-wrap",zl=new TextEncoder;function so(A){let r="";for(let t=0;t<A.length;t++)r+=String.fromCharCode(A[t]);return btoa(r)}function no(A){let r=atob(A),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function Ma(){let A=await crypto.subtle.generateKey(Fs,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",A.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",A.privateKey))}}function Ta(A){return crypto.subtle.importKey("spki",A,Fs,!1,[])}function Wl(A){return crypto.subtle.importKey("pkcs8",A,Fs,!1,["deriveBits"])}async function Pa(A,r){let t=await crypto.subtle.deriveBits({name:"ECDH",public:r},A,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:zl.encode(Vl)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ks(A,r,t){let e=await crypto.subtle.generateKey(Fs,!0,["deriveBits"]),i=await Pa(e.privateKey,await Ta(r)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,A)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:so(o),iv:so(s),ct:so(n)}}async function Ha(A,r){let t=await Pa(await Wl(r),await Ta(no(A.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:no(A.iv)},t,no(A.ct)))}var Ua=".stashpad/keys.json",Xl=".stashpad",Yi="_keys";function oo(A){return{v:2,keyId:A,identities:[],slots:[],joinRequests:[]}}var Ss=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(Ua);if(r)return r;try{let e=((await this.a.list(Yi)).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(Xl),await this.a.write(Ua,t),await this.ensureDir(Yi);for(let e=4;e>=1;e--){let i=`${Yi}/keys-${e}.json`,s=`${Yi}/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(`${Yi}/keys-1.json`,t)}catch{}}};var Re="stashpad-vault-encryption";function $i(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function Ge(A){let r="";for(let t=0;t<A.length;t++)r+=String.fromCharCode(A[t]);return btoa(r)}function Xt(A){let r=atob(A),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}var Ra=32,bs=class{constructor(r,t,e,i=()=>0){this.app=r;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.folderSessionKeys=new Map;this.idleTimer=null;this.kf=null;this.keyfiles=new Ss(r)}argonProbe(){return Oi()}async init(){await this.refresh()}async refresh(){this.kf=await this.keyfiles.load()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}appTag(){return(this.app.appId||"default").toLowerCase().replace(/[^a-z0-9]/g,"").slice(0,20)||"default"}keychainId(){return`${Re}-${this.appTag()}`}legacyAppIdKeychainId(){let r=this.app.appId||"default";return`${Re}-${r}`}isRemembered(){try{let r=this.secretStore();return!!(r?.getSecret(this.keychainId())||r?.getSecret(this.legacyAppIdKeychainId()))}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{let t=r.getSecret(this.legacyAppIdKeychainId());if(t)return t}catch{}try{return r.getSecret(Re)||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(Re)??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(Re):await r?.setSecret(Re,"")}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(Ra)),s=await this.mintIdentity(r,e),n=oo(W(8));n.identities.push(this.identityRecord(s)),n.slots.push(await ks(i,Xt(s.pub),s.id)),await this.keyfiles.save(n),this.kf=n,this.sessionKey=i,t&&await this.remember(r),this.armIdle()}async unlock(r,t=!1){await this.refresh();let e=this.load();if(!this.kf&&e.wrappedKey){let s;try{s=await zt(Xt(e.wrappedKey),r)}catch{return!1}let n=await this.mintIdentity(r,e.identityLabel??void 0),o=oo(W(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await ks(s,Xt(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 zt(Xt(e.identityPrivWrapped),r);try{let n=await Ha(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??[]).filter(n=>!n.label.startsWith("[deprecated]")))try{let n=await zt(Xt(s.wrapped),r);return this.sessionKey=n,t&&await this.remember(r),this.armIdle(),!0}catch{}return!1}hasSharedPassword(){return(this.kf?.passwordSlots??[]).some(r=>!r.label.startsWith("[deprecated]"))}async setSharedPassword(r,t=!1){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 e=(this.kf.passwordSlots??[]).filter(o=>!o.label.startsWith("[deprecated]")),i=this.rememberedPassword();if(i&&e[0])try{await this.secretStore()?.setSecret(`${this.keychainId()}-d-${e[0].id}`,i)}catch{}let s=await Wt(this.sessionKey,r),n=(this.kf.passwordSlots??[]).map(o=>o.label.startsWith("[deprecated]")?o:{...o,label:`[deprecated] ${o.label}`});this.kf.passwordSlots=[{id:W(8),label:"Shared password",wrapped:Ge(s.data),kdf:s.kdf,createdAt:new Date().toISOString()},...n],await this.keyfiles.save(this.kf),(t||this.isRemembered())&&await this.remember(r)}async removeSharedPassword(){await this.refresh(),!(!this.kf||!this.kf.passwordSlots?.length)&&(this.kf.passwordSlots=[],await this.keyfiles.save(this.kf))}owningFolder(r){let t=this.kf?.folderKeys;if(!t)return null;let e=this.cleanFolder(r);for(;e;){if(t[e])return e;let i=e.lastIndexOf("/");if(i<0)break;e=e.slice(0,i)}return null}hasOwnFolderKey(r){return!!this.kf?.folderKeys?.[this.cleanFolder(r)]}folderKeyEntry(r){let t=this.owningFolder(r);return t?this.kf.folderKeys[t]??null:null}hasFolderKey(r){return this.owningFolder(r)!==null}folderPathByKeyId(r){for(let[t,e]of Object.entries(this.kf?.folderKeys??{}))if(e.keyId===r)return t;return null}folderActiveSlots(r){return r.passwordSlots.filter(t=>!t.label.startsWith("[deprecated]"))}isFolderUnlocked(r){let t=this.owningFolder(r);return t?this.folderSessionKeys.has(t):this.isUnlocked()}getFolderKey(r){let t=this.owningFolder(r);if(!t)return this.getSessionKey();let e=this.folderSessionKeys.get(t);return e?(this.armIdle(),e.slice()):null}async setupFolderKey(r,t,e,i=!1){if(!t)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Set up vault encryption first.");let s=this.cleanFolder(r);if(this.kf.folderKeys?.[s])throw new Error("This folder already has its own key.");let n=this.owningFolder(s);if(n&&n!==s)throw new Error(`A parent folder (\u201C${n.split("/").pop()}\u201D) already has its own password; this folder inherits it.`);let o=crypto.getRandomValues(new Uint8Array(Ra)),a=await Wt(o,t),l=W(8),c={keyId:l,folderPath:s,label:e,kcId:this.folderKcId(e,l),passwordSlots:[{id:W(8),label:"Folder password",wrapped:Ge(a.data),kdf:a.kdf,createdAt:new Date().toISOString()}],createdAt:new Date().toISOString()};this.kf.folderKeys={...this.kf.folderKeys??{},[s]:c},await this.keyfiles.save(this.kf),this.folderSessionKeys.set(s,o),i&&await this.rememberFolder(this.folderKcIdFor(c),t),this.armIdle()}async unlockFolder(r,t,e=!1){await this.refresh();let i=this.cleanFolder(r),s=this.folderKeyEntry(i);if(!s)return!1;for(let n of this.folderActiveSlots(s))try{let o=await zt(Xt(n.wrapped),t);this.folderSessionKeys.set(s.folderPath,o);let a=this.folderKcIdFor(s);return(e||this.isFolderRemembered(a))&&await this.rememberFolder(a,t),this.armIdle(),!0}catch{}return!1}async tryAutoUnlockFolder(r){let t=this.folderKeyEntry(r);if(!t||this.isFolderUnlocked(r))return this.isFolderUnlocked(r);let e=this.rememberedFolderPassword(this.folderKcIdFor(t));return e?this.unlockFolder(r,e):!1}async changeFolderPassword(r,t,e=!1){if(!t)throw new Error("Password required.");let i=this.cleanFolder(r);await this.refresh();let s=this.folderKeyEntry(i);if(!s||!this.kf)throw new Error("This folder has no key.");let n=s.folderPath,o=this.folderSessionKeys.get(n);if(!o)throw new Error("Unlock this folder first.");let a=s.passwordSlots.filter(u=>!u.label.startsWith("[deprecated]")),l=this.folderKcIdFor(s),c=this.rememberedFolderPassword(l);if(c&&a[0])try{await this.secretStore()?.setSecret(`${l}-d-${a[0].id}`,c)}catch{}let d=await Wt(o,t),h=s.passwordSlots.map(u=>u.label.startsWith("[deprecated]")?u:{...u,label:`[deprecated] ${u.label}`}),g={...s,kcId:s.kcId??this.folderKcId(s.label,s.keyId),passwordSlots:[{id:W(8),label:"Folder password",wrapped:Ge(d.data),kdf:d.kdf,createdAt:new Date().toISOString()},...h]};this.kf.folderKeys={...this.kf.folderKeys??{},[n]:g},await this.keyfiles.save(this.kf),(e||this.isFolderRemembered(l))&&await this.rememberFolder(this.folderKcIdFor(g),t)}async commitFolderRotation(r,t,e,i,s,n=!1){if(!t)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let o=this.cleanFolder(r),a=this.folderKeyEntry(o),l=a?.folderPath??o,c=a?.keyId??W(8),d=a?this.folderKcIdFor(a):null,h=(a?.passwordSlots??[]).filter(C=>!C.label.startsWith("[deprecated]")),g=d?this.rememberedFolderPassword(d):null;if(g&&h[0])try{await this.secretStore()?.setSecret(`${d}-d-${h[0].id}`,g)}catch{}let u=await Wt(e,t),p=(a?.passwordSlots??[]).map(C=>C.label.startsWith("[deprecated]")?C:{...C,label:`[deprecated] ${C.label}`}),f=s??a?.label??`rotated - ${o.split("/").pop()||o}`,I={keyId:c,folderPath:l,label:f,kcId:this.folderKcId(f,c),rotId:i,passwordSlots:[{id:W(8),label:"Folder password",wrapped:Ge(u.data),kdf:u.kdf,createdAt:new Date().toISOString()},...p],createdAt:a?.createdAt??new Date().toISOString()};this.kf.folderKeys={...this.kf.folderKeys??{},[l]:I},await this.keyfiles.save(this.kf);let m=this.folderSessionKeys.get(l);m&&m!==e&&m.fill(0),this.folderSessionKeys.set(l,e.slice()),(n||d&&this.isFolderRemembered(d))&&await this.rememberFolder(this.folderKcIdFor(I),t)}folderKcId(r,t){return(`sp-${(r||"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")}`.slice(0,44)+`-${t.slice(0,6)}`).replace(/-+/g,"-")}folderKcIdFor(r){return r.kcId||`${Re}-f-${r.keyId}`}isFolderRemembered(r){try{return!!this.secretStore()?.getSecret(r)}catch{return!1}}rememberedFolderPassword(r){try{return this.secretStore()?.getSecret(r)||null}catch{return null}}async rememberFolder(r,t){try{await this.secretStore()?.setSecret(r,t)}catch(e){console.warn("[Stashpad] couldn't save folder password to keychain",e)}}async forgetFolderKeychain(r){let t=this.folderKeyEntry(r);if(!t)return;let e=this.secretStore();if(!e)return;let i=this.folderKcIdFor(t);try{e.removeSecret?await e.removeSecret(i):await e.setSecret(i,"")}catch(s){console.warn("[Stashpad] couldn't clear folder keychain",s)}}async verifyPassword(r){let t=this.load();try{if(t.identityPrivWrapped)return(await zt(Xt(t.identityPrivWrapped),r)).fill(0),!0;if(t.wrappedKey)return(await zt(Xt(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 zt(Xt(s.identityPrivWrapped),r)}catch{return!1}let o=await Wt(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:Ge(o.data),identityPrivKdf:o.kdf}),(e||this.isRemembered())&&await this.remember(t),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||this.isRemembered())&&await this.remember(t)}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 ks(this.sessionKey,Xt(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;for(let r of this.folderSessionKeys.values())r.fill(0);this.folderSessionKeys.clear(),this.clearIdle()}lockFolder(r){let t=this.owningFolder(r)??this.cleanFolder(r),e=this.folderSessionKeys.get(t);e&&(e.fill(0),this.folderSessionKeys.delete(t))}cleanFolder(r){return(r||"").replace(/\/+$/,"")}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($i())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(r,t){let e=await Ma(),i=await Wt(e.privKeyPkcs8,r);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??W(8),o=t??s.identityLabel??"This device",a=Ge(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:a,identityPrivWrapped:Ge(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 Vi=null,Ds=new Set;function xs(A){if(Vi!==A){Vi=A;for(let r of Ds)r()}}function ce(){return Vi}function Ga(A){if(Vi===A){Vi=null;for(let r of Ds)r()}}function La(A){return Ds.add(A),()=>Ds.delete(A)}function Zl(){return x.Platform.isMacOS?"Finder":x.Platform.isWin?"File Explorer":"file manager"}var ni=[{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 lo(){let A={};for(let r of ni)A[r.id]={primary:r.defaultPrimary,secondary:r.defaultSecondary??"",preferRight:!1,useBoth:!!r.defaultUseBoth};return A}var jl=!1,_l=!1,Be={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:$i(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],folderEncPrefs:{},folderIcons:{},folderSwitcherIncludePinned:!1,importExcludePrefixes:"_",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:lo()},Ka=JSON.parse(JSON.stringify(Be)),ro=new Set;function X(){return Ka}function co(A){Ka=A;for(let r of ro)r()}function qa(A){return ro.add(A),()=>ro.delete(A)}function Ts(A){try{let r=A.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:"\u{1F4C1} Folders & Storage"},{id:"importExport",label:"\u{1F504} Import & Export"},{id:"datesTime",label:"\u{1F552} Dates & Time"},{id:"behaviors",label:"\u{1F39B}\uFE0F Behavior"},{id:"notifications",label:"\u{1F514} Notifications"},{id:"encryption",label:"\u{1F512} Encryption"},{id:"authorship",label:"\u2712\uFE0F Authorship"},{id:"templates",label:"\u{1F4C4} Templates"},{id:"organizationSystems",label:"\u{1F5C2}\uFE0F Organization Systems"},{id:"maintenance",label:"\u{1F6E0}\uFE0F Maintenance"},{id:"diagnostics",label:"\u{1FA7A} Diagnostics"},{id:"hotkeys",label:"\u2328\uFE0F Hotkeys"}].sort((A,r)=>{let t=e=>e.replace(/^[^\p{L}\p{N}]+/u,"");return t(A.label).localeCompare(t(r.label))}),ao=null;function tc(A,r){return ao||(ao=class extends x.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new ao(A,r)}var Ms=class extends x.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.pfeSelected=null;this.iconPickFolder=null}display(){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:()=>tc(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"datesTime":return this.buildGeneralCategories().datesTime;case"maintenance":return this.buildGeneralCategories().maintenance;case"behaviors":{let e=this.buildGeneralCategories();return[this.headingDef("\u{1F4CB} List & Display"),...e.listDisplay,this.headingDef("\u2195\uFE0F Moving Notes"),...e.movingNotes,this.headingDef("\u270D\uFE0F Composer & Copying"),...e.composerCopy,this.headingDef("\u{1F5D1}\uFE0F Deleting"),...e.deleting,this.headingDef("\u{1FA9F} Windows & Tabs"),...e.windowsTabs,this.headingDef("\u2699\uFE0F Misc"),...e.misc]}case"organizationSystems":return[this.headingDef("\u{1F522} JD Index (Johnny Decimal)"),...this.jdIndexItems(),this.headingDef("\u{1F4DA} Open Knowledge Format (OKF)"),...this.okfItems()];case"encryption":return this.encryptionItems();case"authorship":return this.authorshipItems();case"templates":return this.templatesItems();default:return null}}renderTabContent(t,e){switch(e){case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(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 ze(this.app,n,s).open()})),["log","history","diagnostics"])]}notificationsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(Kn);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=Kn[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 Mi(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 ze(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)}}}}headingDef(t,e){return this.sectionDef(t,e??"",i=>{let s=new x.Setting(i).setName(t).setHeading();e&&s.setDesc(e)},[t.toLowerCase()])}folderKeyLabel(t){let e=new Date,i=a=>String(a).padStart(2,"0"),s=`${e.getFullYear()}${i(e.getMonth()+1)}${i(e.getDate())}-${i(e.getHours())}${i(e.getMinutes())}`,n=(this.plugin.settings.authorName||"").trim(),o=n?n.split(/\s+/).map(a=>a[0]).join(""):(this.plugin.settings.authorId||"anon").slice(0,4);return`${s} - ${t.split("/").pop()||t} - ${o}`}promptSetFolderPassword(t){new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Set password for \u201C${t.split("/").pop()}\u201D`,intro:"A separate password just for this folder. Share it with collaborators out-of-band (a password manager, Signal, in person). There is NO recovery if it's lost.",onSubmit:async({next:e,remember:i})=>{if(!e)return"Enter a password.";try{await this.plugin.encryption.setupFolderKey(t,e,this.folderKeyLabel(t),i)}catch(s){return s.message}return new x.Notice("Folder password set \u2014 share it securely."),this.update?.(),null}}).open()}promptChangeFolderPassword(t){new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Change password for \u201C${t.split("/").pop()}\u201D`,intro:"Re-wraps this folder's key under a new password. The OLD password stops working on THIS device right away (un-synced copies elsewhere keep working until they sync). To truly cut off someone who left, you'll want \u201CRotate key\u201D (re-encrypts everything) \u2014 coming soon.",onSubmit:async({next:e,remember:i})=>{if(!e)return"Enter a password.";try{await this.plugin.encryption.changeFolderPassword(t,e,i)}catch(s){return s.message}return new x.Notice("Folder password changed."),this.update?.(),null}}).open()}promptRotateFolderKey(t){let e=t.split("/").pop()||t;new it(this.app,`Rotate key for \u201C${e}\u201D?`,`This RE-ENCRYPTS every locked note in \u201C${e}\u201D under a brand-new key, then retires the old password so it can no longer decrypt them \u2014 even copies a collaborator synced earlier. Use this when someone should LOSE access (e.g. they left the org). Large folders can take a while. Everyone who should keep access will need the new password.`,"Rotate key",i=>{i&&new ct(this.app,{mode:"setup",offerKeychain:!0,title:`New password for \u201C${e}\u201D`,intro:"The new password to use after rotating. Share it only with people who should keep access.",onSubmit:async({next:s,remember:n})=>s?await this.plugin.rotateFolderKey(t,s,n)<0?"Rotation failed \u2014 see the notice.":(this.update?.(),null):"Enter a password."}).open()}).open()}promptUnlockFolder(t){new ct(this.app,{mode:"unlock",offerKeychain:!0,title:`Unlock \u201C${t.split("/").pop()}\u201D`,intro:"Enter this folder's password.",onSubmit:async({current:e,remember:i})=>await this.plugin.encryption.unlockFolder(t,e,i)?(new x.Notice("Folder unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()}encryptionOrOnboard(){return this.plugin.encryption?.isConfigured?.()?!0:(new x.Notice("That setting needs vault encryption, which isn't set up yet \u2014 let's set it up first.",6e3),new ct(this.app,{mode:"setup",offerKeychain:!0,title:"Set up encryption",intro:"One password protects what you encrypt in this vault. It's stored only on this device \u2014 there is NO recovery if you lose it.",onSubmit:async({next:t,remember:e})=>{if(!t)return"Enter a password.";try{await this.plugin.encryption.setup(t,e,this.plugin.settings.authorName||"This device")}catch(i){return i.message}return new x.Notice("Encryption set up \u2014 now switch on the setting you wanted."),this.update?.(),null}}).open(),!1)}renderPerFolderEncryption(t){if(!this.plugin.encryption.isConfigured()){t.createEl("p",{cls:"setting-item-description"}).setText("Set up vault encryption above first. Per-folder passwords layer on top: a folder with its own password uses a separate key; folders without one use the vault password.");return}t.createEl("p",{cls:"setting-item-description stashpad-enc-warning"}).setText("\u26A0\uFE0F Encryption has no recovery \u2014 if you lose a password, anything encrypted under it (notes, archived items, and encrypted-trash items) is gone for good. Locking / archiving / secure-deleting permanently removes the plaintext; the encrypted copy is the only one left. A plaintext archive only de-indexes notes from search \u2014 it does NOT encrypt them.");let i=this.plugin.discoverStashpadFolders();if(i.length===0){t.createEl("p",{cls:"setting-item-description"}).setText("No Stashpad folders found yet.");return}(!this.pfeSelected||!i.includes(this.pfeSelected))&&(this.pfeSelected=i[0]),new x.Setting(t).setName("Folder").setDesc("Pick a folder to configure its password, archive, and trash options. Everything below applies to the selected folder only.").addDropdown(n=>{for(let o of i)n.addOption(o,o);n.setValue(this.pfeSelected),n.onChange(o=>{this.pfeSelected=o,this.update?.()})});let s=t.createDiv({cls:"stashpad-folderenc-panel"});this.renderFolderEncPanel(s,this.pfeSelected)}renderFolderEncPanel(t,e){let i=this.plugin.encryption,s=i.hasOwnFolderKey(e),n=i.folderKeyEntry(e)?.folderPath??null,o=!!n&&!s,a=i.isFolderUnlocked(e),l=(this.plugin.settings.folderEncPrefs??{})[e]??{},c=s?a?"Has its own password \xB7 unlocked":"Has its own password \xB7 locked":o?`Inherits \u201C${n.split("/").pop()||n}\u201D's password \xB7 ${a?"unlocked":"locked"}`:"Uses the vault password",d=new x.Setting(t).setName("Password").setDesc(c);o?d.addButton(p=>p.setButtonText("Manage on parent folder").onClick(()=>{this.pfeSelected=n,this.update?.()})):s?a?(d.addButton(p=>p.setButtonText("Lock (forget password)").onClick(()=>{this.plugin.encryption.lockFolder(e),new x.Notice("Folder locked \u2014 you'll re-enter its password next time."),this.update?.()})),d.addButton(p=>p.setButtonText("Change password\u2026").onClick(()=>this.promptChangeFolderPassword(e))),d.addButton(p=>{p.setButtonText("Rotate key\u2026").onClick(()=>this.promptRotateFolderKey(e)),p.buttonEl.addClass("mod-warning")})):d.addButton(p=>p.setButtonText("Unlock\u2026").setCta().onClick(()=>this.promptUnlockFolder(e))):d.addButton(p=>p.setButtonText("Set folder password\u2026").setCta().onClick(()=>this.promptSetFolderPassword(e)));let h=async p=>{this.plugin.settings.folderEncPrefs={...this.plugin.settings.folderEncPrefs??{},[e]:{...(this.plugin.settings.folderEncPrefs??{})[e]??{},...p}},await this.plugin.saveSettings()};new x.Setting(t).setName("Archive").setDesc("De-indexes this folder from cross-folder search; notes moved in get auto-encrypted (when \u201CEncrypt archived notes\u201D is on below).").addToggle(p=>p.setValue(!!l.archive).onChange(async f=>{await h({archive:f,...f&&l.archiveEncryptContent===void 0?{archiveEncryptContent:!0}:{}});let I=new Set((this.plugin.settings.archiveFolders??[]).map(m=>m.replace(/\/+$/,"")));f?I.add(e):I.delete(e),this.plugin.settings.archiveFolders=[...I],!f&&(this.plugin.settings.defaultArchiveFolder??"")===e&&(this.plugin.settings.defaultArchiveFolder=void 0),await this.plugin.saveSettings(),this.plugin.refreshFolderPanels(),this.update?.()})),new x.Setting(t).setName("Trash handling").setDesc("Where notes deleted from this folder go.").addDropdown(p=>p.addOption("","Use global default").addOption("stashpad","Stashpad encrypted trash").addOption("obsidian","Obsidian native trash").setValue(l.trashHandling??"").onChange(f=>h({trashHandling:f||void 0})));let g=(p,f,I,m)=>{new x.Setting(t).setName(p).addToggle(C=>C.setValue(!!l[f]).onChange(async B=>{let w={};w[f]=B,B||(w[I]=!1),await h(w),m&&await m(B),this.update?.()})),new x.Setting(t).setName(`\u21B3 ${p} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(C=>{C.setValue(!!l[I]),C.setDisabled(!l[f]),C.onChange(B=>{let w={};w[I]=B,h(w)})})};g("Encrypt this folder's notes","encryptContent","encryptFilenames",async p=>{p?await this.plugin.lockFolder(e):await this.plugin.unlockFolder(e);let f=(this.plugin.settings.lockedSubtrees??[]).some(I=>(I.folder||"").replace(/\/+$/,"")===e);await h({encryptContent:f,...f?{}:{encryptFilenames:!1}})}),g("Encrypt archived notes","archiveEncryptContent","archiveEncryptFilenames"),g("Encrypt trashed notes","trashEncryptContent","trashEncryptFilenames");let u=this.plugin.discoverStashpadFolders().filter(p=>p!==e&&p.startsWith(e+"/")).sort();if(u.length){new x.Setting(t).setName("Subfolders").setDesc(`${u.length} subfolder${u.length===1?"":"s"} \u2014 they use \u201C${e.split("/").pop()}\u201D's password. Encrypt each individually.`).setHeading();for(let p of u){let f=(this.plugin.settings.folderEncPrefs??{})[p]??{},I=async B=>{this.plugin.settings.folderEncPrefs={...this.plugin.settings.folderEncPrefs??{},[p]:{...(this.plugin.settings.folderEncPrefs??{})[p]??{},...B}},await this.plugin.saveSettings()},m=(this.plugin.settings.lockedSubtrees??[]).some(B=>(B.folder||"").replace(/\/+$/,"")===p),C=p.slice(e.length+1);new x.Setting(t).setName(C).addToggle(B=>B.setValue(m).onChange(async w=>{w?await this.plugin.lockFolder(p):await this.plugin.unlockFolder(p);let y=(this.plugin.settings.lockedSubtrees??[]).some(Q=>(Q.folder||"").replace(/\/+$/,"")===p);await I({encryptContent:y,...y?{}:{encryptFilenames:!1}}),this.update?.()})),new x.Setting(t).setName(`\u21B3 ${C} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(B=>{B.setValue(!!f.encryptFilenames),B.setDisabled(!m),B.onChange(w=>void I({encryptFilenames:w}))})}}}buildGeneralCategories(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,l)=>this.renderDef(s,n,c=>c.addToggle(d=>d.setValue(o()).onChange(async h=>{a(h),await t()})),l),i={foldersStorage:[],importExport:[],datesTime:[],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 ti(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||Be.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.foldersStorage.push(e("Include pinned notes in the folder switcher","When on, the folder switcher / creator (the folder button and the \u201COpen or switch Stashpad folder\u201D command) also lists your pinned notes, so you can jump straight to one. Off keeps the picker focused on folders.",()=>this.plugin.settings.folderSwitcherIncludePinned,s=>{this.plugin.settings.folderSwitcherIncludePinned=s},["pinned","switcher","folder","picker","jump"])),i.foldersStorage.push(this.renderDef("Folder tab icon","Give a folder its own Lucide icon (e.g. rocket, star, book-open) shown on its tab, the folder switcher, and its folder-panel row. Pick a folder, then start typing in the icon box \u2014 matching icons appear with previews; pick one. Blank = the default icon. Set per folder.",s=>{let n=this.plugin.discoverStashpadFolders();if(n.length===0){s.setDesc("No Stashpad folders found yet.");return}(!this.iconPickFolder||!n.includes(this.iconPickFolder))&&(this.iconPickFolder=n[0]);let o=null,a=s.controlEl.createSpan({cls:"stashpad-folder-icon-preview"}),l=c=>{a.empty();let d=c.trim();d&&(0,x.setIcon)(a,d)};s.addDropdown(c=>{for(let d of n)c.addOption(d,d.split("/").pop()||d);c.setValue(this.iconPickFolder),c.onChange(d=>{this.iconPickFolder=d;let h=this.plugin.getFolderIcon(d)??"";o?.setValue(h),l(h)})}),s.addText(c=>{o=c,c.setPlaceholder("type to search\u2026 (e.g. rocket)"),new ys(this.app,c.inputEl),c.setValue(this.plugin.getFolderIcon(this.iconPickFolder)??""),c.onChange(async d=>{l(d),await this.plugin.setFolderIcon(this.iconPickFolder,d.trim())})}),l(this.plugin.getFolderIcon(this.iconPickFolder)??"")},["icon","folder","tab","lucide","emoji","switcher"])),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,"")||Be.exportFolder,await t()})),["export","stash","subfolder"])),i.importExport.push(this.renderDef("Exclude subfolders by prefix","Comma-separated name prefixes (default \u201C_\u201D). A subfolder whose name starts with any of these \u2014 at any depth \u2014 is NOT surfaced as a Stashpad folder or imported (it stays local). To encrypt such a folder, right-click it in Obsidian's file explorer \u2192 \u201C\u{1F512} Encrypt with Stashpad\u201D.",s=>s.addText(n=>n.setValue(this.plugin.settings.importExcludePrefixes??"_").setPlaceholder("_").onChange(async o=>{this.plugin.settings.importExcludePrefixes=o,await t()})),["import","exclude","prefix","subfolder","underscore","ignore"])),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{await this.plugin.runRebootstrapWithUI()}catch{}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"]));{let s=null,n=()=>{s&&s.setText(`Sample: ${ae(Date.now(),this.plugin.settings)}`)};i.datesTime.push(this.renderDef("Date display format","How created / edited timestamps and due dates are shown \u2014 in the notes list, the Tasks panel, and the detail panel. Overridden by the Templates-plugin formats when the option below is on.",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("Use Templates plugin date/time formats","Use the date/time formats configured in the core Templates plugin instead of the Date display format above. Off = the Date display format above is used everywhere.",o=>{o.addToggle(l=>l.setValue(this.plugin.settings.useTemplatesFormat).onChange(async c=>{this.plugin.settings.useTemplatesFormat=c,await t(),n()}));let a=Ts(this.app);o.descEl.createDiv({cls:"stashpad-settings-note"}).setText(a?`Templates plugin: date = "${a.dateFormat}", time = "${a.timeFormat}"`:"Templates plugin not enabled.")},["templates","date","time","format"])),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"),a.addClass("stashpad-settings-section"),s=a.createDiv({cls:"setting-item-description stashpad-settings-note stashpad-date-sample"}),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.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(c){new x.Notice(`Couldn't create: ${c.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.foldersStorage.push(this.headingDef("\u{1F3F7}\uFE0F Note Titles")),i.foldersStorage.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:Vt).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(c=>c.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(a=>a.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Vt],n&&(n.value=Vt.join(` +`)),await t()}))},["slug","stopwords","filename","title","note titles"])),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(h=>h.setButtonText("Set up password\u2026").setCta().onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:g,remember:u})=>{if(!g)return"Enter a password.";try{await t.setup(g,u,o())}catch(p){return p.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(h=>h.setButtonText("Unlock with shared password\u2026").setCta().onClick(()=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(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(h=>h.setButtonText("Request access\u2026").onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:g,remember:u})=>{if(!g)return"Choose a password for this device.";try{await t.requestAccess(o(),g,u)}catch(p){return p.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(h=>h.setButtonText("Try unlock now").setCta().onClick(()=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(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(h=>h.setButtonText("Cancel request").onClick(async()=>{let g=t.myIdentityId();g&&await t.denyJoinRequest(g),new x.Notice("Access request cancelled."),this.update?.()}));return}let c=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"}${c?` \xB7 ${c}`:""}${d}`),t.isUnlocked()?new x.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(h=>h.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(h=>h.setButtonText("Unlock\u2026").setCta().onClick(()=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(new x.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),_l&&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(h=>h.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(h=>h.setButtonText("Change\u2026").onClick(()=>{new ct(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:g,next:u,remember:p})=>await t.changePassword(g,u,p)?(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(h=>{let g=async()=>{let u=await this.plugin.encryptionStateStrict();if(u.live){let f=()=>{new it(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 C=await this.plugin.purgeAllLockedContent();new x.Notice(`Deleted ${C} locked item${C===1?"":"s"}.`),g()}).open()},I=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}g()};new it(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?I():f()},"Delete locked content").open();return}let p=(f,I)=>{new Di(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&&!I){new x.Notice("Encrypted trash appeared while this dialog was open \u2014 removal cancelled. Re-open Remove encryption to handle it.",1e4);return}let C=await this.plugin.listDeletedTrash();for(let B of C)await this.plugin.purgeDeletedAt(B.blob);await t.clear(),new x.Notice("Encryption removed."),this.update?.()}}).open()};if(u.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}p(m>0?` (${m} trash item${m===1?"":"s"} were decrypted back to their folders.)`:"",!0)},I=()=>{new it(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&&p(" \u26A0\uFE0F The encrypted trash is being permanently discarded.",!0)}).open()};new it(this.app,"Encrypted notes in the trash",`There are encrypted, deleted notes in the trash. Removing encryption makes them PERMANENTLY unreadable. +\u2022 Delete locked content \u2014 permanently destroy them (only if you've lost the password).`,"Decrypt everything",m=>{m?I():f()},"Delete locked content").open();return}let p=(f,I)=>{new xi(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&&!I){new x.Notice("Encrypted trash appeared while this dialog was open \u2014 removal cancelled. Re-open Remove encryption to handle it.",1e4);return}let C=await this.plugin.listDeletedTrash();for(let B of C)await this.plugin.purgeDeletedAt(B.blob);await t.clear(),new x.Notice("Encryption removed."),this.update?.()}}).open()};if(u.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}p(m>0?` (${m} trash item${m===1?"":"s"} were decrypted back to their folders.)`:"",!0)},I=()=>{new it(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&&p(" \u26A0\uFE0F The encrypted trash is being permanently discarded.",!0)}).open()};new it(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():I()},"Discard trash").open();return}p("",!1)};h.setButtonText("Remove\u2026").onClick(()=>void g()),h.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(h=>h.setButtonText("Change\u2026").onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,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:g,remember:u})=>{if(!g)return"Enter a password.";try{await t.setSharedPassword(g,u)}catch(p){return p.message}return new x.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(h=>{h.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new x.Notice("Shared password turned off."),this.update?.()}),h.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(h=>h.setButtonText("Set shared password\u2026").onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,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:g,remember:u})=>{if(!g)return"Enter a password.";try{await t.setSharedPassword(g,u)}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."),Xl)if(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 f=p.id===g,I=new x.Setting(i).setName(`${p.label}${f?" \u2014 this device":""}`).setDesc(f?"You":"Member");f||I.addButton(m=>{m.setButtonText("Remove").onClick(async()=>{await t.removeMember(p.id),new x.Notice(`Removed ${p.label}. (Not full revocation without rotating the key.)`),this.update?.()}),m.buttonEl.addClass("mod-warning")})}let u=t.pendingJoinRequests();if(u.length===0)i.createEl("p",{cls:"setting-item-description"}).setText("No pending access requests.");else for(let p of u)new x.Setting(i).setName(p.label).setDesc("Wants access to this vault").addButton(f=>f.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(p.id)}catch(I){new x.Notice(I.message);return}new x.Notice(`Approved ${p.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(f=>f.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.headingDef("Trash & title defaults","Vault-wide defaults for deleted notes and locked-note titles. Per-folder overrides live under \u201CPer-Folder Passwords\u201D below.")),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=>{if(n&&!this.encryptionOrOnboard()){this.update?.();return}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=>{if(n&&!this.encryptionOrOnboard()){this.update?.();return}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 (default)","The DEFAULT for hiding \u{1F512} locked-placeholder titles \u2014 used by any folder/trash that doesn't set its own \u201Chide filenames\u201D option in Per-Folder Passwords below (those override this). Shows a generic label instead of the note's title so a glance doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{if(n&&!this.encryptionOrOnboard()){this.update?.();return}this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.headingDef("Archive","Archive folders are de-indexed from cross-folder search; mark a folder as an archive (and set whether it encrypts) under \u201CPer-Folder Passwords\u201D below.")),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 r of s)n.addOption(r,r);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async r=>{this.plugin.settings.defaultArchiveFolder=r||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e.push(this.sectionDef("Per-Folder Passwords","Give a folder its own password (a separate key) so you can share just that folder with collaborators. Folders without their own password use the vault password.",i=>{this.renderPerFolderEncryption(i)},["folder","per-folder","password","encrypt","key","share","collaborator","archive","unlock","lock"])),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=si.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 c=>{this.plugin.settings.jdIndexScope=c==="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 ti(this.app,l.inputEl),l.setPlaceholder("Path/To/Folder"),l.setValue(this.plugin.settings.jdIndexScopeFolder??""),l.onChange(async c=>{this.plugin.settings.jdIndexScopeFolder=(c||"").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 c=>{this.plugin.settings.jdIndexIncludeStashpadFolders=c,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 ti(this.app,l.inputEl),l.setPlaceholder(s[0]??"(pick a Stashpad folder)"),l.setValue(this.plugin.settings.jdIndexStashpadFolder??""),l.onChange(async c=>{this.plugin.settings.jdIndexStashpadFolder=(c||"").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 c=>{this.plugin.settings.jdIndexSort=c==="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"}),r=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${r}.`),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 c=await gs(this.app,this.plugin,this.plugin.settings);if(c.error==="no-dest"){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(c.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}us(this.app,c),this.display()}catch(c){console.error("[stashpad] preview failed",c),new x.Notice(`Preview failed: ${c?.message??c}`,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 Ui(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let h=await Pn(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 c=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!c){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(c)){new x.Notice(`Folder "${c}" doesn't exist yet.`,5e3);return}try{let h=this.app.vault.adapter.basePath;if(h){let{shell:g}=window.require?.("electron")??{},u=`${h}/${c}`;g?.openPath?.(u)}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=ce()?.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 r of e)o.addOption(r,r);o.setValue(i),o.onChange(r=>{i=r,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),r=new Map(o.map(h=>[h.hex,h.count])),l=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},c=new Set([...r.keys(),...Object.keys(l)]);if(c.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let d=[...c].map(h=>({hex:h,count:r.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=W()),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,"",r=>r.addToggle(l=>l.setValue(s()).onChange(async c=>{n(c),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 r=[];s.authored>0&&r.push(`authored ${s.authored}`),s.contributed>0&&r.push(`contributed to ${s.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${r.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 r=t.createEl("p",{cls:"stashpad-okf-cta"});this.appendCode(r,"\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(r=>{r.setButtonText("Create template + open Templates").setCta(),r.onClick(async()=>{let l;try{l=await this.plugin.ensureOkfTemplate()}catch(c){new x.Notice(`Couldn't create the OKF template: ${c.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(r=>r.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(r=>r.childElementCount===0&&r.textContent?.trim()===t&&!r.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=W()),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 r=[];s.authored>0&&r.push(`authored ${s.authored}`),s.contributed>0&&r.push(`contributed to ${s.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${r.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 r=[];if(s.role&&r.push(s.role),s.department&&r.push(s.department),r.push(`id ${s.id}`),o.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${r.join(" \xB7 ")}`}),s.renames&&s.renames.length>0){let l=n.createDiv({cls:"stashpad-known-author-history"}),c=s.renames.map(d=>`${d.from} \u2192 ${d.to}`).join(", ");l.setText(`Renamed: ${c}`)}}}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(/\/+$/,""),r=i.createDiv({cls:"stashpad-note-template-row"});r.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let c=r.createDiv({cls:"stashpad-note-template-input-wrap"}),d=c.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=c.createDiv({cls:"stashpad-note-template-suggest"});h.setCssStyles({display:"none"});let g=[],u=[],p=-1,f=()=>h.style.display!=="none"&&g.length>0,I=E=>{p=E,u.forEach((S,D)=>S.toggleClass("is-active",D===E)),E>=0&&u[E]&&u[E].scrollIntoView({block:"nearest"})},m=()=>{h.setCssStyles({display:"none"}),p=-1},C=async E=>{d.value=E,await Q(),m()},B=r.createDiv({cls:"stashpad-note-template-warn"});B.setCssStyles({display:"none"});let w=()=>this.app.vault.getMarkdownFiles().map(E=>E.path).filter(E=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(E)).sort(),y=()=>{h.empty(),u=[];let E=d.value.trim().toLowerCase().split(/\s+/).filter(Boolean),S=D=>{let H=D.toLowerCase();return E.every(U=>H.includes(U))};if(g=w().filter(D=>S(D)).slice(0,12),g.length===0){m();return}h.setCssStyles({display:""}),g.forEach((D,H)=>{let U=h.createDiv({cls:"stashpad-note-template-suggest-item",text:D});u.push(U),U.addEventListener("mousemove",()=>I(H)),U.addEventListener("mousedown",async N=>{N.preventDefault(),await C(D)})}),p=p>=0&&p<g.length?p:-1,p>=0&&I(p)},Q=async()=>{let E=d.value.trim(),S={...this.plugin.settings.noteTemplates??{}};E?S[o]=E:delete S[o],this.plugin.settings.noteTemplates=S,await this.plugin.saveSettings(),v()},v=()=>{B.empty(),B.setCssStyles({display:"none"});let E=d.value.trim();if(!E)return;let S=this.app.vault.getAbstractFileByPath(E);if(!S||S.extension!=="md"){B.setCssStyles({display:""}),B.setText(`\u26A0 "${E}" is not a markdown file in this vault.`);return}let D=this.app.metadataCache.getFileCache(S)?.frontmatter??{},U=ue.filter(N=>{let b=D[N];return!(b==null||typeof b=="string"&&b.trim()===""||Array.isArray(b)&&b.length===0)});U.length!==0&&(B.setCssStyles({display:""}),B.setText(`\u26A0 Template defines ${U.join(", ")} \u2014 Stashpad always sets ${U.length===1?"this":"these"} on new notes, so the template value${U.length===1?"":"s"} will be ignored.`))};d.addEventListener("focus",y),d.addEventListener("input",()=>{p=-1,y()}),d.addEventListener("blur",()=>{setTimeout(m,150)}),d.addEventListener("change",()=>{Q()}),d.addEventListener("keydown",E=>{if(E.key==="ArrowDown")E.preventDefault(),f()?I((p+1)%g.length):(y(),g.length&&I(0));else if(E.key==="ArrowUp"){if(!f())return;E.preventDefault(),I((p-1+g.length)%g.length)}else if(E.key==="Enter")f()&&p>=0&&(E.preventDefault(),C(g[p]));else if(E.key==="Escape")f()&&(E.preventDefault(),m());else if(E.key==="Tab"&&!E.shiftKey){if(!f())return;let S=g[p>=0?p:0],D=d.value,H;if(S.toLowerCase().startsWith(D.toLowerCase())){let U=S.indexOf("/",D.length);H=U>=0?S.slice(0,U+1):S}else H=S;H&&H!==D&&(E.preventDefault(),d.value=H,p=-1,y(),g.length===1&&I(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 r=o.createSpan({cls:"stashpad-color-alias-swatch"});r.setCssStyles({background:i}),r.title="Click to bulk-recolor every note of this color in this Stashpad",r.onclick=()=>{let h=this.plugin.settings.customPalette??[];new Pe(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 u=await this.plugin.recolorAllInFolder(e,i,g??null);if(u>0)new x.Notice(`Recolored ${u} note${u===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 u=(this.plugin.settings.customPalette??[]).filter(p=>p.toLowerCase()!==g.toLowerCase());return this.plugin.settings.customPalette=u,await this.plugin.saveSettings(),u}).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 c=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});c.value=this.plugin.getColorAlias(e,i)??"",c.onchange=async()=>{await this.plugin.setColorAlias(e,i,c.value),!c.value.trim()&&s===0&&n()};let d=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});c.value||d.setCssStyles({visibility:"hidden"}),d.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(c.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"}),r=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),l=()=>{let d=r();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."},c=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 c(),n.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),c())},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(r=>r!==o),e.folderPanelDownranked=(e.folderPanelDownranked??[]).filter(r=>r!==o),e.folderPanelHidden=(e.folderPanelHidden??[]).filter(r=>r!==o),await this.plugin.saveSettings(),this.update?.()};for(let o of i){let r=[...e[o.key]??[]].sort();if(r.length===0)continue;t.createEl("div",{cls:"stashpad-folder-placement-group",text:`${o.label} (${r.length})`});let l=t.createDiv({cls:"stashpad-folder-list"});for(let c of r){let d=l.createDiv({cls:"stashpad-folder-row"});d.createSpan({cls:"stashpad-folder-row-label",text:c});let h=d.createEl("button",{text:o.action});h.onclick=()=>void n(c)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},r=u=>{let p=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),f=p.createEl("input",{type:"text"});f.readOnly=!0,f.placeholder="Click & press a key",f.value=Gi(i()[u]),f.classList.add("stashpad-binding-input");let I=()=>{f.size=Math.max(3,f.value.length||f.placeholder.length)};I();let m=u==="primary"?e.defaultPrimary:e.defaultSecondary??"";f.onclick=()=>{mr(f,async y=>{this.plugin.settings.bindings[e.id][u]=y,f.value=Gi(y),I(),await this.plugin.saveSettings(),o(),w()})};let C=p.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});C.title="Clear this slot",C.onclick=async()=>{this.plugin.settings.bindings[e.id][u]="",f.value="",I(),await this.plugin.saveSettings(),o(),w()};let B=p.createEl("button",{cls:"stashpad-binding-revert"});(0,x.setIcon)(B,"rotate-ccw");let w=()=>{let Q=i()[u]!==m;B.toggleClass("is-hidden",!Q),B.title=m?`Revert to default (${Gi(m)})`:"Revert to default (no binding)"};return B.onclick=async()=>{this.plugin.settings.bindings[e.id][u]=m,f.value=Gi(m),I(),await this.plugin.saveSettings(),o(),w()},w(),f};s=r("primary"),n=r("secondary");let l=t.controlEl.createDiv({cls:"stashpad-binding-pill"});l.setAttribute("role","switch"),l.setAttribute("tabindex","0");let c=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 u=i(),p=!!(u.primary&&u.secondary);h.checked=!!u.useBoth,h.disabled=!p,d.toggleClass("is-disabled",!p);let f=!!u.useBoth&&p;l.toggleClass("is-disabled",!p||f),l.toggleClass("is-right",u.preferRight),l.setAttribute("aria-checked",String(u.preferRight)),l.setAttribute("aria-disabled",String(!p||f)),c.setText(u.preferRight?"R":"L"),l.title=p?f?'Overridden by "Use both"':u.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 u=i();!u.primary||!u.secondary||(this.plugin.settings.bindings[e.id].preferRight=!u.preferRight,o(),await this.plugin.saveSettings())};l.onclick=()=>void g(),l.onkeydown=u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),g())},o()}};var ni=class{constructor(a,t){this.app=a;this.ta=t;this.popupEl=null;this.items=[];this.activeIdx=0;this.state=null;this.fileIndex=[];this.tagIndex=[];this.indexBuilt=!1;this.vaultListeners=[];this.scope=null;this.onInput=()=>{let a=this.detectTrigger();if(!a){this.close();return}this.openFor(a)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=a=>{a.key==="Escape"&&(!this.state||!this.items.length||(a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation(),this.close()))};this.onKeyDown=a=>{!this.state||!this.items.length||(a.key==="ArrowDown"?(a.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):a.key==="ArrowUp"?(a.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):a.key==="Enter"||a.key==="Tab"?(a.preventDefault(),a.stopPropagation(),this.commit()):a.key==="Escape"&&(a.preventDefault(),a.stopPropagation(),a.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let a=this.ta.ownerDocument??document;a.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>a.removeEventListener("keydown",this.onDocEscape,!0)),this.buildIndex();let t=()=>{this.indexBuilt=!1},e=this.app.vault;e.on("create",t),e.on("delete",t),e.on("rename",t),this.vaultListeners.push(()=>e.off("create",t),()=>e.off("delete",t),()=>e.off("rename",t))}isOpen(){return!!this.state&&this.items.length>0}detach(){this.close(),this.ta.removeEventListener("input",this.onInput),this.ta.removeEventListener("keydown",this.onKeyDown,!0),this.ta.removeEventListener("blur",this.onBlur);for(let a of this.vaultListeners)a();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let a=X().inheritObsidianExclusions,t=a?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!zo(i.path)&&!Wo(i.path)&&!(a&&Xo(i.path,t))).map(i=>{let s=i.extension==="md",n=s?i.basename:i.name,o=s?i.basename:i.name;return{label:n,lower:n.toLowerCase(),insertText:o,file:i}});let e=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(e).sort((i,s)=>(e[s]||0)-(e[i]||0)),this.indexBuilt=!0}detectTrigger(){let a=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=a.slice(0,t),i=e.match(/\[\[([^\]\[\n]*)$/);if(i){let n=i[1];return{kind:"link",query:n,replaceStart:t-n.length-2,replaceEnd:t}}let s=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(s){let n=s[2];return{kind:"tag",query:n,replaceStart:t-n.length-1,replaceEnd:t}}return null}buildItems(a){this.buildIndex();let t=a.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],i=s=>{if(!e.length)return!0;for(let n of e)if(!s.includes(n))return!1;return!0};return a.kind==="link"?this.fileIndex.filter(n=>i(n.lower)).slice(0,50).map(n=>({label:n.label,insert:`[[${n.insertText}]]`,subtitle:n.file.path})):this.tagIndex.filter(n=>i(n.toLowerCase())).slice(0,30).map(n=>({label:n,insert:n,subtitle:""}))}openFor(a){if(this.state=a,this.items=this.buildItems(a),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let a=new qr.Scope(this.app.scope);a.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=a,this.app.keymap?.pushScope(a)}popScope(){if(this.scope){try{this.app.keymap?.popScope(this.scope)}catch{}this.scope=null}}renderPopup(){if(!this.popupEl){let t=this.ta.ownerDocument??document;this.popupEl=t.body.createDiv({cls:"stashpad-composer-suggest"}),this.popupEl.tabIndex=-1,this.popupEl.addEventListener("mousedown",e=>e.preventDefault())}let a=this.popupEl;a.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],i=a.createDiv({cls:"stashpad-composer-suggest-row"});t===this.activeIdx&&i.addClass("is-active"),i.createSpan({cls:"stashpad-composer-suggest-label",text:e.label}),e.subtitle&&i.createSpan({cls:"stashpad-composer-suggest-sub",text:e.subtitle}),i.onmousedown=s=>{s.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let a=this.popupEl.children;for(let e=0;e<a.length;e++)a[e].toggleClass("is-active",e===this.activeIdx);let t=a[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let a=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=a.top-t-4,i=a.left;this.popupEl.style.left=`${Math.max(8,i)}px`,this.popupEl.style.top=`${Math.max(8,e)}px`,this.popupEl.style.minWidth=`${Math.min(360,a.width)}px`}commit(){if(!this.state||!this.items.length)return;let a=this.items[this.activeIdx];if(!a)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),i=a.insert;this.ta.value=t+i+e;let s=t.length+i.length;this.ta.setSelectionRange(s,s),this.ta.dispatchEvent(new Event("input",{bubbles:!0})),this.close(),this.ta.focus()}close(){this.popupEl&&(this.popupEl.remove(),this.popupEl=null),this.state=null,this.items=[],this.activeIdx=0,this.popScope()}};rt();var xs=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 Se}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??{},r=t.createDiv({cls:"stashpad-detail-scroll"}),l=r.createDiv({cls:"stashpad-detail-header"}),c=l.createDiv({cls:"stashpad-detail-titlerow"});c.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let d=c.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)),f=Number.isNaN(p)?String(o.due):re(p,this.plugin.settings);h.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${f}`})}if(Array.isArray(o.tags))for(let p of o.tags.filter(f=>typeof f=="string"))h.createSpan({cls:"stashpad-detail-meta-tag",text:`#${p.replace(/^#/,"")}`});let g=r.createDiv({cls:"stashpad-detail-body"});try{let p=await this.app.vault.cachedRead(n),f=this.stripFrontmatter(p);await Et.MarkdownRenderer.render(this.app,f,g,n.path,this)}catch(p){g.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${p.message}`})}this.renderFooterMeta(r,n,o,s),this.renderChildren(r,s.folder,s.id),this.renderComposer(t,s);let u=this.composerInputEl;if(e&&u&&(u.focus(),i!=null)){let p=Math.min(i,u.value.length);try{u.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 ni(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 r=t.createDiv({cls:"stashpad-detail-children"});r.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let l=r.createDiv({cls:"stashpad-detail-children-list"});for(let c of o)c.file&&this.renderDetailChildRow(l,s,n,e,c,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let r=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},l=typeof r.color=="string"?r.color:null,c=r.completed===!0,d=i.getChildren(n.id),h=d.length>0,g=`${s}|${n.id}`,u=this.expanded.has(g),p=t.createDiv({cls:"stashpad-detail-child-row"});c&&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 w=p.getBoundingClientRect(),y=B.clientY-w.top<w.height/2;p.toggleClass("drop-before",y),p.toggleClass("drop-after",!y)}),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 w=B.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let y=p.getBoundingClientRect(),Q=B.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,Q?"before":"after")}),p.oncontextmenu=B=>{B.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(B,w)};let f=p.createSpan({cls:"stashpad-detail-child-toggle"});if(h&&(Ie(f,d.length,u),f.onclick=B=>{B.stopPropagation(),this.expanded.has(g)?this.expanded.delete(g):this.expanded.add(g),this.render()}),Ye(r,"task")||r.task===!0||r.completed!==void 0){let B=p.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Et.setIcon)(B,c?"check-square":"square"),B.title=c?"Mark not done":"Mark done",B.addEventListener("mousedown",w=>w.stopPropagation()),B.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),B.onclick=w=>{w.preventDefault(),w.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let m=p.createSpan({cls:"stashpad-detail-child-icon"});(0,Et.setIcon)(m,h?"folder-tree":"file-text"),l&&(m.style.color=l);let C=p.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(C.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},h&&u)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 r=i.contributors.filter(l=>typeof l=="string").map(l=>this.stripWikiLink(l));r.length>0&&o.push({label:"Contributors",value:r.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 r of o){let l=n.createDiv({cls:"stashpad-detail-meta-line"});l.createSpan({cls:"stashpad-detail-meta-key",text:r.label}),l.createSpan({cls:"stashpad-detail-meta-val",text:r.value})}}titleFor(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")}stripFrontmatter(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` ----`,3);return e<0?t:t.slice(e+4).replace(/^\n+/,"")}stripWikiLink(t){let e=t.match(/^\[\[(.+?)(?:\|(.+))?\]\]$/);return e?e[2]??(e[1].split("/").pop()??e[1]).replace(/\.md$/,""):t}formatTime(t){let e=Date.parse(t);return Number.isFinite(e)?re(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==k&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new Et.Notice(`Couldn't open: ${i.message}`)}}};async function Ns(A){let a=A.workspace.getLeavesOfType(Se);if(a.length>0){A.workspace.revealLeaf(a[0]);return}let t=A.workspace.getRightLeaf(!1);if(!t){new Et.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:Se,active:!0}),A.workspace.revealLeaf(t)}var F=require("obsidian");rt();var ye=require("obsidian");rt();function _l(A,a){let t=A.vault.getAbstractFileByPath(a);if(!(t instanceof ye.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof ye.TFile?n.extension==="md"&&e.push(n):n instanceof ye.TFolder&&(wi.has(n.name)||i.push(n))}return e}var Ms=class{constructor(a){this.app=a;this.nodes=new Map;this.byPath=new Map;this.listeners=new Set;this.orderProvider=null;this.synthetic=new Map;this.coalesceTimer=null;this.nodes.set(k,{id:k,parent:null,children:[],file:null,created:""})}setOrderProvider(a){this.orderProvider=a}onChange(a){return this.listeners.add(a),()=>this.listeners.delete(a)}emit(){for(let a of this.listeners)a()}rebuild(a){a!==void 0&&(this.currentFolder=a);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(k,{id:k,parent:null,children:[],file:null,created:""});let s=t?_l(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.id;if(!r){let c=e.get(n.path),d=c?i.get(c):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),r===k){let c=this.nodes.get(k);c.file=n,c.created=o?.created??"",this.byPath.set(n.path,k);continue}let l=o?.parent??null;l===r&&(l=null),this.nodes.set(r,{id:r,parent:l??k,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,r)}for(let n of this.nodes.values()){if(n.id===k)continue;let o=n.parent??k;(this.nodes.get(o)??this.nodes.get(k)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,r)=>{let l=this.nodes.get(o),c=this.nodes.get(r);return(l.created||"").localeCompare(c.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let r=new Map;o.forEach((l,c)=>r.set(l,c)),n.children.sort((l,c)=>{let d=r.has(l)?r.get(l):1/0,h=r.has(c)?r.get(c):1/0;return d===h?0:d-h})}}this.emit()}insertSynthetic(a){if(!a.file)return;let t=a.file.path;this.synthetic.set(t,a),this.nodes.set(a.id,a),this.byPath.set(t,a.id);let e=a.parent??k,i=this.nodes.get(e);i&&!i.children.includes(a.id)&&i.children.push(a.id),this.emit()}get(a){return this.nodes.get(a)}getRoot(){return this.nodes.get(k)}getChildren(a){let t=this.nodes.get(a);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let a=0;for(let t of this.nodes.values())t.file&&a++;return a}pathTo(a){let t=[],e=new Set,i=this.nodes.get(a);for(;i&&i.id!==k&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(a){return this.byPath.get(a)}snapshot(){let a={};for(let t of this.nodes.values())t.id===k||!t.file||(a[t.id]={parent:t.parent===k?null:t.parent,path:t.file.path});return a}hookMetadataCache(a){let t=l=>{let c=this.currentFolder;return c?typeof l!="string"?!1:l===c||l.startsWith(c+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),a())},16))},s=l=>{l instanceof ye.TFile&&t(l.path)&&l.extension==="md"&&(this.applyChange(l),i())},n=l=>{l instanceof ye.TFile&&t(l.path)&&l.extension==="md"&&this.applyChange(l)&&i()},o=l=>{let c=l?.path;typeof c=="string"&&t(c)&&this.applyDelete(c)&&i()},r=(l,c)=>{if(!(l instanceof ye.TFile))return;let d=typeof c=="string"?c: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",r),()=>{this.app.metadataCache.off("changed",s),this.app.vault.off("create",n),this.app.vault.off("delete",o),this.app.vault.off("rename",r),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(a){if($e(a.path))return this.byPath.has(a.path)?this.applyDelete(a.path):!1;let t=this.app.metadataCache.getFileCache(a)?.frontmatter,e=t?.id,i=this.byPath.get(a.path);if(!e){if(i){let c=this.nodes.get(i);if(c&&c.file!==a)return c.file=a,!0}return!1}if(this.synthetic.delete(a.path),e===k){let c=this.nodes.get(k),d=t?.created??"",h=!1;return c.file!==a&&(c.file=a,h=!0),c.created!==d&&(c.created=d,h=!0),this.byPath.get(a.path)!==k&&(this.byPath.set(a.path,k),h=!0),h}let s=t?.parent??k,n=t?.created??"";if(!(s===k||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let r=this.nodes.get(e);if(!r){let c={id:e,parent:s,children:[],file:a,created:n};return this.nodes.set(e,c),this.byPath.set(a.path,e),this.attachToParent(c),this.resortChildrenOf(s),!0}let l=!1;if(r.file!==a&&(r.file=a,l=!0),r.created!==n&&(r.created=n,this.resortChildrenOf(r.parent??k),l=!0),r.parent!==s){let c=r.parent??k;this.detachFromParent(r),r.parent=s,this.attachToParent(r),this.resortChildrenOf(c),this.resortChildrenOf(s),l=!0}return l}applyDelete(a){let t=this.byPath.get(a);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(a),this.synthetic.delete(a),!0;this.detachFromParent(e);let i=this.nodes.get(k);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=k,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(k),this.nodes.delete(t),this.byPath.delete(a),this.synthetic.delete(a),!0}applyRename(a,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||a.path===e||a.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(a);if($e(a.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(a);this.byPath.delete(t),this.byPath.set(a.path,n);let o=this.nodes.get(n);return o&&(o.file=a),!0}detachFromParent(a){let t=this.nodes.get(a.parent??k);if(!t)return;let e=t.children.indexOf(a.id);e>=0&&t.children.splice(e,1)}attachToParent(a){let t=this.nodes.get(a.parent??k);t||(t=this.nodes.get(k)),t.children.includes(a.id)||t.children.push(a.id)}resortChildrenOf(a){let t=this.nodes.get(a);if(t&&(t.children.sort((e,i)=>{let s=this.nodes.get(e),n=this.nodes.get(i);return(s.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(a);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,r=i.has(n)?i.get(n):1/0;return o===r?0:o-r})}}}};var ro=class{constructor(){this.enabled=!1;this.buckets=new Map}record(a,t){if(!this.enabled)return;let e=this.buckets.get(a);e||(e={count:0,total:0,max:0},this.buckets.set(a,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(a,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(a,performance.now()-e)}}async timeAsync(a,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(a,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let a=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(a.length===0)return"Stashpad perf: no samples (enable profiling, then use the app).";let t=["**Stashpad performance profile**","","| label | count | total (ms) | avg (ms) | max (ms) |","| --- | ---: | ---: | ---: | ---: |"];for(let e of a)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` -`)}},vt=new ro;var Kr=".stashpad-order.json",oi=class{constructor(a){this.app=a;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(a){if(this.cache.has(a))return this.cache.get(a);let t=`${a}/${Kr}`,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,r]of Object.entries(n))Array.isArray(r)&&r.every(l=>typeof l=="string")&&(i[o]=r)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(a,i),i}async save(a){this.scheduleWrite(a)}async flush(a){let t=this.pendingTimers.get(a);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(a)),await this.writeNow(a)}scheduleWrite(a){let t=this.pendingTimers.get(a);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(a),this.writeNow(a)},150);this.pendingTimers.set(a,e)}async writeNow(a){let e=(this.writeInFlight.get(a)??Promise.resolve()).then(()=>this.doWrite(a));this.writeInFlight.set(a,e);try{await e}finally{this.writeInFlight.get(a)===e&&this.writeInFlight.delete(a)}}async doWrite(a){let t=this.cache.get(a)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(a,e);let i=`${a}/${Kr}`,s=this.app.vault.adapter;try{if(Object.keys(e).length===0)try{await s.remove(i)}catch{}else await s.write(i,JSON.stringify(e,null,2))}catch(n){console.warn("Stashpad: order save failed",n)}}getOrder(a,t){return this.cache.get(a)?.[t]?.slice()??[]}setOrder(a,t,e){let i=this.cache.get(a)??{};i[t]=e.slice(),this.cache.set(a,i)}appendChild(a,t,e){let i=this.cache.get(a)??{},s=i[t]??[];s.includes(e)||s.push(e),i[t]=s,this.cache.set(a,i)}removeChild(a,t){let e=this.cache.get(a);if(e)for(let i of Object.values(e)){let s=i.indexOf(t);s>=0&&i.splice(s,1)}}invalidate(a){this.cache.delete(a)}};var ri={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"},ao=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],tc=new Set(ao),Jr=".stashpad-sort.json",Ts=class{constructor(a){this.app=a;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(a){if(this.cache.has(a))return this.cache.get(a);let t=`${a}/${Jr}`,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"&&tc.has(o)&&(i[n]=o)}}catch(s){console.warn("Stashpad: sort load failed",s)}return this.cache.set(a,i),i}async save(a){this.scheduleWrite(a)}async flush(a){let t=this.pendingTimers.get(a);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(a)),await this.writeNow(a)}scheduleWrite(a){let t=this.pendingTimers.get(a);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(a),this.writeNow(a)},150);this.pendingTimers.set(a,e)}async writeNow(a){let e=(this.writeInFlight.get(a)??Promise.resolve()).then(()=>this.doWrite(a));this.writeInFlight.set(a,e);try{await e}finally{this.writeInFlight.get(a)===e&&this.writeInFlight.delete(a)}}async doWrite(a){let t=this.cache.get(a)??{},e=`${a}/${Jr}`,i=this.app.vault.adapter;try{if(Object.keys(t).length===0)try{await i.remove(e)}catch{}else await i.write(e,JSON.stringify(t,null,2))}catch(s){console.warn("Stashpad: sort save failed",s)}}getMode(a,t){return this.cache.get(a)?.[t]??"manual"}setMode(a,t,e){let i=this.cache.get(a)??{};e==="manual"?delete i[t]:i[t]=e,this.cache.set(a,i)}removeParent(a,t){let e=this.cache.get(a);e&&delete e[t]}invalidate(a){this.cache.delete(a)}};rt();var we="parentLink",ai="children";var Us=class Us{constructor(a,t){this.app=a;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(a){return this.activityListeners.add(a),()=>this.activityListeners.delete(a)}emitActivity(){let a=this.pending.size;for(let t of this.activityListeners)try{t(a)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(a){if(!a||!X().writeRecoveryLinks)return;let t=this.pending.size;this.pending.add(a),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(a,t,e){this.schedule(a),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(a){let t=this.getTree(),e=i=>{this.schedule(i);for(let s of t.getChildren(i))e(s.id)};e(a)}scheduleParentOfDeleted(a){a&&this.schedule(a)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let a=this.pending.values().next().value;if(a===void 0)break;this.pending.delete(a),this.emitActivity(),await this.syncOne(a)}}pendingCount(){return this.pending.size}onError(a){return this.errorListeners.add(a),()=>this.errorListeners.delete(a)}emitError(a,t){for(let e of this.errorListeners)try{e(a,t)}catch(i){console.warn("[Stashpad] fmSync error listener failed",i)}}reset(){this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null),this.pending.clear()}kick(){this.timer!=null||this.pending.size===0||(this.timer=window.setTimeout(()=>this.tick(),Us.PACING_MS))}async tick(){this.timer=null;let a=this.pending.values().next().value;if(a!==void 0){this.pending.delete(a),this.emitActivity();try{await this.syncOne(a)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(a){let e=this.getTree().get(a);if(!e||!e.file)return!1;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e),n=this.app.metadataCache.getFileCache(e.file)?.frontmatter,o=n&&typeof n[we]=="string"?n[we]:null,r=n?.[ai],l=Array.isArray(r)?r.filter(c=>typeof c=="string"):[];if((o??null)!==(i??null)||l.length!==s.length)return!0;for(let c=0;c<l.length;c++)if(l[c]!==s[c])return!0;return!1}async syncOne(a){let e=this.getTree().get(a);if(!e||!e.file||!this.wouldWrite(a))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await vt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[we]=i:delete n[we],s.length>0?n[ai]=s:delete n[ai]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(a){if(a.id===k)return null;let t=this.getTree();if(!a.parent||a.parent===k){let i=t.getRoot();return i&&i.id!==a.id&&i.file?Ps(i.file.path):null}let e=t.get(a.parent);return e?.file?Ps(e.file.path):null}computeChildrenLinks(a){return this.getTree().getChildren(a.id).filter(e=>!!e.file).map(e=>Ps(e.file.path))}};Us.PACING_MS=100;var Hs=Us;async function li(A,a){let t=a.endsWith("/")?a:a+"/",e=new Map,i=new Map;for(let c of A.vault.getMarkdownFiles()){if(c.path!==a&&!c.path.startsWith(t))continue;let d=A.metadataCache.getFileCache(c)?.frontmatter,h=typeof d?.id=="string"?d.id:null;if(!h)continue;let g=typeof d?.parent=="string"?d.parent:k;e.set(h,{file:c,id:h,parent:g});let u=i.get(g)??[];u.push(h),i.set(g,u)}let s=c=>Ps(c.file.path),n=c=>{if(c.id===k)return null;if(c.parent===k||!c.parent){let h=e.get(k);return h?s(h):null}let d=e.get(c.parent);return d?s(d):null},o=c=>{let d=i.get(c.id)??[],h=[];for(let g of d){let u=e.get(g);u&&h.push(s(u))}return h},r=0,l=0;for(let c of e.values()){r+=1;let d=n(c),h=o(c),g=A.metadataCache.getFileCache(c.file)?.frontmatter,u=g&&typeof g[we]=="string"?g[we]:null,p=g?.[ai],f=Array.isArray(p)?p.filter(C=>typeof C=="string"):[],I=(u??null)===(d??null),m=f.length===h.length&&f.every((C,B)=>C===h[B]);if(!(I&&m))try{await A.fileManager.processFrontMatter(c.file,C=>{d?C[we]=d:delete C[we],h.length>0?C[ai]=h:delete C[ai]}),l+=1,await new Promise(C=>setTimeout(C,50))}catch(C){console.warn("[Stashpad] rebootstrap fm sync failed",c.file.path,C)}}return{checked:r,written:l}}function Ps(A){return`[[${A.replace(/\.md$/i,"")}]]`}Gt();je();var Rs=class{constructor(a,t){this.tree=a;this.log=t}async sweep(a){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!a)return!0;let o=a.replace(/\/+$/,"");return n===o||n.startsWith(o+"/")};for(let[n,o]of Object.entries(e)){let r=t[n];r?r.parent!==o.parent?await this.log.append({type:"parent_change",id:n,payload:{from:r.parent,to:o.parent}}):r.path!==o.path&&await this.log.append({type:"rename",id:n,payload:{from:r.path,to:o.path}}):await this.log.append({type:"create",id:n,payload:{path:o.path,parent:o.parent}})}for(let[n,o]of Object.entries(t))!e[n]&&i(o.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:o.path}});let s={};for(let[n,o]of Object.entries(t))i(o.path)||(s[n]=o);for(let[n,o]of Object.entries(e))s[n]=o;await this.log.writeState(s)}};var gt=require("obsidian");rt();Dn();var mt=gt.moment;function lo(A){let a=A.trim().toLowerCase();if(!a)return null;let t=Date.now(),e=p=>mt(p).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=a,r=i.exec(a);if(r&&(r[3]||r[2])){let p=parseInt(r[1],10),f=r[2]?parseInt(r[2],10):0,I=r[3];I==="pm"&&p<12&&(p+=12),I==="am"&&p===12&&(p=0),p>=0&&p<24&&f>=0&&f<60&&(s=(p*3600+f*60)*1e3,n=!0,o=a.replace(r[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 c=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=["sun","mon","tue","wed","thu","fri","sat"],h=c.indexOf(o)>=0?c.indexOf(o):d.indexOf(o);if(h>=0){let p=mt().startOf("day"),I=(p.day()-h+7)%7;return l(p.subtract(I,"days").valueOf())}let g=/^(\d+)\s*([dwmy])$/.exec(o);if(g){let p=parseInt(g[1],10),f={d:"days",w:"weeks",m:"months",y:"years"}[g[2]];return l(mt().subtract(p,f).startOf("day").valueOf())}let u=mt(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return u.isValid()?l(u.startOf("day").valueOf()):null}function Or(A){let a={text:[],filters:{}},t=(A||"").trim();if(!t)return a;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")a.filters.in=o.toLowerCase();else if(n==="before"){let r=lo(o);r!=null&&(a.filters.before=r)}else if(n==="after"){let r=lo(o);r!=null&&(a.filters.after=r)}else if(n==="on"){let r=lo(o);if(r!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))a.filters.on={start:r-6e4,end:r+6e4};else{let c=mt(r).startOf("day").valueOf();a.filters.on={start:c,end:c+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&a.text.push(n.toLowerCase());return a}var Zt=class A extends gt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let r=this.tree.get(n);r?.file&&n!==k?this.notes.push({node:r,title:`${" ".repeat(o)}${this.titleFn(r)}`,body:""}):r?.file&&n===k&&this.notes.push({node:r,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(k))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(r=>{o.body=this.stripFm(r)})}}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=Or(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=m=>{if(!s.length)return!0;for(let C of s)if(!m.includes(C))return!1;return!0},o=null,r=null;if(i.filters.in){let m=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,r=new Map;let C=y=>m.every(Q=>y.toLowerCase().includes(Q)),B=y=>{if(!o.has(y)){o.add(y);for(let Q of this.tree.getChildren(y))B(Q.id)}};for(let y of this.notes)!y.node||y.cross||C(y.title)&&B(y.node.id);let w=new Map;for(let y of this.notes){if(!y.cross)continue;let Q=w.get(y.cross.folder)??[];Q.push(y),w.set(y.cross.folder,Q)}for(let[y,Q]of w){let v=new Map;for(let D of Q){let H=D.cross?.parentId??null;if(!H)continue;let U=v.get(H)??[];U.push(D.cross.id),v.set(H,U)}let E=new Set;r.set(y,E);let S=D=>{if(!E.has(D)){E.add(D);for(let H of v.get(D)??[])S(H)}};for(let D of Q)C(D.title)&&S(D.cross.id)}}let l=m=>{let C=i.filters;if(o||r)if(m.cross){let B=r?.get(m.cross.folder);if(!B||!B.has(m.cross.id))return!1}else if(m.node){if(!o||!o.has(m.node.id))return!1}else return!1;if(C.before||C.after||C.on){let B=this.createdMsFor(m);if(B==null||C.before!=null&&B>=C.before||C.after!=null&&B<=C.after||C.on&&(B<C.on.start||B>=C.on.end))return!1}return!0},c=m=>n(m.toLowerCase()),d=this.notes.filter(m=>!m.cross),h=this.notes.filter(m=>m.cross),g=(m,C)=>({id:m.cross?`cross:${m.cross.folder}:${m.cross.id}`:m.node.id,label:m.title,node:m.node,kind:"note",bodyPreview:this.previewFromBody(m.body,C),matchLine:C,crossFolder:m.cross?.folder,crossFile:m.cross?.file,crossId:m.cross?.id}),u=m=>{let C=[];for(let B of m)if(l(B))if(this.opts.mode==="search"){if(!e){C.push(g(B,-1));continue}let w=n(B.title.toLowerCase()),y=B.body.split(/\r?\n/),Q=[];for(let E=0;E<y.length;E++)c(y[E])&&Q.push(E);let v=Q.length>0||n(B.body.toLowerCase());if(!w&&!v)continue;if(Q.length===0)C.push(g(B,-1));else{let E=[],S=-100;for(let H of Q)H-S>5&&E.push(H),S=H;let D=5;for(let H of E.slice(0,D))C.push(g(B,H))}}else{if(e&&!n(B.title.toLowerCase())&&!n(B.body.toLowerCase()))continue;C.push(g(B,-1))}return C},p=u(d),f=[...p];if(this.opts.mode==="search"?e?!0:p.length<10:!!e){let m=u(h);this.opts.mode==="search"&&!e&&(f.length=Math.min(f.length,50)),f.push(...m)}if(this.opts.folderResults){let m=this.opts.folderResults(),C={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};m.length>0&&(e?m.some(B=>{let w=B.split("/").pop()??B;return n(`${B.toLowerCase()} ${w.toLowerCase()}`)})&&f.push(C):f.unshift(C))}if(this.opts.allowCreate&&e&&!f.some(m=>m.label.trim().toLowerCase()===e)&&f.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let m=B=>B.kind==="note"&&(B.id===k||B.crossId===k)&&n(B.label.toLowerCase()),C=f.filter(m);if(C.length>0){let B=f.filter(w=>!m(w));f.splice(0,f.length,...C,...B)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&f.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),f}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(r=>r.trim().length>0).slice(0,3).join(` +\u2022 Discard trash \u2014 let them be permanently erased with the key.`,"Decrypt Trash",m=>{m?f():I()},"Discard trash").open();return}p("",!1)};h.setButtonText("Remove\u2026").onClick(()=>void g()),h.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(h=>h.setButtonText("Change\u2026").onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,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:g,remember:u})=>{if(!g)return"Enter a password.";try{await t.setSharedPassword(g,u)}catch(p){return p.message}return new x.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(h=>{h.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new x.Notice("Shared password turned off."),this.update?.()}),h.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(h=>h.setButtonText("Set shared password\u2026").onClick(()=>{new ct(this.app,{mode:"setup",offerKeychain:!0,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:g,remember:u})=>{if(!g)return"Enter a password.";try{await t.setSharedPassword(g,u)}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."),jl)if(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 f=p.id===g,I=new x.Setting(i).setName(`${p.label}${f?" \u2014 this device":""}`).setDesc(f?"You":"Member");f||I.addButton(m=>{m.setButtonText("Remove").onClick(async()=>{await t.removeMember(p.id),new x.Notice(`Removed ${p.label}. (Not full revocation without rotating the key.)`),this.update?.()}),m.buttonEl.addClass("mod-warning")})}let u=t.pendingJoinRequests();if(u.length===0)i.createEl("p",{cls:"setting-item-description"}).setText("No pending access requests.");else for(let p of u)new x.Setting(i).setName(p.label).setDesc("Wants access to this vault").addButton(f=>f.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(p.id)}catch(I){new x.Notice(I.message);return}new x.Notice(`Approved ${p.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(f=>f.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.headingDef("Trash & title defaults","Vault-wide defaults for deleted notes and locked-note titles. Per-folder overrides live under \u201CPer-Folder Passwords\u201D below.")),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=>{if(n&&!this.encryptionOrOnboard()){this.update?.();return}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=>{if(n&&!this.encryptionOrOnboard()){this.update?.();return}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 (default)","The DEFAULT for hiding \u{1F512} locked-placeholder titles \u2014 used by any folder/trash that doesn't set its own \u201Chide filenames\u201D option in Per-Folder Passwords below (those override this). Shows a generic label instead of the note's title so a glance doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{if(n&&!this.encryptionOrOnboard()){this.update?.();return}this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.headingDef("Archive","Archive folders are de-indexed from cross-folder search; mark a folder as an archive (and set whether it encrypts) under \u201CPer-Folder Passwords\u201D below.")),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.push(this.sectionDef("Per-Folder Passwords","Give a folder its own password (a separate key) so you can share just that folder with collaborators. Folders without their own password use the vault password.",i=>{this.renderPerFolderEncryption(i)},["folder","per-folder","password","encrypt","key","share","collaborator","archive","unlock","lock"])),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=ni.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("div",{cls:"stashpad-settings-section"}).createEl("p",{cls:"setting-item-description"});i.appendText("Builds a Johnny-Decimal-style index inside a designated Stashpad folder. Two commands:"),i.createEl("br"),i.createEl("strong",{text:"Preview"}),i.appendText(" overwrites the designated folder\u2019s HOME note body with the would-be hierarchy + everything that didn\u2019t match. Frontmatter is preserved; everything below it is replaced."),i.createEl("br"),i.createEl("strong",{text:"Build"}),i.appendText(" creates an actual hierarchy of Stashpad notes (one per prefix), with child\u2192parent relationships matching the dotted segments."),i.createEl("br"),i.appendText("Matches strict prefixes only: all-digits ("),i.createEl("code",{text:"10 Life"}),i.appendText(") or alphanumeric-with-dots ("),i.createEl("code",{text:"1.2 Family"}),i.appendText(", "),i.createEl("code",{text:"animal.duck.yellow Eggs"}),i.appendText("). 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 c=>{this.plugin.settings.jdIndexScope=c==="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 ti(this.app,l.inputEl),l.setPlaceholder("Path/To/Folder"),l.setValue(this.plugin.settings.jdIndexScopeFolder??""),l.onChange(async c=>{this.plugin.settings.jdIndexScopeFolder=(c||"").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 c=>{this.plugin.settings.jdIndexIncludeStashpadFolders=c,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 ti(this.app,l.inputEl),l.setPlaceholder(s[0]??"(pick a Stashpad folder)"),l.setValue(this.plugin.settings.jdIndexStashpadFolder??""),l.onChange(async c=>{this.plugin.settings.jdIndexStashpadFolder=(c||"").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 c=>{this.plugin.settings.jdIndexSort=c==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=_e(this.app,this.plugin,this.plugin.settings),o=t.createEl("div",{cls:"stashpad-settings-section"}).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").setClass("stashpad-jd-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 c=await Is(this.app,this.plugin,this.plugin.settings);if(c.error==="no-dest"){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(c.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}ms(this.app,c),this.display()}catch(c){console.error("[stashpad] preview failed",c),new x.Notice(`Preview failed: ${c?.message??c}`,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 Ri(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let h=await Gn(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 ${Zl()}`),l.setTooltip("Open the designated Stashpad folder in your OS file browser."),l.onClick(async()=>{let c=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!c){new x.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(c)){new x.Notice(`Folder "${c}" doesn't exist yet.`,5e3);return}try{let h=this.app.vault.adapter.basePath;if(h){let{shell:g}=window.require?.("electron")??{},u=`${h}/${c}`;g?.openPath?.(u)}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=ce()?.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(/\/+$/,"")]??{},c=new Set([...a.keys(),...Object.keys(l)]);if(c.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let d=[...c].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=W()),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 c=>{n(c),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){new x.Setting(t).setName("Folders you've worked in").setHeading();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 Stashpad's own Templates section (the \u{1F4C4} Templates settings here \u2014 NOT Obsidian's core Templates plugin) \u2014 all / some / none, 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 Stashpad's \u{1F4C4} Templates section (here in Stashpad's settings \u2014 not Obsidian's core Templates plugin) 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(c){new x.Notice(`Couldn't create the OKF template: ${c.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=W()),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"}),c=s.renames.map(d=>`${d.from} \u2192 ${d.to}`).join(", ");l.setText(`Renamed: ${c}`)}}}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 c=a.createDiv({cls:"stashpad-note-template-input-wrap"}),d=c.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=c.createDiv({cls:"stashpad-note-template-suggest"});h.setCssStyles({display:"none"});let g=[],u=[],p=-1,f=()=>h.style.display!=="none"&&g.length>0,I=E=>{p=E,u.forEach((S,D)=>S.toggleClass("is-active",D===E)),E>=0&&u[E]&&u[E].scrollIntoView({block:"nearest"})},m=()=>{h.setCssStyles({display:"none"}),p=-1},C=async E=>{d.value=E,await Q(),m()},B=a.createDiv({cls:"stashpad-note-template-warn"});B.setCssStyles({display:"none"});let w=()=>this.app.vault.getMarkdownFiles().map(E=>E.path).filter(E=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(E)).sort(),y=()=>{h.empty(),u=[];let E=d.value.trim().toLowerCase().split(/\s+/).filter(Boolean),S=D=>{let H=D.toLowerCase();return E.every(U=>H.includes(U))};if(g=w().filter(D=>S(D)).slice(0,12),g.length===0){m();return}h.setCssStyles({display:""}),g.forEach((D,H)=>{let U=h.createDiv({cls:"stashpad-note-template-suggest-item",text:D});u.push(U),U.addEventListener("mousemove",()=>I(H)),U.addEventListener("mousedown",async N=>{N.preventDefault(),await C(D)})}),p=p>=0&&p<g.length?p:-1,p>=0&&I(p)},Q=async()=>{let E=d.value.trim(),S={...this.plugin.settings.noteTemplates??{}};E?S[o]=E:delete S[o],this.plugin.settings.noteTemplates=S,await this.plugin.saveSettings(),v()},v=()=>{B.empty(),B.setCssStyles({display:"none"});let E=d.value.trim();if(!E)return;let S=this.app.vault.getAbstractFileByPath(E);if(!S||S.extension!=="md"){B.setCssStyles({display:""}),B.setText(`\u26A0 "${E}" is not a markdown file in this vault.`);return}let D=this.app.metadataCache.getFileCache(S)?.frontmatter??{},U=ue.filter(N=>{let b=D[N];return!(b==null||typeof b=="string"&&b.trim()===""||Array.isArray(b)&&b.length===0)});U.length!==0&&(B.setCssStyles({display:""}),B.setText(`\u26A0 Template defines ${U.join(", ")} \u2014 Stashpad always sets ${U.length===1?"this":"these"} on new notes, so the template value${U.length===1?"":"s"} will be ignored.`))};d.addEventListener("focus",y),d.addEventListener("input",()=>{p=-1,y()}),d.addEventListener("blur",()=>{setTimeout(m,150)}),d.addEventListener("change",()=>{Q()}),d.addEventListener("keydown",E=>{if(E.key==="ArrowDown")E.preventDefault(),f()?I((p+1)%g.length):(y(),g.length&&I(0));else if(E.key==="ArrowUp"){if(!f())return;E.preventDefault(),I((p-1+g.length)%g.length)}else if(E.key==="Enter")f()&&p>=0&&(E.preventDefault(),C(g[p]));else if(E.key==="Escape")f()&&(E.preventDefault(),m());else if(E.key==="Tab"&&!E.shiftKey){if(!f())return;let S=g[p>=0?p:0],D=d.value,H;if(S.toLowerCase().startsWith(D.toLowerCase())){let U=S.indexOf("/",D.length);H=U>=0?S.slice(0,U+1):S}else H=S;H&&H!==D&&(E.preventDefault(),d.value=H,p=-1,y(),g.length===1&&I(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 Pe(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 u=await this.plugin.recolorAllInFolder(e,i,g??null);if(u>0)new x.Notice(`Recolored ${u} note${u===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 u=(this.plugin.settings.customPalette??[]).filter(p=>p.toLowerCase()!==g.toLowerCase());return this.plugin.settings.customPalette=u,await this.plugin.saveSettings(),u}).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 c=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});c.value=this.plugin.getColorAlias(e,i)??"",c.onchange=async()=>{await this.plugin.setColorAlias(e,i,c.value),!c.value.trim()&&s===0&&n()};let d=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});c.value||d.setCssStyles({visibility:"hidden"}),d.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(c.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."},c=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 c(),n.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),c())},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 c of a){let d=l.createDiv({cls:"stashpad-folder-row"});d.createSpan({cls:"stashpad-folder-row-label",text:c});let h=d.createEl("button",{text:o.action});h.onclick=()=>void n(c)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc),t.settingEl.addClass("stashpad-binding-row");let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=async g=>{},l=t.controlEl.createDiv({cls:"stashpad-binding-seg",attr:{role:"group","aria-label":"Active binding"}}),c={left:l.createEl("button",{cls:"stashpad-binding-seg-btn",text:"Left"}),both:l.createEl("button",{cls:"stashpad-binding-seg-btn",text:"Both"}),right:l.createEl("button",{cls:"stashpad-binding-seg-btn",text:"Right"})};["left","both","right"].forEach(g=>{c[g].onclick=()=>void a(g)});let d=t.controlEl.createDiv({cls:"stashpad-binding-slots"}),h=g=>{let u=d.createDiv({cls:"stashpad-binding-slot"}),p=u.createEl("input",{type:"text"});p.readOnly=!0,p.placeholder="Click & press a key",p.value=Li(i()[g]),p.classList.add("stashpad-binding-input");let f=()=>{p.size=Math.max(3,p.value.length||p.placeholder.length)};f();let I=g==="primary"?e.defaultPrimary:e.defaultSecondary??"";p.onclick=()=>{Ba(p,async y=>{this.plugin.settings.bindings[e.id][g]=y,p.value=Li(y),f(),await this.plugin.saveSettings(),o(),w()})};let m=u.createDiv({cls:"stashpad-binding-slot-btns"}),C=m.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});C.title="Clear this slot",C.onclick=async()=>{this.plugin.settings.bindings[e.id][g]="",p.value="",f(),await this.plugin.saveSettings(),o(),w()};let B=m.createEl("button",{cls:"stashpad-binding-revert"});(0,x.setIcon)(B,"rotate-ccw");let w=()=>{let Q=i()[g]!==I;B.toggleClass("is-hidden",!Q),B.title=I?`Revert to default (${Li(I)})`:"Revert to default (no binding)"};return B.onclick=async()=>{this.plugin.settings.bindings[e.id][g]=I,p.value=Li(I),f(),await this.plugin.saveSettings(),o(),w()},w(),p};s=h("primary"),n=h("secondary"),a=async g=>{let u=this.plugin.settings.bindings[e.id];u.primary&&u.secondary&&(g==="both"?u.useBoth=!0:(u.useBoth=!1,u.preferRight=g==="right"),await this.plugin.saveSettings(),o())},o=()=>{let g=i(),u=!!(g.primary&&g.secondary),p=g.useBoth?"both":g.preferRight?"right":"left";["left","both","right"].forEach(f=>{c[f].toggleClass("is-active",u&&f===p),c[f].disabled=!u}),l.toggleClass("is-disabled",!u),l.title=u?"Which binding is active \u2014 Left, Both, or Right":"Bind both slots to choose Left / Both / Right"},o()}};var oi=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=X().inheritObsidianExclusions,t=r?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!jo(i.path)&&!_o(i.path)&&!(r&&ta(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 Ja.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()}};at();var Ps=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 Se}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?.()===q&&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?.()===q&&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"}),c=l.createDiv({cls:"stashpad-detail-titlerow"});c.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let d=c.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)),f=Number.isNaN(p)?String(o.due):ae(p,this.plugin.settings);h.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${f}`})}if(Array.isArray(o.tags))for(let p of o.tags.filter(f=>typeof f=="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),f=this.stripFrontmatter(p);await Et.MarkdownRenderer.render(this.app,f,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 u=this.composerInputEl;if(e&&u&&(u.focus(),i!=null)){let p=Math.min(i,u.value.length);try{u.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 oi(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?.()!==q||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?.()!==q)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 c of o)c.file&&this.renderDetailChildRow(l,s,n,e,c,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},l=typeof a.color=="string"?a.color:null,c=a.completed===!0,d=i.getChildren(n.id),h=d.length>0,g=`${s}|${n.id}`,u=this.expanded.has(g),p=t.createDiv({cls:"stashpad-detail-child-row"});c&&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 w=p.getBoundingClientRect(),y=B.clientY-w.top<w.height/2;p.toggleClass("drop-before",y),p.toggleClass("drop-after",!y)}),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 w=B.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let y=p.getBoundingClientRect(),Q=B.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,Q?"before":"after")}),p.oncontextmenu=B=>{B.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(B,w)};let f=p.createSpan({cls:"stashpad-detail-child-toggle"});if(h&&(Ie(f,d.length,u),f.onclick=B=>{B.stopPropagation(),this.expanded.has(g)?this.expanded.delete(g):this.expanded.add(g),this.render()}),Ye(a,"task")||a.task===!0||a.completed!==void 0){let B=p.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Et.setIcon)(B,c?"check-square":"square"),B.title=c?"Mark not done":"Mark done",B.addEventListener("mousedown",w=>w.stopPropagation()),B.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),B.onclick=w=>{w.preventDefault(),w.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let m=p.createSpan({cls:"stashpad-detail-child-icon"});(0,Et.setIcon)(m,h?"folder-tree":"file-text"),l&&(m.style.color=l);let C=p.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(C.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},h&&u)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)?ae(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==k&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new Et.Notice(`Couldn't open: ${i.message}`)}}};async function Hs(A){let r=A.workspace.getLeavesOfType(Se);if(r.length>0){A.workspace.revealLeaf(r[0]);return}let t=A.workspace.getRightLeaf(!1);if(!t){new Et.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:Se,active:!0}),A.workspace.revealLeaf(t)}var F=require("obsidian");at();var ye=require("obsidian");at();function ec(A,r){let t=A.vault.getAbstractFileByPath(r);if(!(t instanceof ye.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof ye.TFile?n.extension==="md"&&e.push(n):n instanceof ye.TFolder&&(Qi.has(n.name)||i.push(n))}return e}var Us=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(k,{id:k,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(k,{id:k,parent:null,children:[],file:null,created:""});let s=t?ec(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=o?.id;if(!a){let c=e.get(n.path),d=c?i.get(c):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===k){let c=this.nodes.get(k);c.file=n,c.created=o?.created??"",this.byPath.set(n.path,k);continue}let l=o?.parent??null;l===a&&(l=null),this.nodes.set(a,{id:a,parent:l??k,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===k)continue;let o=n.parent??k;(this.nodes.get(o)??this.nodes.get(k)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let l=this.nodes.get(o),c=this.nodes.get(a);return(l.created||"").localeCompare(c.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((l,c)=>a.set(l,c)),n.children.sort((l,c)=>{let d=a.has(l)?a.get(l):1/0,h=a.has(c)?a.get(c):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??k,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(k)}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!==k&&!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===k||!t.file||(r[t.id]={parent:t.parent===k?null:t.parent,path:t.file.path});return r}hookMetadataCache(r){let t=l=>{let c=this.currentFolder;return c?typeof l!="string"?!1:l===c||l.startsWith(c+"/"):!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 ye.TFile&&t(l.path)&&l.extension==="md"&&(this.applyChange(l),i())},n=l=>{l instanceof ye.TFile&&t(l.path)&&l.extension==="md"&&this.applyChange(l)&&i()},o=l=>{let c=l?.path;typeof c=="string"&&t(c)&&this.applyDelete(c)&&i()},a=(l,c)=>{if(!(l instanceof ye.TFile))return;let d=typeof c=="string"?c: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($e(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 c=this.nodes.get(i);if(c&&c.file!==r)return c.file=r,!0}return!1}if(this.synthetic.delete(r.path),e===k){let c=this.nodes.get(k),d=t?.created??"",h=!1;return c.file!==r&&(c.file=r,h=!0),c.created!==d&&(c.created=d,h=!0),this.byPath.get(r.path)!==k&&(this.byPath.set(r.path,k),h=!0),h}let s=t?.parent??k,n=t?.created??"";if(!(s===k||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let c={id:e,parent:s,children:[],file:r,created:n};return this.nodes.set(e,c),this.byPath.set(r.path,e),this.attachToParent(c),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??k),l=!0),a.parent!==s){let c=a.parent??k;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(c),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(k);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=k,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(k),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($e(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??k);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??k);t||(t=this.nodes.get(k)),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 Ao=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(` +`)}},vt=new Ao;var Oa=".stashpad-order.json",ai=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}/${Oa}`,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}/${Oa}`,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 ri={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"},ho=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],ic=new Set(ho),Ya=".stashpad-sort.json",Rs=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}/${Ya}`,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"&&ic.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}/${Ya}`,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)}};at();var we="parentLink",li="children";var Ks=class Ks{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||!X().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(),Ks.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[we]=="string"?n[we]:null,a=n?.[li],l=Array.isArray(a)?a.filter(c=>typeof c=="string"):[];if((o??null)!==(i??null)||l.length!==s.length)return!0;for(let c=0;c<l.length;c++)if(l[c]!==s[c])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 vt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[we]=i:delete n[we],s.length>0?n[li]=s:delete n[li]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(r){if(r.id===k)return null;let t=this.getTree();if(!r.parent||r.parent===k){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))}};Ks.PACING_MS=100;var Ls=Ks;async function ci(A,r){let t=r.endsWith("/")?r:r+"/",e=new Map,i=new Map;for(let c of A.vault.getMarkdownFiles()){if(c.path!==r&&!c.path.startsWith(t))continue;let d=A.metadataCache.getFileCache(c)?.frontmatter,h=typeof d?.id=="string"?d.id:null;if(!h)continue;let g=typeof d?.parent=="string"?d.parent:k;e.set(h,{file:c,id:h,parent:g});let u=i.get(g)??[];u.push(h),i.set(g,u)}let s=c=>Gs(c.file.path),n=c=>{if(c.id===k)return null;if(c.parent===k||!c.parent){let h=e.get(k);return h?s(h):null}let d=e.get(c.parent);return d?s(d):null},o=c=>{let d=i.get(c.id)??[],h=[];for(let g of d){let u=e.get(g);u&&h.push(s(u))}return h},a=0,l=0;for(let c of e.values()){a+=1;let d=n(c),h=o(c),g=A.metadataCache.getFileCache(c.file)?.frontmatter,u=g&&typeof g[we]=="string"?g[we]:null,p=g?.[li],f=Array.isArray(p)?p.filter(C=>typeof C=="string"):[],I=(u??null)===(d??null),m=f.length===h.length&&f.every((C,B)=>C===h[B]);if(!(I&&m))try{await A.fileManager.processFrontMatter(c.file,C=>{d?C[we]=d:delete C[we],h.length>0?C[li]=h:delete C[li]}),l+=1,await new Promise(C=>setTimeout(C,50))}catch(C){console.warn("[Stashpad] rebootstrap fm sync failed",c.file.path,C)}}return{checked:a,written:l}}function Gs(A){return`[[${A.replace(/\.md$/i,"")}]]`}Gt();je();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 gt=require("obsidian");at();Tn();var mt=gt.moment;function po(A){let r=A.trim().toLowerCase();if(!r)return null;let t=Date.now(),e=p=>mt(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),f=a[2]?parseInt(a[2],10):0,I=a[3];I==="pm"&&p<12&&(p+=12),I==="am"&&p===12&&(p=0),p>=0&&p<24&&f>=0&&f<60&&(s=(p*3600+f*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 c=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],d=["sun","mon","tue","wed","thu","fri","sat"],h=c.indexOf(o)>=0?c.indexOf(o):d.indexOf(o);if(h>=0){let p=mt().startOf("day"),I=(p.day()-h+7)%7;return l(p.subtract(I,"days").valueOf())}let g=/^(\d+)\s*([dwmy])$/.exec(o);if(g){let p=parseInt(g[1],10),f={d:"days",w:"weeks",m:"months",y:"years"}[g[2]];return l(mt().subtract(p,f).startOf("day").valueOf())}let u=mt(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return u.isValid()?l(u.startOf("day").valueOf()):null}function $a(A){let r={text:[],filters:{}},t=(A||"").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=po(o);a!=null&&(r.filters.before=a)}else if(n==="after"){let a=po(o);a!=null&&(r.filters.after=a)}else if(n==="on"){let a=po(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 c=mt(a).startOf("day").valueOf();r.filters.on={start:c,end:c+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&r.text.push(n.toLowerCase());return r}var Zt=class A extends gt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==k?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===k&&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(k))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=$a(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=m=>{if(!s.length)return!0;for(let C of s)if(!m.includes(C))return!1;return!0},o=null,a=null;if(i.filters.in){let m=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,a=new Map;let C=y=>m.every(Q=>y.toLowerCase().includes(Q)),B=y=>{if(!o.has(y)){o.add(y);for(let Q of this.tree.getChildren(y))B(Q.id)}};for(let y of this.notes)!y.node||y.cross||C(y.title)&&B(y.node.id);let w=new Map;for(let y of this.notes){if(!y.cross)continue;let Q=w.get(y.cross.folder)??[];Q.push(y),w.set(y.cross.folder,Q)}for(let[y,Q]of w){let v=new Map;for(let D of Q){let H=D.cross?.parentId??null;if(!H)continue;let U=v.get(H)??[];U.push(D.cross.id),v.set(H,U)}let E=new Set;a.set(y,E);let S=D=>{if(!E.has(D)){E.add(D);for(let H of v.get(D)??[])S(H)}};for(let D of Q)C(D.title)&&S(D.cross.id)}}let l=m=>{let C=i.filters;if(o||a)if(m.cross){let B=a?.get(m.cross.folder);if(!B||!B.has(m.cross.id))return!1}else if(m.node){if(!o||!o.has(m.node.id))return!1}else return!1;if(C.before||C.after||C.on){let B=this.createdMsFor(m);if(B==null||C.before!=null&&B>=C.before||C.after!=null&&B<=C.after||C.on&&(B<C.on.start||B>=C.on.end))return!1}return!0},c=m=>n(m.toLowerCase()),d=this.notes.filter(m=>!m.cross),h=this.notes.filter(m=>m.cross),g=(m,C)=>({id:m.cross?`cross:${m.cross.folder}:${m.cross.id}`:m.node.id,label:m.title,node:m.node,kind:"note",bodyPreview:this.previewFromBody(m.body,C),matchLine:C,crossFolder:m.cross?.folder,crossFile:m.cross?.file,crossId:m.cross?.id}),u=m=>{let C=[];for(let B of m)if(l(B))if(this.opts.mode==="search"){if(!e){C.push(g(B,-1));continue}let w=n(B.title.toLowerCase()),y=B.body.split(/\r?\n/),Q=[];for(let E=0;E<y.length;E++)c(y[E])&&Q.push(E);let v=Q.length>0||n(B.body.toLowerCase());if(!w&&!v)continue;if(Q.length===0)C.push(g(B,-1));else{let E=[],S=-100;for(let H of Q)H-S>5&&E.push(H),S=H;let D=5;for(let H of E.slice(0,D))C.push(g(B,H))}}else{if(e&&!n(B.title.toLowerCase())&&!n(B.body.toLowerCase()))continue;C.push(g(B,-1))}return C},p=u(d),f=[...p];if(this.opts.mode==="search"?e?!0:p.length<10:!!e){let m=u(h);this.opts.mode==="search"&&!e&&(f.length=Math.min(f.length,50)),f.push(...m)}if(this.opts.folderResults){let m=this.opts.folderResults(),C={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};m.length>0&&(e?m.some(B=>{let w=B.split("/").pop()??B;return n(`${B.toLowerCase()} ${w.toLowerCase()}`)})&&f.push(C):f.unshift(C))}if(this.opts.allowCreate&&e&&!f.some(m=>m.label.trim().toLowerCase()===e)&&f.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let m=B=>B.kind==="note"&&(B.id===k||B.crossId===k)&&n(B.label.toLowerCase()),C=f.filter(m);if(C.length>0){let B=f.filter(w=>!m(w));f.splice(0,f.length,...C,...B)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&f.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),f}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 u=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),p=u.createSpan({cls:"stashpad-search-excluded-icon"});(0,gt.setIcon)(p,"folder-search"),u.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(u=>t.crossFolder?u.cross?.folder===t.crossFolder&&u.cross?.id===t.crossId:u.node?.id===t.id),n=Or(this.inputEl?.value??"").text,o=this.firstLineOfBody(s?.body??"")||t.label.trim(),r=i.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(r,o,n);let l=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let u=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(u,t.bodyPreview,n)}let c="";if(t.crossFolder?c=s?.cross?.parentBlurb??"":c=this.parentBlurbFor(t.node),c){let u=i.createDiv({cls:"stashpad-suggest-preview"});u.appendText("Parent: "),this.highlightInto(u,c,n)}let d=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),h=t.crossFolder??this.opts.localFolder??null;if(h||d){let u=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),f=[h?h.split("/").pop()||h:"",d].filter(I=>I&&I.length>0).join(" \u203A ");f&&u.setText(f)}let g=s?this.createdMsFor(s):null;if(g!=null||l){let u=e.createDiv({cls:"stashpad-suggest-rail"});if(g!=null){let p=u.createDiv({cls:"stashpad-suggest-time"});p.setText(this.formatRelativeTime(g)),p.title=mt(g).format("YYYY-MM-DD HH:mm")}l&&u.createDiv({cls:"stashpad-suggest-folder-badge",text:l.split("/").pop()||l})}}formatRelativeTime(t){let e=mt(t),i=mt().startOf("day").diff(mt(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(c=>c&&c.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let c of s){let d=0;for(;(d=n.indexOf(c,d))!==-1;)o.push([d,d+c.length]),d+=c.length}if(!o.length){t.appendText(e);return}o.sort((c,d)=>c[0]-d[0]);let r=[];for(let c of o){let d=r[r.length-1];d&&c[0]<=d[1]?d[1]=Math.max(d[1],c[1]):r.push([c[0],c[1]])}let l=0;for(let[c,d]of r)c>l&&t.appendText(e.slice(l,c)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(c,d)}),l=d;l<e.length&&t.appendText(e.slice(l))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===k)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==k&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==k?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 c=this.crossFolderIndex.get(l.cross.folder);c||(c=new Map,this.crossFolderIndex.set(l.cross.folder,c)),c.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]),r=s.parentId?e.get(s.parentId):null;for(;r&&!o.has(r.id);)o.add(r.id),n.unshift(r.title),r=r.parentId?e.get(r.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===k)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!gt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(gt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",c=>{if(c.key==="["){c.preventDefault();let d=t.selectionStart??t.value.length,h=t.selectionEnd??d,g=t.value.slice(0,d),u=t.value.slice(d,h),p=t.value.slice(h);t.value=`${g}[${u}]${p}`;let f=d+1+u.length;t.setSelectionRange(f,f),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(c.key==="]"){let d=t.selectionStart??-1;d>=0&&t.value[d]==="]"&&(c.preventDefault(),t.setSelectionRange(d+1,d+1));return}if(c.key==="Backspace"&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&t.selectionStart===t.selectionEnd){let d=t.selectionStart??-1;if(d>0&&t.value[d-1]==="["&&t.value[d]==="]"){c.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",c=>{c.preventDefault()}),n.addEventListener("click",c=>{c.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),n.click())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",c=>{c.preventDefault()}),o.addEventListener("click",c=>{c.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let r=new gt.Scope(this.scope),l=c=>{let d=document.activeElement;return d?.classList?.contains("stashpad-search-filter-chip")?(c.preventDefault(),d.click(),!1):c.key==="Enter"&&!c.isComposing?(c.preventDefault(),this.selectActiveSuggestion?.(c),!1):!0};r.register([],"Enter",l),r.register([]," ",l),r.register(["Mod"],"f",c=>{c.preventDefault();let d=this.inputEl;return d&&(d.focus(),d.select()),!1}),r.register([],"Tab",c=>{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(f=>!f.hasAttribute("disabled")&&f.tabIndex!==-1&&f.offsetParent!==null);if(g.length===0)return!0;let u=document.activeElement,p=u?g.indexOf(u):-1;if(c.shiftKey){if(p<=0)return c.preventDefault(),g[g.length-1].focus(),!1}else if(p===g.length-1)return c.preventDefault(),(h??g[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(r),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(r)}catch{}})}appendFilterToInput(t,e,i){let s=t.value,o=`${s.length>0&&!/\s$/.test(s)?" ":""}${e}: [`,r="]",l=i;t.value=`${s}${o}${l}${r}`;let c=s.length+o.length+l.length;if(t.setSelectionRange(c,c+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"}],r={};for(let f of o){let I=document.createElement("button");I.type="button",I.className="stashpad-when-tab",I.textContent=f.label,this.whenMode===f.id&&I.addClass("is-active"),I.addEventListener("mousedown",m=>m.preventDefault()),I.addEventListener("click",m=>{if(m.preventDefault(),this.whenMode===f.id)return;let C=this.whenMode;C!=="between"&&f.id==="between"?this.whenBetweenEndText="":C==="between"&&f.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=f.id;for(let B in r)r[B].toggleClass("is-active",B===f.id);p()}),r[f.id]=I,n.appendChild(I)}s.appendChild(n);let l=document.createElement("div");l.className="stashpad-when-body",s.appendChild(l);let c=(f,I,m="single")=>{let C=mt().format("YYYY-MM-DD"),B=!I||I===C;if(m==="betweenStart")return"00:00";if(m==="betweenEnd")return"23:59";switch(f){case"after":return"00:00";case"on":return B?mt().format("HH:mm"):"23:59";case"before":return B?mt().format("HH:mm"):"23:59";default:return"23:59"}},d=(f,I)=>{f.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.stopPropagation(),I()):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),this.closeWhenBuilder())})},h=(f,I)=>{let m=f.selectionStart??f.value.length,C=f.selectionEnd??f.value.length,w=`${m>0&&!/\s$/.test(f.value.slice(0,m))?" ":""}${I}`,y=f.value.slice(0,m)+w+f.value.slice(C);f.value=y;let Q=m+w.length;f.setSelectionRange(Q,Q),f.focus(),f.dispatchEvent(new Event("input",{bubbles:!0}))},g=(f,I)=>{let C=f.slice(0,I).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return C?C[1]:null},u=(f,I,m,C)=>{let B=l.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=B.createDiv({cls:"stashpad-when-icon-slot"}),y=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,gt.setIcon)(y,"calendar-days");let Q=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});Q.tabIndex=-1;let v=B.createDiv({cls:"stashpad-when-icon-slot"}),E=v.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});E.type="button",E.title="Pick time",(0,gt.setIcon)(E,"clock");let S=B.createDiv({cls:"stashpad-when-icon-slot"}),D=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});D.type="button",D.title="Pick day",(0,gt.setIcon)(D,"calendar");let H=B.createDiv({cls:"stashpad-when-icon-slot"}),U=H.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});U.type="button",U.title="Pick timeframe",(0,gt.setIcon)(U,"history");let N=B.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:f}});N.value=I(),N.addEventListener("input",()=>m(N.value));let b=B.createEl("button",{cls:"stashpad-when-clear"});b.type="button",b.textContent="\xD7",b.title="Clear";for(let $ of[y,E,D,U,b])$.addEventListener("mousedown",V=>V.preventDefault());let T=null,P=($,V)=>{T&&T();let L=$.createDiv({cls:"stashpad-when-popover"}),z=new gt.Scope(this.scope),J=null,O=j=>{J=j},st=!1,lt=j=>{!L.contains(j.target)&&j.target!==$&&!$.contains(j.target)&&tt()},tt=()=>{if(!st){st=!0,L.remove(),document.removeEventListener("mousedown",lt,!0);try{this.app.keymap?.popScope(z)}catch{}T===tt&&(T=null)}};T=tt,z.register([],"Escape",j=>(j.preventDefault(),tt(),!1)),z.register([],"Enter",j=>(j.preventDefault(),J&&J(),!1));try{V(L,tt,O)}catch(j){console.error("[stashpad] popover fill threw:",j),L.remove(),T=null;return}this.app.keymap?.pushScope(z),this.pendingCleanups.push(tt),setTimeout(()=>document.addEventListener("mousedown",lt,!0),0)};U.addEventListener("click",$=>{$.preventDefault(),P(H,(V,L,z)=>{let J=this.whenMode==="on",O=(nt,wt)=>{if(!J)return`${nt}${wt}`;let ke={d:"days",w:"weeks",m:"months",y:"years"}[wt];return mt().subtract(nt,ke).format("YYYY-MM-DD")},st=V.createDiv({cls:"stashpad-when-pop-row"}),lt=[{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 nt of lt){let wt=st.createEl("button",{cls:"stashpad-when-pop-chip",text:nt.label});wt.type="button",wt.addEventListener("mousedown",ke=>ke.preventDefault()),wt.addEventListener("click",ke=>{ke.preventDefault(),h(N,O(nt.n,nt.unit)),L()})}let tt=V.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});tt.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let j=tt.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),yt=tt.createEl("select",{cls:"stashpad-when-pop-unit"});for(let nt of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let wt=yt.createEl("option",{text:nt.label});wt.value=nt.v}let ht=tt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ht.type="button";let Mt=()=>{let nt=parseInt(j.value,10);!Number.isFinite(nt)||nt<1||(h(N,O(nt,yt.value)),L())};ht.addEventListener("mousedown",nt=>nt.preventDefault()),ht.addEventListener("click",nt=>{nt.preventDefault(),Mt()}),z(Mt),j.focus(),j.select()})});let R=($,V,L,z,J)=>{P(V,(O,st,lt)=>{as(O,{seedH:L,seedM:z,seedPeriod:J,close:st,setOnEnter:lt,onFinalize:tt=>h($,rr(tt))})})};D.addEventListener("click",$=>{$.preventDefault(),P(S,(V,L,z)=>{let J=V.createDiv({cls:"stashpad-when-pop-row"});for(let j of["Today","Yesterday"]){let yt=J.createEl("button",{cls:"stashpad-when-pop-chip",text:j});yt.type="button",yt.addEventListener("mousedown",ht=>ht.preventDefault()),yt.addEventListener("click",ht=>{ht.preventDefault(),h(N,j),L()})}let O=V.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),st=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],tt=(mt().day()+6)%7;for(let j=0;j<st.length;j++){let yt=st[j],ht=O.createEl("button",{cls:"stashpad-when-pop-chip",text:yt.slice(0,3)});ht.type="button",ht.title=yt,j===tt&&ht.addClass("is-today"),ht.addEventListener("mousedown",Mt=>Mt.preventDefault()),ht.addEventListener("click",Mt=>{if(Mt.preventDefault(),C==="betweenEnd"){let nt=j,wt=mt().startOf("day"),ke=(wt.day()+6)%7,Bn=(nt-ke+7)%7;Bn===0&&(Bn=7);let tl=wt.clone().add(Bn,"days").format("YYYY-MM-DD");h(N,tl)}else h(N,yt);L()})}})});let Z=($,V)=>{$.value||($.value=V);let L=$;if(typeof L.showPicker=="function")try{L.showPicker();return}catch{}$.focus(),$.click()};return y.addEventListener("click",$=>{$.preventDefault(),Z(Q,mt().format("YYYY-MM-DD"))}),Q.addEventListener("change",()=>{Q.value&&h(N,Q.value)}),E.addEventListener("click",$=>{$.preventDefault();let V=N.selectionStart??N.value.length,L=g(N.value,V),z=c(this.whenMode,L,C),[J,O]=z.split(":"),st=parseInt(J,10),lt=parseInt(O,10),tt=st%12;tt===0&&(tt=12);let j=st>=12?"pm":"am";R(N,v,tt,lt,j)}),b.addEventListener("click",$=>{$.preventDefault(),N.value="",m(""),N.focus()}),N},p=()=>{if(l.empty(),this.whenMode==="between"){let f=u("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),I=u("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),m=l.createDiv({cls:"stashpad-when-actions"}),C=m.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",y=>y.preventDefault());let B=()=>{let y=f.value.trim(),Q=I.value.trim();y&&this.appendFilterToInput(t,"after",y),Q&&this.appendFilterToInput(t,"before",Q),this.closeWhenBuilder()};C.addEventListener("click",y=>{y.preventDefault(),B()});let w=m.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),d(f,B),d(I,B),f.focus(),f.setSelectionRange(f.value.length,f.value.length)}else{let f=u("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),I=l.createDiv({cls:"stashpad-when-actions"}),m=I.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",w=>w.preventDefault());let C=()=>{let w=f.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};m.addEventListener("click",w=>{w.preventDefault(),C()});let B=I.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});B.type="button",B.addEventListener("mousedown",w=>w.preventDefault()),B.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),d(f,C),f.focus(),f.setSelectionRange(f.value.length,f.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 u=g.split("/").pop()??g;this.opts.onPick({id:`folder:${g}`,label:`Open folder \u201C${u}\u201D in a new tab`,node:null,kind:"folder-open",folder:g})},o=new co(this.app,e,n),r=o.onClose.bind(o),l=this.tree,c=this.titleFn,d=this.opts,h=this.app;o.onClose=()=>{if(r(),!s){let g=new A(h,l,c,d);g.open(),setTimeout(()=>{let u=g.inputEl;u&&(i&&(u.value=i,u.dispatchEvent(new Event("input",{bubbles:!0}))),u.focus(),u.setSelectionRange(u.value.length,u.value.length))},0)}},o.open();return}this.opts.onPick(t)}},co=class extends gt.FuzzySuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onChosen=i;this.setPlaceholder("Open which folder?")}getItems(){return this.folders}getItemText(t){let e=t.split("/").pop()??t;return e===t?t:`${e} \u2014 ${t}`}onChooseItem(t){this.onChosen(t)}};var Yr=require("obsidian");rt();var Gs=class extends Yr.SuggestModal{constructor(a){super(a),this.setPlaceholder("Run a Stashpad command\u2026");let t=this.app.commands?.commands??{};this.commands=Object.keys(t).filter(e=>e.startsWith("stashpad:")).filter(e=>e!=="stashpad:stashpad-command-palette").map(e=>({id:e,name:ec(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(a){return this.commands.filter(t=>os(a,t.name))}renderSuggestion(a,t){t.createDiv({text:a.name,cls:"stashpad-cmd-palette-name"})}onChooseSuggestion(a){this.app.commands?.executeCommandById?.(a.id)}};function ec(A){return A.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||A}kt();var Ao=require("obsidian");function ic(A,a){return!a||A.metaKey||A.ctrlKey||A.altKey?!1:A.key.toLowerCase()===a.toLowerCase()}function ci(A,a){return a?a.includes("+")?sc(A,a):ic(A,a):!1}function G(A,a){if(!a)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=a;return t&&e?s?ci(A,t)||ci(A,e):i?ci(A,e):ci(A,t):ci(A,t)||ci(A,e)}function Vi(A){if(!A)return"";let a=Ao.Platform.isMacOS;return A.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?a?"Cmd":"Ctrl":e.toLowerCase()==="alt"?a?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function sc(A,a){if(!a)return!1;let t=a.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"),r=i.has("alt")||i.has("option"),l=i.has("shift"),d=Ao.Platform.isMacOS?A.metaKey:A.ctrlKey;return s&&!d||n&&!A.ctrlKey||o&&!A.metaKey||r!==A.altKey||l!==A.shiftKey||!s&&(!n&&A.ctrlKey||!o&&A.metaKey)?!1:A.key.toLowerCase()===e}var Le=require("obsidian");kt();var Tt=class Tt{constructor(a){this.host=a;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let a of this.contribTimers.values())clearTimeout(a);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let a=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!a||!t)return null;let e=a.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=a.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:a,id:t}}claimSelectedAsAuthor(){this.claimAuthorship({scope:"selection",contributorMode:!1})}claimFolderAsAuthor(){this.claimAuthorship({scope:"folder",contributorMode:!1})}claimSelectedWithContributor(){this.claimAuthorship({scope:"selection",contributorMode:!0})}claimFolderWithContributor(){this.claimAuthorship({scope:"folder",contributorMode:!0})}fileBackedNotesInFolder(){let a=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==a&&!e.startsWith(a+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(a,t){for(let s=0;s<a.length;s++){let n=this.host.app.vault.getAbstractFileByPath(a[s]);if(n instanceof Le.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,a[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",a[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(a){let t=this.currentAuthorLink();if(!t){new Le.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=a.scope==="selection"?this.host.getActionTargets().map(g=>g.file).filter(g=>!!g):this.fileBackedNotesInFolder();if(i.length===0){new Le.Notice(a.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let g of i){let u=this.host.app.metadataCache.getFileCache(g)?.frontmatter,p=typeof u?.author=="string"?u.author:"";if(!p.trim()){s.push(g.path);continue}if(p.includes(e)||!a.contributorMode)continue;(Array.isArray(u?.contributors)?u.contributors.filter(I=>typeof I=="string"):[]).some(I=>I.includes(e))||n.push(g.path)}let o=s.length+n.length;if(o===0){new Le.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(a.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 it(this.host.app,"Claim authorship",`${g.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",p).open()}))return}let r=this.host.noteFolder,l=t.link,c=new Set,d=async()=>{await this.pacedFrontmatter(s,(g,u)=>{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))),c.add(u))}),await this.pacedFrontmatter(n,g=>{let u=Array.isArray(g.contributors)?g.contributors.filter(p=>typeof p=="string"):[];u.some(p=>p.includes(e))||u.push(l),g.contributors=u})};this.ensureAuthorFile(t),await d(),this.host.plugin.getUndoStack(r).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(g,u)=>{if(typeof g.author=="string"&&g.author.includes(e)&&delete g.author,c.has(u)){let p=Array.isArray(g.contributors)?g.contributors.filter(f=>typeof f=="string"):[];p.some(f=>f.includes(e))||p.push(l),g.contributors=p}}),await this.pacedFrontmatter(n,g=>{Array.isArray(g.contributors)&&(g.contributors=g.contributors.filter(u=>!(typeof u=="string"&&u.includes(e))))}),this.host.debouncedRender()},redo:async()=>{c.clear(),await d(),this.host.debouncedRender()}});let h=[];s.length&&h.push(`authored ${s.length}`),n.length&&h.push(`contributing to ${n.length}`),new Le.Notice(`Claimed authorship: ${h.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(a){try{a.id&&this.host.plugin.authorRegistry.record({id:a.id,name:a.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(a.path))return;let e=a.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:a.id,name:a.name,role:e?this.host.plugin.settings.authorRole:void 0,department:e?this.host.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.host.app.vault.create(a.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(a){let t=new Set,e=i=>{if(typeof i!="string")return null;let s=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return s?s[1]:null};for(let i of a){if(!i.file)continue;let s=this.host.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!s)continue;let n=e(s.author);if(n&&t.add(n),Array.isArray(s.contributors))for(let o of s.contributors){let r=e(o);r&&t.add(r)}}return Array.from(t)}pruneContribMaps(){let a=Date.now(),t=Tt.EXTERNAL_WRITE_GRACE_MS*20,e=Tt.EXTERNAL_QUIESCENCE_MS*12;for(let[i,s]of this.recentSelfWrites)a-s>t&&this.recentSelfWrites.delete(i);for(let[i,s]of this.lastExternalModify)a-s>e&&this.lastExternalModify.delete(i);if(this.knownBodies.size>64)for(let i of this.knownBodies.keys())this.host.tree.idForPath(i)||this.knownBodies.delete(i)}noteModify(a){let t=Date.now(),e=this.recentSelfWrites.get(a.path);e!==void 0&&t-e<Tt.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(a.path,t),this.scheduleContribution(a)}scheduleContribution(a){let t=this.contribTimers.get(a.path);t&&clearTimeout(t);let e=this.isFileActivelyEdited(a),i=Tt.CONTRIB_DEBOUNCE_MS+(e?Tt.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),s=setTimeout(()=>{if(this.contribTimers.delete(a.path),this.isFileActivelyEdited(a)){this.scheduleContribution(a);return}let n=this.lastExternalModify.get(a.path);if(n!==void 0&&Date.now()-n<Tt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(a);return}this.maybeRecordContribution(a)},i);this.contribTimers.set(a.path,s)}isFileActivelyEdited(a){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==a.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(a){let t="";try{t=await this.host.app.vault.cachedRead(a)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(a.path);if(this.knownBodies.set(a.path,e),i===void 0||i===e||this.host.plugin.rebootstrapInProgress)return;let s=this.currentAuthorLink();if(!s)return;this.ensureAuthorFile(s);let n=new Date().toISOString();this.recentSelfWrites.set(a.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(a,o=>{o.modified=n;let r=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(g=>typeof g=="string"):[],c=`-${s.id}`,d=r.includes(c),h=l.some(g=>g.includes(c));!d&&!h&&l.push(s.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Tt.CONTRIB_DEBOUNCE_MS=4e3,Tt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Tt.EXTERNAL_WRITE_GRACE_MS=1500,Tt.EXTERNAL_QUIESCENCE_MS=5e3;var Ls=Tt;var qs=class{constructor(a){this.host=a;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(a,t,e){a.addEventListener("dragstart",i=>{let s=this.host.selection.has(t.id)&&this.host.selection.size>1?[...this.host.selection]:[t.id];if(this.dragSourceIds=s,this.dragRowHeight=a.offsetHeight,a.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.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 r=this.dragPlaceholder.nextElementSibling,l=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let c,d="before";r&&r.classList.contains("stashpad-note")?(c=r.dataset.id,d="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,d="after"),c&&this.host.reorderToTarget(o,c,d)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(a,12,12)}catch{}}}),a.addEventListener("dragend",()=>{a.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),a.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,a);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),a.addClass("drop-into")):(a.removeClass("drop-into"),this.placePlaceholder(a,s==="drop-above"?"before":"after"))}),a.addEventListener("dragleave",i=>{let s=a.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&a.removeClass("drop-into")}),a.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,a);this.clearDropIndicators(),this.removeDragPlaceholder(),a.removeClass("is-dragging"),n==="drop-into"?this.host.reorderToTarget(s,t.id,"into"):this.host.reorderToTarget(s,t.id,n==="drop-above"?"before":"after")})}attachListDnD(a){a.addEventListener("dragover",t=>{if(!this.dragSourceIds)return;let e=t.target;if(e&&e.closest&&e.closest(".stashpad-note"))return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move");let i=Array.from(a.querySelectorAll(".stashpad-note"));if(i.length!==0){for(let s of i){let n=s.getBoundingClientRect();if(t.clientY<n.top+n.height/2){this.placePlaceholder(s,"before");return}}this.placePlaceholder(i[i.length-1],"after")}}),a.addEventListener("drop",t=>{if(!this.dragSourceIds)return;t.preventDefault();let e=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let i=this.dragPlaceholder.nextElementSibling,s=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),i&&i.classList.contains("stashpad-note")){let n=i.dataset.id;n&&this.host.reorderToTarget(e,n,"before")}else if(s&&s.classList.contains("stashpad-note")){let n=s.dataset.id;n&&this.host.reorderToTarget(e,n,"after")}})}placePlaceholder(a,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?a:a.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===a||t==="after"&&this.dragPlaceholder.previousSibling===a)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),this.dragPlaceholder.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 a=this.dragPlaceholder;a.setCssStyles({height:"0px",opacity:"0"}),setTimeout(()=>{a.parentElement&&a.remove()},150)}dropZone(a,t){let e=t.getBoundingClientRect(),i=a.clientY-e.top;return i<e.height*.3?"drop-above":i>e.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.host.listEl)for(let a of Array.from(this.host.listEl.querySelectorAll(".drop-into")))a.removeClass("drop-into")}};var $r=require("obsidian");var Ks=class{constructor(a,t,e){this.host=a;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(a){let t=this.renderCache.get(a.path);if(t&&t.mtime===a.stat.mtime)return vt.record("render.row.cacheHit",0),t;let e=await vt.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(a)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await vt.timeAsync("render.row.markdown",()=>$r.MarkdownRenderer.render(this.host.app,s,o,a.path,this.component));let r=o.innerHTML,l={mtime:a.stat.mtime,text:s,attachments:n,html:r};return this.renderCache.set(a.path,l),l}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(a=>{for(let t of a){if(!t.isIntersecting)continue;let e=t.target,i=this.lazyBodies.get(e);this.bodyObserver?.unobserve(e),this.lazyBodies.delete(e),i&&i()}},{root:this.host.contentEl,rootMargin:"1400px 0px"})}dispose(){this.bodyObserver?.disconnect(),this.bodyObserver=null}isArmed(){return!!this.bodyObserver}hasFreshRenderCache(a){let t=this.renderCache.get(a.path);return!!t&&t.mtime===a.stat.mtime}defer(a,t){this.lazyBodies.set(a,t),this.bodyObserver?.observe(a)}splitAttachments(a){let t=[];return{text:a.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` +`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let u=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),p=u.createSpan({cls:"stashpad-search-excluded-icon"});(0,gt.setIcon)(p,"folder-search"),u.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(u=>t.crossFolder?u.cross?.folder===t.crossFolder&&u.cross?.id===t.crossId:u.node?.id===t.id),n=$a(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 u=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(u,t.bodyPreview,n)}let c="";if(t.crossFolder?c=s?.cross?.parentBlurb??"":c=this.parentBlurbFor(t.node),c){let u=i.createDiv({cls:"stashpad-suggest-preview"});u.appendText("Parent: "),this.highlightInto(u,c,n)}let d=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),h=t.crossFolder??this.opts.localFolder??null;if(h||d){let u=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),f=[h?h.split("/").pop()||h:"",d].filter(I=>I&&I.length>0).join(" \u203A ");f&&u.setText(f)}let g=s?this.createdMsFor(s):null;if(g!=null||l){let u=e.createDiv({cls:"stashpad-suggest-rail"});if(g!=null){let p=u.createDiv({cls:"stashpad-suggest-time"});p.setText(this.formatRelativeTime(g)),p.title=mt(g).format("YYYY-MM-DD HH:mm")}l&&u.createDiv({cls:"stashpad-suggest-folder-badge",text:l.split("/").pop()||l})}}formatRelativeTime(t){let e=mt(t),i=mt().startOf("day").diff(mt(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(c=>c&&c.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let c of s){let d=0;for(;(d=n.indexOf(c,d))!==-1;)o.push([d,d+c.length]),d+=c.length}if(!o.length){t.appendText(e);return}o.sort((c,d)=>c[0]-d[0]);let a=[];for(let c of o){let d=a[a.length-1];d&&c[0]<=d[1]?d[1]=Math.max(d[1],c[1]):a.push([c[0],c[1]])}let l=0;for(let[c,d]of a)c>l&&t.appendText(e.slice(l,c)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(c,d)}),l=d;l<e.length&&t.appendText(e.slice(l))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===k)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==k&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==k?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 c=this.crossFolderIndex.get(l.cross.folder);c||(c=new Map,this.crossFolderIndex.set(l.cross.folder,c)),c.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===k)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!gt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(gt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",c=>{if(c.key==="["){c.preventDefault();let d=t.selectionStart??t.value.length,h=t.selectionEnd??d,g=t.value.slice(0,d),u=t.value.slice(d,h),p=t.value.slice(h);t.value=`${g}[${u}]${p}`;let f=d+1+u.length;t.setSelectionRange(f,f),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(c.key==="]"){let d=t.selectionStart??-1;d>=0&&t.value[d]==="]"&&(c.preventDefault(),t.setSelectionRange(d+1,d+1));return}if(c.key==="Backspace"&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&t.selectionStart===t.selectionEnd){let d=t.selectionStart??-1;if(d>0&&t.value[d-1]==="["&&t.value[d]==="]"){c.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",c=>{c.preventDefault()}),n.addEventListener("click",c=>{c.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),n.click())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",c=>{c.preventDefault()}),o.addEventListener("click",c=>{c.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",c=>{(c.key==="Enter"||c.key===" ")&&(c.preventDefault(),c.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new gt.Scope(this.scope),l=c=>{let d=document.activeElement;return d?.classList?.contains("stashpad-search-filter-chip")?(c.preventDefault(),d.click(),!1):c.key==="Enter"&&!c.isComposing?(c.preventDefault(),this.selectActiveSuggestion?.(c),!1):!0};a.register([],"Enter",l),a.register([]," ",l),a.register(["Mod"],"f",c=>{c.preventDefault();let d=this.inputEl;return d&&(d.focus(),d.select()),!1}),a.register([],"Tab",c=>{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(f=>!f.hasAttribute("disabled")&&f.tabIndex!==-1&&f.offsetParent!==null);if(g.length===0)return!0;let u=document.activeElement,p=u?g.indexOf(u):-1;if(c.shiftKey){if(p<=0)return c.preventDefault(),g[g.length-1].focus(),!1}else if(p===g.length-1)return c.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 c=s.length+o.length+l.length;if(t.setSelectionRange(c,c+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 f of o){let I=document.createElement("button");I.type="button",I.className="stashpad-when-tab",I.textContent=f.label,this.whenMode===f.id&&I.addClass("is-active"),I.addEventListener("mousedown",m=>m.preventDefault()),I.addEventListener("click",m=>{if(m.preventDefault(),this.whenMode===f.id)return;let C=this.whenMode;C!=="between"&&f.id==="between"?this.whenBetweenEndText="":C==="between"&&f.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=f.id;for(let B in a)a[B].toggleClass("is-active",B===f.id);p()}),a[f.id]=I,n.appendChild(I)}s.appendChild(n);let l=document.createElement("div");l.className="stashpad-when-body",s.appendChild(l);let c=(f,I,m="single")=>{let C=mt().format("YYYY-MM-DD"),B=!I||I===C;if(m==="betweenStart")return"00:00";if(m==="betweenEnd")return"23:59";switch(f){case"after":return"00:00";case"on":return B?mt().format("HH:mm"):"23:59";case"before":return B?mt().format("HH:mm"):"23:59";default:return"23:59"}},d=(f,I)=>{f.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.stopPropagation(),I()):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),this.closeWhenBuilder())})},h=(f,I)=>{let m=f.selectionStart??f.value.length,C=f.selectionEnd??f.value.length,w=`${m>0&&!/\s$/.test(f.value.slice(0,m))?" ":""}${I}`,y=f.value.slice(0,m)+w+f.value.slice(C);f.value=y;let Q=m+w.length;f.setSelectionRange(Q,Q),f.focus(),f.dispatchEvent(new Event("input",{bubbles:!0}))},g=(f,I)=>{let C=f.slice(0,I).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return C?C[1]:null},u=(f,I,m,C)=>{let B=l.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=B.createDiv({cls:"stashpad-when-icon-slot"}),y=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,gt.setIcon)(y,"calendar-days");let Q=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});Q.tabIndex=-1;let v=B.createDiv({cls:"stashpad-when-icon-slot"}),E=v.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});E.type="button",E.title="Pick time",(0,gt.setIcon)(E,"clock");let S=B.createDiv({cls:"stashpad-when-icon-slot"}),D=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});D.type="button",D.title="Pick day",(0,gt.setIcon)(D,"calendar");let H=B.createDiv({cls:"stashpad-when-icon-slot"}),U=H.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});U.type="button",U.title="Pick timeframe",(0,gt.setIcon)(U,"history");let N=B.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:f}});N.value=I(),N.addEventListener("input",()=>m(N.value));let b=B.createEl("button",{cls:"stashpad-when-clear"});b.type="button",b.textContent="\xD7",b.title="Clear";for(let $ of[y,E,D,U,b])$.addEventListener("mousedown",V=>V.preventDefault());let T=null,P=($,V)=>{T&&T();let L=$.createDiv({cls:"stashpad-when-popover"}),z=new gt.Scope(this.scope),J=null,O=j=>{J=j},st=!1,lt=j=>{!L.contains(j.target)&&j.target!==$&&!$.contains(j.target)&&tt()},tt=()=>{if(!st){st=!0,L.remove(),document.removeEventListener("mousedown",lt,!0);try{this.app.keymap?.popScope(z)}catch{}T===tt&&(T=null)}};T=tt,z.register([],"Escape",j=>(j.preventDefault(),tt(),!1)),z.register([],"Enter",j=>(j.preventDefault(),J&&J(),!1));try{V(L,tt,O)}catch(j){console.error("[stashpad] popover fill threw:",j),L.remove(),T=null;return}this.app.keymap?.pushScope(z),this.pendingCleanups.push(tt),setTimeout(()=>document.addEventListener("mousedown",lt,!0),0)};U.addEventListener("click",$=>{$.preventDefault(),P(H,(V,L,z)=>{let J=this.whenMode==="on",O=(nt,wt)=>{if(!J)return`${nt}${wt}`;let ke={d:"days",w:"weeks",m:"months",y:"years"}[wt];return mt().subtract(nt,ke).format("YYYY-MM-DD")},st=V.createDiv({cls:"stashpad-when-pop-row"}),lt=[{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 nt of lt){let wt=st.createEl("button",{cls:"stashpad-when-pop-chip",text:nt.label});wt.type="button",wt.addEventListener("mousedown",ke=>ke.preventDefault()),wt.addEventListener("click",ke=>{ke.preventDefault(),h(N,O(nt.n,nt.unit)),L()})}let tt=V.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});tt.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let j=tt.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),yt=tt.createEl("select",{cls:"stashpad-when-pop-unit"});for(let nt of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let wt=yt.createEl("option",{text:nt.label});wt.value=nt.v}let ht=tt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ht.type="button";let Mt=()=>{let nt=parseInt(j.value,10);!Number.isFinite(nt)||nt<1||(h(N,O(nt,yt.value)),L())};ht.addEventListener("mousedown",nt=>nt.preventDefault()),ht.addEventListener("click",nt=>{nt.preventDefault(),Mt()}),z(Mt),j.focus(),j.select()})});let R=($,V,L,z,J)=>{P(V,(O,st,lt)=>{As(O,{seedH:L,seedM:z,seedPeriod:J,close:st,setOnEnter:lt,onFinalize:tt=>h($,la(tt))})})};D.addEventListener("click",$=>{$.preventDefault(),P(S,(V,L,z)=>{let J=V.createDiv({cls:"stashpad-when-pop-row"});for(let j of["Today","Yesterday"]){let yt=J.createEl("button",{cls:"stashpad-when-pop-chip",text:j});yt.type="button",yt.addEventListener("mousedown",ht=>ht.preventDefault()),yt.addEventListener("click",ht=>{ht.preventDefault(),h(N,j),L()})}let O=V.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),st=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],tt=(mt().day()+6)%7;for(let j=0;j<st.length;j++){let yt=st[j],ht=O.createEl("button",{cls:"stashpad-when-pop-chip",text:yt.slice(0,3)});ht.type="button",ht.title=yt,j===tt&&ht.addClass("is-today"),ht.addEventListener("mousedown",Mt=>Mt.preventDefault()),ht.addEventListener("click",Mt=>{if(Mt.preventDefault(),C==="betweenEnd"){let nt=j,wt=mt().startOf("day"),ke=(wt.day()+6)%7,En=(nt-ke+7)%7;En===0&&(En=7);let il=wt.clone().add(En,"days").format("YYYY-MM-DD");h(N,il)}else h(N,yt);L()})}})});let Z=($,V)=>{$.value||($.value=V);let L=$;if(typeof L.showPicker=="function")try{L.showPicker();return}catch{}$.focus(),$.click()};return y.addEventListener("click",$=>{$.preventDefault(),Z(Q,mt().format("YYYY-MM-DD"))}),Q.addEventListener("change",()=>{Q.value&&h(N,Q.value)}),E.addEventListener("click",$=>{$.preventDefault();let V=N.selectionStart??N.value.length,L=g(N.value,V),z=c(this.whenMode,L,C),[J,O]=z.split(":"),st=parseInt(J,10),lt=parseInt(O,10),tt=st%12;tt===0&&(tt=12);let j=st>=12?"pm":"am";R(N,v,tt,lt,j)}),b.addEventListener("click",$=>{$.preventDefault(),N.value="",m(""),N.focus()}),N},p=()=>{if(l.empty(),this.whenMode==="between"){let f=u("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),I=u("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),m=l.createDiv({cls:"stashpad-when-actions"}),C=m.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",y=>y.preventDefault());let B=()=>{let y=f.value.trim(),Q=I.value.trim();y&&this.appendFilterToInput(t,"after",y),Q&&this.appendFilterToInput(t,"before",Q),this.closeWhenBuilder()};C.addEventListener("click",y=>{y.preventDefault(),B()});let w=m.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),d(f,B),d(I,B),f.focus(),f.setSelectionRange(f.value.length,f.value.length)}else{let f=u("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),I=l.createDiv({cls:"stashpad-when-actions"}),m=I.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",w=>w.preventDefault());let C=()=>{let w=f.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};m.addEventListener("click",w=>{w.preventDefault(),C()});let B=I.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});B.type="button",B.addEventListener("mousedown",w=>w.preventDefault()),B.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),d(f,C),f.focus(),f.setSelectionRange(f.value.length,f.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 u=g.split("/").pop()??g;this.opts.onPick({id:`folder:${g}`,label:`Open folder \u201C${u}\u201D in a new tab`,node:null,kind:"folder-open",folder:g})},o=new go(this.app,e,n),a=o.onClose.bind(o),l=this.tree,c=this.titleFn,d=this.opts,h=this.app;o.onClose=()=>{if(a(),!s){let g=new A(h,l,c,d);g.open(),setTimeout(()=>{let u=g.inputEl;u&&(i&&(u.value=i,u.dispatchEvent(new Event("input",{bubbles:!0}))),u.focus(),u.setSelectionRange(u.value.length,u.value.length))},0)}},o.open();return}this.opts.onPick(t)}},go=class extends gt.FuzzySuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onChosen=i;this.setPlaceholder("Open which folder?")}getItems(){return this.folders}getItemText(t){let e=t.split("/").pop()??t;return e===t?t:`${e} \u2014 ${t}`}onChooseItem(t){this.onChosen(t)}};var Va=require("obsidian");at();var Js=class extends Va.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:sc(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(r){return this.commands.filter(t=>as(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 sc(A){return A.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||A}kt();var uo=require("obsidian");function nc(A,r){return!r||A.metaKey||A.ctrlKey||A.altKey?!1:A.key.toLowerCase()===r.toLowerCase()}function Ai(A,r){return r?r.includes("+")?oc(A,r):nc(A,r):!1}function G(A,r){if(!r)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=r;return t&&e?s?Ai(A,t)||Ai(A,e):i?Ai(A,e):Ai(A,t):Ai(A,t)||Ai(A,e)}function zi(A){if(!A)return"";let r=uo.Platform.isMacOS;return A.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 oc(A,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?A.metaKey:A.ctrlKey;return s&&!d||n&&!A.ctrlKey||o&&!A.metaKey||a!==A.altKey||l!==A.shiftKey||!s&&(!n&&A.ctrlKey||!o&&A.metaKey)?!1:A.key.toLowerCase()===e}var Le=require("obsidian");kt();var Tt=class Tt{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 Le.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 Le.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 Le.Notice(r.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let g of i){let u=this.host.app.metadataCache.getFileCache(g)?.frontmatter,p=typeof u?.author=="string"?u.author:"";if(!p.trim()){s.push(g.path);continue}if(p.includes(e)||!r.contributorMode)continue;(Array.isArray(u?.contributors)?u.contributors.filter(I=>typeof I=="string"):[]).some(I=>I.includes(e))||n.push(g.path)}let o=s.length+n.length;if(o===0){new Le.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 it(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,c=new Set,d=async()=>{await this.pacedFrontmatter(s,(g,u)=>{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))),c.add(u))}),await this.pacedFrontmatter(n,g=>{let u=Array.isArray(g.contributors)?g.contributors.filter(p=>typeof p=="string"):[];u.some(p=>p.includes(e))||u.push(l),g.contributors=u})};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,u)=>{if(typeof g.author=="string"&&g.author.includes(e)&&delete g.author,c.has(u)){let p=Array.isArray(g.contributors)?g.contributors.filter(f=>typeof f=="string"):[];p.some(f=>f.includes(e))||p.push(l),g.contributors=p}}),await this.pacedFrontmatter(n,g=>{Array.isArray(g.contributors)&&(g.contributors=g.contributors.filter(u=>!(typeof u=="string"&&u.includes(e))))}),this.host.debouncedRender()},redo:async()=>{c.clear(),await d(),this.host.debouncedRender()}});let h=[];s.length&&h.push(`authored ${s.length}`),n.length&&h.push(`contributing to ${n.length}`),new Le.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=Tt.EXTERNAL_WRITE_GRACE_MS*20,e=Tt.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<Tt.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=Tt.CONTRIB_DEBOUNCE_MS+(e?Tt.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<Tt.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"):[],c=`-${s.id}`,d=a.includes(c),h=l.some(g=>g.includes(c));!d&&!h&&l.push(s.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Tt.CONTRIB_DEBOUNCE_MS=4e3,Tt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Tt.EXTERNAL_WRITE_GRACE_MS=1500,Tt.EXTERNAL_QUIESCENCE_MS=5e3;var Os=Tt;var Ys=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 c,d="before";a&&a.classList.contains("stashpad-note")?(c=a.dataset.id,d="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,d="after"),c&&this.host.reorderToTarget(o,c,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 za=require("obsidian");var $s=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 vt.record("render.row.cacheHit",0),t;let e=await vt.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 vt.timeAsync("render.row.markdown",()=>za.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 zr(A,a,t){return A.tree.getChildren(a).slice().sort((i,s)=>nc(A,i,s,t)).map(i=>i.id)}function nc(A,a,t,e){switch(e){case"created-asc":return(a.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(a.created||"");case"modified-asc":case"modified-desc":{let i=Vr(A,a)||a.created||"",s=Vr(A,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=A.titleForNode(a),s=A.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 Vr(A,a){if(!a.file)return"";let t=A.app.metadataCache.getFileCache(a.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Ai=require("obsidian");Fi();async function ho(A){let a=A.getActionTargets();if(!a.length)return;let t=X().prefixTimestampsOnCopy,e=[];for(let i of a){if(!i.file)continue;let s=await A.app.vault.cachedRead(i.file),n=A.stripFrontmatter(s).trim();e.push(t?`${A.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function Xa(A,r,t){return A.tree.getChildren(r).slice().sort((i,s)=>ac(A,i,s,t)).map(i=>i.id)}function ac(A,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=Wa(A,r)||r.created||"",s=Wa(A,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=A.titleForNode(r),s=A.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 Wa(A,r){if(!r.file)return"";let t=A.app.metadataCache.getFileCache(r.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var di=require("obsidian");ki();async function fo(A){let r=A.getActionTargets();if(!r.length)return;let t=X().prefixTimestampsOnCopy,e=[];for(let i of r){if(!i.file)continue;let s=await A.app.vault.cachedRead(i.file),n=A.stripFrontmatter(s).trim();e.push(t?`${A.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` -`)),A.plugin.notifications.show({message:`Copied ${A.titleList(a)} to clipboard`,kind:"success",category:"system",affectedIds:a.map(i=>i.id),folder:A.noteFolder})}async function Wr(A){let a=A.getActionTargets();if(!a.length||!a[0].file){new Ai.Notice("Nothing to copy from.");return}let t=a[0],e=await A.app.vault.cachedRead(t.file),i=A.stripFrontmatter(e),s=ir(i);if(s.length===0){A.plugin.notifications.show({message:`No codeblock found in "${A.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:A.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),A.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${A.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:A.noteFolder});return}let n=s.map((r,l)=>({kind:"one",idx:l,label:`${l+1}. ${r.lang||"(no language)"} \u2014 ${r.code.split(` -`)[0].slice(0,60)}${r.code.includes(` -`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends Ai.SuggestModal{getSuggestions(r){let l=r.trim().toLowerCase();if(!l)return n;let c=l.split(/\s+/).filter(Boolean);return n.filter(d=>{let h=d.label.toLowerCase();return c.every(g=>h.includes(g))})}renderSuggestion(r,l){l.createDiv({cls:"stashpad-suggest-title",text:r.label})}async onChooseSuggestion(r){let l=r.kind==="all"?s.map(c=>c.code).join(` +`)),A.plugin.notifications.show({message:`Copied ${A.titleList(r)} to clipboard`,kind:"success",category:"system",affectedIds:r.map(i=>i.id),folder:A.noteFolder})}async function Za(A){let r=A.getActionTargets();if(!r.length||!r[0].file){new di.Notice("Nothing to copy from.");return}let t=r[0],e=await A.app.vault.cachedRead(t.file),i=A.stripFrontmatter(e),s=na(i);if(s.length===0){A.plugin.notifications.show({message:`No codeblock found in "${A.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:A.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),A.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${A.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:A.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 di.SuggestModal{getSuggestions(a){let l=a.trim().toLowerCase();if(!l)return n;let c=l.split(/\s+/).filter(Boolean);return n.filter(d=>{let h=d.label.toLowerCase();return c.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(c=>c.code).join(` -`):s[r.idx].code;await navigator.clipboard.writeText(l),A.plugin.notifications.show({message:r.kind==="all"?`Copied all ${s.length} codeblocks from "${A.titleForNode(t)}".`:`Copied codeblock${s[r.idx].lang?` (${s[r.idx].lang})`:""} from "${A.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:A.noteFolder})}}(A.app);o.setPlaceholder(`${s.length} codeblocks in "${A.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function Xr(A){let a=A.getActionTargets();if(a.length===0){let n=A.tree.get(A.focusId);n?.file&&(a=[n])}if(a.length===0){new Ai.Notice("Nothing to copy.");return}let t=X().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let r=await A.app.vault.cachedRead(n.file),l=A.stripFrontmatter(r).trim().split(/\r?\n/).join(" "),c=t?`${A.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${c}${l}`)}for(let r of A.tree.getChildren(n.id))await i(r,o+1)};for(let n of a)await i(n,0);let s=e.join(` -`);await navigator.clipboard.writeText(s),A.plugin.clearNoteClipboard(),A.plugin.noteClipboard={mode:"copy",folder:A.noteFolder,ids:a.map(n=>n.id),text:s},A.render(),A.plugin.notifications.show({message:`Copied tree of ${A.titleList(a)} (${e.length} entries) \u2014 paste in the list to clone, in a note to drop the outline in`,kind:"success",category:"system",affectedIds:a.map(n=>n.id),folder:A.noteFolder})}async function Zr(A){let a=A.getActionTargets();if(a.length===0){let i=A.tree.get(A.focusId);i?.file&&(a=[i])}if(a.length===0){new Ai.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 A.tree.getChildren(i.id))e(o,s+1)};for(let i of a)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),A.plugin.notifications.show({message:`Copied outline of ${A.titleList(a)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:a.map(i=>i.id),folder:A.noteFolder})}var Bt=require("obsidian");rt();var zs=require("obsidian");Vs();Gt();rt();var te="stash",Ia=1;function ua(A){let t=(A.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var Fo=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Ee(A,a){let t=[],e=kc([...a.rootNotes,...a.allDescendants]),i=new Map,s=[];for(let o of e){let r=await A.vault.read(o.file),l=r,c=ma(r);for(let d of c){let h=A.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 A.vault.readBinary(h)),l=Sc(l,d,g)}l=xc(l,A,o.file.path),t.push({name:`notes/${o.file.name}`,data:l})}for(let[o,r]of i)t.push({name:`attachments/${o}`,data:r});let n={stashSchema:Ia,exportedAt:new Date().toISOString(),sourceFolder:a.sourceFolder,noteCount:e.length,rootIds:a.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(` -`)}),di(t,6)}async function ee(A,a,t,e,i={}){let s=await hi(a),n=s["manifest.json"];if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse($s(n));if(typeof o.stashSchema!="number"||o.stashSchema>Ia)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await fa(A,t);let r=Object.entries(s).filter(([Q])=>Q.startsWith("notes/")&&Q.endsWith(".md")),l=[];for(let[Q,v]of r){let E=$s(v),{fm:S,body:D}=dt(E),H=ua(Q.slice(6))||`${S.id||"imported-"+W(4)}.md`;l.push({originalName:H,fm:S,body:D})}let c=new Map,d=0;for(let Q of l){let v=Q.fm.id;v&&(i.forceNewIds?c.set(v,W(6)):e.has(v)||c.has(v)?(c.set(v,`${v}-${W(4)}-Imported`),d++):c.set(v,v))}let h=new Date().toISOString(),g=[],u=`${t}/_attachments`,p=0,f=Object.entries(s).filter(([Q])=>Q.startsWith("attachments/")),I=new Map,m=null;if(i.dedupeExisting){m=new Map;for(let Q of A.vault.getFiles())m.has(Q.name)||m.set(Q.name,Q.path)}let C=(Q,v)=>{if(Q.length!==v.length)return!1;for(let E=0;E<Q.length;E++)if(Q[E]!==v[E])return!1;return!0},B=!1;for(let[Q,v]of f){let E=ua(Q.slice(12));if(!E)continue;let S=v,D=[],H=m?.get(E);H&&D.push(H);let U=`${u}/${E}`;await A.vault.adapter.exists(U)&&D.push(U);let N=null;for(let T of D)try{if(C(new Uint8Array(await A.vault.adapter.readBinary(T)),S)){N=T;break}}catch{}if(N){I.set(E,N);continue}let b=U;for(let T=1;await A.vault.adapter.exists(b);T++)b=`${u}/${bc(E,T)}`;I.set(E,b),B||(await fa(A,u),B=!0),await A.vault.createBinary(b,S.buffer),p++}let w=0;for(let Q of l){let v=Q.fm.id;if(!v){g.push(`Skipped ${Q.originalName} \u2014 no id in frontmatter`);continue}let E=c.get(v),S=Q.fm.parent??null,D=S;!S||S===k?D=i.reparentRootsTo??S??k:c.has(S)?D=c.get(S):D=e.has(S)?S:i.reparentRootsTo??k;let H=Dc(Q.body,I,u),U={...Q.fm,id:E,parent:D,import_date:h};Array.isArray(U.attachments)&&(U.attachments=U.attachments.map(P=>{let R=Ca(be(P));return $t(I.get(R)??`${u}/${R}`)}));let N=ve(U,H),b=E===v?Q.originalName:Mc(Q.originalName,v,E),T=`${t}/${b}`;await A.vault.adapter.exists(T)&&(b=`${b.replace(/\.md$/,"")}-${W(4)}.md`,T=`${t}/${b}`),await A.vault.create(T,N),w++}let y;if(o.colorAliases&&typeof o.colorAliases=="object"){let Q={};for(let[v,E]of Object.entries(o.colorAliases)){let S=String(v).trim().toLowerCase(),D=String(E??"").trim();/^#([0-9a-f]{6})$/.test(S)&&D&&(Q[S]=D.slice(0,60))}Object.keys(Q).length&&(y=Q)}return{notesWritten:w,attachmentsWritten:p,collisionsRenamed:d,warnings:g,colorAliases:y,idRemap:Object.fromEntries(c)}}function kc(A){let a=new Set,t=[];for(let e of A)a.has(e.id)||(a.add(e.id),t.push(e));return t}function ma(A){let a=new Set,t;for(Fo.lastIndex=0;(t=Fo.exec(A))!==null;)a.add(t[1]);return[...a]}async function Ws(A,a){let t=await A.vault.read(a),e=[],i=new Set;for(let s of ma(t)){let n=A.metadataCache.getFirstLinkpathDest(s,a.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Sc(A,a,t){return A.replace(new RegExp(`!\\[\\[${Nc(a)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function bc(A,a){let t=A.lastIndexOf(".");return t>0?`${A.slice(0,t)}-${a}${A.slice(t)}`:`${A}-${a}`}function Dc(A,a,t){return A.replace(Fo,(e,i,s)=>{if(i.includes("/"))return e;let n=a.get(i)??`${t}/${i}`;return e.replace(i,n)})}function xc(A,a,t){let e=dt(A);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return A;let i=e.fm.attachments.map(n=>{let o=a.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:Ca(n)}),s={...e.fm,attachments:i};return ve(s,e.body)}function Nc(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ca(A){let a=A.lastIndexOf("/");return a<0?A:A.slice(a+1)}function Mc(A,a,t){return A.includes(a)?A.replace(a,t):A.replace(/\.md$/,`-${t}.md`)}function dt(A){if(!A.startsWith("---"))return{fm:{},body:A};let a=A.indexOf(` ----`,3);if(a<0)return{fm:{},body:A};let t=A.slice(3,a).replace(/^\n/,""),e=A.slice(a+4),i={};try{i=(0,zs.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` -`)?e.slice(1):e;return{fm:i,body:s}}function ve(A,a){return`--- -${(0,zs.stringifyYaml)(A).trimEnd()} +`):s[a.idx].code;await navigator.clipboard.writeText(l),A.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${A.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${A.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:A.noteFolder})}}(A.app);o.setPlaceholder(`${s.length} codeblocks in "${A.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function ja(A){let r=A.getActionTargets();if(r.length===0){let n=A.tree.get(A.focusId);n?.file&&(r=[n])}if(r.length===0){new di.Notice("Nothing to copy.");return}let t=X().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await A.app.vault.cachedRead(n.file),l=A.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),c=t?`${A.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${c}${l}`)}for(let a of A.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),A.plugin.clearNoteClipboard(),A.plugin.noteClipboard={mode:"copy",folder:A.noteFolder,ids:r.map(n=>n.id),text:s},A.render(),A.plugin.notifications.show({message:`Copied tree of ${A.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:A.noteFolder})}async function _a(A){let r=A.getActionTargets();if(r.length===0){let i=A.tree.get(A.focusId);i?.file&&(r=[i])}if(r.length===0){new di.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 A.tree.getChildren(i.id))e(o,s+1)};for(let i of r)e(i,0);await navigator.clipboard.writeText(t.join(` +`)),A.plugin.notifications.show({message:`Copied outline of ${A.titleList(r)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:r.map(i=>i.id),folder:A.noteFolder})}var Bt=require("obsidian");at();var js=require("obsidian");Zs();Gt();at();var te="stash",Cr=1;function Ir(A){let t=(A.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var Do=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Ee(A,r){let t=[],e=bc([...r.rootNotes,...r.allDescendants]),i=new Map,s=[];for(let o of e){let a=await A.vault.read(o.file),l=a,c=Br(a);for(let d of c){let h=A.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 A.vault.readBinary(h)),l=Dc(l,d,g)}l=Mc(l,A,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:Cr,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(` +`)}),hi(t,6)}async function ee(A,r,t,e,i={}){let s=await pi(r),n=s["manifest.json"];if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(Xs(n));if(typeof o.stashSchema!="number"||o.stashSchema>Cr)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await mr(A,t);let a=Object.entries(s).filter(([Q])=>Q.startsWith("notes/")&&Q.endsWith(".md")),l=[];for(let[Q,v]of a){let E=Xs(v),{fm:S,body:D}=dt(E),H=Ir(Q.slice(6))||`${S.id||"imported-"+W(4)}.md`;l.push({originalName:H,fm:S,body:D})}let c=new Map,d=0;for(let Q of l){let v=Q.fm.id;v&&(i.forceNewIds?c.set(v,W(6)):e.has(v)||c.has(v)?(c.set(v,`${v}-${W(4)}-Imported`),d++):c.set(v,v))}let h=new Date().toISOString(),g=[],u=`${t}/_attachments`,p=0,f=Object.entries(s).filter(([Q])=>Q.startsWith("attachments/")),I=new Map,m=null;if(i.dedupeExisting){m=new Map;for(let Q of A.vault.getFiles())m.has(Q.name)||m.set(Q.name,Q.path)}let C=(Q,v)=>{if(Q.length!==v.length)return!1;for(let E=0;E<Q.length;E++)if(Q[E]!==v[E])return!1;return!0},B=!1;for(let[Q,v]of f){let E=Ir(Q.slice(12));if(!E)continue;let S=v,D=[],H=m?.get(E);H&&D.push(H);let U=`${u}/${E}`;await A.vault.adapter.exists(U)&&D.push(U);let N=null;for(let T of D)try{if(C(new Uint8Array(await A.vault.adapter.readBinary(T)),S)){N=T;break}}catch{}if(N){I.set(E,N);continue}let b=U;for(let T=1;await A.vault.adapter.exists(b);T++)b=`${u}/${xc(E,T)}`;I.set(E,b),B||(await mr(A,u),B=!0),await A.vault.createBinary(b,S.buffer),p++}let w=0;for(let Q of l){let v=Q.fm.id;if(!v){g.push(`Skipped ${Q.originalName} \u2014 no id in frontmatter`);continue}let E=c.get(v),S=Q.fm.parent??null,D=S;!S||S===k?D=i.reparentRootsTo??S??k:c.has(S)?D=c.get(S):D=e.has(S)?S:i.reparentRootsTo??k;let H=Nc(Q.body,I,u),U={...Q.fm,id:E,parent:D,import_date:h};Array.isArray(U.attachments)&&(U.attachments=U.attachments.map(P=>{let R=yr(be(P));return $t(I.get(R)??`${u}/${R}`)}));let N=ve(U,H),b=E===v?Q.originalName:Pc(Q.originalName,v,E),T=`${t}/${b}`;await A.vault.adapter.exists(T)&&(b=`${b.replace(/\.md$/,"")}-${W(4)}.md`,T=`${t}/${b}`),await A.vault.create(T,N),w++}let y;if(o.colorAliases&&typeof o.colorAliases=="object"){let Q={};for(let[v,E]of Object.entries(o.colorAliases)){let S=String(v).trim().toLowerCase(),D=String(E??"").trim();/^#([0-9a-f]{6})$/.test(S)&&D&&(Q[S]=D.slice(0,60))}Object.keys(Q).length&&(y=Q)}return{notesWritten:w,attachmentsWritten:p,collisionsRenamed:d,warnings:g,colorAliases:y,idRemap:Object.fromEntries(c)}}function bc(A){let r=new Set,t=[];for(let e of A)r.has(e.id)||(r.add(e.id),t.push(e));return t}function Br(A){let r=new Set,t;for(Do.lastIndex=0;(t=Do.exec(A))!==null;)r.add(t[1]);return[...r]}async function _s(A,r){let t=await A.vault.read(r),e=[],i=new Set;for(let s of Br(t)){let n=A.metadataCache.getFirstLinkpathDest(s,r.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Dc(A,r,t){return A.replace(new RegExp(`!\\[\\[${Tc(r)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function xc(A,r){let t=A.lastIndexOf(".");return t>0?`${A.slice(0,t)}-${r}${A.slice(t)}`:`${A}-${r}`}function Nc(A,r,t){return A.replace(Do,(e,i,s)=>{if(i.includes("/"))return e;let n=r.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Mc(A,r,t){let e=dt(A);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return A;let i=e.fm.attachments.map(n=>{let o=r.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:yr(n)}),s={...e.fm,attachments:i};return ve(s,e.body)}function Tc(A){return A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yr(A){let r=A.lastIndexOf("/");return r<0?A:A.slice(r+1)}function Pc(A,r,t){return A.includes(r)?A.replace(r,t):A.replace(/\.md$/,`-${t}.md`)}function dt(A){if(!A.startsWith("---"))return{fm:{},body:A};let r=A.indexOf(` +---`,3);if(r<0)return{fm:{},body:A};let t=A.slice(3,r).replace(/^\n/,""),e=A.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 ve(A,r){return`--- +${(0,js.stringifyYaml)(A).trimEnd()} --- -${a}`}async function fa(A,a){if(!(!a||await A.vault.adapter.exists(a)))try{await A.vault.createFolder(a)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}ls();kt();Vs();var Dt="stashenc",Ba="stashmeta";function Rt(A){return A.replace(/\.stashenc$/,`.${Ba}`)}async function js(A,a){try{return JSON.parse(await A.vault.adapter.read(Rt(a)))}catch{return null}}async function Fe(A,a,t){let e=a.replace(/\/+$/,""),i=[];for(let c of A.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let d;try{d=dt(await A.vault.read(c)).fm}catch{continue}typeof d.id=="string"&&i.push({id:d.id,file:c,parent:typeof d.parent=="string"?d.parent:null,created:typeof d.created=="string"?d.created:""})}let s=i.find(c=>c.id===t);if(!s)return null;let n=new Map;for(let c of i){if(!c.parent)continue;let d=n.get(c.parent)??[];d.push(c),n.set(c.parent,d)}let o=[],r=new Set([t]),l=[t];for(;l.length;){let c=[];for(let d of l)for(let h of n.get(d)??[])r.has(h.id)||(r.add(h.id),o.push(h),c.push(h.id));l=c}return{rootNote:s,descendants:o,parentId:s.parent}}function Xs(A){if(!A)return null;let a=A.replace(/\/+$/,"");return!a||a.startsWith("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a)||a.split("/").some(t=>t===".."||t===".")?null:a}async function pi(A,a,t){await A.vault.adapter.writeBinary(a,t);let e;try{e=new Uint8Array(await A.vault.adapter.readBinary(a))}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 A.vault.adapter.remove(a)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function Zs(A){return A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||A.basename}function qe(A){return(A.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function ya(A,a,t){let e=new Set(a.map(r=>r.file.path)),i=new Map;for(let r of a)for(let l of await Ws(A,r.file))i.set(l.path,l);let s=new Set,n=A.metadataCache.resolvedLinks??{};for(let r of Object.keys(n))if(!e.has(r))for(let l of Object.keys(n[r]??{}))i.has(l)&&s.add(l);let o=[];for(let r of a){let l=t?.get(r.file.path);if(l!=null)try{let c=await A.vault.adapter.stat(r.file.path);if(c&&c.mtime!==l){console.warn("[Stashpad] note changed since it was bundled \u2014 keeping plaintext",r.file.path),o.push(r.file.path);continue}}catch{}try{await A.vault.delete(r.file)}catch(c){console.warn("[Stashpad] couldn't delete plaintext note",r.file.path,c),o.push(r.file.path)}}for(let[r,l]of i)if(!s.has(r))try{await A.vault.delete(l)}catch(c){console.warn("[Stashpad] couldn't delete exclusive attachment",r,c),o.push(r)}return{unpurged:o}}async function wa(A,a,t,e,i=null,s=!1,n){let o=await Fe(A,a,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:r,descendants:l,parentId:c}=o,d=[r,...l],h=new Map;for(let y of d)try{let Q=await A.vault.adapter.stat(y.file.path);Q&&h.set(y.file.path,Q.mtime)}catch{}let g=await Ee(A,{rootNotes:[{id:r.id,file:r.file}],allDescendants:l.map(y=>({id:y.id,file:y.file})),sourceFolder:a}),u=await Ce(g,e),p=await Qt(u,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size mismatch).");for(let y=0;y<g.length;y++)if(p[y]!==g[y])throw new Error("Encryption self-check failed (content mismatch).");let f=(n??a).replace(/\/+$/,"");n&&!await A.vault.adapter.exists(f)&&await A.vault.adapter.mkdir(f);let I=qe(s?t:Zs(r.file)),m=`${f}/${I}.${Dt}`;for(let y=1;await A.vault.adapter.exists(m);y++)m=`${f}/${I} (${y}).${Dt}`;await pi(A,m,u);let C=d,B={v:1,parentId:c,title:s?"":Zs(r.file),count:C.length,created:r.created,rootId:t,prevSibling:i};try{await A.vault.adapter.write(Rt(m),JSON.stringify(B))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:w}=await ya(A,C,h);return{blobPath:m,noteCount:C.length,rootId:t,parentId:c,title:B.title,created:r.created,unpurged:w}}async function Qa(A,a,t,e,i){let s=new Uint8Array(await A.vault.adapter.readBinary(a));if(!xt(s))throw new Error("Not an encrypted bundle.");let n=await Qt(s,t),o=Xs(i)??a.replace(/\/[^/]*$/,""),r=await ee(A,n,o,e,{dedupeExisting:!0});await A.vault.adapter.remove(a);try{await A.vault.adapter.remove(Rt(a))}catch{}return{notesWritten:r.notesWritten,restoredTo:o}}var Ht="_deleted";function Ea(A){let a="";for(let t=0;t<A.length;t++)a+=String.fromCharCode(A[t]);return btoa(a)}function va(A){let a=atob(A),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}async function ko(A,a,t,e){let i=Xs(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=Xs(new TextDecoder().decode(await Qt(va(t.originalFolderEnc),e)))}catch{i=null}if(i)return await A.vault.adapter.exists(i)||await A.vault.adapter.mkdir(i),i;let s=a.replace(/\/[^/]*$/,"");if(s===Ht||s.startsWith(`${Ht}/`))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 Fa(A,a,t,e,i,s=!1,n){let o=await Fe(A,a,t);if(!o)throw new Error("Couldn't find that note to delete.");let{rootNote:r,descendants:l,parentId:c}=o,d=[r,...l],h=new Map;for(let Q of d)try{let v=await A.vault.adapter.stat(Q.file.path);v&&h.set(Q.file.path,v.mtime)}catch{}let g=await Ee(A,{rootNotes:[{id:r.id,file:r.file}],allDescendants:l.map(Q=>({id:Q.id,file:Q.file})),sourceFolder:a}),u=await Ce(g,e),p=await Qt(u,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let Q=0;Q<g.length;Q++)if(p[Q]!==g[Q])throw new Error("Encryption self-check failed (content).");await A.vault.adapter.exists(Ht)||await A.vault.adapter.mkdir(Ht);let f=a.replace(/\/+$/,""),I=f.split("/").pop()||"vault",m=qe(s?t:`${I} ${Zs(r.file)}`),C=`${Ht}/${m}.${Dt}`;for(let Q=1;await A.vault.adapter.exists(C);Q++)C=`${Ht}/${m} (${Q}).${Dt}`;await pi(A,C,u);let B=d,w={v:1,kind:"deleted",originalFolder:s?"":f,...s?{originalFolderEnc:Ea(await Ce(new TextEncoder().encode(f),e))}:{},parentId:c,title:s?"":Zs(r.file),count:B.length,created:r.created,rootId:t,deletedAt:i,...n?{keyId:n}:{}};try{await A.vault.adapter.write(Rt(C),JSON.stringify(w))}catch(Q){console.warn("[Stashpad] couldn't write deleted sidecar",Q)}let{unpurged:y}=await ya(A,B,h);return{blobPath:C,noteCount:B.length,rootId:t,originalFolder:f,title:w.title,unpurged:y}}async function ka(A,a,t,e){let i=new Uint8Array(await A.vault.adapter.readBinary(a));if(!xt(i))throw new Error("Not an encrypted bundle.");let s=await he(A,a),n=await ko(A,a,s,t),o=await Qt(i,t),r=await ee(A,o,n,e,{dedupeExisting:!0});await A.vault.adapter.remove(a);try{await A.vault.adapter.remove(Rt(a))}catch{}return{notesWritten:r.notesWritten,restoredTo:n}}async function he(A,a){try{return JSON.parse(await A.vault.adapter.read(Rt(a)))}catch{return null}}async function So(A,a){await A.vault.adapter.remove(a);try{await A.vault.adapter.remove(Rt(a))}catch{}}var Ut=".trash";async function _s(A,a){let t=[],e=[a];for(;e.length;){let i=e.shift(),s;try{s=await A.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function Sa(A){let a=A.split("/").filter(Boolean);if(a.length===0)return null;for(let t of a)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return a.join("/")}async function ba(A,a,t,e=!1){if(!await A.vault.adapter.exists(Ut))return null;let i=await _s(A,Ut);if(i.length===0)return null;let s=[],n=new Map;for(let u of i){let p=u.slice(Ut.length+1);s.push({name:`files/${p}`,data:await A.vault.adapter.readBinary(u)});try{let f=await A.vault.adapter.stat(u);f&&n.set(u,f.mtime)}catch{}}let o=await di(s),r=await Ce(o,a),l=await Qt(r,a);if(l.length!==o.length)throw new Error("Encryption self-check failed (size).");for(let u=0;u<o.length;u++)if(l[u]!==o[u])throw new Error("Encryption self-check failed (content).");await A.vault.adapter.exists(Ht)||await A.vault.adapter.mkdir(Ht);let c=qe(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),d=`${Ht}/${c}.${Dt}`;for(let u=1;await A.vault.adapter.exists(d);u++)d=`${Ht}/${c} (${u}).${Dt}`;await pi(A,d,r);let h={v:1,kind:"rawtrash",originalFolder:Ut,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await A.vault.adapter.write(Rt(d),JSON.stringify(h))}catch(u){console.warn("[Stashpad] couldn't write backfill sidecar",u)}let g=[];for(let u of i){let p=n.get(u);try{if(p!=null){let f=await A.vault.adapter.stat(u);if(f&&f.mtime!==p){g.push(u);continue}}await A.vault.adapter.remove(u)}catch(f){console.warn("[Stashpad] couldn't delete trash file",u,f),g.push(u)}}return{blobPath:d,fileCount:i.length,unpurged:g}}async function Da(A,a,t){let e=new Uint8Array(await A.vault.adapter.readBinary(a));if(!xt(e))throw new Error("Not an encrypted bundle.");let i=await Qt(e,t),s=await hi(i),n=0;for(let[o,r]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 c=`${Ut}/${l}`.split("/").slice(0,-1).join("/"),d="";for(let g of c.split("/"))d=d?`${d}/${g}`:g,await A.vault.adapter.exists(d)||await A.vault.adapter.mkdir(d);let h=`${Ut}/${l}`;for(let g=1;await A.vault.adapter.exists(h);g++)h=`${Ut}/${l.replace(/(\.[^./]*)?$/,` (${g})$1`)}`;await A.vault.adapter.writeBinary(h,r.buffer),n++}await A.vault.adapter.remove(a);try{await A.vault.adapter.remove(Rt(a))}catch{}return{filesWritten:n}}async function xa(A,a,t,e){let i=new Uint8Array(await A.vault.adapter.readBinary(a));if(!xt(i))throw new Error(`Not an encrypted blob: ${a}`);let s=await Qt(i,t);try{let n=await Ce(s,e),o=await Qt(n,e);if(o.length!==s.length)throw new Error("Rotation self-check failed (size).");for(let r=0;r<s.length;r++)if(o[r]!==s[r])throw new Error("Rotation self-check failed (content).");await pi(A,`${a}.rot`,n)}finally{s.fill(0)}}async function Na(A,a,t,e){let i=await he(A,a);if(!i?.originalFolderEnc)return;let s=await Qt(va(i.originalFolderEnc),t);try{i.originalFolderEnc=Ea(await Ce(s,e))}finally{s.fill(0)}await A.vault.adapter.write(Rt(a),JSON.stringify(i))}async function bo(A,a){let t=[];for(let e of await sn(A))(await he(A,e))?.keyId===a&&t.push(e);return t}async function tn(A,a){let t=`${a}.rot`;if(!await A.vault.adapter.exists(t))return;let e=new Uint8Array(await A.vault.adapter.readBinary(t));await pi(A,a,e);try{await A.vault.adapter.remove(t)}catch{}}async function en(A,a){let t=a.replace(/\/+$/,"");for(let e of await _s(A,t))if(e.endsWith(`.${Dt}.rot`))try{await A.vault.adapter.remove(e)}catch{}}async function Ma(A,a){let t=a.replace(/\/+$/,"");return(await _s(A,t)).filter(e=>e.endsWith(`.${Dt}.rot`)).map(e=>e.replace(/\.rot$/,""))}async function Ta(A,a,t,e,i){let s=a.replace(/\/+$/,""),n=(await _s(A,s)).filter(f=>!f.endsWith(`.${Dt}`)&&!f.endsWith(`.${Ba}`));if(n.length===0)throw new Error("This folder has no files to encrypt.");let o=[],r=new Map;for(let f of n){o.push({name:`files/${f.slice(s.length+1)}`,data:await A.vault.adapter.readBinary(f)});try{let I=await A.vault.adapter.stat(f);I&&r.set(f,I.mtime)}catch{}}let l=await di(o),c=await Ce(l,t),d=await Qt(c,t);if(d.length!==l.length)throw new Error("Encryption self-check failed (size).");for(let f=0;f<l.length;f++)if(d[f]!==l[f])throw new Error("Encryption self-check failed (content).");let h=qe(s.split("/").pop()||"folder"),g=`${s}/${h}.${Dt}`;for(let f=1;await A.vault.adapter.exists(g);f++)g=`${s}/${h} (${f}).${Dt}`;await pi(A,g,c);let u={v:1,kind:"rawfolder",originalFolder:s,parentId:null,title:s.split("/").pop()||"",count:n.length,created:i,rootId:"",deletedAt:i,...e?{keyId:e}:{}};try{await A.vault.adapter.write(Rt(g),JSON.stringify(u))}catch(f){console.warn("[Stashpad] couldn't write rawfolder sidecar",f)}let p=[];for(let f of n){let I=r.get(f);try{if(I!=null){let m=await A.vault.adapter.stat(f);if(m&&m.mtime!==I){p.push(f);continue}}await A.vault.adapter.remove(f)}catch(m){console.warn("[Stashpad] couldn't delete file",f,m),p.push(f)}}if(p.length===0){let f=[...new Set(n.map(I=>I.slice(0,I.lastIndexOf("/"))))].filter(I=>I.length>s.length).sort((I,m)=>m.length-I.length);for(let I of f)try{let m=await A.vault.adapter.list(I);!m.files.length&&!m.folders.length&&await A.vault.adapter.rmdir(I,!0)}catch{}}return{blobPath:g,fileCount:n.length,unpurged:p}}async function Pa(A,a,t){let e=new Uint8Array(await A.vault.adapter.readBinary(a));if(!xt(e))throw new Error("Not an encrypted bundle.");let i=await he(A,a),s=Xs(i?.originalFolder)??a.replace(/\/[^/]*$/,""),n=await Qt(e,t),o=await hi(n),r=0;for(let[l,c]of Object.entries(o)){if(!l.startsWith("files/"))continue;let d=Sa(l.slice(6));if(!d){console.warn("[Stashpad] skipped unsafe folder entry",l);continue}let h=`${s}/${d}`.split("/").slice(0,-1).join("/"),g="";for(let p of h.split("/"))g=g?`${g}/${p}`:p,g&&!await A.vault.adapter.exists(g)&&await A.vault.adapter.mkdir(g);let u=`${s}/${d}`;for(let p=1;await A.vault.adapter.exists(u);p++)u=`${s}/${d.replace(/(\.[^./]*)?$/,` (${p})$1`)}`;await A.vault.adapter.writeBinary(u,c.buffer),r++}await A.vault.adapter.remove(a);try{await A.vault.adapter.remove(Rt(a))}catch{}return{filesWritten:r,folder:s}}async function Do(A,a){let t=a.replace(/\/+$/,"");try{let e=await A.vault.adapter.list(t);for(let i of e.files){if(!i.endsWith(`.${Dt}`))continue;if((await he(A,i))?.kind==="rawfolder")return i}}catch{}return null}async function Ha(A){let a=[];for(let t of A.vault.getFiles())if(t.extension===Dt)try{(await he(A,t.path))?.kind==="rawfolder"&&a.push({folder:t.parent?.path?.replace(/\/+$/,"")??"",blobPath:t.path})}catch{}return a}async function sn(A){if(!await A.vault.adapter.exists(Ht))return[];try{return(await A.vault.adapter.list(Ht)).files.filter(t=>t.endsWith(`.${Dt}`))}catch{return[]}}function Ua(A){return A.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function Ra(A,a){let t=qa(A,a);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Ka(A,t);if(e.length===0){new Bt.Notice("No exportable notes (no files attached).");return}let i=(A.noteFolder.split("/").pop()||A.noteFolder).trim(),s=t.length===1?A.titleForNode(t[0]):`${i}-${t.length}notes`;new Xe(A.app,s,e.length,(n,o,r)=>{Pc(A,t,e,n,o,r)},Ji).open()}async function Ga(A,a){let t=a.replace(/\/[^/]*$/,"").replace(/\/+$/,""),e=await A.ensureFolderUnlocked(t);if(!e)return;let i;try{let l=new Uint8Array(await A.app.vault.adapter.readBinary(a));i=await Qt(l,e)}catch(l){new Bt.Notice(`Couldn't decrypt this note to export it: ${l.message}`);return}finally{e.fill(0)}let s=await js(A.app,a),n=(A.settings.lockedSubtrees??[]).find(l=>l.blob===a),o=n?.title||s?.title||"locked-note",r=n?.count??s?.count??1;new Xe(A.app,o,r,(l,c,d)=>{Tc(A,t,l,i,c,d)},Ji).open()}async function Tc(A,a,t,e,i,s=!1){try{let n=e,o="";if(i){let u=await Wt(n,i);n=u.data;let p=jn[u.kdf];o=p.strong?` (encrypted \xB7 ${p.label})`:` (encrypted \xB7 ${p.label} \u2014 Argon2id unavailable here, weaker)`}let r=(0,Bt.moment)().format("YYYYMMDD-HHmmss"),c=(A.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,"").split("/").filter(u=>u&&u!=="."&&u!==".."&&!/[\\:]/.test(u)).join("/")||"_exports",d=`${a}/${c}`;await A.app.vault.adapter.exists(d)||await A.app.vault.adapter.mkdir(d);let h=`${Ua(t)}-${r}`,g=`${d}/${h}.${te}`;if(await A.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i)try{A.app.secretStorage?.setSecret(Ve(h),i)}catch(u){console.warn("[Stashpad] couldn't save export passphrase",u)}new Bt.Notice(`Exported encrypted note${o} \u2192 ${g}`,0)}catch(n){new Bt.Notice(`Export failed: ${n.message}`),console.error(n)}finally{try{e.fill(0)}catch{}}}async function La(A,a){let t=qa(A,a);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Ka(A,t);if(e.length===0){new Bt.Notice("No exportable notes.");return}let i=(A.noteFolder.split("/").pop()||A.noteFolder).trim(),s=t.length===1?A.titleForNode(t[0]):`${i}-okf`;new Ti(A.app,s,e.length,(n,o)=>{(async()=>{try{let r=await A.plugin.exportOkf(A.noteFolder,t.map(l=>l.id),n,o);if(!r.length){new Bt.Notice("Nothing exported.");return}A.plugin.notifications.show({message:`Exported OKF \u2014 ${r.length} file${r.length===1?"":"s"} \u2192 \`${A.noteFolder}/${A.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:r,folder:A.noteFolder,duration:0}),await A.log.append({type:"stash_export",id:t[0].id,payload:{okf:!0,paths:r,noteCount:e.length,rootIds:t.map(l=>l.id)}})}catch(r){new Bt.Notice(`OKF export failed: ${r.message}`),console.error(r)}})()}).open()}async function Pc(A,a,t,e,i,s=!1){try{let n=await Ee(A.app,{rootNotes:a.filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),allDescendants:t.filter(u=>!a.some(p=>p.id===u.id)).filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),sourceFolder:A.noteFolder}),o="";if(i){let u=await Wt(n,i);n=u.data;let p=jn[u.kdf];o=p.strong?` (encrypted \xB7 ${p.label})`:` (encrypted \xB7 ${p.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let r=(0,Bt.moment)().format("YYYYMMDD-HHmmss"),l=Ua(e),c=(A.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),d=`${A.noteFolder}/${c}`;await A.ensureFolder(d);let h=`${l}-${r}`,g=`${d}/${h}.${te}`;if(await A.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let u=A.app.secretStorage;try{u?.setSecret(Ve(h),i)}catch(p){console.warn("[Stashpad] couldn't save export passphrase to secret storage",p)}}await A.log.append({type:"stash_export",id:a[0].id,payload:{path:g,noteCount:t.length,rootIds:a.map(u=>u.id)}}),A.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:A.noteFolder,actions:A.actionsForFile(g),duration:0})}catch(n){A.plugin.notifications.show({message:`Stashpad: export failed +${r}`}async function mr(A,r){if(!(!r||await A.vault.adapter.exists(r)))try{await A.vault.createFolder(r)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}ds();kt();Zs();var Dt="stashenc",wr="stashmeta";function Rt(A){return A.replace(/\.stashenc$/,`.${wr}`)}async function sn(A,r){try{return JSON.parse(await A.vault.adapter.read(Rt(r)))}catch{return null}}async function Fe(A,r,t){let e=r.replace(/\/+$/,""),i=[];for(let c of A.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let d;try{d=dt(await A.vault.read(c)).fm}catch{continue}typeof d.id=="string"&&i.push({id:d.id,file:c,parent:typeof d.parent=="string"?d.parent:null,created:typeof d.created=="string"?d.created:""})}let s=i.find(c=>c.id===t);if(!s)return null;let n=new Map;for(let c of i){if(!c.parent)continue;let d=n.get(c.parent)??[];d.push(c),n.set(c.parent,d)}let o=[],a=new Set([t]),l=[t];for(;l.length;){let c=[];for(let d of l)for(let h of n.get(d)??[])a.has(h.id)||(a.add(h.id),o.push(h),c.push(h.id));l=c}return{rootNote:s,descendants:o,parentId:s.parent}}function tn(A){if(!A)return null;let r=A.replace(/\/+$/,"");return!r||r.startsWith("/")||r.includes("\\")||/^[a-zA-Z]:/.test(r)||r.split("/").some(t=>t===".."||t===".")?null:r}async function gi(A,r,t){await A.vault.adapter.writeBinary(r,t);let e;try{e=new Uint8Array(await A.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 A.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 en(A){return A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||A.basename}function Ke(A){return(A.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function Qr(A,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 _s(A,a.file))i.set(l.path,l);let s=new Set,n=A.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 c=await A.vault.adapter.stat(a.file.path);if(c&&c.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 A.vault.delete(a.file)}catch(c){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,c),o.push(a.file.path)}}for(let[a,l]of i)if(!s.has(a))try{await A.vault.delete(l)}catch(c){console.warn("[Stashpad] couldn't delete exclusive attachment",a,c),o.push(a)}return{unpurged:o}}async function Er(A,r,t,e,i=null,s=!1,n){let o=await Fe(A,r,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:l,parentId:c}=o,d=[a,...l],h=new Map;for(let y of d)try{let Q=await A.vault.adapter.stat(y.file.path);Q&&h.set(y.file.path,Q.mtime)}catch{}let g=await Ee(A,{rootNotes:[{id:a.id,file:a.file}],allDescendants:l.map(y=>({id:y.id,file:y.file})),sourceFolder:r}),u=await Ce(g,e),p=await Qt(u,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size mismatch).");for(let y=0;y<g.length;y++)if(p[y]!==g[y])throw new Error("Encryption self-check failed (content mismatch).");let f=(n??r).replace(/\/+$/,"");n&&!await A.vault.adapter.exists(f)&&await A.vault.adapter.mkdir(f);let I=Ke(s?t:en(a.file)),m=`${f}/${I}.${Dt}`;for(let y=1;await A.vault.adapter.exists(m);y++)m=`${f}/${I} (${y}).${Dt}`;await gi(A,m,u);let C=d,B={v:1,parentId:c,title:s?"":en(a.file),count:C.length,created:a.created,rootId:t,prevSibling:i};try{await A.vault.adapter.write(Rt(m),JSON.stringify(B))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:w}=await Qr(A,C,h);return{blobPath:m,noteCount:C.length,rootId:t,parentId:c,title:B.title,created:a.created,unpurged:w}}async function vr(A,r,t,e,i){let s=new Uint8Array(await A.vault.adapter.readBinary(r));if(!xt(s))throw new Error("Not an encrypted bundle.");let n=await Qt(s,t),o=tn(i)??r.replace(/\/[^/]*$/,""),a=await ee(A,n,o,e,{dedupeExisting:!0});await A.vault.adapter.remove(r);try{await A.vault.adapter.remove(Rt(r))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ht="_deleted";function Fr(A){let r="";for(let t=0;t<A.length;t++)r+=String.fromCharCode(A[t]);return btoa(r)}function kr(A){let r=atob(A),t=new Uint8Array(r.length);for(let e=0;e<r.length;e++)t[e]=r.charCodeAt(e);return t}async function xo(A,r,t,e){let i=tn(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=tn(new TextDecoder().decode(await Qt(kr(t.originalFolderEnc),e)))}catch{i=null}if(i)return await A.vault.adapter.exists(i)||await A.vault.adapter.mkdir(i),i;let s=r.replace(/\/[^/]*$/,"");if(s===Ht||s.startsWith(`${Ht}/`))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 Sr(A,r,t,e,i,s=!1,n){let o=await Fe(A,r,t);if(!o)throw new Error("Couldn't find that note to delete.");let{rootNote:a,descendants:l,parentId:c}=o,d=[a,...l],h=new Map;for(let Q of d)try{let v=await A.vault.adapter.stat(Q.file.path);v&&h.set(Q.file.path,v.mtime)}catch{}let g=await Ee(A,{rootNotes:[{id:a.id,file:a.file}],allDescendants:l.map(Q=>({id:Q.id,file:Q.file})),sourceFolder:r}),u=await Ce(g,e),p=await Qt(u,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let Q=0;Q<g.length;Q++)if(p[Q]!==g[Q])throw new Error("Encryption self-check failed (content).");await A.vault.adapter.exists(Ht)||await A.vault.adapter.mkdir(Ht);let f=r.replace(/\/+$/,""),I=f.split("/").pop()||"vault",m=Ke(s?t:`${I} ${en(a.file)}`),C=`${Ht}/${m}.${Dt}`;for(let Q=1;await A.vault.adapter.exists(C);Q++)C=`${Ht}/${m} (${Q}).${Dt}`;await gi(A,C,u);let B=d,w={v:1,kind:"deleted",originalFolder:s?"":f,...s?{originalFolderEnc:Fr(await Ce(new TextEncoder().encode(f),e))}:{},parentId:c,title:s?"":en(a.file),count:B.length,created:a.created,rootId:t,deletedAt:i,...n?{keyId:n}:{}};try{await A.vault.adapter.write(Rt(C),JSON.stringify(w))}catch(Q){console.warn("[Stashpad] couldn't write deleted sidecar",Q)}let{unpurged:y}=await Qr(A,B,h);return{blobPath:C,noteCount:B.length,rootId:t,originalFolder:f,title:w.title,unpurged:y}}async function br(A,r,t,e){let i=new Uint8Array(await A.vault.adapter.readBinary(r));if(!xt(i))throw new Error("Not an encrypted bundle.");let s=await he(A,r),n=await xo(A,r,s,t),o=await Qt(i,t),a=await ee(A,o,n,e,{dedupeExisting:!0});await A.vault.adapter.remove(r);try{await A.vault.adapter.remove(Rt(r))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function he(A,r){try{return JSON.parse(await A.vault.adapter.read(Rt(r)))}catch{return null}}async function No(A,r){await A.vault.adapter.remove(r);try{await A.vault.adapter.remove(Rt(r))}catch{}}var Ut=".trash";async function nn(A,r){let t=[],e=[r];for(;e.length;){let i=e.shift(),s;try{s=await A.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function Dr(A){let r=A.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 xr(A,r,t,e=!1){if(!await A.vault.adapter.exists(Ut))return null;let i=await nn(A,Ut);if(i.length===0)return null;let s=[],n=new Map;for(let u of i){let p=u.slice(Ut.length+1);s.push({name:`files/${p}`,data:await A.vault.adapter.readBinary(u)});try{let f=await A.vault.adapter.stat(u);f&&n.set(u,f.mtime)}catch{}}let o=await hi(s),a=await Ce(o,r),l=await Qt(a,r);if(l.length!==o.length)throw new Error("Encryption self-check failed (size).");for(let u=0;u<o.length;u++)if(l[u]!==o[u])throw new Error("Encryption self-check failed (content).");await A.vault.adapter.exists(Ht)||await A.vault.adapter.mkdir(Ht);let c=Ke(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),d=`${Ht}/${c}.${Dt}`;for(let u=1;await A.vault.adapter.exists(d);u++)d=`${Ht}/${c} (${u}).${Dt}`;await gi(A,d,a);let h={v:1,kind:"rawtrash",originalFolder:Ut,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await A.vault.adapter.write(Rt(d),JSON.stringify(h))}catch(u){console.warn("[Stashpad] couldn't write backfill sidecar",u)}let g=[];for(let u of i){let p=n.get(u);try{if(p!=null){let f=await A.vault.adapter.stat(u);if(f&&f.mtime!==p){g.push(u);continue}}await A.vault.adapter.remove(u)}catch(f){console.warn("[Stashpad] couldn't delete trash file",u,f),g.push(u)}}return{blobPath:d,fileCount:i.length,unpurged:g}}async function Nr(A,r,t){let e=new Uint8Array(await A.vault.adapter.readBinary(r));if(!xt(e))throw new Error("Not an encrypted bundle.");let i=await Qt(e,t),s=await pi(i),n=0;for(let[o,a]of Object.entries(s)){if(!o.startsWith("files/"))continue;let l=Dr(o.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",o);continue}let c=`${Ut}/${l}`.split("/").slice(0,-1).join("/"),d="";for(let g of c.split("/"))d=d?`${d}/${g}`:g,await A.vault.adapter.exists(d)||await A.vault.adapter.mkdir(d);let h=`${Ut}/${l}`;for(let g=1;await A.vault.adapter.exists(h);g++)h=`${Ut}/${l.replace(/(\.[^./]*)?$/,` (${g})$1`)}`;await A.vault.adapter.writeBinary(h,a.buffer),n++}await A.vault.adapter.remove(r);try{await A.vault.adapter.remove(Rt(r))}catch{}return{filesWritten:n}}async function Mr(A,r,t,e){let i=new Uint8Array(await A.vault.adapter.readBinary(r));if(!xt(i))throw new Error(`Not an encrypted blob: ${r}`);let s=await Qt(i,t);try{let n=await Ce(s,e),o=await Qt(n,e);if(o.length!==s.length)throw new Error("Rotation self-check failed (size).");for(let a=0;a<s.length;a++)if(o[a]!==s[a])throw new Error("Rotation self-check failed (content).");await gi(A,`${r}.rot`,n)}finally{s.fill(0)}}async function Tr(A,r,t,e){let i=await he(A,r);if(!i?.originalFolderEnc)return;let s=await Qt(kr(i.originalFolderEnc),t);try{i.originalFolderEnc=Fr(await Ce(s,e))}finally{s.fill(0)}await A.vault.adapter.write(Rt(r),JSON.stringify(i))}async function Mo(A,r){let t=[];for(let e of await rn(A))(await he(A,e))?.keyId===r&&t.push(e);return t}async function on(A,r){let t=`${r}.rot`;if(!await A.vault.adapter.exists(t))return;let e=new Uint8Array(await A.vault.adapter.readBinary(t));await gi(A,r,e);try{await A.vault.adapter.remove(t)}catch{}}async function an(A,r){let t=r.replace(/\/+$/,"");for(let e of await nn(A,t))if(e.endsWith(`.${Dt}.rot`))try{await A.vault.adapter.remove(e)}catch{}}async function Pr(A,r){let t=r.replace(/\/+$/,"");return(await nn(A,t)).filter(e=>e.endsWith(`.${Dt}.rot`)).map(e=>e.replace(/\.rot$/,""))}async function Hr(A,r,t,e,i){let s=r.replace(/\/+$/,""),n=(await nn(A,s)).filter(f=>!f.endsWith(`.${Dt}`)&&!f.endsWith(`.${wr}`));if(n.length===0)throw new Error("This folder has no files to encrypt.");let o=[],a=new Map;for(let f of n){o.push({name:`files/${f.slice(s.length+1)}`,data:await A.vault.adapter.readBinary(f)});try{let I=await A.vault.adapter.stat(f);I&&a.set(f,I.mtime)}catch{}}let l=await hi(o),c=await Ce(l,t),d=await Qt(c,t);if(d.length!==l.length)throw new Error("Encryption self-check failed (size).");for(let f=0;f<l.length;f++)if(d[f]!==l[f])throw new Error("Encryption self-check failed (content).");let h=Ke(s.split("/").pop()||"folder"),g=`${s}/${h}.${Dt}`;for(let f=1;await A.vault.adapter.exists(g);f++)g=`${s}/${h} (${f}).${Dt}`;await gi(A,g,c);let u={v:1,kind:"rawfolder",originalFolder:s,parentId:null,title:s.split("/").pop()||"",count:n.length,created:i,rootId:"",deletedAt:i,...e?{keyId:e}:{}};try{await A.vault.adapter.write(Rt(g),JSON.stringify(u))}catch(f){console.warn("[Stashpad] couldn't write rawfolder sidecar",f)}let p=[];for(let f of n){let I=a.get(f);try{if(I!=null){let m=await A.vault.adapter.stat(f);if(m&&m.mtime!==I){p.push(f);continue}}await A.vault.adapter.remove(f)}catch(m){console.warn("[Stashpad] couldn't delete file",f,m),p.push(f)}}if(p.length===0){let f=[...new Set(n.map(I=>I.slice(0,I.lastIndexOf("/"))))].filter(I=>I.length>s.length).sort((I,m)=>m.length-I.length);for(let I of f)try{let m=await A.vault.adapter.list(I);!m.files.length&&!m.folders.length&&await A.vault.adapter.rmdir(I,!0)}catch{}}return{blobPath:g,fileCount:n.length,unpurged:p}}async function Ur(A,r,t){let e=new Uint8Array(await A.vault.adapter.readBinary(r));if(!xt(e))throw new Error("Not an encrypted bundle.");let i=await he(A,r),s=tn(i?.originalFolder)??r.replace(/\/[^/]*$/,""),n=await Qt(e,t),o=await pi(n),a=0;for(let[l,c]of Object.entries(o)){if(!l.startsWith("files/"))continue;let d=Dr(l.slice(6));if(!d){console.warn("[Stashpad] skipped unsafe folder entry",l);continue}let h=`${s}/${d}`.split("/").slice(0,-1).join("/"),g="";for(let p of h.split("/"))g=g?`${g}/${p}`:p,g&&!await A.vault.adapter.exists(g)&&await A.vault.adapter.mkdir(g);let u=`${s}/${d}`;for(let p=1;await A.vault.adapter.exists(u);p++)u=`${s}/${d.replace(/(\.[^./]*)?$/,` (${p})$1`)}`;await A.vault.adapter.writeBinary(u,c.buffer),a++}await A.vault.adapter.remove(r);try{await A.vault.adapter.remove(Rt(r))}catch{}return{filesWritten:a,folder:s}}async function To(A,r){let t=r.replace(/\/+$/,"");try{let e=await A.vault.adapter.list(t);for(let i of e.files){if(!i.endsWith(`.${Dt}`))continue;if((await he(A,i))?.kind==="rawfolder")return i}}catch{}return null}async function Rr(A){let r=[];for(let t of A.vault.getFiles())if(t.extension===Dt)try{(await he(A,t.path))?.kind==="rawfolder"&&r.push({folder:t.parent?.path?.replace(/\/+$/,"")??"",blobPath:t.path})}catch{}return r}async function rn(A){if(!await A.vault.adapter.exists(Ht))return[];try{return(await A.vault.adapter.list(Ht)).files.filter(t=>t.endsWith(`.${Dt}`))}catch{return[]}}function Gr(A){return A.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function Lr(A,r){let t=Jr(A,r);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Or(A,t);if(e.length===0){new Bt.Notice("No exportable notes (no files attached).");return}let i=(A.noteFolder.split("/").pop()||A.noteFolder).trim(),s=t.length===1?A.titleForNode(t[0]):`${i}-${t.length}notes`;new Xe(A.app,s,e.length,(n,o,a)=>{Uc(A,t,e,n,o,a)},Oi).open()}async function Kr(A,r){let t=r.replace(/\/[^/]*$/,"").replace(/\/+$/,""),e=await A.ensureFolderUnlocked(t);if(!e)return;let i;try{let l=new Uint8Array(await A.app.vault.adapter.readBinary(r));i=await Qt(l,e)}catch(l){new Bt.Notice(`Couldn't decrypt this note to export it: ${l.message}`);return}finally{e.fill(0)}let s=await sn(A.app,r),n=(A.settings.lockedSubtrees??[]).find(l=>l.blob===r),o=n?.title||s?.title||"locked-note",a=n?.count??s?.count??1;new Xe(A.app,o,a,(l,c,d)=>{Hc(A,t,l,i,c,d)},Oi).open()}async function Hc(A,r,t,e,i,s=!1){try{let n=e,o="";if(i){let u=await Wt(n,i);n=u.data;let p=io[u.kdf];o=p.strong?` (encrypted \xB7 ${p.label})`:` (encrypted \xB7 ${p.label} \u2014 Argon2id unavailable here, weaker)`}let a=(0,Bt.moment)().format("YYYYMMDD-HHmmss"),c=(A.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,"").split("/").filter(u=>u&&u!=="."&&u!==".."&&!/[\\:]/.test(u)).join("/")||"_exports",d=`${r}/${c}`;await A.app.vault.adapter.exists(d)||await A.app.vault.adapter.mkdir(d);let h=`${Gr(t)}-${a}`,g=`${d}/${h}.${te}`;if(await A.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i)try{A.app.secretStorage?.setSecret(Ve(h),i)}catch(u){console.warn("[Stashpad] couldn't save export passphrase",u)}new Bt.Notice(`Exported encrypted note${o} \u2192 ${g}`,0)}catch(n){new Bt.Notice(`Export failed: ${n.message}`),console.error(n)}finally{try{e.fill(0)}catch{}}}async function qr(A,r){let t=Jr(A,r);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Or(A,t);if(e.length===0){new Bt.Notice("No exportable notes.");return}let i=(A.noteFolder.split("/").pop()||A.noteFolder).trim(),s=t.length===1?A.titleForNode(t[0]):`${i}-okf`;new Pi(A.app,s,e.length,(n,o)=>{(async()=>{try{let a=await A.plugin.exportOkf(A.noteFolder,t.map(l=>l.id),n,o);if(!a.length){new Bt.Notice("Nothing exported.");return}A.plugin.notifications.show({message:`Exported OKF \u2014 ${a.length} file${a.length===1?"":"s"} \u2192 \`${A.noteFolder}/${A.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:a,folder:A.noteFolder,duration:0}),await A.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 Bt.Notice(`OKF export failed: ${a.message}`),console.error(a)}})()}).open()}async function Uc(A,r,t,e,i,s=!1){try{let n=await Ee(A.app,{rootNotes:r.filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),allDescendants:t.filter(u=>!r.some(p=>p.id===u.id)).filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),sourceFolder:A.noteFolder}),o="";if(i){let u=await Wt(n,i);n=u.data;let p=io[u.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,Bt.moment)().format("YYYYMMDD-HHmmss"),l=Gr(e),c=(A.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),d=`${A.noteFolder}/${c}`;await A.ensureFolder(d);let h=`${l}-${a}`,g=`${d}/${h}.${te}`;if(await A.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let u=A.app.secretStorage;try{u?.setSecret(Ve(h),i)}catch(p){console.warn("[Stashpad] couldn't save export passphrase to secret storage",p)}}await A.log.append({type:"stash_export",id:r[0].id,payload:{path:g,noteCount:t.length,rootIds:r.map(u=>u.id)}}),A.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:A.noteFolder,actions:A.actionsForFile(g),duration:0})}catch(n){A.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 qa(A,a){if(a?.file)return[a];if(A.selection.size>0)return[...A.selection].map(e=>A.tree.get(e)).filter(e=>!!e?.file);if(A.cursorIdx>=0&&A.currentChildren[A.cursorIdx])return[A.currentChildren[A.cursorIdx]];let t=A.tree.get(A.focusId);return t?.file?[t]:[]}function Ka(A,a){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of A.tree.getChildren(s.id))i(n)}};for(let s of a)i(s);return e}async function Ja(A){let a=A.app.vault.getFiles().filter(e=>e.extension===te);if(a.length===0){new Bt.Notice("No .stash files found in this vault.");return}let t=new class extends Bt.FuzzySuggestModal{getItems(){return a}getItemText(e){return e.path}onChooseItem(e){xo(A,e)}}(A.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function xo(A,a){try{let t=new Uint8Array(await A.app.vault.readBinary(a)),e=await ii(A.app,t,{secretId:Ve(a.basename)});if(!e)return;let i=await ee(A.app,e,A.noteFolder,Hc(A));A.tree.rebuild(A.noteFolder),A.render(),await A.log.append({type:"stash_import",id:k,payload:{from:a.path,into:A.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await A.app.fileManager.trashFile(a)}catch{}A.plugin.importService.clearPendingEncrypted(a.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),A.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:A.noteFolder})}catch(t){A.plugin.notifications.show({message:`Stashpad: import failed -File: \`${a.name}\` +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function Jr(A,r){if(r?.file)return[r];if(A.selection.size>0)return[...A.selection].map(e=>A.tree.get(e)).filter(e=>!!e?.file);if(A.cursorIdx>=0&&A.currentChildren[A.cursorIdx])return[A.currentChildren[A.cursorIdx]];let t=A.tree.get(A.focusId);return t?.file?[t]:[]}function Or(A,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 A.tree.getChildren(s.id))i(n)}};for(let s of r)i(s);return e}async function Yr(A){let r=A.app.vault.getFiles().filter(e=>e.extension===te);if(r.length===0){new Bt.Notice("No .stash files found in this vault.");return}let t=new class extends Bt.FuzzySuggestModal{getItems(){return r}getItemText(e){return e.path}onChooseItem(e){Po(A,e)}}(A.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Po(A,r){try{let t=new Uint8Array(await A.app.vault.readBinary(r)),e=await si(A.app,t,{secretId:Ve(r.basename)});if(!e)return;let i=await ee(A.app,e,A.noteFolder,Rc(A));A.tree.rebuild(A.noteFolder),A.render(),await A.log.append({type:"stash_import",id:k,payload:{from:r.path,into:A.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await A.app.fileManager.trashFile(r)}catch{}A.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)`),A.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:A.noteFolder})}catch(t){A.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:[a.path],actions:A.actionsForFile(a.path)}),console.error(t)}}function Hc(A){let a=new Set,t=e=>{if(a.add(e),!!A.tree.get(e))for(let s of A.tree.getChildren(e))t(s.id)};return t(k),a}Fi();Fi();var Rc=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),ji={nested:"Nested",flat:"Flat",everything:"Everything"},_i=[{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"}],ts=class ts extends F.ItemView{constructor(t,e){super(t);this.focusId=k;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.barOverflowRO=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.cursorExpandOverride=new Set;this.cursorHasMoved=!1;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||er(t.target))return;let e=X().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 c=l.value.length;l.setSelectionRange(c,c);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let l=this.listEl,c=!!l&&l.scrollTop+l.clientHeight>=l.scrollHeight-2,d=l?.scrollTop??0;if(this.render(),l){let h=c?l.scrollHeight:d;l.scrollTop=h,requestAnimationFrame(()=>{l.scrollTop=c?l.scrollHeight:d}),setTimeout(()=>{l.scrollTop=c?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,X().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 c=l.value.length;l.setSelectionRange(c,c)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let 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 c=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,c>=0&&(this.cursorIdx=c)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=X().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 r=this.tree.get(this.focusId);if(r?.file){if(G(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(r);return}if(G(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(r);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 F.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 F.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Ms(this.app),this.log=e.newLog(),this.integrity=new Rs(this.tree,this.log),this.order=new oi(this.app),this.sortStore=new Ts(this.app),this.fmSync=new Hs(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):zr(this,i,n);return this.hoistListPinned(i,o)}),this.debouncedRender=(0,F.debounce)(()=>{this.renderSuppressed()||this.render()},80),this.authorship=new Ls(this),this.dnd=new qs(this),this.bodyRenderer=new Ks(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!==k){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 this.plugin.getFolderIcon(this.noteFolder)??"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",()=>ks(this)),this.viewRoot.addEventListener("click",()=>ks(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())}),ks(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new F.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 c=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,c>=0&&(this.cursorIdx=c)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",l=>{let c=l.relatedTarget;c&&this.viewRoot&&this.viewRoot.contains(c)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",l=>{if(l.extension!=="md")return;let c=this.app.metadataCache.getFileCache(l)?.frontmatter;this.completedState.set(l.path,!!c?.completed),this.taskTaggedState.set(l.path,this.taggedFromFm(c))})),this.registerEvent(this.app.vault.on("rename",(l,c)=>{for(let d of[this.completedState,this.taskTaggedState])d.has(c)&&(d.set(l.path,d.get(c)),d.delete(c))})),this.registerEvent(this.app.vault.on("delete",l=>{this.completedState.delete(l.path),this.taskTaggedState.delete(l.path);let c=l.path.lastIndexOf("/"),d=(c>=0?l.path.slice(0,c):"").replace(/\/+$/,"");l.path.endsWith(".md")&&d===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=Lr(()=>{this.loadConfig();let l=this.plugin.settings.drafts?.[this.noteFolder]??"",c=this.composerInputEl?.value??"";l===""&&this.composerDraft!==""&&c===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):l===""&&c!==""&&(this.composerDraft=c),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(l){let c=l?.message??"";/already exists/i.test(c)||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[c,d]of l)this.lastCursorByFocus.set(c,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 r=this.foldRestoredSelection(n);r&&(this.pendingFocusIds=r),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(!X().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(){Ur(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.barOverflowRO?.disconnect(),this.barOverflowRO=null,this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();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=r=>r&&typeof r.folder=="string"&&typeof r.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear(),this.lastSelectionByFocus.clear();try{let c=this.plugin.loadLastCursor(this.noteFolder);for(let[d,h]of c)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),r;o&&this.tree.get(o)?(this.pendingFocusIds=[o],r={kind:"scroll-to-id",id:o,align:"start"}):r={kind:"pin-bottom",until:"next-user-input"};let l=this.foldRestoredSelection(o);l&&(this.pendingFocusIds=l),this.render(r),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(r=>this.currentChildren.some(l=>l.id===r));if(!i.length)return;let s=[...this.selection],n=new Set(i);if(s.length<i.length&&s.every(r=>n.has(r))){this.selection.clear();for(let r of i)this.selection.add(r);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 F.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=k,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 F.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 F.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 F.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,c)=>({path:l.path,content:n[c]})),r=[];if(e){let l=new Set,c=[];for(let h of n)for(let g of this.extractAttachments(this.stripFrontmatter(h))){let u=this.app.metadataCache.getFirstLinkpathDest(g,"");u&&!l.has(u.path)&&(l.add(u.path),c.push(u))}let d=await Promise.all(c.map(h=>this.app.vault.readBinary(h)));for(let h=0;h<c.length;h++)r.push({path:c[h].path,data:d[h]})}return{notes:o,attachments:r}}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,F.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 F.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof F.TFolder){s.push(o);continue}if(!(o instanceof F.TFile)||o.extension!=="md")continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!r||!Array.isArray(r.attachments)))for(let l of r.attachments){if(typeof l!="string")continue;let c=be(l),d=this.app.metadataCache.getFirstLinkpathDest(c,o.path);d?t.add(d.path):t.add(c)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof F.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),r=[],l=[i];for(;l.length;){let c=l.pop();for(let d of c.children){if(d instanceof F.TFolder){let h=d.name;if(c===i&&o.has(h)||c===i&&h==="_attachments"&&!s)continue;l.push(d);continue}d instanceof F.TFile&&d.extension!=="md"&&(d.name===".stashpad-order.json"||d.name===".stashpad-sort.json"||!s&&n.has(d.path)||r.push(d))}}return r}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&&F.Platform.isMobile&&!this.compactMode&&(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(),r;if(o==="unlocked")r=[];else if(i==="nested")r=this.plugin.lockedSubtreesFor(this.noteFolder,e.id);else{let d=new Set([e.id,...this.currentChildren.map(g=>g.id)]),h=new Set;r=[];for(let g of d)for(let u of this.plugin.lockedSubtreesFor(this.noteFolder,g))h.has(u.blob)||(h.add(u.blob),r.push(u))}let l=r.map(d=>({lk:d,ts:n(d)})).sort((d,h)=>d.ts-h.ts),c=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(c&&l.length>0){let d=new Map(this.currentChildren.map((f,I)=>[f.id,I])),h=new Map;for(let{lk:f}of l)f.rootId&&h.set(f.rootId,f);let g=this.currentChildren.map(f=>f.id),u=l.map(({lk:f})=>f).filter(f=>f.rootId).sort((f,I)=>n(I)-n(f)),p=!0;for(;u.length&&p;){p=!1;for(let f=0;f<u.length;f++){let I=u[f],m=I.prevSibling??null,C;if(m==null)C=0;else{let B=g.indexOf(m);if(B<0)continue;C=B+1}g.splice(C,0,I.rootId),u.splice(f,1),f--,p=!0}}for(let f of u)g.push(f.rootId);for(let f of g){let I=d.get(f);if(I!==void 0)this.renderNote(t,this.currentChildren[I],I);else{let m=h.get(f);m&&this.renderLockedPlaceholder(t,m)}}for(let f of s.slice().sort((I,m)=>I.stat.ctime-m.stat.ctime))this.renderFileRow(t,f)}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&&F.Platform.isMobile&&!this.compactMode&&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,F.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,F.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let r=async c=>{c.preventDefault(),c.stopPropagation();let d=(this.plugin.settings.lockedSubtrees??[]).find(f=>f.blob===e.blob),h=e.rootId??d?.rootId??null,g=e.parentId??d?.parentId??k,u=e.prevSibling??d?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,h){let f=this.order.getOrder(this.noteFolder,g),I=this.sortStore.getMode(this.noteFolder,g)==="manual";if(f.length===0&&I&&(f=this.tree.getChildren(g).map(m=>m.id)),f.length>0){let m=f.filter(B=>B!==h),C=u&&m.includes(u)?m.indexOf(u)+1:0;m.splice(Math.max(0,C),0,h),this.order.setOrder(this.noteFolder,g,m),this.order.flush(this.noteFolder)}this.pendingCursorId=h}this.render()}};o.onclick=r;let l=c=>{c.preventDefault(),c.stopPropagation();let d=new F.Menu;if(d.addItem(h=>h.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void r(c))),!F.Platform.isMobile){let h=F.Platform.isMacOS?"Finder":F.Platform.isWin?"File Explorer":"file manager";d.addItem(g=>g.setTitle(`Show in ${h}`).setIcon("folder-search").onClick(()=>{try{let u=window.require?.("electron")?.shell,p=this.app.vault.adapter?.getFullPath?.(e.blob);p&&u?.showItemInFolder&&u.showItemInFolder(p)}catch(u){console.warn("[Stashpad] showItemInFolder failed",u)}}))}d.addItem(h=>h.setTitle("Export to .stash\u2026").setIcon("package").onClick(()=>{this.plugin.exportLockedSubtree(e.blob)})),d.addItem(h=>h.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let g=e.blob;if(!F.Platform.isMobile)try{g=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(g),new F.Notice("Path copied.")})),d.showAtMouseEvent(c)};if(i.oncontextmenu=l,F.Platform.isMobile){let c=i.createEl("button",{cls:"stashpad-locked-menu"});(0,F.setIcon)(c,"more-vertical"),c.setAttr("aria-label","Locked note menu"),c.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=[],r=l=>{o.push(l);for(let c of this.tree.getChildren(l.id))r(c)};for(let l of n)r(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(),r=this.importedOnly,l=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!r&&!l?t:t.filter(c=>{if(r&&(!c.file||this.app.metadataCache.getFileCache(c.file)?.frontmatter?.imported!==!0))return!1;if(l){if(!c.file)return!1;let d=fe(this.app.metadataCache.getFileCache(c.file)?.frontmatter?.author);if(!d||d.id!==l)return!1}if(e&&c.created){let d=Date.parse(c.created);if(!Number.isNaN(d)&&d<e)return!1}if(i){if(!c.file)return!1;if(this.tagFilter===xe){if(!this.nodeHasAnyTag(c))return!1}else if(this.tagFilter===Ne){if(this.nodeHasAnyTag(c))return!1}else if(!this.nodeHasTag(c,i))return!1}return!(s&&(this.colorForNode(c)?.toLowerCase()??null)!==s||n&&this.isCompleted(c)&&!this.hasIncompleteDescendant(c)||o&&!this.hasAttachmentInSubtree(c))})}collapseVersions(t){if(!this.plugin.settings.enableSheetVersions)return t;let e=new Map,i=!1;for(let n of t){let o=It(this.app,n);if(!Bi(o))continue;i=!0;let r=Yt(o),l=e.get(r);l?l.push(n):e.set(r,[n])}if(!i)return t;let s=new Set;for(let[n,o]of e){let r=this.activeVersionNode(n,o);r&&s.add(r.id)}return t.filter(n=>Bi(It(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 $o(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 r of n.tags){let l=(r.tag||"").replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}let o=n?.frontmatter?.tags;if(o){let r=Array.isArray(o)?o:[o];for(let l of r){if(typeof l!="string")continue;let c=l.replace(/^#/,"");c&&t.set(c,(t.get(c)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let r=n.getBoundingClientRect().top-e;if(r>=0){s={id:o,offsetFromListTop:r};break}s={id:o,offsetFromListTop:r}}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){vt.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 r=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);e.empty(),e.toggleClass("is-mobile",F.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 c=this.containerEl.closest(".workspace-tabs");if(c&&c.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode)this.renderTinyHeader(e);else{let p=this.compactMode&&F.Platform.isMobile;(!this.compactMode||F.Platform.isMobile)&&this.renderTimeFilterBar(e),p||this.renderBreadcrumb(e)}let d=this.tree.get(this.focusId)??this.tree.getRoot();d.file&&!F.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 f=-1;for(let I of p){let m=this.currentChildren.findIndex(C=>C.id===I);m>=0&&(this.selection.add(I),f<0&&(f=m))}this.cursorIdx=f,f>=0&&(this.lastSelected=p.find(I=>this.currentChildren.some(m=>m.id===I))??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),F.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(vt.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 f=this.composerInputEl;if(f&&f.isConnected){if(f.focus({preventScroll:!0}),p!=null){let I=Math.min(p,f.value.length);try{f.setSelectionRange(I,I)}catch{}}}else requestAnimationFrame(()=>{let I=this.composerInputEl;if(I&&(I.focus({preventScroll:!0}),p!=null)){let m=Math.min(p,I.value.length);try{I.setSelectionRange(m,m)}catch{}}})}let u=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,u&&this.listEl){let p=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,u.kind){case"preserve":p?this.scrollListToBottom():r?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let f=u.scrollTop,I=this.listEl,m=()=>{this.suppressScrollSave=!0;let C=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop=Math.min(f,C),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let f=u.id,I=u.align,m=this.listEl,C=()=>{this.suppressScrollSave=!0;let B=m.querySelector(`[data-id="${f}"]`);B&&B.scrollIntoView({block:I,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&r?this.scrollListToBottom():this.listEl&&i>0&&(this.listEl.scrollTop=i);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let p=this.listEl,f=p.scrollTop,I=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){p.scrollTop=p.scrollHeight,f=p.scrollTop;return}let C=Math.max(0,p.scrollHeight-p.clientHeight);p.scrollTop<f&&f<=C?p.scrollTop=f:f=p.scrollTop});I.observe(p),this.listResizeObserver=I,p.addEventListener("wheel",C=>{C.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let m=0;p.addEventListener("touchstart",C=>{m=C.touches[0]?.clientY??0},{passive:!0}),p.addEventListener("touchmove",C=>{let B=C.touches[0]?.clientY??m;B>m&&(this.stickToListBottom=!1),m=B},{passive:!0}),p.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),p.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}refreshFolderSwitcherIcon(){let t=this.containerEl.querySelector(".stashpad-folder-btn .stashpad-btn-icon");t&&(t.empty(),(0,F.setIcon)(t,this.plugin.getFolderIcon(this.noteFolder)??"folder"))}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"});if(!F.Platform.isMobile){let c=e.createEl("button",{cls:"stashpad-folder-btn"}),d=!!this.folderOverride,h=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,F.setIcon)(c.createSpan({cls:"stashpad-btn-icon"}),this.plugin.getFolderIcon(this.noteFolder)??"folder"),c.createSpan({text:h,cls:"stashpad-btn-text"}),c.title=d?`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:A.actionsForFile(r.path)}),console.error(t)}}function Rc(A){let r=new Set,t=e=>{if(r.add(e),!!A.tree.get(e))for(let s of A.tree.getChildren(e))t(s.id)};return t(k),r}ki();ki();var Lc=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),_i={nested:"Nested",flat:"Flat",everything:"Everything"},ts=[{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"}],es=class es extends F.ItemView{constructor(t,e){super(t);this.focusId=k;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.barOverflowRO=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.cursorExpandOverride=new Set;this.cursorHasMoved=!1;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||sa(t.target))return;let e=X().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 c=l.value.length;l.setSelectionRange(c,c);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let l=this.listEl,c=!!l&&l.scrollTop+l.clientHeight>=l.scrollHeight-2,d=l?.scrollTop??0;if(this.render(),l){let h=c?l.scrollHeight:d;l.scrollTop=h,requestAnimationFrame(()=>{l.scrollTop=c?l.scrollHeight:d}),setTimeout(()=>{l.scrollTop=c?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,X().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 c=l.value.length;l.setSelectionRange(c,c)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let 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 c=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,c>=0&&(this.cursorIdx=c)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=X().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 F.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 F.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Us(this.app),this.log=e.newLog(),this.integrity=new qs(this.tree,this.log),this.order=new ai(this.app),this.sortStore=new Rs(this.app),this.fmSync=new Ls(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):Xa(this,i,n);return this.hoistListPinned(i,o)}),this.debouncedRender=(0,F.debounce)(()=>{this.renderSuppressed()||this.render()},80),this.authorship=new Os(this),this.dnd=new Ys(this),this.bodyRenderer=new $s(this,this,this.plugin.renderCacheStore)}getViewType(){return q}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==k){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 this.plugin.getFolderIcon(this.noteFolder)??"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",()=>xs(this)),this.viewRoot.addEventListener("click",()=>xs(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())}),xs(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new F.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 c=this.currentChildren.findIndex(d=>d.id===l);this.selection.add(l),this.lastSelected=l,c>=0&&(this.cursorIdx=c)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",l=>{let c=l.relatedTarget;c&&this.viewRoot&&this.viewRoot.contains(c)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",l=>{if(l.extension!=="md")return;let c=this.app.metadataCache.getFileCache(l)?.frontmatter;this.completedState.set(l.path,!!c?.completed),this.taskTaggedState.set(l.path,this.taggedFromFm(c))})),this.registerEvent(this.app.vault.on("rename",(l,c)=>{for(let d of[this.completedState,this.taskTaggedState])d.has(c)&&(d.set(l.path,d.get(c)),d.delete(c))})),this.registerEvent(this.app.vault.on("delete",l=>{this.completedState.delete(l.path),this.taskTaggedState.delete(l.path);let c=l.path.lastIndexOf("/"),d=(c>=0?l.path.slice(0,c):"").replace(/\/+$/,"");l.path.endsWith(".md")&&d===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=qa(()=>{this.loadConfig();let l=this.plugin.settings.drafts?.[this.noteFolder]??"",c=this.composerInputEl?.value??"";l===""&&this.composerDraft!==""&&c===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):l===""&&c!==""&&(this.composerDraft=c),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(l){let c=l?.message??"";/already exists/i.test(c)||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[c,d]of l)this.lastCursorByFocus.set(c,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(!X().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(){Ga(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.barOverflowRO?.disconnect(),this.barOverflowRO=null,this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();this.authorship.dispose();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear(),this.lastSelectionByFocus.clear();try{let c=this.plugin.loadLastCursor(this.noteFolder);for(let[d,h]of c)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 F.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=k,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 F.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 F.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 F.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,c)=>({path:l.path,content:n[c]})),a=[];if(e){let l=new Set,c=[];for(let h of n)for(let g of this.extractAttachments(this.stripFrontmatter(h))){let u=this.app.metadataCache.getFirstLinkpathDest(g,"");u&&!l.has(u.path)&&(l.add(u.path),c.push(u))}let d=await Promise.all(c.map(h=>this.app.vault.readBinary(h)));for(let h=0;h<c.length;h++)a.push({path:c[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,F.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 F.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof F.TFolder){s.push(o);continue}if(!(o instanceof F.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 c=be(l),d=this.app.metadataCache.getFirstLinkpathDest(c,o.path);d?t.add(d.path):t.add(c)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof F.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 c=l.pop();for(let d of c.children){if(d instanceof F.TFolder){let h=d.name;if(c===i&&o.has(h)||c===i&&h==="_attachments"&&!s)continue;l.push(d);continue}d instanceof F.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&&F.Platform.isMobile&&!this.compactMode&&(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 u of this.plugin.lockedSubtreesFor(this.noteFolder,g))h.has(u.blob)||(h.add(u.blob),a.push(u))}let l=a.map(d=>({lk:d,ts:n(d)})).sort((d,h)=>d.ts-h.ts),c=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(c&&l.length>0){let d=new Map(this.currentChildren.map((f,I)=>[f.id,I])),h=new Map;for(let{lk:f}of l)f.rootId&&h.set(f.rootId,f);let g=this.currentChildren.map(f=>f.id),u=l.map(({lk:f})=>f).filter(f=>f.rootId).sort((f,I)=>n(I)-n(f)),p=!0;for(;u.length&&p;){p=!1;for(let f=0;f<u.length;f++){let I=u[f],m=I.prevSibling??null,C;if(m==null)C=0;else{let B=g.indexOf(m);if(B<0)continue;C=B+1}g.splice(C,0,I.rootId),u.splice(f,1),f--,p=!0}}for(let f of u)g.push(f.rootId);for(let f of g){let I=d.get(f);if(I!==void 0)this.renderNote(t,this.currentChildren[I],I);else{let m=h.get(f);m&&this.renderLockedPlaceholder(t,m)}}for(let f of s.slice().sort((I,m)=>I.stat.ctime-m.stat.ctime))this.renderFileRow(t,f)}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&&F.Platform.isMobile&&!this.compactMode&&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,F.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,F.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async c=>{c.preventDefault(),c.stopPropagation();let d=(this.plugin.settings.lockedSubtrees??[]).find(f=>f.blob===e.blob),h=e.rootId??d?.rootId??null,g=e.parentId??d?.parentId??k,u=e.prevSibling??d?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,h){let f=this.order.getOrder(this.noteFolder,g),I=this.sortStore.getMode(this.noteFolder,g)==="manual";if(f.length===0&&I&&(f=this.tree.getChildren(g).map(m=>m.id)),f.length>0){let m=f.filter(B=>B!==h),C=u&&m.includes(u)?m.indexOf(u)+1:0;m.splice(Math.max(0,C),0,h),this.order.setOrder(this.noteFolder,g,m),this.order.flush(this.noteFolder)}this.pendingCursorId=h}this.render()}};o.onclick=a;let l=c=>{c.preventDefault(),c.stopPropagation();let d=new F.Menu;if(d.addItem(h=>h.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(c))),!F.Platform.isMobile){let h=F.Platform.isMacOS?"Finder":F.Platform.isWin?"File Explorer":"file manager";d.addItem(g=>g.setTitle(`Show in ${h}`).setIcon("folder-search").onClick(()=>{try{let u=window.require?.("electron")?.shell,p=this.app.vault.adapter?.getFullPath?.(e.blob);p&&u?.showItemInFolder&&u.showItemInFolder(p)}catch(u){console.warn("[Stashpad] showItemInFolder failed",u)}}))}d.addItem(h=>h.setTitle("Export to .stash\u2026").setIcon("package").onClick(()=>{this.plugin.exportLockedSubtree(e.blob)})),d.addItem(h=>h.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let g=e.blob;if(!F.Platform.isMobile)try{g=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(g),new F.Notice("Path copied.")})),d.showAtMouseEvent(c)};if(i.oncontextmenu=l,F.Platform.isMobile){let c=i.createEl("button",{cls:"stashpad-locked-menu"});(0,F.setIcon)(c,"more-vertical"),c.setAttr("aria-label","Locked note menu"),c.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 c of this.tree.getChildren(l.id))a(c)};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(c=>{if(a&&(!c.file||this.app.metadataCache.getFileCache(c.file)?.frontmatter?.imported!==!0))return!1;if(l){if(!c.file)return!1;let d=fe(this.app.metadataCache.getFileCache(c.file)?.frontmatter?.author);if(!d||d.id!==l)return!1}if(e&&c.created){let d=Date.parse(c.created);if(!Number.isNaN(d)&&d<e)return!1}if(i){if(!c.file)return!1;if(this.tagFilter===xe){if(!this.nodeHasAnyTag(c))return!1}else if(this.tagFilter===Ne){if(this.nodeHasAnyTag(c))return!1}else if(!this.nodeHasTag(c,i))return!1}return!(s&&(this.colorForNode(c)?.toLowerCase()??null)!==s||n&&this.isCompleted(c)&&!this.hasIncompleteDescendant(c)||o&&!this.hasAttachmentInSubtree(c))})}collapseVersions(t){if(!this.plugin.settings.enableSheetVersions)return t;let e=new Map,i=!1;for(let n of t){let o=It(this.app,n);if(!yi(o))continue;i=!0;let a=Yt(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=>yi(It(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 c=l.replace(/^#/,"");c&&t.set(c,(t.get(c)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){vt.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",F.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 c=this.containerEl.closest(".workspace-tabs");if(c&&c.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode)this.renderTinyHeader(e);else{let p=this.compactMode&&F.Platform.isMobile;(!this.compactMode||F.Platform.isMobile)&&this.renderTimeFilterBar(e),p||this.renderBreadcrumb(e)}let d=this.tree.get(this.focusId)??this.tree.getRoot();d.file&&!F.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 f=-1;for(let I of p){let m=this.currentChildren.findIndex(C=>C.id===I);m>=0&&(this.selection.add(I),f<0&&(f=m))}this.cursorIdx=f,f>=0&&(this.lastSelected=p.find(I=>this.currentChildren.some(m=>m.id===I))??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),F.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(vt.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 f=this.composerInputEl;if(f&&f.isConnected){if(f.focus({preventScroll:!0}),p!=null){let I=Math.min(p,f.value.length);try{f.setSelectionRange(I,I)}catch{}}}else requestAnimationFrame(()=>{let I=this.composerInputEl;if(I&&(I.focus({preventScroll:!0}),p!=null)){let m=Math.min(p,I.value.length);try{I.setSelectionRange(m,m)}catch{}}})}let u=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,u&&this.listEl){let p=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,u.kind){case"preserve":p?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let f=u.scrollTop,I=this.listEl,m=()=>{this.suppressScrollSave=!0;let C=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop=Math.min(f,C),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let f=u.id,I=u.align,m=this.listEl,C=()=>{this.suppressScrollSave=!0;let B=m.querySelector(`[data-id="${f}"]`);B&&B.scrollIntoView({block:I,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,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,f=p.scrollTop,I=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){p.scrollTop=p.scrollHeight,f=p.scrollTop;return}let C=Math.max(0,p.scrollHeight-p.clientHeight);p.scrollTop<f&&f<=C?p.scrollTop=f:f=p.scrollTop});I.observe(p),this.listResizeObserver=I,p.addEventListener("wheel",C=>{C.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let m=0;p.addEventListener("touchstart",C=>{m=C.touches[0]?.clientY??0},{passive:!0}),p.addEventListener("touchmove",C=>{let B=C.touches[0]?.clientY??m;B>m&&(this.stickToListBottom=!1),m=B},{passive:!0}),p.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),p.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}refreshFolderSwitcherIcon(){let t=this.containerEl.querySelector(".stashpad-folder-btn .stashpad-btn-icon");t&&(t.empty(),(0,F.setIcon)(t,this.plugin.getFolderIcon(this.noteFolder)??"folder"))}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"});if(!F.Platform.isMobile){let c=e.createEl("button",{cls:"stashpad-folder-btn"}),d=!!this.folderOverride,h=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,F.setIcon)(c.createSpan({cls:"stashpad-btn-icon"}),this.plugin.getFolderIcon(this.noteFolder)??"folder"),c.createSpan({text:h,cls:"stashpad-btn-text"}),c.title=d?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,d&&c.addClass("is-override"),c.onclick=u=>{u.preventDefault(),this.openFolderPicker()};let g=e.createEl("button",{cls:"stashpad-search-btn"});Ft(g,"search","\u{1F50D}"),g.title="Search notes (Mod+F)",g.onclick=u=>{u.preventDefault(),this.openSearchModal()}}F.Platform.isMobile?(this.renderActionsCluster(e),this.renderMobileFiltersButton(e)):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let i=e.createDiv({cls:"stashpad-time-filter-btns"}),s=i.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,F.setIcon)(s,this.timeFilterCalendar?"calendar":"history"),s.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&&s.addClass("is-active"),s.onclick=c=>{c.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let c of _i){let d=this.timeFilterCalendar?c.calShort:c.rollShort,h=this.timeFilterCalendar?c.calLong:c.rollLong,g=i.createEl("button",{cls:"stashpad-time-filter-btn",text:d});g.title=h,this.timeFilter===c.key&&g.addClass("is-active"),g.onclick=u=>{u.preventDefault(),this.setTimeFilter(c.key)}}let n=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let c of _i){let d=this.timeFilterCalendar?c.calLong:c.rollLong,h=n.createEl("option",{text:d});h.value=c.key,this.timeFilter===c.key&&(h.selected=!0)}n.onchange=()=>this.setTimeFilter(n.value);let o=e.createDiv({cls:"stashpad-view-mode-btns"});if(!F.Platform.isMobile){let c=o.createEl("button",{cls:"stashpad-view-mode-btn"});(0,F.setIcon)(c,"minimize-2"),c.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",c.onclick=d=>{d.preventDefault(),this.plugin.openTinyWindow()}}let r=o.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,F.setIcon)(r,this.compactMode?"panel-top":"rows-2"),r.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&&r.addClass("is-active"),r.onclick=c=>{c.preventDefault(),this.toggleCompactMode()},F.Platform.isMobile)return;let l=o.createEl("button",{cls:"stashpad-view-mode-btn"});(0,F.setIcon)(l,"external-link"),l.title=X().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.)",l.onclick=c=>{c.preventDefault();let d=X().popoutDuplicates;try{let h=this.app.workspace;if(d){let g=this.leaf.getViewState(),u=h.openPopoutLeaf?.();u?u.setViewState({...g,active:!0}):new F.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else h.moveLeafToPopout?.(this.leaf)}catch(h){new F.Notice(`Stashpad: open-in-new-window failed (${h.message})`)}},this.setupBarOverflow(e)}setupBarOverflow(t){let e=[{key:"nav",icon:"folder-search",title:"Folder & search",memberSel:[".stashpad-folder-btn",".stashpad-search-btn"],memberKeys:["folder","search"],collapsePrio:5,displayIdx:0},{key:"filter",icon:"filter",title:"Tag & color",memberSel:[".stashpad-tag-filter-btn",".stashpad-color-filter-btn"],memberKeys:["tag","color"],collapsePrio:3,displayIdx:1},{key:"arrange",icon:"sliders-horizontal",title:"Sort & view",memberSel:[".stashpad-sort-btn",".stashpad-view-btn"],memberKeys:["sort","view"],collapsePrio:4,displayIdx:2},{key:"time",icon:"clock",title:"Time",memberSel:[".stashpad-time-filter-btns",".stashpad-time-filter-select"],memberKeys:["time"],collapsePrio:2,displayIdx:3},{key:"window",icon:"app-window",title:"Window & layout",memberSel:[".stashpad-view-mode-btns"],memberKeys:["mode"],collapsePrio:1,displayIdx:4}];t.addClass("stashpad-overflow-managed");let i=[];for(let u of[...e].sort((p,f)=>p.displayIdx-f.displayIdx)){let p=u.memberSel.map(B=>t.querySelector(B)).filter(B=>!!B);if(p.length===0)continue;let f=createDiv({cls:"stashpad-bar-group"});t.insertBefore(f,p[0]);let I=f.createDiv({cls:"stashpad-bar-group-expanded"});for(let B of p)I.appendChild(B);let m=f.createDiv({cls:"stashpad-bar-overflow-btn stashpad-bar-group-icon stashpad-overflow-hidden"});m.setAttribute("role","button"),m.setAttribute("tabindex","0"),(0,F.setIcon)(m.createSpan({cls:"stashpad-bar-group-icon-glyph"}),u.icon),m.title=`${u.title} \u2014 combined menu`;let C=B=>{B.preventDefault(),this.openBarOverflowMenu(m,u.memberKeys)};m.onclick=C,m.onkeydown=B=>{(B.key==="Enter"||B.key===" ")&&C(B)},i.push({...u,wrapper:f,expanded:I,iconBtn:m})}let s=t.createDiv({cls:"stashpad-bar-overflow-btn stashpad-bar-kebab stashpad-overflow-hidden"});s.setAttribute("role","button"),s.setAttribute("tabindex","0"),(0,F.setIcon)(s.createSpan({cls:"stashpad-bar-overflow-icon"}),"more-horizontal"),s.title="More filters / view options";let n=[...i].sort((u,p)=>u.collapsePrio-p.collapsePrio),o=[...i].sort((u,p)=>p.displayIdx-u.displayIdx),r=[],l=()=>t.scrollWidth<=t.clientWidth+1,c=()=>{if(!t.isConnected||t.clientWidth===0)return;for(let p of i)p.wrapper.removeClass("stashpad-overflow-hidden"),p.expanded.removeClass("stashpad-overflow-hidden"),p.iconBtn.addClass("stashpad-overflow-hidden"),p.iconBtn.toggleClass("is-active",p.memberKeys.some(f=>this.barUnitActive(f)));if(s.addClass("stashpad-overflow-hidden"),r=[],l())return;for(let p of n){if(l())break;p.expanded.addClass("stashpad-overflow-hidden"),p.iconBtn.removeClass("stashpad-overflow-hidden")}if(l())return;s.removeClass("stashpad-overflow-hidden");let u=[];for(let p of o){if(l())break;p.wrapper.addClass("stashpad-overflow-hidden"),u.push(p)}r=[...u].sort((p,f)=>p.displayIdx-f.displayIdx).flatMap(p=>p.memberKeys),s.toggleClass("is-active",r.some(p=>this.barUnitActive(p)))},d=u=>{u.preventDefault(),this.openBarOverflowMenu(s,r)};s.onclick=d,s.onkeydown=u=>{(u.key==="Enter"||u.key===" ")&&d(u)};try{this.barOverflowRO?.disconnect()}catch{}let h=(t.ownerDocument?.defaultView??window).ResizeObserver,g=-1;this.barOverflowRO=new h(u=>{let p=Math.round(u[u.length-1].contentRect.width);p!==g&&(g=p,c())}),this.barOverflowRO.observe(t),requestAnimationFrame(()=>c())}barUnitActive(t){switch(t){case"folder":return!!this.folderOverride;case"tag":return!!this.tagFilter;case"color":return!!this.colorFilter;case"time":return this.timeFilter!=="all";case"sort":return this.currentViewMode()==="nested"&&this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual";case"view":return this.currentViewMode()!=="nested"||this.currentEncryptionFilter()!=="all"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();case"mode":return this.compactMode;default:return!1}}openBarOverflowMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-mobile-filters-popover").forEach(p=>p.remove());let s=i.body.createDiv({cls:"stashpad-mobile-filters-popover"}),n=t.getBoundingClientRect(),o=i.defaultView??window;s.setCssStyles({right:`${Math.max(8,o.innerWidth-n.right)}px`,left:"auto",top:`${n.bottom+4}px`,maxWidth:"min(360px, calc(100vw - 16px))",width:"max-content",minWidth:"260px"});let r=new F.Scope(this.app.scope),l=()=>{s.remove(),i.removeEventListener("mousedown",c,!0);try{this.app.keymap?.popScope(r)}catch{}},c=p=>{!s.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&l()},h=[{key:"folder",title:"Folder",summary:()=>this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad",populate:p=>this.populateFolderMenuBody(p,l)},{key:"search",title:"Search",summary:()=>"Search notes (Mod+F)",populate:p=>this.populateSearchMenuBody(p,l)},{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,l)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),l)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":ri[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:p=>{if(this.currentViewMode()!=="nested"){p.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(p,l)}},{key:"view",title:"View",summary:()=>ji[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,l)},{key:"time",title:"Time filter",summary:()=>{let p=_i.find(f=>f.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,l)},{key:"mode",title:"View mode",summary:()=>this.compactMode?"Compact on":"Tiny \xB7 Compact \xB7 Window",populate:p=>this.populateModeMenuBody(p,l)}].filter(p=>e.includes(p.key)),g="",u=()=>{s.empty();for(let p of h){let f=s.createDiv({cls:"stashpad-mobile-filters-section"}),I=f.createDiv({cls:"stashpad-mobile-filters-header"}),m=I.createSpan({cls:"stashpad-mobile-filters-chev"});(0,F.setIcon)(m,g===p.key?"chevron-down":"chevron-right"),I.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),I.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),I.onclick=C=>{C.preventDefault(),C.stopPropagation(),g=g===p.key?"":p.key,u()},g===p.key&&p.populate(f.createDiv({cls:"stashpad-mobile-filters-body"}))}};u(),r.register([],"Escape",p=>(p.preventDefault(),l(),!1)),this.app.keymap?.pushScope(r),setTimeout(()=>{i.addEventListener("mousedown",c,!0)},0)}populateFolderMenuBody(t,e){let i=t.createDiv({cls:"stashpad-sort-popover-row"});i.createSpan({cls:"stashpad-sort-popover-label",text:this.folderOverride?"Change folder (override active)\u2026":"Change folder for this tab\u2026"}),i.onclick=s=>{s.preventDefault(),s.stopPropagation(),e(),this.openFolderPicker()}}populateSearchMenuBody(t,e){let i=t.createDiv({cls:"stashpad-sort-popover-row"});i.createSpan({cls:"stashpad-sort-popover-label",text:"Search notes\u2026"}),i.onclick=s=>{s.preventDefault(),s.stopPropagation(),e(),this.openSearchModal()}}populateModeMenuBody(t,e){let i=(n,o)=>{let r=t.createDiv({cls:"stashpad-sort-popover-row"});r.createSpan({cls:"stashpad-sort-popover-label",text:n}),r.onclick=l=>{l.preventDefault(),l.stopPropagation(),e(),o()}};i("Tiny mode (popout window)",()=>void this.plugin.openTinyWindow());let s=t.createDiv({cls:"stashpad-sort-popover-row"});this.compactMode&&s.addClass("is-active"),s.createSpan({cls:"stashpad-sort-popover-label",text:this.compactMode?"Compact mode (on)":"Compact mode"}),s.onclick=n=>{n.preventDefault(),n.stopPropagation(),e(),this.toggleCompactMode()},i(X().popoutDuplicates?"Duplicate to new window":"Move to new window",()=>{try{let n=this.app.workspace;if(X().popoutDuplicates){let o=n.openPopoutLeaf?.();o?o.setViewState({...this.leaf.getViewState(),active:!0}):new F.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else n.moveLeafToPopout?.(this.leaf)}catch(n){new F.Notice(`Stashpad: open-in-new-window failed (${n.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"});Ft(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==k;i.title=this.navBackStack.length>0?"Back":this.focusId!==k?"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"});Ft(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;if(n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=d=>{d.preventDefault(),this.navigateForward()},F.Platform.isMobile){let d=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ft(d,"route","\u22D4"),d.title="Jump to a level in the path",d.onclick=h=>{h.preventDefault(),this.openBreadcrumbLevelsModal()}}let r=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),l=this.mobileSelectMode;Ft(r,l?"check-square":"square",l?"\u2611":"\u2610"),r.title=l?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",l&&r.addClass("is-active"),r.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(u=>u.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 F.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let c=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ft(c,"zap","\u26A1"),c.title="Actions (move, delete, undo, \u2026)",c.onclick=d=>{d.preventDefault(),this.openMobileActionsMenu(c)}}openMobileActionsMenu(t){let e=new F.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 Gs(this.app).open()}tagFilterLabel(){return this.tagFilter===xe?"Tagged":this.tagFilter===Ne?"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"});Ft(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(w=>w.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 F.Scope(this.app.scope),o=()=>{i.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(n)}catch{}},r=w=>{!i.contains(w.target)&&w.target!==t&&!t.contains(w.target)&&o()},l=i.createDiv({cls:"stashpad-tag-filter-search"}),c=l.createSpan({cls:"stashpad-tag-filter-search-icon"});Ft(c,"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"}});Ft(h,"x","\xD7"),h.setCssStyles({display:"none"});let g=i.createDiv({cls:"stashpad-tag-filter-list"}),u=this.collectFolderTags(),p=[],f=0,I=w=>{this.setTagFilter(w),o()},m=w=>{if(p.length===0){f=0;return}f=(w+p.length)%p.length,p.forEach((y,Q)=>y.el.toggleClass("is-highlighted",Q===f)),p[f].el.scrollIntoView({block:"nearest"})},C=(w,y,Q,v)=>{let E=g.createDiv({cls:"stashpad-tag-filter-row"});v&&E.addClass("is-active"),E.createSpan({cls:"stashpad-tag-filter-row-label",text:w}),typeof Q=="number"&&E.createSpan({cls:"stashpad-tag-filter-row-count",text:String(Q)});let S=p.length;p.push({value:y,el:E}),E.onmousedown=D=>{D.preventDefault(),I(y)},E.onmouseenter=()=>m(S)},B=()=>{let w=d.value;h.setCssStyles({display:w?"":"none"}),g.empty(),p=[];let y=this.tagFilter?.toLowerCase();if(w.trim()){let Q=nr(w,u);if(Q.length===0)g.createDiv({cls:"stashpad-tag-filter-empty",text:"No matching tags"});else for(let v of Q)C(`#${v.label}`,v.raw,v.count,y===v.raw.toLowerCase())}else{C("All tags",null,void 0,!this.tagFilter),C("Tagged",xe,void 0,this.tagFilter===xe),C("Untagged",Ne,void 0,this.tagFilter===Ne);for(let Q of u)C(`#${Q.label}`,Q.raw,Q.count,y===Q.raw.toLowerCase())}m(0)};h.onclick=()=>{d.value="",B(),d.focus()},d.addEventListener("input",B),d.addEventListener("keydown",w=>{w.key==="ArrowDown"?(w.preventDefault(),m(f+1)):w.key==="ArrowUp"?(w.preventDefault(),m(f-1)):w.key==="Enter"&&(w.preventDefault(),p[f]&&I(p[f].value))}),n.register([],"Escape",w=>(w.preventDefault(),o(),!1)),this.app.keymap?.pushScope(n),B(),setTimeout(()=>{e.addEventListener("mousedown",r,!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"}),r=i.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let l=this.colorFilter.toLowerCase();o.setCssStyles({background:l});let c=this.plugin.getColorAlias(this.noteFolder,l);r.setText(c??l)}else e.length===0?(o.addClass("is-empty"),r.setText("No colors"),i.addClass("is-disabled")):(o.addClass("is-empty"),r.setText("All colors"))})();let n=o=>{o.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(i,e)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openColorFilterMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-color-filter-popover").forEach(c=>c.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.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 F.Scope(this.app.scope),r=()=>{s.remove(),i.removeEventListener("mousedown",l,!0);try{this.app.keymap?.popScope(o)}catch{}},l=c=>{!s.contains(c.target)&&c.target!==t&&!t.contains(c.target)&&r()};o.register([],"Escape",c=>(c.preventDefault(),r(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,r),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",r=t.createDiv({cls:"stashpad-sort-btn"});r.setAttribute("role","button"),r.setAttribute("tabindex",o?"-1":"0"),o&&r.addClass("is-disabled");let l=r.createSpan({cls:"stashpad-sort-icon"});(0,F.setIcon)(l,"arrow-up-down");let c=r.createSpan({cls:"stashpad-sort-label"});o?(c.setText("Sort: \u2014"),r.title=`Sort is per-parent and applies only to Nested view. The current view (${ji[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(c.setText(ri[s]),s!=="manual"&&r.addClass("is-active"),r.title=s==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${ri[s]}. Drag-reorder will revert this parent to Manual.`);let d=h=>{o||(h.preventDefault(),this.openSortMenu(r))};r.onclick=d,r.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(r)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateSortMenuBody(i,n);let r=new F.Scope(this.app.scope);r.register([],"Escape",l=>(l.preventDefault(),n(),!1)),this.app.keymap?.pushScope(r),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,F.setIcon)(i,"sliders-horizontal"),e.title="Filters / view options";let s=!!this.tagFilter,n=!!this.colorFilter,o=this.timeFilter!=="all",r=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",l=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||r||l)&&e.addClass("is-active");let c=d=>{d.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=c,e.onkeydown=d=>{(d.key==="Enter"||d.key===" ")&&c(d)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(u=>u.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window,o=s.bottom+280>n.innerHeight;i.setCssStyles({right:`${Math.max(8,n.innerWidth-s.right)}px`,left:"auto",...o?{bottom:`${Math.max(8,n.innerHeight-s.top+4)}px`,top:"auto"}:{top:`${s.bottom+4}px`,bottom:"auto"},maxWidth:"min(360px, calc(100vw - 16px))",maxHeight:"min(60vh, 420px)",overflowY:"auto",width:"max-content",minWidth:"260px"});let r=()=>{i.remove(),e.removeEventListener("mousedown",l,!0);try{this.app.keymap?.popScope(g)}catch{}},l=u=>{!i.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&r()},c=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:u=>this.populateTagMenuBody(u,r)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:u=>this.populateColorMenuBody(u,this.collectFolderColors(),r)},{key:"time",title:"Time filter",summary:()=>{let u=_i.find(p=>p.key===this.timeFilter);return u?this.timeFilterCalendar?u.calShort:u.rollShort:"All"},populate:u=>this.populateTimeMenuBody(u,r)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":ri[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:u=>{if(this.currentViewMode()!=="nested"){u.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(u,r)}},{key:"view",title:"View",summary:()=>ji[this.currentViewMode()],populate:u=>this.populateViewMenuBody(u,r)}],d="",h=()=>{i.empty();for(let u of c){let p=i.createDiv({cls:"stashpad-mobile-filters-section"}),f=p.createDiv({cls:"stashpad-mobile-filters-header"}),I=f.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,F.setIcon)(I,d===u.key?"chevron-down":"chevron-right"),f.createSpan({cls:"stashpad-mobile-filters-title",text:u.title}),f.createSpan({cls:"stashpad-mobile-filters-summary",text:u.summary()}),f.onclick=m=>{m.preventDefault(),m.stopPropagation(),d=d===u.key?"":u.key,h()},d===u.key){let m=p.createDiv({cls:"stashpad-mobile-filters-body"});u.populate(m)}}};h();let g=new F.Scope(this.app.scope);g.register([],"Escape",u=>(u.preventDefault(),r(),!1)),this.app.keymap?.pushScope(g),setTimeout(()=>{e.addEventListener("mousedown",l,!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,F.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(ji[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=r=>{r.preventDefault(),this.openViewMenu(i)};i.onclick=o,i.onkeydown=r=>{(r.key==="Enter"||r.key===" ")&&o(r)}}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"});F.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(r)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateViewMenuBody(i,n);let r=new F.Scope(this.app.scope);r.register([],"Escape",l=>(l.preventDefault(),n(),!1)),this.app.keymap?.pushScope(r),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(y,Q)=>{let v=t.createDiv({cls:"stashpad-view-popover-row"});y===i&&v.addClass("is-active"),v.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:ji[y]}),v.createDiv({cls:"stashpad-view-popover-desc",text:Q}),v.onclick=async S=>{S.preventDefault(),S.stopPropagation(),e(),y!==i&&(await this.setViewMode(y),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 y=this.currentEncryptionFilter(),Q=(v,E,S)=>{let D=t.createDiv({cls:"stashpad-view-popover-row"});v===y&&D.addClass("is-active"),D.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:E}),D.createDiv({cls:"stashpad-view-popover-desc",text:S}),D.onclick=async H=>{H.preventDefault(),H.stopPropagation(),v!==y&&(await this.setEncryptionFilter(v),this.refreshList()),e()}};Q("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),Q("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),Q("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 y=>{y.target!==o&&(y.preventDefault(),o.checked=!o.checked),await this.setHideChildless(o.checked),this.refreshList()};let r=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),l=r.createEl("input",{type:"checkbox"});l.checked=this.currentHideCompleted(),r.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide completed notes"}),r.createDiv({cls:"stashpad-view-popover-desc",text:"Hide notes marked complete. A completed parent stays visible while any descendant is still incomplete."}),r.onclick=async y=>{y.target!==l&&(y.preventDefault(),l.checked=!l.checked),await this.setHideCompleted(l.checked),this.refreshList()};let c=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),d=c.createEl("input",{type:"checkbox"});d.checked=this.currentAttachmentsOnly(),c.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),c.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),c.onclick=async y=>{y.target!==d&&(y.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 y=>{i==="everything"&&(y.target!==g&&(y.preventDefault(),g.checked=!g.checked),await this.setIncludeAttachments(g.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let u=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),p=u.createEl("input",{type:"checkbox"});p.checked=this.importedOnly,u.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),u.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),u.onclick=y=>{y.target!==p&&(y.preventDefault(),p.checked=!p.checked),this.importedOnly=p.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let f=new Map,I=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==I)continue;let Q=fe(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);Q&&f.set(Q.id,Q.name)}let m=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),C=m.createDiv({cls:"stashpad-view-popover-main"});C.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let B=C.createEl("select",{cls:"stashpad-view-author-select"}),w=B.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[y,Q]of[...f.entries()].sort((v,E)=>v[1].localeCompare(E[1]))){let v=B.createEl("option",{text:Q,value:y});this.authorFilter===y&&(v.selected=!0)}B.onclick=y=>y.stopPropagation(),B.onchange=()=>{this.authorFilter=B.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},m.createDiv({cls:"stashpad-view-popover-desc",text:f.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 ao){let r=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&r.addClass("is-active"),r.createSpan({cls:"stashpad-sort-popover-label",text:ri[o]}),r.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 _i){let o=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&o.addClass("is-active");let r=this.timeFilterCalendar?n.calLong:n.rollLong;o.createSpan({cls:"stashpad-sort-popover-label",text:r}),o.onclick=l=>{l.preventDefault(),l.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,r)=>{let l=t.createDiv({cls:"stashpad-color-filter-popover-row"}),c=l.createSpan({cls:"stashpad-color-filter-swatch"});o?c.setCssStyles({background:o}):c.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(),r(),i()}};s("All colors",null,()=>this.setColorFilter(null));for(let n of e){let o=this.plugin.getColorAlias(this.noteFolder,n.hex),r=o?`${o} (${n.count})`:`${n.hex} (${n.count})`;s(r,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let i=this.collectFolderTags(),s=(n,o)=>{let r=t.createDiv({cls:"stashpad-color-filter-popover-row"});r.createSpan({cls:"stashpad-color-filter-swatch is-empty"}),r.createSpan({cls:"stashpad-color-filter-popover-label"}).setText(n),(this.tagFilter??"")===(o??"")&&r.addClass("is-active"),r.onclick=d=>{d.preventDefault(),d.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null),s("Tagged",xe),s("Untagged",Ne);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"});Ft(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==k||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==k?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Ft(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(),r=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),l=this.focusId===k?r:`${r} / ${this.titleForNode(o).trim()}`,c=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),d=c.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,F.setIcon)(d,"folder"),c.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:l}),c.title=`${this.noteFolder}${this.focusId!==k?` / ${this.titleForNode(o).trim()}`:""} -Click to switch / create folder.`,c.onclick=f=>{f.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()},!F.Platform.isMobile){let f=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,F.setIcon)(f,"contrast"),f.title="Window transparency",this.tinyOpacity<1&&f.addClass("is-active"),f.onclick=I=>{I.stopPropagation(),this.toggleTinyOpacityPopover(f)}}let u=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,F.setIcon)(u,this.compactMode?"panel-top":"rows-2"),u.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&u.addClass("is-active"),u.onclick=()=>{this.toggleCompactMode()};let p=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,F.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 r=d=>{e.contains(d.target)||d.target===t||t.contains(d.target)||c()},l=d=>{d.key==="Escape"&&c()},c=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",r,!0),document.removeEventListener("keydown",l,!0)};setTimeout(()=>{document.addEventListener("mousedown",r,!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),F.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"});F.Platform.isMobile||this.renderActionsCluster(e);let i=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(F.Platform.isMobile?((0,F.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(k),this.focusId===k){let h=this.tree.getChildren(this.focusId).length;if(h>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${h}`}).title=`${h} direct child${h===1?"":"ren"}`),this.compactMode){let g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,F.setIcon)(g,"panel-top"),g.title="Exit compact mode",g.onclick=u=>{u.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),r=o.map(h=>{let g=this.titleForNode(h),u=g.length>s?g.slice(0,s-1)+"\u2026":g;return{id:h.id,label:u}}),l=h=>h.reduce((g,u)=>g+u.label.length+3,0);if(l(r)>n&&r.length>2){let h=!1;for(;l(r)>n&&r.length>2;)r.splice(1,1),h||(r.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),h=!0)}let c=F.Platform.isMobile?"/":" / ";for(let h of r)if(e.createSpan({cls:"stashpad-crumb-sep",text:c}),h.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:h.label}).title=o.map(g=>this.titleForNode(g)).join(" / ");else{let g=h.id,u=e.createSpan({cls:"stashpad-crumb",text:h.label});u.title=h.label,u.onclick=()=>this.navigateTo(g),u.oncontextmenu=p=>{p.preventDefault(),this.openCrumbMenu(p,g)},F.Platform.isMobile&&this.attachLongPress(u,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",h=>{h.preventDefault(),this.openCrumbMenu(h,k)}),F.Platform.isMobile){let h=e.querySelector(".stashpad-crumb-home");h&&this.attachLongPress(h,()=>this.openCrumbMenu(null,k))}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,F.setIcon)(h,"panel-top"),h.title="Exit compact mode",h.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}F.Platform.isMobile||this.renderBreadcrumbLevelsButton(e)}renderBreadcrumbLevelsButton(t){let e=t.createEl("button",{cls:"stashpad-mobile-action-btn stashpad-crumb-levels-btn"});Ft(e,"route","\u22D4"),e.title="Show all levels \u2014 jump to any level in the path",e.onclick=i=>{i.preventDefault(),this.openBreadcrumbLevelsModal()}}openBreadcrumbLevelsModal(){let t=this.tree.pathTo(this.focusId),e=[{id:k,label:"Home",level:0,isCurrent:this.focusId===k,isHome:!0}];t.forEach((i,s)=>{e.push({id:i.id,label:this.titleForNode(i),level:s+1,isCurrent:i.id===this.focusId})}),new xi(this.app,e,i=>this.navigateTo(i),{onContext:(i,s,n,o)=>this.openCrumbMenu(s,i,n,o),attachLongPress:(i,s)=>this.attachLongPress(i,s)}).open()}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",r=>{let l=r.touches[0];s=l?.clientX??0,n=l?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",r=>{let l=r.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,i,s){let n=this.tree.get(e);if(!n)return;let o=new F.Menu;if(o.addItem(r=>r.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>{s?.(),this.navigateTo(e)})),o.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>{s?.(),this.cmdOpenInNewStashpadTab(n)})),n.file&&o.addItem(r=>r.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>{s?.(),this.cmdOpenInEditor(n)})),t&&(t.clientX>0||t.clientY>0))o.showAtMouseEvent(t);else{let l=(i??t?.target??null)?.getBoundingClientRect();o.showAtPosition({x:l?.left??8,y:(l?.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,F.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=r=>{r.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 r=s.createDiv({cls:"stashpad-focused-body"});r.addEventListener("click",h=>this.handleRenderedClick(h,e));let l=s.createDiv({cls:"stashpad-focused-actions"}),c=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,F.setIcon)(c,"pencil"),c.title="Edit in new tab",c.onclick=()=>void this.openFileAtEnd(i);let d=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,F.setIcon)(d,"copy"),d.title="Open this Stashpad in a new tab (clone)",d.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(r,e,{clamp:F.Platform.isMobile,toggleHost:l,toggleAnchor:c})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(r=>r.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((r,l)=>{let c=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(r)});c.title=`Focus into "${this.titleForNode(r)}"`,c.onclick=d=>{d.stopPropagation(),this.navigateTo(r.id)},l<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Cs(this.app,t,F.Platform.isMobile)}bulkActionMessage(t){let e=t.nodes.map(r=>`"${this.titleForNode(r).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(r=>`\u2022 ${r}`).join(` -`):e.slice(0,n).map(r=>`\u2022 ${r}`).join(` +Click to override for this tab.`,d&&c.addClass("is-override"),c.onclick=u=>{u.preventDefault(),this.openFolderPicker()};let g=e.createEl("button",{cls:"stashpad-search-btn"});Ft(g,"search","\u{1F50D}"),g.title="Search notes (Mod+F)",g.onclick=u=>{u.preventDefault(),this.openSearchModal()}}F.Platform.isMobile?(this.renderActionsCluster(e),this.renderMobileFiltersButton(e)):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let i=e.createDiv({cls:"stashpad-time-filter-btns"}),s=i.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,F.setIcon)(s,this.timeFilterCalendar?"calendar":"history"),s.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&&s.addClass("is-active"),s.onclick=c=>{c.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let c of ts){let d=this.timeFilterCalendar?c.calShort:c.rollShort,h=this.timeFilterCalendar?c.calLong:c.rollLong,g=i.createEl("button",{cls:"stashpad-time-filter-btn",text:d});g.title=h,this.timeFilter===c.key&&g.addClass("is-active"),g.onclick=u=>{u.preventDefault(),this.setTimeFilter(c.key)}}let n=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let c of ts){let d=this.timeFilterCalendar?c.calLong:c.rollLong,h=n.createEl("option",{text:d});h.value=c.key,this.timeFilter===c.key&&(h.selected=!0)}n.onchange=()=>this.setTimeFilter(n.value);let o=e.createDiv({cls:"stashpad-view-mode-btns"});if(!F.Platform.isMobile){let c=o.createEl("button",{cls:"stashpad-view-mode-btn"});(0,F.setIcon)(c,"minimize-2"),c.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",c.onclick=d=>{d.preventDefault(),this.plugin.openTinyWindow()}}let a=o.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,F.setIcon)(a,this.compactMode?"panel-top":"rows-2"),a.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&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),this.toggleCompactMode()},F.Platform.isMobile)return;let l=o.createEl("button",{cls:"stashpad-view-mode-btn"});(0,F.setIcon)(l,"external-link"),l.title=X().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.)",l.onclick=c=>{c.preventDefault();let d=X().popoutDuplicates;try{let h=this.app.workspace;if(d){let g=this.leaf.getViewState(),u=h.openPopoutLeaf?.();u?u.setViewState({...g,active:!0}):new F.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else h.moveLeafToPopout?.(this.leaf)}catch(h){new F.Notice(`Stashpad: open-in-new-window failed (${h.message})`)}},this.setupBarOverflow(e)}setupBarOverflow(t){let e=[{key:"nav",icon:"folder-search",title:"Folder & search",memberSel:[".stashpad-folder-btn",".stashpad-search-btn"],memberKeys:["folder","search"],collapsePrio:5,displayIdx:0},{key:"filter",icon:"filter",title:"Tag & color",memberSel:[".stashpad-tag-filter-btn",".stashpad-color-filter-btn"],memberKeys:["tag","color"],collapsePrio:3,displayIdx:1},{key:"arrange",icon:"sliders-horizontal",title:"Sort & view",memberSel:[".stashpad-sort-btn",".stashpad-view-btn"],memberKeys:["sort","view"],collapsePrio:4,displayIdx:2},{key:"time",icon:"clock",title:"Time",memberSel:[".stashpad-time-filter-btns",".stashpad-time-filter-select"],memberKeys:["time"],collapsePrio:2,displayIdx:3},{key:"window",icon:"app-window",title:"Window & layout",memberSel:[".stashpad-view-mode-btns"],memberKeys:["mode"],collapsePrio:1,displayIdx:4}];t.addClass("stashpad-overflow-managed");let i=[];for(let u of[...e].sort((p,f)=>p.displayIdx-f.displayIdx)){let p=u.memberSel.map(B=>t.querySelector(B)).filter(B=>!!B);if(p.length===0)continue;let f=createDiv({cls:"stashpad-bar-group"});t.insertBefore(f,p[0]);let I=f.createDiv({cls:"stashpad-bar-group-expanded"});for(let B of p)I.appendChild(B);let m=f.createDiv({cls:"stashpad-bar-overflow-btn stashpad-bar-group-icon stashpad-overflow-hidden"});m.setAttribute("role","button"),m.setAttribute("tabindex","0"),(0,F.setIcon)(m.createSpan({cls:"stashpad-bar-group-icon-glyph"}),u.icon),m.title=`${u.title} \u2014 combined menu`;let C=B=>{B.preventDefault(),this.openBarOverflowMenu(m,u.memberKeys)};m.onclick=C,m.onkeydown=B=>{(B.key==="Enter"||B.key===" ")&&C(B)},i.push({...u,wrapper:f,expanded:I,iconBtn:m})}let s=t.createDiv({cls:"stashpad-bar-overflow-btn stashpad-bar-kebab stashpad-overflow-hidden"});s.setAttribute("role","button"),s.setAttribute("tabindex","0"),(0,F.setIcon)(s.createSpan({cls:"stashpad-bar-overflow-icon"}),"more-horizontal"),s.title="More filters / view options";let n=[...i].sort((u,p)=>u.collapsePrio-p.collapsePrio),o=[...i].sort((u,p)=>p.displayIdx-u.displayIdx),a=[],l=()=>t.scrollWidth<=t.clientWidth+1,c=()=>{if(!t.isConnected||t.clientWidth===0)return;for(let p of i)p.wrapper.removeClass("stashpad-overflow-hidden"),p.expanded.removeClass("stashpad-overflow-hidden"),p.iconBtn.addClass("stashpad-overflow-hidden"),p.iconBtn.toggleClass("is-active",p.memberKeys.some(f=>this.barUnitActive(f)));if(s.addClass("stashpad-overflow-hidden"),a=[],l())return;for(let p of n){if(l())break;p.expanded.addClass("stashpad-overflow-hidden"),p.iconBtn.removeClass("stashpad-overflow-hidden")}if(l())return;s.removeClass("stashpad-overflow-hidden");let u=[];for(let p of o){if(l())break;p.wrapper.addClass("stashpad-overflow-hidden"),u.push(p)}a=[...u].sort((p,f)=>p.displayIdx-f.displayIdx).flatMap(p=>p.memberKeys),s.toggleClass("is-active",a.some(p=>this.barUnitActive(p)))},d=u=>{u.preventDefault(),this.openBarOverflowMenu(s,a)};s.onclick=d,s.onkeydown=u=>{(u.key==="Enter"||u.key===" ")&&d(u)};try{this.barOverflowRO?.disconnect()}catch{}let h=(t.ownerDocument?.defaultView??window).ResizeObserver,g=-1;this.barOverflowRO=new h(u=>{let p=Math.round(u[u.length-1].contentRect.width);p!==g&&(g=p,c())}),this.barOverflowRO.observe(t),requestAnimationFrame(()=>c())}barUnitActive(t){switch(t){case"folder":return!!this.folderOverride;case"tag":return!!this.tagFilter;case"color":return!!this.colorFilter;case"time":return this.timeFilter!=="all";case"sort":return this.currentViewMode()==="nested"&&this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual";case"view":return this.currentViewMode()!=="nested"||this.currentEncryptionFilter()!=="all"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();case"mode":return this.compactMode;default:return!1}}openBarOverflowMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-mobile-filters-popover").forEach(p=>p.remove());let s=i.body.createDiv({cls:"stashpad-mobile-filters-popover"}),n=t.getBoundingClientRect(),o=i.defaultView??window;s.setCssStyles({right:`${Math.max(8,o.innerWidth-n.right)}px`,left:"auto",top:`${n.bottom+4}px`,maxWidth:"min(360px, calc(100vw - 16px))",width:"max-content",minWidth:"260px"});let a=new F.Scope(this.app.scope),l=()=>{s.remove(),i.removeEventListener("mousedown",c,!0);try{this.app.keymap?.popScope(a)}catch{}},c=p=>{!s.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&l()},h=[{key:"folder",title:"Folder",summary:()=>this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad",populate:p=>this.populateFolderMenuBody(p,l)},{key:"search",title:"Search",summary:()=>"Search notes (Mod+F)",populate:p=>this.populateSearchMenuBody(p,l)},{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,l)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),l)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":ri[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:p=>{if(this.currentViewMode()!=="nested"){p.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(p,l)}},{key:"view",title:"View",summary:()=>_i[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,l)},{key:"time",title:"Time filter",summary:()=>{let p=ts.find(f=>f.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,l)},{key:"mode",title:"View mode",summary:()=>this.compactMode?"Compact on":"Tiny \xB7 Compact \xB7 Window",populate:p=>this.populateModeMenuBody(p,l)}].filter(p=>e.includes(p.key)),g="",u=()=>{s.empty();for(let p of h){let f=s.createDiv({cls:"stashpad-mobile-filters-section"}),I=f.createDiv({cls:"stashpad-mobile-filters-header"}),m=I.createSpan({cls:"stashpad-mobile-filters-chev"});(0,F.setIcon)(m,g===p.key?"chevron-down":"chevron-right"),I.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),I.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),I.onclick=C=>{C.preventDefault(),C.stopPropagation(),g=g===p.key?"":p.key,u()},g===p.key&&p.populate(f.createDiv({cls:"stashpad-mobile-filters-body"}))}};u(),a.register([],"Escape",p=>(p.preventDefault(),l(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{i.addEventListener("mousedown",c,!0)},0)}populateFolderMenuBody(t,e){let i=t.createDiv({cls:"stashpad-sort-popover-row"});i.createSpan({cls:"stashpad-sort-popover-label",text:this.folderOverride?"Change folder (override active)\u2026":"Change folder for this tab\u2026"}),i.onclick=s=>{s.preventDefault(),s.stopPropagation(),e(),this.openFolderPicker()}}populateSearchMenuBody(t,e){let i=t.createDiv({cls:"stashpad-sort-popover-row"});i.createSpan({cls:"stashpad-sort-popover-label",text:"Search notes\u2026"}),i.onclick=s=>{s.preventDefault(),s.stopPropagation(),e(),this.openSearchModal()}}populateModeMenuBody(t,e){let i=(n,o)=>{let a=t.createDiv({cls:"stashpad-sort-popover-row"});a.createSpan({cls:"stashpad-sort-popover-label",text:n}),a.onclick=l=>{l.preventDefault(),l.stopPropagation(),e(),o()}};i("Tiny mode (popout window)",()=>void this.plugin.openTinyWindow());let s=t.createDiv({cls:"stashpad-sort-popover-row"});this.compactMode&&s.addClass("is-active"),s.createSpan({cls:"stashpad-sort-popover-label",text:this.compactMode?"Compact mode (on)":"Compact mode"}),s.onclick=n=>{n.preventDefault(),n.stopPropagation(),e(),this.toggleCompactMode()},i(X().popoutDuplicates?"Duplicate to new window":"Move to new window",()=>{try{let n=this.app.workspace;if(X().popoutDuplicates){let o=n.openPopoutLeaf?.();o?o.setViewState({...this.leaf.getViewState(),active:!0}):new F.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else n.moveLeafToPopout?.(this.leaf)}catch(n){new F.Notice(`Stashpad: open-in-new-window failed (${n.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"});Ft(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==k;i.title=this.navBackStack.length>0?"Back":this.focusId!==k?"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"});Ft(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;if(n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=d=>{d.preventDefault(),this.navigateForward()},F.Platform.isMobile){let d=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ft(d,"route","\u22D4"),d.title="Jump to a level in the path",d.onclick=h=>{h.preventDefault(),this.openBreadcrumbLevelsModal()}}let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),l=this.mobileSelectMode;Ft(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(u=>u.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 F.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let c=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ft(c,"zap","\u26A1"),c.title="Actions (move, delete, undo, \u2026)",c.onclick=d=>{d.preventDefault(),this.openMobileActionsMenu(c)}}openMobileActionsMenu(t){let e=new F.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===xe?"Tagged":this.tagFilter===Ne?"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"});Ft(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(w=>w.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 F.Scope(this.app.scope),o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(n)}catch{}},a=w=>{!i.contains(w.target)&&w.target!==t&&!t.contains(w.target)&&o()},l=i.createDiv({cls:"stashpad-tag-filter-search"}),c=l.createSpan({cls:"stashpad-tag-filter-search-icon"});Ft(c,"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"}});Ft(h,"x","\xD7"),h.setCssStyles({display:"none"});let g=i.createDiv({cls:"stashpad-tag-filter-list"}),u=this.collectFolderTags(),p=[],f=0,I=w=>{this.setTagFilter(w),o()},m=w=>{if(p.length===0){f=0;return}f=(w+p.length)%p.length,p.forEach((y,Q)=>y.el.toggleClass("is-highlighted",Q===f)),p[f].el.scrollIntoView({block:"nearest"})},C=(w,y,Q,v)=>{let E=g.createDiv({cls:"stashpad-tag-filter-row"});v&&E.addClass("is-active"),E.createSpan({cls:"stashpad-tag-filter-row-label",text:w}),typeof Q=="number"&&E.createSpan({cls:"stashpad-tag-filter-row-count",text:String(Q)});let S=p.length;p.push({value:y,el:E}),E.onmousedown=D=>{D.preventDefault(),I(y)},E.onmouseenter=()=>m(S)},B=()=>{let w=d.value;h.setCssStyles({display:w?"":"none"}),g.empty(),p=[];let y=this.tagFilter?.toLowerCase();if(w.trim()){let Q=aa(w,u);if(Q.length===0)g.createDiv({cls:"stashpad-tag-filter-empty",text:"No matching tags"});else for(let v of Q)C(`#${v.label}`,v.raw,v.count,y===v.raw.toLowerCase())}else{C("All tags",null,void 0,!this.tagFilter),C("Tagged",xe,void 0,this.tagFilter===xe),C("Untagged",Ne,void 0,this.tagFilter===Ne);for(let Q of u)C(`#${Q.label}`,Q.raw,Q.count,y===Q.raw.toLowerCase())}m(0)};h.onclick=()=>{d.value="",B(),d.focus()},d.addEventListener("input",B),d.addEventListener("keydown",w=>{w.key==="ArrowDown"?(w.preventDefault(),m(f+1)):w.key==="ArrowUp"?(w.preventDefault(),m(f-1)):w.key==="Enter"&&(w.preventDefault(),p[f]&&I(p[f].value))}),n.register([],"Escape",w=>(w.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 c=this.plugin.getColorAlias(this.noteFolder,l);a.setText(c??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(c=>c.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 F.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",l,!0);try{this.app.keymap?.popScope(o)}catch{}},l=c=>{!s.contains(c.target)&&c.target!==t&&!t.contains(c.target)&&a()};o.register([],"Escape",c=>(c.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",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,F.setIcon)(l,"arrow-up-down");let c=a.createSpan({cls:"stashpad-sort-label"});o?(c.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${_i[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(c.setText(ri[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: ${ri[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 F.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,F.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 c=d=>{d.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=c,e.onkeydown=d=>{(d.key==="Enter"||d.key===" ")&&c(d)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(u=>u.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window,o=s.bottom+280>n.innerHeight;i.setCssStyles({right:`${Math.max(8,n.innerWidth-s.right)}px`,left:"auto",...o?{bottom:`${Math.max(8,n.innerHeight-s.top+4)}px`,top:"auto"}:{top:`${s.bottom+4}px`,bottom:"auto"},maxWidth:"min(360px, calc(100vw - 16px))",maxHeight:"min(60vh, 420px)",overflowY:"auto",width:"max-content",minWidth:"260px"});let a=()=>{i.remove(),e.removeEventListener("mousedown",l,!0);try{this.app.keymap?.popScope(g)}catch{}},l=u=>{!i.contains(u.target)&&u.target!==t&&!t.contains(u.target)&&a()},c=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:u=>this.populateTagMenuBody(u,a)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:u=>this.populateColorMenuBody(u,this.collectFolderColors(),a)},{key:"time",title:"Time filter",summary:()=>{let u=ts.find(p=>p.key===this.timeFilter);return u?this.timeFilterCalendar?u.calShort:u.rollShort:"All"},populate:u=>this.populateTimeMenuBody(u,a)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":ri[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:u=>{if(this.currentViewMode()!=="nested"){u.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(u,a)}},{key:"view",title:"View",summary:()=>_i[this.currentViewMode()],populate:u=>this.populateViewMenuBody(u,a)}],d="",h=()=>{i.empty();for(let u of c){let p=i.createDiv({cls:"stashpad-mobile-filters-section"}),f=p.createDiv({cls:"stashpad-mobile-filters-header"}),I=f.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,F.setIcon)(I,d===u.key?"chevron-down":"chevron-right"),f.createSpan({cls:"stashpad-mobile-filters-title",text:u.title}),f.createSpan({cls:"stashpad-mobile-filters-summary",text:u.summary()}),f.onclick=m=>{m.preventDefault(),m.stopPropagation(),d=d===u.key?"":u.key,h()},d===u.key){let m=p.createDiv({cls:"stashpad-mobile-filters-body"});u.populate(m)}}};h();let g=new F.Scope(this.app.scope);g.register([],"Escape",u=>(u.preventDefault(),a(),!1)),this.app.keymap?.pushScope(g),setTimeout(()=>{e.addEventListener("mousedown",l,!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,F.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(_i[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"});F.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 F.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=(y,Q)=>{let v=t.createDiv({cls:"stashpad-view-popover-row"});y===i&&v.addClass("is-active"),v.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:_i[y]}),v.createDiv({cls:"stashpad-view-popover-desc",text:Q}),v.onclick=async S=>{S.preventDefault(),S.stopPropagation(),e(),y!==i&&(await this.setViewMode(y),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 y=this.currentEncryptionFilter(),Q=(v,E,S)=>{let D=t.createDiv({cls:"stashpad-view-popover-row"});v===y&&D.addClass("is-active"),D.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:E}),D.createDiv({cls:"stashpad-view-popover-desc",text:S}),D.onclick=async H=>{H.preventDefault(),H.stopPropagation(),v!==y&&(await this.setEncryptionFilter(v),this.refreshList()),e()}};Q("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),Q("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),Q("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 y=>{y.target!==o&&(y.preventDefault(),o.checked=!o.checked),await this.setHideChildless(o.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),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 y=>{y.target!==l&&(y.preventDefault(),l.checked=!l.checked),await this.setHideCompleted(l.checked),this.refreshList()};let c=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),d=c.createEl("input",{type:"checkbox"});d.checked=this.currentAttachmentsOnly(),c.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),c.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),c.onclick=async y=>{y.target!==d&&(y.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 y=>{i==="everything"&&(y.target!==g&&(y.preventDefault(),g.checked=!g.checked),await this.setIncludeAttachments(g.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let u=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),p=u.createEl("input",{type:"checkbox"});p.checked=this.importedOnly,u.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),u.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),u.onclick=y=>{y.target!==p&&(y.preventDefault(),p.checked=!p.checked),this.importedOnly=p.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let f=new Map,I=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==I)continue;let Q=fe(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);Q&&f.set(Q.id,Q.name)}let m=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),C=m.createDiv({cls:"stashpad-view-popover-main"});C.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let B=C.createEl("select",{cls:"stashpad-view-author-select"}),w=B.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[y,Q]of[...f.entries()].sort((v,E)=>v[1].localeCompare(E[1]))){let v=B.createEl("option",{text:Q,value:y});this.authorFilter===y&&(v.selected=!0)}B.onclick=y=>y.stopPropagation(),B.onchange=()=>{this.authorFilter=B.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},m.createDiv({cls:"stashpad-view-popover-desc",text:f.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 ho){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:ri[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 ts){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"}),c=l.createSpan({cls:"stashpad-color-filter-swatch"});o?c.setCssStyles({background:o}):c.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",xe),s("Untagged",Ne);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"});Ft(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==k||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==k?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Ft(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===k?a:`${a} / ${this.titleForNode(o).trim()}`,c=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),d=c.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,F.setIcon)(d,"folder"),c.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:l}),c.title=`${this.noteFolder}${this.focusId!==k?` / ${this.titleForNode(o).trim()}`:""} +Click to switch / create folder.`,c.onclick=f=>{f.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()},!F.Platform.isMobile){let f=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,F.setIcon)(f,"contrast"),f.title="Window transparency",this.tinyOpacity<1&&f.addClass("is-active"),f.onclick=I=>{I.stopPropagation(),this.toggleTinyOpacityPopover(f)}}let u=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,F.setIcon)(u,this.compactMode?"panel-top":"rows-2"),u.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&u.addClass("is-active"),u.onclick=()=>{this.toggleCompactMode()};let p=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,F.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)||c()},l=d=>{d.key==="Escape"&&c()},c=()=>{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),F.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"});F.Platform.isMobile||this.renderActionsCluster(e);let i=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(F.Platform.isMobile?((0,F.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(k),this.focusId===k){let h=this.tree.getChildren(this.focusId).length;if(h>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${h}`}).title=`${h} direct child${h===1?"":"ren"}`),this.compactMode){let g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,F.setIcon)(g,"panel-top"),g.title="Exit compact mode",g.onclick=u=>{u.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(h=>{let g=this.titleForNode(h),u=g.length>s?g.slice(0,s-1)+"\u2026":g;return{id:h.id,label:u}}),l=h=>h.reduce((g,u)=>g+u.label.length+3,0);if(l(a)>n&&a.length>2){let h=!1;for(;l(a)>n&&a.length>2;)a.splice(1,1),h||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),h=!0)}let c=F.Platform.isMobile?"/":" / ";for(let h of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:c}),h.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:h.label}).title=o.map(g=>this.titleForNode(g)).join(" / ");else{let g=h.id,u=e.createSpan({cls:"stashpad-crumb",text:h.label});u.title=h.label,u.onclick=()=>this.navigateTo(g),u.oncontextmenu=p=>{p.preventDefault(),this.openCrumbMenu(p,g)},F.Platform.isMobile&&this.attachLongPress(u,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",h=>{h.preventDefault(),this.openCrumbMenu(h,k)}),F.Platform.isMobile){let h=e.querySelector(".stashpad-crumb-home");h&&this.attachLongPress(h,()=>this.openCrumbMenu(null,k))}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,F.setIcon)(h,"panel-top"),h.title="Exit compact mode",h.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}F.Platform.isMobile||this.renderBreadcrumbLevelsButton(e)}renderBreadcrumbLevelsButton(t){let e=t.createEl("button",{cls:"stashpad-mobile-action-btn stashpad-crumb-levels-btn"});Ft(e,"route","\u22D4"),e.title="Show all levels \u2014 jump to any level in the path",e.onclick=i=>{i.preventDefault(),this.openBreadcrumbLevelsModal()}}openBreadcrumbLevelsModal(){let t=this.tree.pathTo(this.focusId),e=[{id:k,label:"Home",level:0,isCurrent:this.focusId===k,isHome:!0}];t.forEach((i,s)=>{e.push({id:i.id,label:this.titleForNode(i),level:s+1,isCurrent:i.id===this.focusId})}),new Ni(this.app,e,i=>this.navigateTo(i),{onContext:(i,s,n,o)=>this.openCrumbMenu(s,i,n,o),attachLongPress:(i,s)=>this.attachLongPress(i,s)}).open()}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,i,s){let n=this.tree.get(e);if(!n)return;let o=new F.Menu;if(o.addItem(a=>a.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>{s?.(),this.navigateTo(e)})),o.addItem(a=>a.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>{s?.(),this.cmdOpenInNewStashpadTab(n)})),n.file&&o.addItem(a=>a.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>{s?.(),this.cmdOpenInEditor(n)})),t&&(t.clientX>0||t.clientY>0))o.showAtMouseEvent(t);else{let l=(i??t?.target??null)?.getBoundingClientRect();o.showAtPosition({x:l?.left??8,y:(l?.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,F.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"}),c=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,F.setIcon)(c,"pencil"),c.title="Edit in new tab",c.onclick=()=>void this.openFileAtEnd(i);let d=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,F.setIcon)(d,"copy"),d.title="Open this Stashpad in a new tab (clone)",d.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:F.Platform.isMobile,toggleHost:l,toggleAnchor:c})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(a=>a.id===this.focusId),n=i.slice(s+1,i.length-1);if(n.length===0)return;let o=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,l)=>{let c=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});c.title=`Focus into "${this.titleForNode(a)}"`,c.onclick=d=>{d.stopPropagation(),this.navigateTo(a.id)},l<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Qs(this.app,t,F.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),r=i===this.cursorIdx,l=this.inListPicker?.activeIdx===i,c=t.createDiv({cls:"stashpad-note"});o&&c.addClass("is-selected"),r&&c.addClass("is-cursor"),r&&this.cursorHasMoved&&this.plugin.settings.autoExpandCursorRow&&!this.cursorExpandOverride.has(e.id)&&c.addClass("is-cursor-expanded"),l&&c.addClass("is-pick-target"),this.isCompleted(e)&&c.addClass("is-completed"),this.isListPinned(e.id)&&c.addClass("is-list-pinned"),this.isCutPending(e.id)?c.addClass("is-cut-pending"):this.isCopyPending(e.id)&&c.addClass("is-copy-pending"),c.dataset.idx=String(i),c.dataset.id=e.id;let d=this.currentViewMode()==="nested";c.draggable=d,d&&this.dnd.attachRowDnD(c,e,i),c.addEventListener("click",Q=>this.handleRowClick(Q,i,e)),c.addEventListener("dblclick",Q=>{if(!this.plugin.settings.doubleClickToFocus)return;let v=this.shouldAbsorbDismissTap();if(v&&this.aimedTapTargetId&&Date.now()-this.aimedTapAt<=ts.AIMED_TAP_WINDOW_MS){let S=this.aimedTapTargetId;this.aimedTapTargetId=null,this.traceTap("dblclick",Q,i,!1),Q.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(S);return}if(this.traceTap("dblclick",Q,i,v),v){Q.preventDefault();return}Q.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(Q.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let h=this.isTask(e)||this.compactMode;h&&(c.addClass("is-task"),F.Platform.isMobile||this.addTaskCheckbox(c,e));let g=c.createDiv({cls:"stashpad-note-meta"}),u=g.createDiv({cls:"stashpad-note-meta-top"});u.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let p=this.colorForNode(e),f=u.createDiv({cls:"stashpad-note-grip"});p&&f.addClass("has-color"),(0,F.setIcon)(f,"grip-vertical"),f.title=p?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",f.draggable=d,d||(f.title=p?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),p&&f.style.setProperty("--stashpad-note-color",p);let I=h&&F.Platform.isMobile,m=this.isListPinned(e.id);if(n>0||I||m){let Q=g.createDiv({cls:"stashpad-note-meta-bottom"});if(m){let v=Q.createSpan({cls:"stashpad-note-listpin"});(0,F.setIcon)(v,"pin"),v.setAttr("aria-label","Pinned to top of list")}if(I&&this.addTaskCheckbox(Q,e),n>0){let v=Q.createSpan({cls:"stashpad-note-enter"});p&&(v.style.color=p),(0,F.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=E=>{E.stopPropagation(),this.navigateTo(e.id)}}}if(p)c.addClass("has-color"),c.style.setProperty("--stashpad-note-color",p);else{let Q=this.inheritedColorForNode(e);Q&&Q.depth>0&&(c.addClass("has-inherited-color"),c.style.setProperty("--stashpad-inherited-color",Q.hex),c.style.setProperty("--stashpad-inherited-depth",String(Q.depth)))}let C=c.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(C,e);let B=C.createDiv({cls:"stashpad-note-body-content"}),w=c.createDiv({cls:"stashpad-note-actions"}),y;if(F.Platform.isMobile){let Q=w.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,F.setIcon)(Q,"ellipsis-vertical"),Q.title="Actions",Q.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},y=Q}else{let Q=w.createEl("button",{cls:"stashpad-pencil"});(0,F.setIcon)(Q,"pencil"),Q.title="Edit in new tab",Q.onclick=E=>{E.stopPropagation(),this.openFileAtEnd(s)};let v=w.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,F.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=E=>{E.stopPropagation(),this.navigateTo(e.id)},y=Q}this.renderNoteBody(B,e,{clamp:!0,toggleHost:w,toggleAnchor:y}),this.renderVersionTabs(C,e),c.oncontextmenu=Q=>{Q.preventDefault(),this.openNoteMenu(Q,e)}}renderVersionTabs(t,e){if(!this.plugin.settings.enableSheetVersions||!Bi(It(this.app,e)))return;let i=Yt(It(this.app,e)),s=e.parent??this.focusId,n=this.tree.getChildren(s),o=vn(this.app,n.filter(c=>{let d=It(this.app,c);return Bi(d)&&Yt(d)===i}));if(o.length<2)return;let r=t.createDiv({cls:"stashpad-version-tabs"});for(let c of o){let d=c.id===e.id,h=It(this.app,c),g=yi(h),u=Jo(h),p=r.createDiv({cls:"stashpad-version-tab"+(d?" is-active":"")+(g?" is-final":"")+(u?" is-original":"")});g&&p.createSpan({cls:"stashpad-version-star",text:"\u2605"}),p.createSpan({cls:"stashpad-version-tab-label",text:Vo(this.app,c,this.titleForNode(c).trim()||"Untitled")});let f=this.titleForNode(c).trim();p.title=u?`${f} (original)`:`${f} (forked)`,d||(p.onclick=I=>{I.stopPropagation(),this.setActiveVersion(i,c.id)})}let l=r.createEl("button",{cls:"stashpad-version-add stashpad-version-fork"});(0,F.setIcon)(l,"git-fork"),l.title="Fork this version (copy)",l.onclick=c=>{c.stopPropagation(),this.cmdForkVersion(e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,F.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:r,attachments:l,html:c}=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=r):d.append((0,F.sanitizeHTMLToDom)(c)),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(h){this.attachExpandToggle(i,t,e,h);return}let u=t.closest?.(".stashpad-note.is-cursor-expanded");u&&u.removeClass("is-cursor-expanded");let p=d.scrollHeight>d.clientHeight+4;if(u&&u.addClass("is-cursor-expanded"),o.ovW=g,o.ovV=p,!p){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 r=!!e.closest?.(".stashpad-note.is-cursor-expanded"),l=s||r,c=o.createEl("button",{cls:"stashpad-expand-toggle"});c.title=l?"Show less":"Show more",n||F.Platform.isMobile?((0,F.setIcon)(c,l?"chevron-up":"chevron-down"),c.addClass("is-icon"),n&&c.addClass("is-inline")):c.setText(l?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(c,t.toggleAnchor),c.addEventListener("dblclick",d=>{d.preventDefault(),d.stopPropagation()}),c.addEventListener("mousedown",d=>{d.stopPropagation()}),c.onclick=d=>{d.stopPropagation();let h=e.closest?.(".stashpad-note"),g=!!h?.classList.contains("is-cursor-expanded"),p=!(this.isNoteExpanded(i.id)||g);g&&!p?(h?.removeClass("is-cursor-expanded"),this.cursorExpandOverride.add(i.id)):p&&this.cursorExpandOverride.delete(i.id),this.setNoteExpanded(i.id,p),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(),r=i.createDiv({cls:"stashpad-att"});if(r.title=s,n&&Rc.has(o)){let l=r.createEl("img",{cls:"stashpad-att-img"});l.src=this.app.vault.getResourcePath(n),l.alt=s}else{r.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let l=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");r.createDiv({cls:"stashpad-att-name",text:l})}r.onclick=l=>{l.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposerNavCluster(t){let e=t.createDiv({cls:"stashpad-composer-nav"}),i=e.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-nav-folder"});(0,F.setIcon)(i,this.plugin.getFolderIcon(this.noteFolder)??"folder");let s=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";i.createSpan({cls:"stashpad-btn-text",text:s}),i.title=`Folder: ${this.noteFolder} -Tap to switch / create.`,this.folderOverride&&i.addClass("is-active"),i.onmousedown=o=>o.preventDefault(),i.onclick=o=>{o.preventDefault(),this.openFolderPicker()};let n=e.createEl("button",{cls:"stashpad-composer-btn"});Ft(n,"search","\u{1F50D}"),n.title="Search notes (Mod+F)",n.onmousedown=o=>o.preventDefault(),n.onclick=o=>{o.preventDefault(),this.openSearchModal()}}renderComposer(t){let e=X(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=t.createDiv({cls:"stashpad-composer"}),r=n.createDiv({cls:"stashpad-composer-input-wrap"}).createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});r.value=this.composerDraft,this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,F.debounce)(N=>{this.saveDraft(N)},250)),r.addEventListener("input",()=>{this.composerDraft=r.value,this.debouncedSaveDraft(r.value)}),r.addEventListener("blur",()=>{this.saveDraft(r.value)});let l=null,c=()=>{l||(l=new F.Scope(this.app.scope),l.register([],"Escape",()=>(this.composerExitAt=Date.now(),r.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(r.addEventListener("focus",c),r.addEventListener("blur",d),document.activeElement===r&&c(),F.Platform.isMobile){let N=()=>{this.keyboardTransitionUntil=Date.now()+600};r.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),N()}),r.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),N(),this.tapSettleUntil=Date.now()+300,F.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=r,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new ni(this.app,r),this.composerAutocomplete.attach();let h=async N=>{let b="";for(let T of N){let P=await this.importAttachment(T);if(!P)continue;let R=r.value+b,Z=R&&!R.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,c=t.createDiv({cls:"stashpad-note"});o&&c.addClass("is-selected"),a&&c.addClass("is-cursor"),a&&this.cursorHasMoved&&this.plugin.settings.autoExpandCursorRow&&!this.cursorExpandOverride.has(e.id)&&c.addClass("is-cursor-expanded"),l&&c.addClass("is-pick-target"),this.isCompleted(e)&&c.addClass("is-completed"),this.isListPinned(e.id)&&c.addClass("is-list-pinned"),this.isCutPending(e.id)?c.addClass("is-cut-pending"):this.isCopyPending(e.id)&&c.addClass("is-copy-pending"),c.dataset.idx=String(i),c.dataset.id=e.id;let d=this.currentViewMode()==="nested";c.draggable=d,d&&this.dnd.attachRowDnD(c,e,i),c.addEventListener("click",Q=>this.handleRowClick(Q,i,e)),c.addEventListener("dblclick",Q=>{if(!this.plugin.settings.doubleClickToFocus)return;let v=this.shouldAbsorbDismissTap();if(v&&this.aimedTapTargetId&&Date.now()-this.aimedTapAt<=es.AIMED_TAP_WINDOW_MS){let S=this.aimedTapTargetId;this.aimedTapTargetId=null,this.traceTap("dblclick",Q,i,!1),Q.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(S);return}if(this.traceTap("dblclick",Q,i,v),v){Q.preventDefault();return}Q.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(Q.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let h=this.isTask(e)||this.compactMode;h&&(c.addClass("is-task"),F.Platform.isMobile||this.addTaskCheckbox(c,e));let g=c.createDiv({cls:"stashpad-note-meta"}),u=g.createDiv({cls:"stashpad-note-meta-top"});u.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let p=this.colorForNode(e),f=u.createDiv({cls:"stashpad-note-grip"});p&&f.addClass("has-color"),(0,F.setIcon)(f,"grip-vertical"),f.title=p?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",f.draggable=d,d||(f.title=p?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),p&&f.style.setProperty("--stashpad-note-color",p);let I=h&&F.Platform.isMobile,m=this.isListPinned(e.id);if(n>0||I||m){let Q=g.createDiv({cls:"stashpad-note-meta-bottom"});if(m){let v=Q.createSpan({cls:"stashpad-note-listpin"});(0,F.setIcon)(v,"pin"),v.setAttr("aria-label","Pinned to top of list")}if(I&&this.addTaskCheckbox(Q,e),n>0){let v=Q.createSpan({cls:"stashpad-note-enter"});p&&(v.style.color=p),(0,F.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=E=>{E.stopPropagation(),this.navigateTo(e.id)}}}if(p)c.addClass("has-color"),c.style.setProperty("--stashpad-note-color",p);else{let Q=this.inheritedColorForNode(e);Q&&Q.depth>0&&(c.addClass("has-inherited-color"),c.style.setProperty("--stashpad-inherited-color",Q.hex),c.style.setProperty("--stashpad-inherited-depth",String(Q.depth)))}let C=c.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(C,e);let B=C.createDiv({cls:"stashpad-note-body-content"}),w=c.createDiv({cls:"stashpad-note-actions"}),y;if(F.Platform.isMobile){let Q=w.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,F.setIcon)(Q,"ellipsis-vertical"),Q.title="Actions",Q.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},y=Q}else{let Q=w.createEl("button",{cls:"stashpad-pencil"});(0,F.setIcon)(Q,"pencil"),Q.title="Edit in new tab",Q.onclick=E=>{E.stopPropagation(),this.openFileAtEnd(s)};let v=w.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,F.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=E=>{E.stopPropagation(),this.navigateTo(e.id)},y=Q}this.renderNoteBody(B,e,{clamp:!0,toggleHost:w,toggleAnchor:y}),this.renderVersionTabs(C,e),c.oncontextmenu=Q=>{Q.preventDefault(),this.openNoteMenu(Q,e)}}renderVersionTabs(t,e){if(!this.plugin.settings.enableSheetVersions||!yi(It(this.app,e)))return;let i=Yt(It(this.app,e)),s=e.parent??this.focusId,n=this.tree.getChildren(s),o=bn(this.app,n.filter(c=>{let d=It(this.app,c);return yi(d)&&Yt(d)===i}));if(o.length<2)return;let a=t.createDiv({cls:"stashpad-version-tabs"});for(let c of o){let d=c.id===e.id,h=It(this.app,c),g=wi(h),u=Vo(h),p=a.createDiv({cls:"stashpad-version-tab"+(d?" is-active":"")+(g?" is-final":"")+(u?" is-original":"")});g&&p.createSpan({cls:"stashpad-version-star",text:"\u2605"}),p.createSpan({cls:"stashpad-version-tab-label",text:Zo(this.app,c,this.titleForNode(c).trim()||"Untitled")});let f=this.titleForNode(c).trim();p.title=u?`${f} (original)`:`${f} (forked)`,d||(p.onclick=I=>{I.stopPropagation(),this.setActiveVersion(i,c.id)})}let l=a.createEl("button",{cls:"stashpad-version-add stashpad-version-fork"});(0,F.setIcon)(l,"git-fork"),l.title="Fork this version (copy)",l.onclick=c=>{c.stopPropagation(),this.cmdForkVersion(e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,F.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:c}=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,F.sanitizeHTMLToDom)(c)),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(h){this.attachExpandToggle(i,t,e,h);return}let u=t.closest?.(".stashpad-note.is-cursor-expanded");u&&u.removeClass("is-cursor-expanded");let p=d.scrollHeight>d.clientHeight+4;if(u&&u.addClass("is-cursor-expanded"),o.ovW=g,o.ovV=p,!p){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=!!e.closest?.(".stashpad-note.is-cursor-expanded"),l=s||a,c=o.createEl("button",{cls:"stashpad-expand-toggle"});c.title=l?"Show less":"Show more",n||F.Platform.isMobile?((0,F.setIcon)(c,l?"chevron-up":"chevron-down"),c.addClass("is-icon"),n&&c.addClass("is-inline")):c.setText(l?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(c,t.toggleAnchor),c.addEventListener("dblclick",d=>{d.preventDefault(),d.stopPropagation()}),c.addEventListener("mousedown",d=>{d.stopPropagation()}),c.onclick=d=>{d.stopPropagation();let h=e.closest?.(".stashpad-note"),g=!!h?.classList.contains("is-cursor-expanded"),p=!(this.isNoteExpanded(i.id)||g);g&&!p?(h?.removeClass("is-cursor-expanded"),this.cursorExpandOverride.add(i.id)):p&&this.cursorExpandOverride.delete(i.id),this.setNoteExpanded(i.id,p),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&&Lc.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)}}}renderComposerNavCluster(t){let e=t.createDiv({cls:"stashpad-composer-nav"}),i=e.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-nav-folder"});(0,F.setIcon)(i,this.plugin.getFolderIcon(this.noteFolder)??"folder");let s=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";i.createSpan({cls:"stashpad-btn-text",text:s}),i.title=`Folder: ${this.noteFolder} +Tap to switch / create.`,this.folderOverride&&i.addClass("is-active"),i.onmousedown=o=>o.preventDefault(),i.onclick=o=>{o.preventDefault(),this.openFolderPicker()};let n=e.createEl("button",{cls:"stashpad-composer-btn"});Ft(n,"search","\u{1F50D}"),n.title="Search notes (Mod+F)",n.onmousedown=o=>o.preventDefault(),n.onclick=o=>{o.preventDefault(),this.openSearchModal()}}renderComposer(t){let e=X(),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,F.debounce)(N=>{this.saveDraft(N)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value)}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let l=null,c=()=>{l||(l=new F.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",c),a.addEventListener("blur",d),document.activeElement===a&&c(),F.Platform.isMobile){let N=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),N()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),N(),this.tapSettleUntil=Date.now()+300,F.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new oi(this.app,a),this.composerAutocomplete.attach();let h=async N=>{let b="";for(let T of N){let P=await this.importAttachment(T);if(!P)continue;let R=a.value+b,Z=R&&!R.endsWith(` `)?` `:"";b+=`${Z}${P} -`}b&&(r.value=r.value+b,this.composerDraft=r.value,this.saveDraft(r.value),r.focus(),r.setSelectionRange(r.value.length,r.value.length))};r.addEventListener("dragover",N=>{if(!(!N.dataTransfer||!Array.from(N.dataTransfer.types).includes("Files"))){N.preventDefault(),N.stopPropagation();try{N.dataTransfer.dropEffect="copy"}catch{}}}),r.addEventListener("drop",N=>{let b=Array.from(N.dataTransfer?.files??[]);b.length!==0&&(N.preventDefault(),N.stopPropagation(),h(b))}),r.addEventListener("paste",N=>{let b=this.plugin.noteClipboard;if(b?.mode==="cut"&&b.text&&N.clipboardData?.getData("text/plain")===b.text){if(this.focusedInsideCut(b.ids)){N.preventDefault(),new F.Notice("Can't paste a cut note into the note you're cutting.");return}N.preventDefault(),this.completeCutIntoComposer();return}let T=[],P=N.clipboardData;if(P){for(let R of Array.from(P.files??[]))T.push(R);if(T.length===0){for(let R of Array.from(P.items??[]))if(R.kind==="file"){let Z=R.getAsFile();Z&&T.push(Z)}}T.length!==0&&(N.preventDefault(),N.stopPropagation(),h(T))}});let g=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});g.setCssStyles({display:"none"});let u=n.createDiv({cls:"stashpad-composer-btn-rail"});F.Platform.isMobile&&this.renderComposerNavCluster(u);let p=u.createDiv({cls:"stashpad-composer-btn-group"}),f=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(f,"list-end");let I=Qi[X().splitMode].toLowerCase();f.title=s?`Split: ON \u2014 ${I} (Mod+/ to toggle, right-click to change)`:`Split into notes (Mod+/) \u2014 right-click to choose: ${I}`,s&&f.addClass("is-active"),f.onmousedown=N=>N.preventDefault(),f.onclick=N=>{N.preventDefault(),this.toggleSplit()},f.oncontextmenu=N=>{N.preventDefault();let b=new F.Menu,T=X().splitMode;["lines","paragraphs","headings"].forEach(P=>{b.addItem(R=>R.setTitle(Qi[P]).setChecked(P===T).onClick(async()=>{this.plugin.settings.splitMode=P,await this.plugin.saveSettings(),this.render()}))}),b.showAtMouseEvent(N)};let m=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(m,"map-pin"),this.nextDestination&&m.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),m.title="Set destination (Mod+D)",this.nextDestination&&m.addClass("is-active"),m.onmousedown=N=>N.preventDefault(),m.onclick=N=>{N.preventDefault();let b=document.activeElement===r;this.openDestinationPicker(b)};let C=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(C,i?"corner-down-left":"arrow-big-down-dash"),C.title=i?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",C.onmousedown=N=>N.preventDefault(),C.onclick=N=>{N.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let B=N=>{let b=r.value&&!r.value.endsWith(` +`}b&&(a.value=a.value+b,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",N=>{if(!(!N.dataTransfer||!Array.from(N.dataTransfer.types).includes("Files"))){N.preventDefault(),N.stopPropagation();try{N.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",N=>{let b=Array.from(N.dataTransfer?.files??[]);b.length!==0&&(N.preventDefault(),N.stopPropagation(),h(b))}),a.addEventListener("paste",N=>{let b=this.plugin.noteClipboard;if(b?.mode==="cut"&&b.text&&N.clipboardData?.getData("text/plain")===b.text){if(this.focusedInsideCut(b.ids)){N.preventDefault(),new F.Notice("Can't paste a cut note into the note you're cutting.");return}N.preventDefault(),this.completeCutIntoComposer();return}let T=[],P=N.clipboardData;if(P){for(let R of Array.from(P.files??[]))T.push(R);if(T.length===0){for(let R of Array.from(P.items??[]))if(R.kind==="file"){let Z=R.getAsFile();Z&&T.push(Z)}}T.length!==0&&(N.preventDefault(),N.stopPropagation(),h(T))}});let g=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});g.setCssStyles({display:"none"});let u=n.createDiv({cls:"stashpad-composer-btn-rail"});F.Platform.isMobile&&this.renderComposerNavCluster(u);let p=u.createDiv({cls:"stashpad-composer-btn-group"}),f=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(f,"list-end");let I=Ei[X().splitMode].toLowerCase();f.title=s?`Split: ON \u2014 ${I} (Mod+/ to toggle, right-click to change)`:`Split into notes (Mod+/) \u2014 right-click to choose: ${I}`,s&&f.addClass("is-active"),f.onmousedown=N=>N.preventDefault(),f.onclick=N=>{N.preventDefault(),this.toggleSplit()},f.oncontextmenu=N=>{N.preventDefault();let b=new F.Menu,T=X().splitMode;["lines","paragraphs","headings"].forEach(P=>{b.addItem(R=>R.setTitle(Ei[P]).setChecked(P===T).onClick(async()=>{this.plugin.settings.splitMode=P,await this.plugin.saveSettings(),this.render()}))}),b.showAtMouseEvent(N)};let m=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(m,"map-pin"),this.nextDestination&&m.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),m.title="Set destination (Mod+D)",this.nextDestination&&m.addClass("is-active"),m.onmousedown=N=>N.preventDefault(),m.onclick=N=>{N.preventDefault();let b=document.activeElement===a;this.openDestinationPicker(b)};let C=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(C,i?"corner-down-left":"arrow-big-down-dash"),C.title=i?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",C.onmousedown=N=>N.preventDefault(),C.onclick=N=>{N.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let B=N=>{let b=a.value&&!a.value.endsWith(` `)?` -`:"";r.value+=`${b}${N} -`,this.composerDraft=r.value},w=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(w,"paperclip"),w.title="Attach files",w.onmousedown=N=>N.preventDefault(),w.onclick=N=>{N.preventDefault();let b=document.activeElement===r;if(g.click(),b){let T=()=>{r.focus()};setTimeout(T,100),setTimeout(T,500)}},g.addEventListener("change",async()=>{let N=Array.from(g.files??[]);g.value="";for(let b of N){let T=await this.importAttachment(b);T&&B(T)}r.focus()});let y=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,F.setIcon)(y,"chevron-left"),y.title="Show more composer options",u.insertBefore(y,p);let Q=N=>{u.toggleClass("is-expanded",N),y.title=N?"Hide options":"Show more composer options",(0,F.setIcon)(y,N?"chevron-right":"chevron-left")};y.onmousedown=N=>N.preventDefault(),y.onclick=N=>{N.preventDefault(),Q(!u.hasClass("is-expanded"))},Q(!1);let v=()=>n.clientWidth<700,E=()=>{let N=v();n.toggleClass("is-narrow",N),Q(!N)};E(),requestAnimationFrame(E);let S=new ResizeObserver(E);S.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=S;let D=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});D.title="Send (Enter)",(0,F.setIcon)(D,"arrow-up");let H=async()=>{let N=r.value.trim();if(!N)return;r.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(N)}catch{}let b=this.modeSplit??X().splitOnLines,T=this.nextDestination,P=this.nextDestinationFolder,R=!!P&&P!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!R,this.scrollToBottomOnNextRender=!R;let Z=R?{targetFolder:P}:void 0,$=T??this.focusId;if(b){let V=Ei(N,X().splitMode);V.length===1?await this.createNoteUnder(V[0],$,Z):V.length>1&&await this.createNotesBatch(V,$,Z,N,R?P:this.noteFolder)}else await this.createNoteUnder(N,$,Z);X().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,R&&this.composerInputEl?.focus())};D.onclick=()=>void H(),r.addEventListener("keydown",N=>{let b=this.modeEnterSubmits;if(N.key==="Escape"){N.preventDefault(),N.stopPropagation(),r.blur(),this.viewRoot.focus({preventScroll:!0});return}if(N.key==="ArrowUp"&&r.selectionStart===0&&r.selectionEnd===0){if(N.preventDefault(),r.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let T=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,P=T?this.currentChildren.findIndex(R=>R.id===T):-1;this.cursorIdx=P>=0?P:this.currentChildren.length-1,this.selectCursor(!1)}return}N.key==="Enter"&&!N.isComposing&&(b?!N.shiftKey:N.shiftKey)&&(N.preventDefault(),N.stopPropagation(),N.stopImmediatePropagation(),H())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return F.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=X().bindings,o=h=>{let g=n[h];return g.primary&&g.secondary?g.preferRight?g.secondary:g.primary:g.primary||g.secondary},r=Vi(o("toggleSplit")),l=Vi(o("pickDestination")),c=Vi(o("search")),d=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${r} split: ${e?"ON":"off"} \xB7 ${l} destination \xB7 ${c} search${d}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===k)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(k),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 r=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(r){let l=this.app.internalPlugins?.plugins?.["global-search"],c=l?.instance?.openGlobalSearch?.bind(l.instance);c&&c(`tag:#${r}`)}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 r=e.file?.path||"";this.app.workspace.openLinkText(o,r,!0)}}}handleRowClick(t,e,i){let s=this.shouldAbsorbDismissTap();if(this.traceTap("click",t,e,s),s){(!this.aimedTapTargetId||Date.now()-this.aimedTapAt>ts.AIMED_TAP_WINDOW_MS)&&(this.aimedTapTargetId=i.id,this.aimedTapAt=Date.now()),t.stopPropagation();return}this.aimedTapTargetId=null,this.cursorHasMoved=!0;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 r=n?.closest?.(".internal-link");if(r){t.preventDefault(),t.stopPropagation();let c=r.getAttribute("data-href")||r.getAttribute("href");if(c){let d=i.file?.path||"";this.app.workspace.openLinkText(c,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 c=this.currentChildren.findIndex(d=>d.id===this.lastSelected);if(l&&(this.firstSelectedId=this.lastSelected),c!==-1){let[d,h]=c<e?[c,e]:[e,c];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 c=this.lastSelected??[...this.selection][this.selection.size-1],d=c?this.currentChildren.findIndex(h=>h.id===c):-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,r=s.top+o,l=s.bottom-o;if(F.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let c=this.viewRoot?.querySelector(".stashpad-composer");c&&(l=Math.min(l,c.getBoundingClientRect().top-o))}n.top<r?i.scrollTop+=n.top-r:n.bottom>l&&(i.scrollTop+=n.bottom-l)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}shouldAbsorbDismissTap(){return F.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,r=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:r?Math.round(r.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(this.cursorHasMoved=!0,!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 r=n;r<=o;r++)this.selection.add(this.currentChildren[r].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??"",r=n===this.cursorIdx;s.classList.toggle("is-cursor",r),s.classList.toggle("is-selected",this.selection.has(o)),r||this.cursorExpandOverride.delete(o),s.classList.toggle("is-cursor-expanded",t&&r&&this.cursorHasMoved&&!this.cursorExpandOverride.has(o)),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 F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 r=o.parent;for(;r;){if(e.has(r))return!1;r=this.tree.get(r)?.parent??null}return!0});if(s.length===0){new F.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let r=this.order.getOrder(this.noteFolder,o.parent??k),l=r.indexOf(o.id),c=l>0?r[l-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,c,{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(){let t=this.getActionTargets();if(t.length===0)return;let e=(this.noteFolder??"").replace(/\/+$/,"");if(this.plugin.isArchiveFolder(e)){new F.Notice(`These notes are already in an archive folder (\u201C${e.split("/").pop()}\u201D).`,6e3);return}let i=(this.plugin.settings.archiveFolders??[]).map(r=>r.replace(/\/+$/,"")).filter(r=>r!==e);if(i.length===0){new F.Notice("No archive folder available. Mark a folder as archive first (Settings \u2192 Stashpad \u2192 Encryption \u2192 Per-folder, or the folder panel right-click).",8e3);return}let s=(this.plugin.settings.defaultArchiveFolder??"").replace(/\/+$/,""),n=s&&i.includes(s)?s:i.length===1?i[0]:null,o=r=>{this.archiveSources(t,r)};if(n){o(n);return}new No(this.app,i,o).open()}async archiveSources(t,e){let i=this.noteFolder,s=e.replace(/\/+$/,"");if(!((this.plugin.settings.folderEncPrefs??{})[s]?.archiveEncryptContent??!0)){let h=new Set(t.map(C=>C.id)),g=t.filter(C=>{let B=C.parent;for(;B;){if(h.has(B))return!1;B=this.tree.get(B)?.parent??null}return!0});if(g.length===0)return;let u=[],p=new Set,f=C=>{if(!p.has(C.id)){p.add(C.id),C.file&&u.push(C.file);for(let B of this.tree.getChildren(C.id))f(B)}};for(let C of g)f(C);let I=[];for(let C of u){let B=C.path,w=C.name,y=w.lastIndexOf("."),Q=y>0?w.slice(0,y):w,v=y>0?w.slice(y):"",E=`${s}/${w}`;for(let S=1;await this.app.vault.adapter.exists(E);S++)E=`${s}/${Q}-${S}${v}`;try{await this.app.fileManager.renameFile(C,E),I.push({from:B,to:E})}catch(S){console.warn("[Stashpad] plaintext archive move failed",B,S)}}this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let m=s.split("/").pop()||s;this.plugin.notifications.show({message:`Moved ${I.length} note${I.length===1?"":"s"} \u2192 plaintext archive \u201C${m}\u201D (de-indexed, not encrypted). Undo to bring ${I.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (plaintext, ${g.length})`,undo:async()=>{for(let C of I){let B=this.app.vault.getAbstractFileByPath(C.to);if(B instanceof F.TFile)try{await this.app.fileManager.renameFile(B,C.from)}catch(w){console.warn("[Stashpad] plaintext archive undo failed",C.to,w)}}this.tree.rebuild(i),this.render()}});return}if(!this.plugin.encryption?.isConfigured?.()){new F.Notice(`Archiving encrypts the notes, but encryption isn't set up yet (Settings \u2192 Stashpad \u2192 Encryption). Set it up \u2014 or turn off \u201CEncrypt archived notes\u201D for \u201C${s.split("/").pop()}\u201D to make it a plaintext archive.`,9e3);return}let o=new Set(t.map(h=>h.id)),r=t.filter(h=>{let g=h.parent;for(;g;){if(o.has(g))return!1;g=this.tree.get(g)?.parent??null}return!0});if(r.length===0)return;let l=r.map(h=>h.id),c=[];for(let h of r){let g=this.order.getOrder(i,h.parent??k),u=g.indexOf(h.id),p=u>0?g[u-1]:null,f=await this.plugin.lockNoteSubtree(i,h.id,p,{silent:!0,blobFolder:e});f&&c.push(f.blobPath)}if(c.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let d=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${c.length} note${c.length===1?"":"s"} \u2192 \u201C${d}\u201D. Undo to bring ${c.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${c.length})`,undo:async()=>{for(let h of c)try{await this.plugin.unlockBundleAt(h,{silent:!0,destFolder:i})}catch(g){console.warn("[Stashpad] archive undo failed",h,g)}c=[],this.tree.rebuild(i),this.render()},redo:async()=>{c=[];for(let h of l){let g=await this.plugin.lockNoteSubtree(i,h,null,{silent:!0,blobFolder:e});g&&c.push(g.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 it(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 F.Notice("Set up encryption first (Settings \u2192 Stashpad \u2192 Encryption).");return}let e=new Set(t.map(r=>r.id)),i=t.filter(r=>{let l=r.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(r=>r.id),o=[];for(let r of n){let l=await this.plugin.encryptDeleteSubtree(s,r);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 r of o)try{await this.plugin.restoreDeletedAt(r,{silent:!0})}catch(l){console.warn("[Stashpad] secure-delete undo failed",r,l)}o=[],this.tree.rebuild(s),this.render()},redo:async()=>{o=[];for(let r of n){let l=await this.plugin.encryptDeleteSubtree(s,r);l&&o.push(l)}this.tree.rebuild(s),this.render()}}))}async cmdUnlockAll(){if(!this.plugin.encryption?.isConfigured?.()){new F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 F.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??X().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Zt(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===k?"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===k&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:k,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!==k&&!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===k},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Zt(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 Zt(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 Zt(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,r=n.crossFolder??this.noteFolder;if(!o)return;let l=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",c=this.app.workspace,d=c.getLeaf("tab");await d.setViewState({type:K,active:!0,state:{focusId:o,folderOverride:r===l?null:r}}),c.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===k&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:k,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 r=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(r))continue;let l=n.get(r);l||(l=[],n.set(r,l)),l.push(o)}for(let o of i){let r=n.get(o)??[],l=new Map;for(let c of r){let d=this.app.metadataCache.getFileCache(c)?.frontmatter;typeof d?.id=="string"&&l.set(d.id,c)}for(let c of r){let d=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof d?.id=="string"?d.id:"";if(!h||h===k)continue;let g=c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),u,p=d?.parent??null;if(p&&p!==k){let f=l.get(p);f&&(u=f.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:c,folder:o,id:h,title:g,body:"",parentBlurb:u,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===k){i.push(s.id);continue}let o=n.parent??k;await this.changeParent(s,o),e.push(s)}if(e.length===0){new F.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 Pe(this.app,i,s,async(n,o)=>{let r=[];for(let h of t)if(h.file){r.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 F.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(u=>u.toLowerCase()===g)||(h.push(n),this.plugin.settings.customPalette=h,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:k,payload:{color:n}}))}this.render();let l=this.noteFolder,c=n,d=async h=>{for(let g of h){let u=this.app.vault.getAbstractFileByPath(g.path);if(u)try{await this.app.fileManager.processFrontMatter(u,p=>{g.col?p.color=g.col:delete p.color})}catch{}}this.tree.rebuild(l),this.render()};this.plugin.getUndoStack(l).push({label:r.length===1?"Color change":`Color change (${r.length})`,undo:()=>d(r.map(h=>({path:h.path,col:h.was}))),redo:()=>d(r.map(h=>({path:h.path,col:c})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(r=>r.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:k,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Zt(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 F.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 r=(g,u)=>{if(!g.file)return;let p=g.file,f=`${s}/${p.name}`;if(o.has(f)){let I=p.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),m=I?I[1]:p.basename,C=I?I[2]:"";for(let B=1;B<1e3;B++){let w=`${m}-${B}${C}.md`,y=`${s}/${w}`;if(!o.has(y)){f=y;break}}}o.add(f),n.push({id:g.id,file:p,oldPath:p.path,newPath:f,oldParent:g.parent,isRoot:u});for(let I of this.tree.getChildren(g.id))r(I,!1)};for(let g of t)r(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,u=>{u.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(u){new F.Notice(`Move failed for ${g.id}: ${u.message}`)}if(X().writeRecoveryLinks){let g=this.noteFolder;window.setTimeout(()=>{li(this.app,g),li(this.app,s)},350)}let l=this.titleList(t);this.tree.rebuild(this.noteFolder);let c=i===k?"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:c,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 u=this.app.vault.getAbstractFileByPath(g.newPath);if(u)try{await this.app.fileManager.renameFile(u,g.oldPath),g.isRoot&&await this.app.fileManager.processFrontMatter(u,p=>{p.parent=g.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let g of n){let u=this.app.vault.getAbstractFileByPath(g.oldPath);if(u)try{await this.app.fileManager.renameFile(u,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(u,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=X().bindings.move,i=Vi(e.primary||e.secondary||"M");new F.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(r=>r.id!==t.id),i=new Map(e.map(r=>[r.id,this.tree.getChildren(r.id).length])),s=[];for(let r of e)await this.changeParent(r,t.id,{silentSuccess:!0})&&s.push(r);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 r=this.currentChildren.findIndex(l=>l.id===t.id);r<0||this.selection.size===1&&this.selection.has(t.id)&&this.cursorIdx===r||(this.selection.clear(),this.selection.add(t.id),this.cursorIdx=r,this.render({kind:"follow-cursor"}))};setTimeout(o,120),setTimeout(o,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new F.Notice("Select 2+ notes to merge.");return}t.sort((f,I)=>(f.created||"").localeCompare(I.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=[],r=[];for(let f of t){if(!f.file)continue;let I=await this.app.vault.cachedRead(f.file);r.push(this.stripFrontmatter(I).trim())}let l=r.map(f=>f.trim()).filter(Boolean).join(` +`:"";a.value+=`${b}${N} +`,this.composerDraft=a.value},w=p.createEl("button",{cls:"stashpad-composer-btn"});(0,F.setIcon)(w,"paperclip"),w.title="Attach files",w.onmousedown=N=>N.preventDefault(),w.onclick=N=>{N.preventDefault();let b=document.activeElement===a;if(g.click(),b){let T=()=>{a.focus()};setTimeout(T,100),setTimeout(T,500)}},g.addEventListener("change",async()=>{let N=Array.from(g.files??[]);g.value="";for(let b of N){let T=await this.importAttachment(b);T&&B(T)}a.focus()});let y=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,F.setIcon)(y,"chevron-left"),y.title="Show more composer options",u.insertBefore(y,p);let Q=N=>{u.toggleClass("is-expanded",N),y.title=N?"Hide options":"Show more composer options",(0,F.setIcon)(y,N?"chevron-right":"chevron-left")};y.onmousedown=N=>N.preventDefault(),y.onclick=N=>{N.preventDefault(),Q(!u.hasClass("is-expanded"))},Q(!1);let v=()=>n.clientWidth<700,E=()=>{let N=v();n.toggleClass("is-narrow",N),Q(!N)};E(),requestAnimationFrame(E);let S=new ResizeObserver(E);S.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=S;let D=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});D.title="Send (Enter)",(0,F.setIcon)(D,"arrow-up");let H=async()=>{let N=a.value.trim();if(!N)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(N)}catch{}let b=this.modeSplit??X().splitOnLines,T=this.nextDestination,P=this.nextDestinationFolder,R=!!P&&P!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!R,this.scrollToBottomOnNextRender=!R;let Z=R?{targetFolder:P}:void 0,$=T??this.focusId;if(b){let V=vi(N,X().splitMode);V.length===1?await this.createNoteUnder(V[0],$,Z):V.length>1&&await this.createNotesBatch(V,$,Z,N,R?P:this.noteFolder)}else await this.createNoteUnder(N,$,Z);X().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,R&&this.composerInputEl?.focus())};D.onclick=()=>void H(),a.addEventListener("keydown",N=>{let b=this.modeEnterSubmits;if(N.key==="Escape"){N.preventDefault(),N.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(N.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(N.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let T=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,P=T?this.currentChildren.findIndex(R=>R.id===T):-1;this.cursorIdx=P>=0?P:this.currentChildren.length-1,this.selectCursor(!1)}return}N.key==="Enter"&&!N.isComposing&&(b?!N.shiftKey:N.shiftKey)&&(N.preventDefault(),N.stopPropagation(),N.stopImmediatePropagation(),H())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return F.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=X().bindings,o=h=>{let g=n[h];return g.primary&&g.secondary?g.preferRight?g.secondary:g.primary:g.primary||g.secondary},a=zi(o("toggleSplit")),l=zi(o("pickDestination")),c=zi(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 ${c} search${d}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===k)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(k),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"],c=l?.instance?.openGlobalSearch?.bind(l.instance);c&&c(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=this.shouldAbsorbDismissTap();if(this.traceTap("click",t,e,s),s){(!this.aimedTapTargetId||Date.now()-this.aimedTapAt>es.AIMED_TAP_WINDOW_MS)&&(this.aimedTapTargetId=i.id,this.aimedTapAt=Date.now()),t.stopPropagation();return}this.aimedTapTargetId=null,this.cursorHasMoved=!0;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 c=a.getAttribute("data-href")||a.getAttribute("href");if(c){let d=i.file?.path||"";this.app.workspace.openLinkText(c,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 c=this.currentChildren.findIndex(d=>d.id===this.lastSelected);if(l&&(this.firstSelectedId=this.lastSelected),c!==-1){let[d,h]=c<e?[c,e]:[e,c];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 c=this.lastSelected??[...this.selection][this.selection.size-1],d=c?this.currentChildren.findIndex(h=>h.id===c):-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(F.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let c=this.viewRoot?.querySelector(".stashpad-composer");c&&(l=Math.min(l,c.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 F.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(this.cursorHasMoved=!0,!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)),a||this.cursorExpandOverride.delete(o),s.classList.toggle("is-cursor-expanded",t&&a&&this.cursorHasMoved&&!this.cursorExpandOverride.has(o)),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 F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 F.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??k),l=a.indexOf(o.id),c=l>0?a[l-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,c,{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(){let t=this.getActionTargets();if(t.length===0)return;let e=(this.noteFolder??"").replace(/\/+$/,"");if(this.plugin.isArchiveFolder(e)){new F.Notice(`These notes are already in an archive folder (\u201C${e.split("/").pop()}\u201D).`,6e3);return}let i=(this.plugin.settings.archiveFolders??[]).map(a=>a.replace(/\/+$/,"")).filter(a=>a!==e);if(i.length===0){new F.Notice("No archive folder available. Mark a folder as archive first (Settings \u2192 Stashpad \u2192 Encryption \u2192 Per-folder, or the folder panel right-click).",8e3);return}let s=(this.plugin.settings.defaultArchiveFolder??"").replace(/\/+$/,""),n=s&&i.includes(s)?s:i.length===1?i[0]:null,o=a=>{this.archiveSources(t,a)};if(n){o(n);return}new Ho(this.app,i,o).open()}async archiveSources(t,e){let i=this.noteFolder,s=e.replace(/\/+$/,"");if(!((this.plugin.settings.folderEncPrefs??{})[s]?.archiveEncryptContent??!0)){let h=new Set(t.map(C=>C.id)),g=t.filter(C=>{let B=C.parent;for(;B;){if(h.has(B))return!1;B=this.tree.get(B)?.parent??null}return!0});if(g.length===0)return;let u=[],p=new Set,f=C=>{if(!p.has(C.id)){p.add(C.id),C.file&&u.push(C.file);for(let B of this.tree.getChildren(C.id))f(B)}};for(let C of g)f(C);let I=[];for(let C of u){let B=C.path,w=C.name,y=w.lastIndexOf("."),Q=y>0?w.slice(0,y):w,v=y>0?w.slice(y):"",E=`${s}/${w}`;for(let S=1;await this.app.vault.adapter.exists(E);S++)E=`${s}/${Q}-${S}${v}`;try{await this.app.fileManager.renameFile(C,E),I.push({from:B,to:E})}catch(S){console.warn("[Stashpad] plaintext archive move failed",B,S)}}this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let m=s.split("/").pop()||s;this.plugin.notifications.show({message:`Moved ${I.length} note${I.length===1?"":"s"} \u2192 plaintext archive \u201C${m}\u201D (de-indexed, not encrypted). Undo to bring ${I.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (plaintext, ${g.length})`,undo:async()=>{for(let C of I){let B=this.app.vault.getAbstractFileByPath(C.to);if(B instanceof F.TFile)try{await this.app.fileManager.renameFile(B,C.from)}catch(w){console.warn("[Stashpad] plaintext archive undo failed",C.to,w)}}this.tree.rebuild(i),this.render()}});return}if(!this.plugin.encryption?.isConfigured?.()){new F.Notice(`Archiving encrypts the notes, but encryption isn't set up yet (Settings \u2192 Stashpad \u2192 Encryption). Set it up \u2014 or turn off \u201CEncrypt archived notes\u201D for \u201C${s.split("/").pop()}\u201D to make it a plaintext archive.`,9e3);return}let o=new Set(t.map(h=>h.id)),a=t.filter(h=>{let g=h.parent;for(;g;){if(o.has(g))return!1;g=this.tree.get(g)?.parent??null}return!0});if(a.length===0)return;let l=a.map(h=>h.id),c=[];for(let h of a){let g=this.order.getOrder(i,h.parent??k),u=g.indexOf(h.id),p=u>0?g[u-1]:null,f=await this.plugin.lockNoteSubtree(i,h.id,p,{silent:!0,blobFolder:e});f&&c.push(f.blobPath)}if(c.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let d=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${c.length} note${c.length===1?"":"s"} \u2192 \u201C${d}\u201D. Undo to bring ${c.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${c.length})`,undo:async()=>{for(let h of c)try{await this.plugin.unlockBundleAt(h,{silent:!0,destFolder:i})}catch(g){console.warn("[Stashpad] archive undo failed",h,g)}c=[],this.tree.rebuild(i),this.render()},redo:async()=>{c=[];for(let h of l){let g=await this.plugin.lockNoteSubtree(i,h,null,{silent:!0,blobFolder:e});g&&c.push(g.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 it(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 F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 F.Notice("Set up encryption first (Settings \u2192 Stashpad \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 F.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??X().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Zt(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===k?"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===k&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:k,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!==k&&!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===k},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Zt(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 Zt(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 Zt(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",c=this.app.workspace,d=c.getLeaf("tab");await d.setViewState({type:q,active:!0,state:{focusId:o,folderOverride:a===l?null:a}}),c.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===k&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:k,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 c of a){let d=this.app.metadataCache.getFileCache(c)?.frontmatter;typeof d?.id=="string"&&l.set(d.id,c)}for(let c of a){let d=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof d?.id=="string"?d.id:"";if(!h||h===k)continue;let g=c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),u,p=d?.parent??null;if(p&&p!==k){let f=l.get(p);f&&(u=f.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:c,folder:o,id:h,title:g,body:"",parentBlurb:u,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===k){i.push(s.id);continue}let o=n.parent??k;await this.changeParent(s,o),e.push(s)}if(e.length===0){new F.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 Pe(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 F.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(u=>u.toLowerCase()===g)||(h.push(n),this.plugin.settings.customPalette=h,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:k,payload:{color:n}}))}this.render();let l=this.noteFolder,c=n,d=async h=>{for(let g of h){let u=this.app.vault.getAbstractFileByPath(g.path);if(u)try{await this.app.fileManager.processFrontMatter(u,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:c})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:k,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Zt(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 F.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,u)=>{if(!g.file)return;let p=g.file,f=`${s}/${p.name}`;if(o.has(f)){let I=p.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),m=I?I[1]:p.basename,C=I?I[2]:"";for(let B=1;B<1e3;B++){let w=`${m}-${B}${C}.md`,y=`${s}/${w}`;if(!o.has(y)){f=y;break}}}o.add(f),n.push({id:g.id,file:p,oldPath:p.path,newPath:f,oldParent:g.parent,isRoot:u});for(let I of this.tree.getChildren(g.id))a(I,!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,u=>{u.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(u){new F.Notice(`Move failed for ${g.id}: ${u.message}`)}if(X().writeRecoveryLinks){let g=this.noteFolder;window.setTimeout(()=>{ci(this.app,g),ci(this.app,s)},350)}let l=this.titleList(t);this.tree.rebuild(this.noteFolder);let c=i===k?"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:c,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 u=this.app.vault.getAbstractFileByPath(g.newPath);if(u)try{await this.app.fileManager.renameFile(u,g.oldPath),g.isRoot&&await this.app.fileManager.processFrontMatter(u,p=>{p.parent=g.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let g of n){let u=this.app.vault.getAbstractFileByPath(g.oldPath);if(u)try{await this.app.fileManager.renameFile(u,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(u,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=X().bindings.move,i=zi(e.primary||e.secondary||"M");new F.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 F.Notice("Select 2+ notes to merge.");return}t.sort((f,I)=>(f.created||"").localeCompare(I.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 f of t){if(!f.file)continue;let I=await this.app.vault.cachedRead(f.file);a.push(this.stripFrontmatter(I).trim())}let l=a.map(f=>f.trim()).filter(Boolean).join(` `),c=await this.app.vault.read(e.file),d=c.startsWith("---")?c.indexOf(` ---`,3)+4:0,g=`${c.slice(0,d)} ${l} -`;await this.app.vault.modify(e.file,g);for(let f=1;f<t.length;f++){let I=t[f];if(I.file){for(let m of this.tree.getChildren(I.id))m.file&&o.push({childId:m.id,childPath:m.file.path,oldParent:m.parent}),await this.changeParent(m,e.id,{record:!1});await this.app.fileManager.trashFile(I.file),await this.log.append({type:"delete",id:I.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let u=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${u}"`}),kind:"success",category:"merge",affectedIds:t.map(f=>f.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let f=e.id,I=this.selectionGuardKey,m=()=>{if(this.selectionGuardKey!==I||this.selection.has(f))return;let C=this.currentChildren.findIndex(B=>B.id===f);C<0||(this.selection.add(f),this.cursorIdx=C,this.render({kind:"follow-cursor"}))};setTimeout(m,120),setTimeout(m,400)}let p=this.noteFolder;this.plugin.getUndoStack(p).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(I=>I.id));let f=this.app.vault.getAbstractFileByPath(i);f&&await this.app.vault.modify(f,s);for(let I of o){let m=this.app.vault.getAbstractFileByPath(I.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=I.oldParent})}this.pendingFocusIds=t.map(I=>I.id),this.tree.rebuild(p),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let f=this.app.vault.getAbstractFileByPath(i);f&&await this.app.vault.modify(f,g);for(let I of o){let m=this.app.vault.getAbstractFileByPath(I.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=e.id})}this.tree.rebuild(p),this.render()}})}cmdCopy(){return ho(this)}cmdCopyCodeBlock(){return Wr(this)}cmdCopyTree(){return Xr(this)}cmdCopyOutline(){return Zr(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,s={}){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new F.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let n=this.tree.getChildren(t.id).slice(),o=t.file,r=await this.app.vault.read(o),l=this.stripFrontmatter(r),c=this.app.metadataCache.getFileCache(o)?.frontmatter??{},d=W(),h=St(l,this.activeStopwords()),g=bt(h,d),u=`${this.noteFolder}/${g}`,p=new Date().toISOString(),f=s.preserveCreated&&t.created?t.created:p,I=this.extractAttachments(l),m=["---",`id: ${d}`,`parent: ${e}`,`created: ${f}`];if(I.length>0){m.push("attachments:");for(let B of I)m.push(` - "${B.replace(/"/g,'\\"')}"`)}else m.push("attachments: []");m.push("---",l),await this.ensureFolder(this.noteFolder),await this.app.vault.create(u,m.join(` -`)),i.push(u);let C=this.app.vault.getAbstractFileByPath(u);if(C){try{await this.app.fileManager.processFrontMatter(C,B=>{for(let[w,y]of Object.entries(c))ue.includes(w)||En.includes(w)||(B[w]=y);s.preserveCreated&&(B.modified=p),s.copyKind==="fork"&&(B[Qn]=p)})}catch(B){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",B)}try{this.tree.insertSynthetic({id:d,parent:e,children:[],file:C,created:f})}catch{}this.fmSync.scheduleParentChange(d,null,e)}for(let B of n)await this.cloneSubtree(B,d,i,s);return d}async cmdClone(){let t=this.getActionTargets();if(!t.length){new F.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let l of t){if(!l.file)continue;let c=l.parent??this.focusId,d=await this.cloneSubtree(l,c,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:me(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 c=this.app.vault.getAbstractFileByPath(l);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let r=s.map(l=>this.tree.get(l)).filter(l=>!!l);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:r,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 F.Notice("Nothing to fork.");return}let e=t.parent??k,i=e===k?null:this.tree.get(e),s=i?this.titleForNode(i):"Home";new Zt(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 F.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,{preserveCreated:!0,copyKind:"fork"});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[Ci]=`[[${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 r=s.map(d=>this.app.vault.getAbstractFileByPath(d)).filter(d=>!!d&&d.extension==="md").map(d=>({id:me(d.basename)??d.basename,parent:null,children:[],file:d,created:new Date().toISOString()})),l=await this.snapshotNotes(r,!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 c=this.tree.get(n);this.plugin.notifications.show({message:c?`Forked "${this.titleForNode(t)}" \u2192 "${this.titleForNode(c)}" (${s.length} file${s.length===1?"":"s"})`:"Forked note",kind:"success",category:"clone",affectedIds:[n],folder:i})}async ensureSheetGroup(t){let e=Yt(this.app.metadataCache.getFileCache(t)?.frontmatter);if(e)return e;let i=Yo();return await this.app.fileManager.processFrontMatter(t,s=>{s[Ii]=i,typeof s[ne]!="number"&&(s[ne]=0),s[mi]=!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&&Yt(n)===t.gid&&i(s),t.originName&&(s.basename===t.originName||Oo(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[Ot]=i:delete s[Ot]})}}async cmdForkVersion(t){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings(),new F.Notice("Sheet versions enabled."));let e=t??this.getActionTargets()[0];if(!e?.file){new F.Notice("Select a note to version.");return}let i=this.noteFolder,s={...this.app.metadataCache.getFileCache(e.file)?.frontmatter??{}},n=await this.ensureSheetGroup(e.file),o=e.parent??this.focusId,r=typeof s[ne]=="number"?s[ne]:0;for(let p of this.tree.getChildren(o)){if(p.id===e.id)continue;let f=It(this.app,p);if(Yt(f)!==n)continue;let I=f?.[ne];typeof I=="number"&&I>r&&(r=I)}let l=r+1,c=[],d=await this.cloneSubtree(e,o,c,{preserveCreated:!0,copyKind:"fork"});if(!d||!c.length){new F.Notice("Sheets: could not create version.");return}let h=this.app.vault.getAbstractFileByPath(c[0]);h&&await this.app.fileManager.processFrontMatter(h,p=>{p[Ii]=n,p[ne]=l,delete p[Ke],delete p[mi],p[Ci]=`[[${e.file.basename}]]`}),this.tree.rebuild(i),this.activeVersionByGroup.set(n,d),this.plugin.saveActiveVersion(i,n,d),this.render();let g=this.app.vault.getAbstractFileByPath(c[0]);await this.syncForkSiblings(this.forkFamilyFiles({gid:n,include:[e.file,g]})),this.plugin.getUndoStack(i).push({label:"Fork version",undo:async()=>{for(let p of[...c].reverse()){let f=this.app.vault.getAbstractFileByPath(p);if(f)try{await this.app.fileManager.trashFile(f)}catch{}}this.activeVersionByGroup.delete(n),this.tree.rebuild(i),this.render()},redo:async()=>{}});let u=c.length;new F.Notice(`Forked a new version${u>1?` (${u} 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=Yt(It(this.app,e));if(!i){new F.Notice("Not a versioned note.");return}let s=!yi(It(this.app,e)),n=e.parent??this.focusId,o=this.tree.getChildren(n).filter(r=>Yt(It(this.app,r))===i);for(let r of o){if(!r.file)continue;let l=yi(It(this.app,r)),c=s&&r.id===e.id;l!==c&&await this.app.fileManager.processFrontMatter(r.file,d=>{c?d[Ke]=!0:delete d[Ke]})}this.render()}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new F.Notice("Nothing to copy.");return}await ho(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 f=1;f<t.length;f++){let I=t[f];if(I.file){for(let m of this.tree.getChildren(I.id))m.file&&o.push({childId:m.id,childPath:m.file.path,oldParent:m.parent}),await this.changeParent(m,e.id,{record:!1});await this.app.fileManager.trashFile(I.file),await this.log.append({type:"delete",id:I.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let u=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${u}"`}),kind:"success",category:"merge",affectedIds:t.map(f=>f.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let f=e.id,I=this.selectionGuardKey,m=()=>{if(this.selectionGuardKey!==I||this.selection.has(f))return;let C=this.currentChildren.findIndex(B=>B.id===f);C<0||(this.selection.add(f),this.cursorIdx=C,this.render({kind:"follow-cursor"}))};setTimeout(m,120),setTimeout(m,400)}let p=this.noteFolder;this.plugin.getUndoStack(p).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(I=>I.id));let f=this.app.vault.getAbstractFileByPath(i);f&&await this.app.vault.modify(f,s);for(let I of o){let m=this.app.vault.getAbstractFileByPath(I.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=I.oldParent})}this.pendingFocusIds=t.map(I=>I.id),this.tree.rebuild(p),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let f=this.app.vault.getAbstractFileByPath(i);f&&await this.app.vault.modify(f,g);for(let I of o){let m=this.app.vault.getAbstractFileByPath(I.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=e.id})}this.tree.rebuild(p),this.render()}})}cmdCopy(){return fo(this)}cmdCopyCodeBlock(){return Za(this)}cmdCopyTree(){return ja(this)}cmdCopyOutline(){return _a(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,s={}){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new F.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let n=this.tree.getChildren(t.id).slice(),o=t.file,a=await this.app.vault.read(o),l=this.stripFrontmatter(a),c=this.app.metadataCache.getFileCache(o)?.frontmatter??{},d=W(),h=St(l,this.activeStopwords()),g=bt(h,d),u=`${this.noteFolder}/${g}`,p=new Date().toISOString(),f=s.preserveCreated&&t.created?t.created:p,I=this.extractAttachments(l),m=["---",`id: ${d}`,`parent: ${e}`,`created: ${f}`];if(I.length>0){m.push("attachments:");for(let B of I)m.push(` - "${B.replace(/"/g,'\\"')}"`)}else m.push("attachments: []");m.push("---",l),await this.ensureFolder(this.noteFolder),await this.app.vault.create(u,m.join(` +`)),i.push(u);let C=this.app.vault.getAbstractFileByPath(u);if(C){try{await this.app.fileManager.processFrontMatter(C,B=>{for(let[w,y]of Object.entries(c))ue.includes(w)||Sn.includes(w)||(B[w]=y);s.preserveCreated&&(B.modified=p),s.copyKind==="fork"&&(B[kn]=p)})}catch(B){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",B)}try{this.tree.insertSynthetic({id:d,parent:e,children:[],file:C,created:f})}catch{}this.fmSync.scheduleParentChange(d,null,e)}for(let B of n)await this.cloneSubtree(B,d,i,s);return d}async cmdClone(){let t=this.getActionTargets();if(!t.length){new F.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let l of t){if(!l.file)continue;let c=l.parent??this.focusId,d=await this.cloneSubtree(l,c,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:me(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 c=this.app.vault.getAbstractFileByPath(l);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(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 F.Notice("Nothing to fork.");return}let e=t.parent??k,i=e===k?null:this.tree.get(e),s=i?this.titleForNode(i):"Home";new Zt(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 F.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,{preserveCreated:!0,copyKind:"fork"});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[Bi]=`[[${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:me(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 c=this.tree.get(n);this.plugin.notifications.show({message:c?`Forked "${this.titleForNode(t)}" \u2192 "${this.titleForNode(c)}" (${s.length} file${s.length===1?"":"s"})`:"Forked note",kind:"success",category:"clone",affectedIds:[n],folder:i})}async ensureSheetGroup(t){let e=Yt(this.app.metadataCache.getFileCache(t)?.frontmatter);if(e)return e;let i=Wo();return await this.app.fileManager.processFrontMatter(t,s=>{s[mi]=i,typeof s[ne]!="number"&&(s[ne]=0),s[Ci]=!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&&Yt(n)===t.gid&&i(s),t.originName&&(s.basename===t.originName||zo(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[Ot]=i:delete s[Ot]})}}async cmdForkVersion(t){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings(),new F.Notice("Sheet versions enabled."));let e=t??this.getActionTargets()[0];if(!e?.file){new F.Notice("Select a note to version.");return}let i=this.noteFolder,s={...this.app.metadataCache.getFileCache(e.file)?.frontmatter??{}},n=await this.ensureSheetGroup(e.file),o=e.parent??this.focusId,a=typeof s[ne]=="number"?s[ne]:0;for(let p of this.tree.getChildren(o)){if(p.id===e.id)continue;let f=It(this.app,p);if(Yt(f)!==n)continue;let I=f?.[ne];typeof I=="number"&&I>a&&(a=I)}let l=a+1,c=[],d=await this.cloneSubtree(e,o,c,{preserveCreated:!0,copyKind:"fork"});if(!d||!c.length){new F.Notice("Sheets: could not create version.");return}let h=this.app.vault.getAbstractFileByPath(c[0]);h&&await this.app.fileManager.processFrontMatter(h,p=>{p[mi]=n,p[ne]=l,delete p[qe],delete p[Ci],p[Bi]=`[[${e.file.basename}]]`}),this.tree.rebuild(i),this.activeVersionByGroup.set(n,d),this.plugin.saveActiveVersion(i,n,d),this.render();let g=this.app.vault.getAbstractFileByPath(c[0]);await this.syncForkSiblings(this.forkFamilyFiles({gid:n,include:[e.file,g]})),this.plugin.getUndoStack(i).push({label:"Fork version",undo:async()=>{for(let p of[...c].reverse()){let f=this.app.vault.getAbstractFileByPath(p);if(f)try{await this.app.fileManager.trashFile(f)}catch{}}this.activeVersionByGroup.delete(n),this.tree.rebuild(i),this.render()},redo:async()=>{}});let u=c.length;new F.Notice(`Forked a new version${u>1?` (${u} 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=Yt(It(this.app,e));if(!i){new F.Notice("Not a versioned note.");return}let s=!wi(It(this.app,e)),n=e.parent??this.focusId,o=this.tree.getChildren(n).filter(a=>Yt(It(this.app,a))===i);for(let a of o){if(!a.file)continue;let l=wi(It(this.app,a)),c=s&&a.id===e.id;l!==c&&await this.app.fileManager.processFrontMatter(a.file,d=>{c?d[qe]=!0:delete d[qe]})}this.render()}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new F.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} ${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!==k&&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 F.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 F.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??k,u=t.mode,p=t.folder,f=await this.plugin.crossFolderPaste(p,t.ids,this.noteFolder,g,u);if(!f||!f.rootIds.length)return;u==="cut"&&this.plugin.clearNoteClipboard();let I=this.noteFolder;this.tree.rebuild(I),this.pendingFocusIds=f.rootIds.slice(),this.render(),u==="cut"&&this.plugin.refreshOpenViewsForFolder(p);let m=p.split("/").pop(),C=f.rootIds.length,B=()=>{this.tree.rebuild(I),this.render(),this.plugin.refreshOpenViewsForFolder(p)};this.plugin.getUndoStack(I).push({label:`${u==="cut"?"Move":"Paste"} ${C} note${C===1?"":"s"} from ${m}`,undo:async()=>{await f.undo(),B()},redo:async()=>{await f.redo(),B()}});let w=u==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${w} ${C} note${C===1?"":"s"} (${f.noteCount} total) from "${m}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:u==="cut"?"move":"clone",affectedIds:f.rootIds,folder:I,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 F.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??k;if(t.mode==="cut"){let h=new Set(t.ids);for(let u=s;u&&u!==k;u=this.tree.get(u)?.parent??null)if(h.has(u)){new F.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(u=>u.id),s,g,"after");return}let n=this.noteFolder,o=[],r=[];for(let h of e){let g=await this.cloneSubtree(h,s,o);g&&r.push(g)}if(!r.length)return;this.tree.rebuild(n),this.pendingFocusIds=r.slice(),this.render();let l=o.map(h=>this.app.vault.getAbstractFileByPath(h)).filter(h=>!!h&&h.extension==="md").map(h=>({id:me(h.basename)??h.basename,parent:null,children:[],file:h,created:new Date().toISOString()})),c=await this.snapshotNotes(l,!1);this.plugin.getUndoStack(n).push({label:`Paste ${r.length} note${r.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(c,r)}});let d=r.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:r,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,u=t.ids.slice();this.plugin.clearNoteClipboard();let p=await this.plugin.orderedSubtreeNodes(g,u),f=X().prefixTimestampsOnCopy,I=[];for(let{file:y,created:Q,depth:v}of p)try{let E=this.stripFrontmatter(await this.app.vault.cachedRead(y)).trim().split(/\r?\n/).join(" "),S=f?`${this.formatTimeInline(Q)} `:"";I.push(`${" ".repeat(v)}- ${S}${E}`)}catch{}this.insertIntoComposer(I.length?I.join(` -`):t.text??"");let m=await this.plugin.subtreeFilePaths(g,u),C=await this.plugin.snapshotPaths(m),B=await this.plugin.trashSubtrees(g,u);this.plugin.refreshOpenViewsForFolder(g);let w=B.filter(y=>y.extension==="md").length;this.plugin.getUndoStack(g).push({label:`Cut ${u.length} note${u.length===1?"":"s"} into composer (from ${g.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(C),this.plugin.refreshOpenViewsForFolder(g)},redo:async()=>{await this.plugin.trashSubtrees(g,u),this.plugin.refreshOpenViewsForFolder(g)}}),this.plugin.notifications.show({message:`Pasted the text of ${u.length} cut note${u.length===1?"":"s"} from "${g.split("/").pop()}" into the composer and removed the original${w===1?"":"s"} (${w} note${w===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:u,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,u)=>{if(!s.has(g.id)){s.add(g.id),i.push({node:g,depth:u});for(let p of this.tree.getChildren(g.id))n(p,u+1)}};for(let g of e)n(g,0);let o=this.noteFolder,r=X().prefixTimestampsOnCopy,l=[];for(let{node:g,depth:u}of i)if(g.file)try{let p=this.stripFrontmatter(await this.app.vault.cachedRead(g.file)).trim().split(/\r?\n/).join(" "),f=r?`${this.formatTimeInline(g.created)} `:"";l.push(`${" ".repeat(u)}- ${f}${p}`)}catch{}this.insertIntoComposer(l.join(` -`));let c=i.map(g=>g.node),d=await this.snapshotNotes(c,!1);for(let g of[...c].reverse())if(g.file)try{await this.app.fileManager.trashFile(g.file)}catch(u){console.warn("[Stashpad] cut-paste delete failed",g.file.path,u)}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 u=this.app.vault.getAbstractFileByPath(g.path);if(u)try{await this.app.fileManager.trashFile(u)}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"} (${c.length} note${c.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:h,folder:o,duration:0})}cmdInsertTemplate(){new Zt(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 F.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:me(l.basename)??l.basename,parent:null,children:[],file:l,created:new Date().toISOString()})),r=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let l of[...s].reverse()){let c=this.app.vault.getAbstractFileByPath(l);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(r,[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!==xe&&this.tagFilter!==Ne){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(r=>r.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(r=>r.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!==k&&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(k)}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 F.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(r=>r.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=[k],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 F.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??k,u=t.mode,p=t.folder,f=await this.plugin.crossFolderPaste(p,t.ids,this.noteFolder,g,u);if(!f||!f.rootIds.length)return;u==="cut"&&this.plugin.clearNoteClipboard();let I=this.noteFolder;this.tree.rebuild(I),this.pendingFocusIds=f.rootIds.slice(),this.render(),u==="cut"&&this.plugin.refreshOpenViewsForFolder(p);let m=p.split("/").pop(),C=f.rootIds.length,B=()=>{this.tree.rebuild(I),this.render(),this.plugin.refreshOpenViewsForFolder(p)};this.plugin.getUndoStack(I).push({label:`${u==="cut"?"Move":"Paste"} ${C} note${C===1?"":"s"} from ${m}`,undo:async()=>{await f.undo(),B()},redo:async()=>{await f.redo(),B()}});let w=u==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${w} ${C} note${C===1?"":"s"} (${f.noteCount} total) from "${m}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:u==="cut"?"move":"clone",affectedIds:f.rootIds,folder:I,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 F.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??k;if(t.mode==="cut"){let h=new Set(t.ids);for(let u=s;u&&u!==k;u=this.tree.get(u)?.parent??null)if(h.has(u)){new F.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(u=>u.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:me(h.basename)??h.basename,parent:null,children:[],file:h,created:new Date().toISOString()})),c=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(c,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,u=t.ids.slice();this.plugin.clearNoteClipboard();let p=await this.plugin.orderedSubtreeNodes(g,u),f=X().prefixTimestampsOnCopy,I=[];for(let{file:y,created:Q,depth:v}of p)try{let E=this.stripFrontmatter(await this.app.vault.cachedRead(y)).trim().split(/\r?\n/).join(" "),S=f?`${this.formatTimeInline(Q)} `:"";I.push(`${" ".repeat(v)}- ${S}${E}`)}catch{}this.insertIntoComposer(I.length?I.join(` +`):t.text??"");let m=await this.plugin.subtreeFilePaths(g,u),C=await this.plugin.snapshotPaths(m),B=await this.plugin.trashSubtrees(g,u);this.plugin.refreshOpenViewsForFolder(g);let w=B.filter(y=>y.extension==="md").length;this.plugin.getUndoStack(g).push({label:`Cut ${u.length} note${u.length===1?"":"s"} into composer (from ${g.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(C),this.plugin.refreshOpenViewsForFolder(g)},redo:async()=>{await this.plugin.trashSubtrees(g,u),this.plugin.refreshOpenViewsForFolder(g)}}),this.plugin.notifications.show({message:`Pasted the text of ${u.length} cut note${u.length===1?"":"s"} from "${g.split("/").pop()}" into the composer and removed the original${w===1?"":"s"} (${w} note${w===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:u,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,u)=>{if(!s.has(g.id)){s.add(g.id),i.push({node:g,depth:u});for(let p of this.tree.getChildren(g.id))n(p,u+1)}};for(let g of e)n(g,0);let o=this.noteFolder,a=X().prefixTimestampsOnCopy,l=[];for(let{node:g,depth:u}of i)if(g.file)try{let p=this.stripFrontmatter(await this.app.vault.cachedRead(g.file)).trim().split(/\r?\n/).join(" "),f=a?`${this.formatTimeInline(g.created)} `:"";l.push(`${" ".repeat(u)}- ${f}${p}`)}catch{}this.insertIntoComposer(l.join(` +`));let c=i.map(g=>g.node),d=await this.snapshotNotes(c,!1);for(let g of[...c].reverse())if(g.file)try{await this.app.fileManager.trashFile(g.file)}catch(u){console.warn("[Stashpad] cut-paste delete failed",g.file.path,u)}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 u=this.app.vault.getAbstractFileByPath(g.path);if(u)try{await this.app.fileManager.trashFile(u)}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"} (${c.length} note${c.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:h,folder:o,duration:0})}cmdInsertTemplate(){new Zt(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 F.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:me(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 c=this.app.vault.getAbstractFileByPath(l);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter&&this.tagFilter!==xe&&this.tagFilter!==Ne){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!==k&&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(k)}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 F.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=[k],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!==k)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let c=this.app.vault.getAbstractFileByPath(e);if(c instanceof F.TFile)return c}catch(c){console.warn("[Stashpad] home note rename failed; keeping legacy path",c)}return o}let s=new Date().toISOString(),n=["---",`id: ${k}`,"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===k)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,r=>{r.parent=k}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:k,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(c=>{c===s&&(l=!0)}),l})())return;e.offref(n),(()=>{let l=!1;return e.iterateAllLeaves(c=>{c===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:k,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let r=s.on("active-leaf-change",()=>{if((()=>{let d=!1;return s.iterateAllLeaves(h=>{h===o&&(d=!0)}),d})())return;s.offref(r),(()=>{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 F.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))}),r=s.view?.editor;r&&requestAnimationFrame(()=>{try{let l=r.lastLine(),c=r.getLine(l)?.length??0;r.setCursor({line:l,ch:c}),r.scrollIntoView({from:{line:l,ch:c},to:{line:l,ch:c}},!0),r.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 F.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 F.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new F.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,c)=>this.listPinnedAt(l)-this.listPinnedAt(c)),r=n.filter(l=>!this.isListPinned(l));return[...o,...r]}async cmdToggleListPin(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new F.Notice("Nothing to pin.");return}let e=t.some(r=>!this.isListPinned(r.id)),i=[],s=new Date().toISOString(),n=[];for(let r of t){if(!r.file)continue;let l=this.app.metadataCache.getFileCache(r.file)?.frontmatter;i.push({path:r.file.path,listPinned:l?.listPinned,listPinnedAt:l?.listPinnedAt});let c=e?typeof l?.listPinnedAt=="string"&&Date.parse(l.listPinnedAt)||Date.parse(s):0;this.listPinnedState.set(r.file.path,{pinned:e,at:c}),await this.app.fileManager.processFrontMatter(r.file,d=>{e?(d.listPinned=!0,d.listPinnedAt||(d.listPinnedAt=s)):(delete d.listPinned,delete d.listPinnedAt)}),n.push(r.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 r of i){let l=this.app.vault.getAbstractFileByPath(r.path);if(!l)continue;await this.app.fileManager.processFrontMatter(l,h=>{r.listPinned===void 0?delete h.listPinned:h.listPinned=r.listPinned,r.listPinnedAt===void 0?delete h.listPinnedAt:h.listPinnedAt=r.listPinnedAt});let c=r.listPinned===!0,d=typeof r.listPinnedAt=="string"&&Date.parse(r.listPinnedAt)||0;this.listPinnedState.set(r.path,{pinned:c,at:d})}this.tree.rebuild(o),this.render()}})}async cmdToggleComplete(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new F.Notice("Nothing to toggle.");return}let i=t.some(r=>!this.isCompleted(r)),s=[],n=[];for(let r of t){if(!r.file)continue;let l=this.isCompleted(r);s.push({id:r.id,path:r.file.path,was:l}),l!==i&&(await this.app.fileManager.processFrontMatter(r.file,c=>{i?c.completed=!0:delete c.completed}),this.completedState.set(r.file.path,i),n.push(r.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 r=n.map(l=>this.tree.get(l)).filter(l=>!!l);this.plugin.notifications.show({message:this.bulkActionMessage({verb:i?"Marked complete":"Unmarked",nodes:r}),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 r=[];for(let l of s){let c=this.app.vault.getAbstractFileByPath(l.path);c&&(await this.app.fileManager.processFrontMatter(c,d=>{l.was?d.completed=!0:delete d.completed}),n.includes(l.id)&&r.push(l.id))}r.length>0&&await this.log.append({type:i?"uncomplete":"complete",id:r[0],payload:{ids:r,count:r.length,undo:!0}}),this.tree.rebuild(o),this.render()},redo:async()=>{for(let r of s){let l=this.app.vault.getAbstractFileByPath(r.path);l&&await this.app.fileManager.processFrontMatter(l,c=>{i?c.completed=!0:delete c.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}taggedFromFm(t){return t?Ye(t,"task")||t.task===!0:!1}cmdSetDue(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new F.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=De(i??{});new Ze(this.app,s,r=>{this.applyDue(t,r.iso,r.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let c of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,c.id,c.name);let r=i.map(c=>this.plugin.authorRefFor(this.noteFolder,c.id,c.name));for(let c of t){if(!c.file)continue;let d=this.app.metadataCache.getFileCache(c.file)?.frontmatter,h=this.isTaskTagged(c);s.push({id:c.id,path:c.file.path,due:d?.due,task:d?.task,assignedTo:d?.assignedTo,assignedBy:d?.assignedBy,wasTagged:h}),await this.app.fileManager.processFrontMatter(c.file,u=>{e===null?delete u.due:(u.due=e,u.task=!0),r.length>0?(u.assignedTo=r,o&&(u.assignedBy=o.link),u.task=!0):(delete u.assignedTo,delete u.assignedBy)});let g=e!==null||r.length>0;this.taskTaggedState.set(c.file.path,g||h),n.push(c.id)}if(this.render(),n.length>0){let c=n.map(d=>this.tree.get(d)).filter(d=>!!d);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${re(Date.parse(e),this.plugin.settings)}`,nodes:c}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let 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 c of s){let d=this.app.vault.getAbstractFileByPath(c.path);d&&(await this.app.fileManager.processFrontMatter(d,h=>{c.due===void 0?delete h.due:h.due=c.due,c.task===void 0?delete h.task:h.task=c.task,c.assignedTo===void 0?delete h.assignedTo:h.assignedTo=c.assignedTo,c.assignedBy===void 0?delete h.assignedBy:h.assignedBy=c.assignedBy}),this.taskTaggedState.set(c.path,c.wasTagged))}this.tree.rebuild(l),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new F.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=De(i??{});new Ze(this.app,s,r=>{this.applyDue(t,r.iso,r.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 r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new F.Notice("Nothing to toggle.");return}let e=t.some(r=>!this.isTaskTagged(r)),i=[],s=[];for(let r of t){if(!r.file)continue;let l=this.isTaskTagged(r),c=this.app.metadataCache.getFileCache(r.file)?.frontmatter;if(i.push({id:r.id,path:r.file.path,tags:c?.tags,completed:c?.completed,task:c?.task,wasTagged:l}),l===e)continue;let d=!1;await this.app.fileManager.processFrontMatter(r.file,h=>{e?(kn(h,"task"),h.completed===void 0&&(h.completed=!1),d=h.completed===!0,delete h.task):(Sn(h,"task"),delete h.completed,delete h.task,d=!1)}),this.completedState.set(r.file.path,d),this.taskTaggedState.set(r.file.path,e),s.push(r.id)}if(this.render(),s.length>0){let r=e?"marked as task":"unmarked as task",l;if(s.length===1){let c=this.tree.get(s[0]);l=`"${c&&this.titleForNode(c).trim()||"(untitled)"}" ${r}`}else l=`${s.length} notes ${r}`;this.plugin.notifications.show({message:l,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let r of i){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.tags===void 0?delete c.tags:c.tags=r.tags,r.completed===void 0?delete c.completed:c.completed=r.completed,r.task===void 0?delete c.task:c.task=r.task}),this.completedState.set(r.path,!!r.completed),this.taskTaggedState.set(r.path,r.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 r of i){let l=this.app.vault.getAbstractFileByPath(r.path);if(!l)continue;let c=!1;await this.app.fileManager.processFrontMatter(l,d=>{e?(kn(d,"task"),d.completed===void 0&&(d.completed=!1),c=d.completed===!0,delete d.task):(Sn(d,"task"),delete d.completed,delete d.task,c=!1)}),this.completedState.set(r.path,c),this.taskTaggedState.set(r.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!==k&&!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 E=this.tree.get(v);E?.file&&(n.push({id:v,path:E.file.path,oldParent:E.parent}),o.add(E.parent??k))}o.add(e);let r=this.authorship.collectAuthorIds(t.map(v=>this.tree.get(v)).filter(v=>!!v)),l=this.noteFolder,c={};for(let v of o)c[v]=this.order.getOrder(l,v).slice();for(let v of n){let E=this.app.vault.getAbstractFileByPath(v.path);E&&(await this.app.fileManager.processFrontMatter(E,S=>{S.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)),u=g.indexOf(i);u<0&&(u=g.length),s==="after"&&(u+=1);let p=[...g.slice(0,u),...t.filter(v=>!!this.tree.get(v)),...g.slice(u)];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 f=this.focusId===e,I=f?t[0]:e,m=f?t.slice():[e];f?this.pendingFocusIds=m:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=m),this.tree.rebuild(l),this.render({kind:"follow-cursor"});let C=this.selectionGuardKey,B=()=>{if(this.selectionGuardKey!==C||this.selection.has(I))return;let v=this.currentChildren.findIndex(E=>E.id===I);v<0||(this.selection.add(I),this.cursorIdx=v,this.render({kind:"follow-cursor"}))};setTimeout(B,120),setTimeout(B,400);let w=t.map(v=>this.tree.get(v)).filter(v=>!!v),y=this.tree.get(e),Q=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${Q}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:r,folder:l,actions:e===k?[]:[{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 E=this.app.vault.getAbstractFileByPath(v.path);E&&(await this.app.fileManager.processFrontMatter(E,S=>{v.oldParent===null||v.oldParent===void 0?S.parent=k:S.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,E]of Object.entries(c))if(E.length===0){let S=this.order.cache.get(l)??{};delete S[v],this.order.cache.set(l,S)}else this.order.setOrder(l,v,E);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 E=this.app.vault.getAbstractFileByPath(v.path);E&&(await this.app.fileManager.processFrontMatter(E,S=>{S.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(C=>this.tree.get(C)).filter(C=>!!C&&!!C.file);if(n.length===0)return;if(n.some(C=>C.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 C of n)if(this.isDescendant(e,C.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(C)}" 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??k;if(n.some(C=>(C.parent??k)!==o)){let C=X(),B=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(C.confirmCrossParentDrag){let w=this.titleForNode(s),y=n.length,Q=i==="into"?"Nest":"Move",v=i==="into"?"as children of":"under";new it(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${Q} ${y} note${y===1?"":"s"} ${v} "${w}"? Their parent will change.`,Q,E=>{E&&B()}).open()}else await B();return}let l=o,c=n.map(C=>C.id),d=this.tree.getChildren(l).map(C=>C.id),h=new Set(c),g=d.filter(C=>!h.has(C)),u=g.indexOf(e);if(u<0)return;i==="after"&&(u+=1);let p=[...g.slice(0,u),...c,...g.slice(u)];if(bn(p,d))return;let f=this.noteFolder,I=this.order.getOrder(f,l).slice();this.order.setOrder(f,l,p),await this.order.save(f),await this.forceManualMode(l),await this.log.append({type:"reorder",id:l,payload:{dir:"drag",parent:l,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(f),this.render();let m=c.map(C=>this.tree.get(C)).filter(C=>!!C);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:m}),kind:"success",category:"reorder",affectedIds:c,folder:f}),this.plugin.getUndoStack(f).push({label:`Reorder (drag, ${c.length})`,undo:async()=>{if(I.length===0){let C=this.order.cache.get(f)??{};delete C[l],this.order.cache.set(f,C)}else this.order.setOrder(f,l,I);await this.order.save(f),await this.log.append({type:"reorder",id:l,payload:{dir:"undo",parent:l,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(f),this.render()},redo:async()=>{this.order.setOrder(f,l,p),await this.order.save(f),await this.log.append({type:"reorder",id:l,payload:{dir:"redo:drag",parent:l,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(f),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(u=>this.tree.get(u)).filter(u=>!!u&&!!u.file);if(h.length===0)return;if(new Set(h.map(u=>u.parent)).size>1){new F.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 F.Notice("Nothing to reorder.");return}let i=e[0].parent??k,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 r=sr(s,o,t);if(bn(r,s))return;let l=this.noteFolder,c=this.order.getOrder(l,i).slice();this.order.setOrder(l,i,r),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(c.length===0){let h=this.order.cache.get(l)??{};delete h[i],this.order.cache.set(l,h)}else this.order.setOrder(l,i,c);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,r),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 C=this.tree.get(this.focusId);C?.file&&(t=[C])}if(t.length===0){new F.Notice("Nothing selected to delete.");return}let e=(this.noteFolder??"").replace(/\/+$/,""),i=(this.plugin.settings.folderEncPrefs??{})[e]??{},s=i.trashEncryptContent??this.plugin.settings.encryptTrash??!1,n=i.trashHandling?i.trashHandling==="obsidian":this.plugin.settings.encryptTrashFollowObsidian??!1;if(s&&!n){if(!this.plugin.encryption?.isConfigured?.()){new F.Notice("\u201CEncrypt items sent to trash\u201D is ON but encryption isn't set up (Settings \u2192 Stashpad \u2192 Encryption). Nothing was deleted.");return}await this.secureDeleteSources(t);return}if(t.length===1){await this.deleteNote(t[0]);return}let o=[],r=new Set,l=C=>{if(!r.has(C.id)){r.add(C.id);for(let B of this.tree.getChildren(C.id))l(B);o.push(C)}};for(let C of t)l(C);let c=o.filter(C=>!!C.file),d=await Promise.all(c.map(C=>this.app.vault.read(C.file))),h=[];for(let C=0;C<c.length;C++){let B=c[C];h.push(...this.extractAttachments(this.stripFrontmatter(d[C])));let w=this.app.metadataCache.getFileCache(B.file)?.frontmatter;if(Array.isArray(w?.attachments))for(let y of w.attachments)typeof y=="string"&&y.trim()&&h.push(be(y))}let g=[...new Set(h)],u=o.length-t.length,p=async C=>{let B=await this.snapshotNotes(o,C),w=0;if(C)for(let P of g){let R=this.app.metadataCache.getFirstLinkpathDest(P,"");if(R)try{await this.app.fileManager.trashFile(R),await this.log.append({type:"attachment_remove",id:k,payload:{path:R.path}}),this.plugin.notifications.show({message:`Deleted attachment "${R.name}"`,kind:"warning",category:"attachment",affectedPaths:[R.path],folder:this.noteFolder}),w+=1}catch{}}let y=new Set;for(let P of o)P.parent&&y.add(P.parent);let Q=this.authorship.collectAuthorIds(o),v=new Set(t.map(P=>P.id)),E=this.currentChildren.map((P,R)=>v.has(P.id)?R:-1).filter(P=>P>=0),S=E.length>0?E[0]:-1,D=null;if(S>=0){for(let P=S+1;P<this.currentChildren.length;P++)if(!v.has(this.currentChildren[P].id)){D=this.currentChildren[P].id;break}if(!D){for(let P=S-1;P>=0;P--)if(!v.has(this.currentChildren[P].id)){D=this.currentChildren[P].id;break}}}for(let P of o)if(P.file){try{await this.app.fileManager.trashFile(P.file)}catch{}await this.log.append({type:"delete",id:P.id,payload:{path:P.file.path,attachmentsRemoved:C?g:[]}})}this.selection.clear(),this.cursorIdx=-1,D&&(this.pendingFocusIds=[D]),this.tree.rebuild(this.noteFolder);for(let P of y)o.some(R=>R.id===P)||this.fmSync.scheduleParentOfDeleted(P);this.render({kind:"follow-cursor"});let H=w>0?` with ${w} attachment${w===1?"":"s"}`:"",U=this.noteFolder,N=t.map(P=>P.id),b=!1,T=async()=>{b||(b=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(B,N.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:H.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(P=>P.id),affectedAuthorIds:Q,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void T()}]}),this.plugin.getUndoStack(U).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await T()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,b=!1,await this.trashNotesAndAttachments(B)}}),this.focusView()},f=X(),I=f.confirmBulkDelete,m=g.length>0&&f.confirmAttachmentDelete;if(!I&&!m){await p(!1);return}new We(this.app,`${t.length} selected note${t.length===1?"":"s"}`,u,g.length,m,p).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new F.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 F.Notice("Note is too short to split.");return}let r=s,l=i.path,c=async(h,g,u)=>{if(!h.trim()||!g.trim()){new F.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===k)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=k}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:k,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:q,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(c=>{c===s&&(l=!0)}),l})())return;e.offref(n),(()=>{let l=!1;return e.iterateAllLeaves(c=>{c===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:q,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:q,active:!0,state:{focusId:k,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 F.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(),c=a.getLine(l)?.length??0;a.setCursor({line:l,ch:c}),a.scrollIntoView({from:{line:l,ch:c},to:{line:l,ch:c}},!0),a.focus()}catch{}})}cmdSelectAll(){if(this.currentChildren.length!==0){this.selection.clear();for(let t of this.currentChildren)this.selection.add(t.id);this.firstSelectedId=this.currentChildren[0].id,this.lastSelected=this.currentChildren[this.currentChildren.length-1].id,this.cursorIdx=this.currentChildren.length-1,this.render()}}async cmdTogglePin(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new F.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 F.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new F.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,c)=>this.listPinnedAt(l)-this.listPinnedAt(c)),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 F.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 c=e?typeof l?.listPinnedAt=="string"&&Date.parse(l.listPinnedAt)||Date.parse(s):0;this.listPinnedState.set(a.file.path,{pinned:e,at:c}),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 c=a.listPinned===!0,d=typeof a.listPinnedAt=="string"&&Date.parse(a.listPinnedAt)||0;this.listPinnedState.set(a.path,{pinned:c,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 F.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,c=>{i?c.completed=!0:delete c.completed}),this.completedState.set(a.file.path,i),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(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 c=this.app.vault.getAbstractFileByPath(l.path);c&&(await this.app.fileManager.processFrontMatter(c,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,c=>{i?c.completed=!0:delete c.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}taggedFromFm(t){return t?Ye(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 F.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=De(i??{});new Ze(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let c of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,c.id,c.name);let a=i.map(c=>this.plugin.authorRefFor(this.noteFolder,c.id,c.name));for(let c of t){if(!c.file)continue;let d=this.app.metadataCache.getFileCache(c.file)?.frontmatter,h=this.isTaskTagged(c);s.push({id:c.id,path:c.file.path,due:d?.due,task:d?.task,assignedTo:d?.assignedTo,assignedBy:d?.assignedBy,wasTagged:h}),await this.app.fileManager.processFrontMatter(c.file,u=>{e===null?delete u.due:(u.due=e,u.task=!0),a.length>0?(u.assignedTo=a,o&&(u.assignedBy=o.link),u.task=!0):(delete u.assignedTo,delete u.assignedBy)});let g=e!==null||a.length>0;this.taskTaggedState.set(c.file.path,g||h),n.push(c.id)}if(this.render(),n.length>0){let c=n.map(d=>this.tree.get(d)).filter(d=>!!d);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${ae(Date.parse(e),this.plugin.settings)}`,nodes:c}),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 c of s){let d=this.app.vault.getAbstractFileByPath(c.path);d&&(await this.app.fileManager.processFrontMatter(d,h=>{c.due===void 0?delete h.due:h.due=c.due,c.task===void 0?delete h.task:h.task=c.task,c.assignedTo===void 0?delete h.assignedTo:h.assignedTo=c.assignedTo,c.assignedBy===void 0?delete h.assignedBy:h.assignedBy=c.assignedBy}),this.taskTaggedState.set(c.path,c.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 F.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=De(i??{});new Ze(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 F.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),c=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:c?.tags,completed:c?.completed,task:c?.task,wasTagged:l}),l===e)continue;let d=!1;await this.app.fileManager.processFrontMatter(a.file,h=>{e?(xn(h,"task"),h.completed===void 0&&(h.completed=!1),d=h.completed===!0,delete h.task):(Nn(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 c=this.tree.get(s[0]);l=`"${c&&this.titleForNode(c).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,c=>{a.tags===void 0?delete c.tags:c.tags=a.tags,a.completed===void 0?delete c.completed:c.completed=a.completed,a.task===void 0?delete c.task:c.task=a.task}),this.completedState.set(a.path,!!a.completed),this.taskTaggedState.set(a.path,a.wasTagged))}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:o,redo:async()=>{for(let a of i){let l=this.app.vault.getAbstractFileByPath(a.path);if(!l)continue;let c=!1;await this.app.fileManager.processFrontMatter(l,d=>{e?(xn(d,"task"),d.completed===void 0&&(d.completed=!1),c=d.completed===!0,delete d.task):(Nn(d,"task"),delete d.completed,delete d.task,c=!1)}),this.completedState.set(a.path,c),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==k&&!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 E=this.tree.get(v);E?.file&&(n.push({id:v,path:E.file.path,oldParent:E.parent}),o.add(E.parent??k))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(v=>this.tree.get(v)).filter(v=>!!v)),l=this.noteFolder,c={};for(let v of o)c[v]=this.order.getOrder(l,v).slice();for(let v of n){let E=this.app.vault.getAbstractFileByPath(v.path);E&&(await this.app.fileManager.processFrontMatter(E,S=>{S.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)),u=g.indexOf(i);u<0&&(u=g.length),s==="after"&&(u+=1);let p=[...g.slice(0,u),...t.filter(v=>!!this.tree.get(v)),...g.slice(u)];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 f=this.focusId===e,I=f?t[0]:e,m=f?t.slice():[e];f?this.pendingFocusIds=m:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=m),this.tree.rebuild(l),this.render({kind:"follow-cursor"});let C=this.selectionGuardKey,B=()=>{if(this.selectionGuardKey!==C||this.selection.has(I))return;let v=this.currentChildren.findIndex(E=>E.id===I);v<0||(this.selection.add(I),this.cursorIdx=v,this.render({kind:"follow-cursor"}))};setTimeout(B,120),setTimeout(B,400);let w=t.map(v=>this.tree.get(v)).filter(v=>!!v),y=this.tree.get(e),Q=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${Q}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:l,actions:e===k?[]:[{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 E=this.app.vault.getAbstractFileByPath(v.path);E&&(await this.app.fileManager.processFrontMatter(E,S=>{v.oldParent===null||v.oldParent===void 0?S.parent=k:S.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,E]of Object.entries(c))if(E.length===0){let S=this.order.cache.get(l)??{};delete S[v],this.order.cache.set(l,S)}else this.order.setOrder(l,v,E);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 E=this.app.vault.getAbstractFileByPath(v.path);E&&(await this.app.fileManager.processFrontMatter(E,S=>{S.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(C=>this.tree.get(C)).filter(C=>!!C&&!!C.file);if(n.length===0)return;if(n.some(C=>C.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 C of n)if(this.isDescendant(e,C.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(C)}" 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??k;if(n.some(C=>(C.parent??k)!==o)){let C=X(),B=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(C.confirmCrossParentDrag){let w=this.titleForNode(s),y=n.length,Q=i==="into"?"Nest":"Move",v=i==="into"?"as children of":"under";new it(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${Q} ${y} note${y===1?"":"s"} ${v} "${w}"? Their parent will change.`,Q,E=>{E&&B()}).open()}else await B();return}let l=o,c=n.map(C=>C.id),d=this.tree.getChildren(l).map(C=>C.id),h=new Set(c),g=d.filter(C=>!h.has(C)),u=g.indexOf(e);if(u<0)return;i==="after"&&(u+=1);let p=[...g.slice(0,u),...c,...g.slice(u)];if(Mn(p,d))return;let f=this.noteFolder,I=this.order.getOrder(f,l).slice();this.order.setOrder(f,l,p),await this.order.save(f),await this.forceManualMode(l),await this.log.append({type:"reorder",id:l,payload:{dir:"drag",parent:l,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(f),this.render();let m=c.map(C=>this.tree.get(C)).filter(C=>!!C);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:m}),kind:"success",category:"reorder",affectedIds:c,folder:f}),this.plugin.getUndoStack(f).push({label:`Reorder (drag, ${c.length})`,undo:async()=>{if(I.length===0){let C=this.order.cache.get(f)??{};delete C[l],this.order.cache.set(f,C)}else this.order.setOrder(f,l,I);await this.order.save(f),await this.log.append({type:"reorder",id:l,payload:{dir:"undo",parent:l,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(f),this.render()},redo:async()=>{this.order.setOrder(f,l,p),await this.order.save(f),await this.log.append({type:"reorder",id:l,payload:{dir:"redo:drag",parent:l,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(f),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(u=>this.tree.get(u)).filter(u=>!!u&&!!u.file);if(h.length===0)return;if(new Set(h.map(u=>u.parent)).size>1){new F.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 F.Notice("Nothing to reorder.");return}let i=e[0].parent??k,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=oa(s,o,t);if(Mn(a,s))return;let l=this.noteFolder,c=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(c.length===0){let h=this.order.cache.get(l)??{};delete h[i],this.order.cache.set(l,h)}else this.order.setOrder(l,i,c);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 C=this.tree.get(this.focusId);C?.file&&(t=[C])}if(t.length===0){new F.Notice("Nothing selected to delete.");return}let e=(this.noteFolder??"").replace(/\/+$/,""),i=(this.plugin.settings.folderEncPrefs??{})[e]??{},s=i.trashEncryptContent??this.plugin.settings.encryptTrash??!1,n=i.trashHandling?i.trashHandling==="obsidian":this.plugin.settings.encryptTrashFollowObsidian??!1;if(s&&!n){if(!this.plugin.encryption?.isConfigured?.()){new F.Notice("\u201CEncrypt items sent to trash\u201D is ON but encryption isn't set up (Settings \u2192 Stashpad \u2192 Encryption). Nothing was deleted.");return}await this.secureDeleteSources(t);return}if(t.length===1){await this.deleteNote(t[0]);return}let o=[],a=new Set,l=C=>{if(!a.has(C.id)){a.add(C.id);for(let B of this.tree.getChildren(C.id))l(B);o.push(C)}};for(let C of t)l(C);let c=o.filter(C=>!!C.file),d=await Promise.all(c.map(C=>this.app.vault.read(C.file))),h=[];for(let C=0;C<c.length;C++){let B=c[C];h.push(...this.extractAttachments(this.stripFrontmatter(d[C])));let w=this.app.metadataCache.getFileCache(B.file)?.frontmatter;if(Array.isArray(w?.attachments))for(let y of w.attachments)typeof y=="string"&&y.trim()&&h.push(be(y))}let g=[...new Set(h)],u=o.length-t.length,p=async C=>{let B=await this.snapshotNotes(o,C),w=0;if(C)for(let P of g){let R=this.app.metadataCache.getFirstLinkpathDest(P,"");if(R)try{await this.app.fileManager.trashFile(R),await this.log.append({type:"attachment_remove",id:k,payload:{path:R.path}}),this.plugin.notifications.show({message:`Deleted attachment "${R.name}"`,kind:"warning",category:"attachment",affectedPaths:[R.path],folder:this.noteFolder}),w+=1}catch{}}let y=new Set;for(let P of o)P.parent&&y.add(P.parent);let Q=this.authorship.collectAuthorIds(o),v=new Set(t.map(P=>P.id)),E=this.currentChildren.map((P,R)=>v.has(P.id)?R:-1).filter(P=>P>=0),S=E.length>0?E[0]:-1,D=null;if(S>=0){for(let P=S+1;P<this.currentChildren.length;P++)if(!v.has(this.currentChildren[P].id)){D=this.currentChildren[P].id;break}if(!D){for(let P=S-1;P>=0;P--)if(!v.has(this.currentChildren[P].id)){D=this.currentChildren[P].id;break}}}for(let P of o)if(P.file){try{await this.app.fileManager.trashFile(P.file)}catch{}await this.log.append({type:"delete",id:P.id,payload:{path:P.file.path,attachmentsRemoved:C?g:[]}})}this.selection.clear(),this.cursorIdx=-1,D&&(this.pendingFocusIds=[D]),this.tree.rebuild(this.noteFolder);for(let P of y)o.some(R=>R.id===P)||this.fmSync.scheduleParentOfDeleted(P);this.render({kind:"follow-cursor"});let H=w>0?` with ${w} attachment${w===1?"":"s"}`:"",U=this.noteFolder,N=t.map(P=>P.id),b=!1,T=async()=>{b||(b=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(B,N.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:H.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(P=>P.id),affectedAuthorIds:Q,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void T()}]}),this.plugin.getUndoStack(U).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await T()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,b=!1,await this.trashNotesAndAttachments(B)}}),this.focusView()},f=X(),I=f.confirmBulkDelete,m=g.length>0&&f.confirmAttachmentDelete;if(!I&&!m){await p(!1);return}new We(this.app,`${t.length} selected note${t.length===1?"":"s"}`,u,g.length,m,p).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new F.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 F.Notice("Note is too short to split.");return}let a=s,l=i.path,c=async(h,g,u)=>{if(!h.trim()||!g.trim()){new F.Notice("Split would leave one part empty.");return}try{let p=s.startsWith("---")?s.slice(0,s.indexOf(` ---`,3)+4):"",f=p+(p?` `:"")+h+` -`;await this.app.vault.modify(i,f);let I=e.parent??k,m=Date.parse(e.created||""),C=Number.isFinite(m)?new Date(m+1).toISOString():new Date().toISOString(),B=await this.createNoteUnder(g,I,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:B,...u}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let w=B?this.tree.get(B):void 0,y=w?.file?.path,Q=y?await this.app.vault.read(w.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(y){let S=this.app.vault.getAbstractFileByPath(y);if(S)try{await this.app.fileManager.trashFile(S)}catch{}}let E=this.app.vault.getAbstractFileByPath(l);E&&await this.app.vault.modify(E,r),this.tree.rebuild(v),this.render()},redo:async()=>{let E=this.app.vault.getAbstractFileByPath(l);E&&await this.app.vault.modify(E,f),y&&Q&&!await this.app.vault.adapter.exists(y)&&await this.app.vault.create(y,Q),this.tree.rebuild(v),this.render()}})}catch(p){new F.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(` +`;await this.app.vault.modify(i,f);let I=e.parent??k,m=Date.parse(e.created||""),C=Number.isFinite(m)?new Date(m+1).toISOString():new Date().toISOString(),B=await this.createNoteUnder(g,I,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:B,...u}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let w=B?this.tree.get(B):void 0,y=w?.file?.path,Q=y?await this.app.vault.read(w.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(y){let S=this.app.vault.getAbstractFileByPath(y);if(S)try{await this.app.fileManager.trashFile(S)}catch{}}let E=this.app.vault.getAbstractFileByPath(l);E&&await this.app.vault.modify(E,a),this.tree.rebuild(v),this.render()},redo:async()=>{let E=this.app.vault.getAbstractFileByPath(l);E&&await this.app.vault.modify(E,f),y&&Q&&!await this.app.vault.adapter.exists(y)&&await this.app.vault.create(y,Q),this.tree.rebuild(v),this.render()}})}catch(p){new F.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(` ---`,3)+4):"",u=h[0].replace(/\s+$/,"");if(!u.trim()){new F.Notice("Split would leave the first part empty.");return}let p=g+(g?` `:"")+u+` -`;await this.app.vault.modify(i,p);let f=e.parent??k,I=Date.parse(e.created||""),m=Number.isFinite(I)?I:Date.now(),C=[];this.beginBulkRender();try{for(let y=1;y<h.length;y++)await this.createNoteUnder(h[y],f,{record:!1,createdOverride:new Date(m+y).toISOString(),deferRender:!0,collectInto:C})}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=C.slice(),w=this.noteFolder;this.plugin.getUndoStack(w).push({label:`Split note into ${h.length}`,undo:async()=>{for(let{path:Q}of B){let v=this.app.vault.getAbstractFileByPath(Q);if(v)try{await this.app.fileManager.trashFile(v)}catch{}}let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,r),this.tree.rebuild(w),this.render()},redo:async()=>{let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,p);for(let{path:Q,content:v}of B)await this.app.vault.adapter.exists(Q)||await this.app.vault.create(Q,v);this.tree.rebuild(w),this.render()}})}catch(g){new F.Notice(`Stashpad: split failed (${g.message})`),console.error(g)}};new Si(this.app,n,async h=>{let g=o.slice(0,h).join(` +`;await this.app.vault.modify(i,p);let f=e.parent??k,I=Date.parse(e.created||""),m=Number.isFinite(I)?I:Date.now(),C=[];this.beginBulkRender();try{for(let y=1;y<h.length;y++)await this.createNoteUnder(h[y],f,{record:!1,createdOverride:new Date(m+y).toISOString(),deferRender:!0,collectInto:C})}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=C.slice(),w=this.noteFolder;this.plugin.getUndoStack(w).push({label:`Split note into ${h.length}`,undo:async()=>{for(let{path:Q}of B){let v=this.app.vault.getAbstractFileByPath(Q);if(v)try{await this.app.fileManager.trashFile(v)}catch{}}let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,a),this.tree.rebuild(w),this.render()},redo:async()=>{let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,p);for(let{path:Q,content:v}of B)await this.app.vault.adapter.exists(Q)||await this.app.vault.create(Q,v);this.tree.rebuild(w),this.render()}})}catch(g){new F.Notice(`Stashpad: split failed (${g.message})`),console.error(g)}};new bi(this.app,n,async h=>{let g=o.slice(0,h).join(` `).replace(/\s+$/,""),u=o.slice(h).join(` -`).replace(/^\s+|\s+$/g,"");await c(g,u,{mode:"line",splitAtLine:h})},async h=>{let g=n.slice(0,h).replace(/\s+$/,""),u=n.slice(h).replace(/^\s+|\s+$/g,"");await c(g,u,{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 Ra(this,t)}cmdExportOkf(t){return La(this,t)}cmdImportStash(){return Ja(this)}processStashFile(t){return xo(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=W(),r=null;{let I=(this.plugin.settings.noteTemplates??{})[s];if(I){let m=this.app.vault.getAbstractFileByPath(I);if(m&&m.extension==="md")try{let C=await this.app.vault.cachedRead(m),B=this.stripFrontmatter(C);r=this.app.metadataCache.getFileCache(m)?.frontmatter??{},B.includes("{{body}}")?t=B.replace(/\{\{body\}\}/g,t):t.trim()?B.trim()&&(t=`${t} +`).replace(/^\s+|\s+$/g,"");await c(g,u,{mode:"line",splitAtLine:h})},async h=>{let g=n.slice(0,h).replace(/\s+$/,""),u=n.slice(h).replace(/^\s+|\s+$/g,"");await c(g,u,{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 Lr(this,t)}cmdExportOkf(t){return qr(this,t)}cmdImportStash(){return Yr(this)}processStashFile(t){return Po(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=W(),a=null;{let I=(this.plugin.settings.noteTemplates??{})[s];if(I){let m=this.app.vault.getAbstractFileByPath(I);if(m&&m.extension==="md")try{let C=await this.app.vault.cachedRead(m),B=this.stripFrontmatter(C);a=this.app.metadataCache.getFileCache(m)?.frontmatter??{},B.includes("{{body}}")?t=B.replace(/\{\{body\}\}/g,t):t.trim()?B.trim()&&(t=`${t} ${B}`):t=B}catch(C){console.warn("[Stashpad] template read failed",C)}}}let l=St(t,this.activeStopwords()),c=bt(l,o),d=`${s}/${c}`,h=e??this.focusId,g=i.createdOverride??new Date().toISOString(),u=this.extractAttachments(t),p=this.authorship.currentAuthorLink();p&&this.authorship.ensureAuthorFile(p);let f=["---",`id: ${o}`,`parent: ${h}`,`created: ${g}`,`modified: ${g}`];if(p&&f.push(`author: "${p.link.replace(/"/g,'\\"')}"`),u.length>0){f.push("attachments:");for(let I of u)f.push(` - "${I.replace(/"/g,'\\"')}"`)}else f.push("attachments: []");f.push("---",t);try{let I=f.join(` `);this.plugin.importService.suppress(d,6e4),await vt.timeAsync("write.createNote.file",()=>this.app.vault.create(d,I)),i.collectInto?.push({path:d,content:I});try{let m=this.app.vault.getAbstractFileByPath(d);if(m&&m.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:h,children:[],file:m,created:g}),i.deferRender||this.render(),this.fmSync.scheduleParentChange(o,null,h);else{i.deferRender||this.render();let C=s.split("/").pop()||s,B=(t.split(` -`).find(w=>w.trim())??"note").trim().slice(0,60);i.deferUndo||this.plugin.notifications.show({message:`"${B}" landed in \`${C}\``,kind:"success",category:"create",duration:0,folder:s,affectedIds:[o],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(s,o)}}]})}if(r)try{await this.app.fileManager.processFrontMatter(m,C=>{for(let[B,w]of Object.entries(r))ue.includes(B)||En.includes(B)||C[B]===void 0&&(C[B]=w)})}catch(C){console.warn("[Stashpad] template fm overlay failed",C)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:d,parent:h}}),i.record!==!1&&!i.deferUndo){let m=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let C=this.app.vault.getAbstractFileByPath(d);if(C)try{await this.app.fileManager.trashFile(C)}catch{}if(this.composerDraft=m,this.saveDraft(m),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=m;let B=m.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,I),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(m),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(I){return new F.Notice(`Stashpad: failed to create note (${I.message})`),null}}async createNotesBatch(t,e,i,s,n){let o=t.length,r=[],l=!!i?.targetFolder&&i.targetFolder!==this.noteFolder,c=8,d=null;if(o>=c){let h=new F.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"}),f=g.createDiv({cls:"stashpad-split-progress-label",text:`0 / ${o}`});d={notice:h,fill:p,label:f}}this.beginBulkRender();try{for(let h=0;h<o;h++)if(await this.createNoteUnder(t[h],e,{...i??{},deferRender:!0,deferUndo:!0,collectInto:r}),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(u=>window.setTimeout(u,0))}}finally{d?.notice.hide();try{await this.fmSync.flush()}catch{}this.endBulkRender()}if(r.length){let h=r.slice();this.plugin.getUndoStack(n).push({label:`Create ${h.length} notes`,undo:async()=>{for(let{path:g}of h){let u=this.app.vault.getAbstractFileByPath(g);if(u)try{await this.app.fileManager.trashFile(u)}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:u}of h)await this.app.vault.adapter.exists(g)||await this.app.vault.create(g,u);this.composerDraft="",this.saveDraft(""),this.composerInputEl&&(this.composerInputEl.value=""),l||this.tree.rebuild(this.noteFolder),this.render()}})}o>=c&&this.plugin.notifications.show({message:`Created ${r.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 F.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}/${ps(s,n)}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:k,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 F.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()!==""):[],r=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",l=i.showAuthor&&!!n,c=i.showContributors&&o.length>0,d=i.showLastEdit&&!!r;if(!l&&!c&&!d)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),g=(p,f)=>{let I=f.replace(/^\[\[/,"").replace(/\]\]$/,""),m=I.indexOf("|"),C=m>=0?I.slice(0,m):I,B=m>=0?I.slice(m+1):I.split("/").pop()??I,w=p.createEl("a",{cls:"internal-link",text:B});w.setAttribute("data-href",C),w.setAttribute("href",C)},u=[];l&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"by "}),g(p,n)}),c&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((f,I)=>{I>0&&p.createSpan({text:", "}),g(p,f)})}),d&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"edited "}),p.createSpan({text:this.formatTimeInline(r)})}),u.forEach((p,f)=>{f>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let I=h.createSpan({cls:"stashpad-authorship-piece"});p(I)}),h.addEventListener("click",p=>this.handleRenderedClick(p,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Vt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,F.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=me(t.basename);if(!e||e===k)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=St(s,this.activeStopwords()),o=bt(n,e);if(t.name===o)return;let r=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(r))return;let l=t.path;try{await this.app.fileManager.renameFile(t,r),await this.log.append({type:"rename",id:e,payload:{from:l,to:r}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,F.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,r=(Array.isArray(n?.attachments)?n.attachments:[]).filter(d=>typeof d=="string").map(d=>be(d));if(r.length===s.length&&r.every((d,h)=>d===s[h]))return;let c=s.map(d=>$t(d));await this.app.fileManager.processFrontMatter(t,d=>{d.attachments=c})}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,F.moment)(t);if(!e.isValid())return"";if(X().useTemplatesFormat){let s=Ds(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,F.moment)(t);if(!e.isValid())return"";if(X().useTemplatesFormat){let s=Ds(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,F.Platform.isMobile){let r=0,l=()=>{!this.stickToListBottom||r>=8||(r++,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 r of Array.from(t.children))r instanceof HTMLElement&&i.observe(r);this.stickyRowObserver=i;let s=performance.now(),n=t.scrollHeight,o=()=>{if(!this.stickToListBottom)return;let r=t.scrollHeight;r!==n&&(t.scrollTop=r,n=r),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 F.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??k),g=h.indexOf(e.id),u=g>0?h[g-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,u)&&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,k),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==k&&this.navigateTo(k)}));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 r=this.isListPinned(e.id);s.addItem(d=>d.setTitle(r?"Unpin from top of list":"Pin to top of list").setIcon(r?"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)},c=d=>{let h=this.isTask(e);if(h){let g=this.isCompleted(e);d.addItem(u=>u.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"?c(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 f of this.tree.getChildren(p.id))i(f),e.push(f)};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))),r=[];for(let p=0;p<n.length;p++){let f=n[p];r.push(...this.extractAttachments(this.stripFrontmatter(o[p])));let I=this.app.metadataCache.getFileCache(f.file)?.frontmatter;if(Array.isArray(I?.attachments))for(let m of I.attachments)typeof m=="string"&&m.trim()&&r.push(be(m))}let l=[...new Set(r)],c=this.authorship.collectAuthorIds(s),d=async p=>{let f=await this.snapshotNotes(s,p),I=0;if(p)for(let D of l){let H=this.app.metadataCache.getFirstLinkpathDest(D,"");if(H)try{await this.app.fileManager.trashFile(H),await this.log.append({type:"attachment_remove",id:k,payload:{path:H.path}}),this.plugin.notifications.show({message:`Deleted attachment "${H.name}"`,kind:"warning",category:"attachment",affectedPaths:[H.path],folder:this.noteFolder}),I+=1}catch{}}let m=new Set;for(let D of s)D.parent&&m.add(D.parent);let C=this.currentChildren.findIndex(D=>D.id===t.id),B=null;if(C>=0){for(let D=C+1;D<this.currentChildren.length;D++)if(this.currentChildren[D].id!==t.id){B=this.currentChildren[D].id;break}if(!B){for(let D=C-1;D>=0;D--)if(this.currentChildren[D].id!==t.id){B=this.currentChildren[D].id;break}}}for(let D of s)if(D.file){try{await this.app.fileManager.trashFile(D.file)}catch{}await this.log.append({type:"delete",id:D.id,payload:{path:D.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 D of m)s.some(H=>H.id===D)||this.fmSync.scheduleParentOfDeleted(D);let w=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,Q=t.id,v=I>0?` with ${I} attachment${I===1?"":"s"}`:"",E=!1,S=async()=>{E||(E=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(f,[Q]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${v}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:c,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void S()}]}),this.plugin.getUndoStack(w).push({label:y,undo:async()=>{await S()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,E=!1,await this.trashNotesAndAttachments(f)}})},h=X(),g=e.length>0&&h.confirmBulkDelete,u=l.length>0&&h.confirmAttachmentDelete;if(!g&&!u){await d(!1),this.focusView();return}new We(this.app,this.titleForNode(t),e.length,l.length,u,async p=>{await d(p),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new F.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===k){new F.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new F.Notice("Couldn't find the parent note.");return}let i=e.parent??k,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(l=>l.id!==t.id).length,r=[`"${n}" becomes a child of "${s}".`];o>0&&r.push(`${o} sibling${o===1?"":"s"} move with it.`),new it(this.app,"Swap notes?",r.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,r=[`"${s}" becomes a child of "${n}".`];o>0&&r.push(`${o} sibling${o===1?"":"s"} move with it.`),new it(this.app,"Confirm Note Swap",r.join(` -`),"Swap",async l=>{if(!l)return;let c=t.parent??k;await this.swapParentChild(t,i,c)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new F.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(u=>u.id!==e.id).filter(u=>!!u.file),r=o.map(u=>({id:u.id,path:u.file.path,was:u.parent})),l=this.order.getOrder(s,i).slice(),c=this.order.getOrder(s,e.id).slice(),d=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,u=>{u.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,u=>{u.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let u of o)await this.app.fileManager.processFrontMatter(u.file,p=>{p.parent=e.id}),this.fmSync.scheduleParentChange(u.id,t.id,e.id);if(l.length>0){let u=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,u)}let h=o.map(u=>u.id),g=[t.id,...c.filter(u=>u!==t.id&&!h.includes(u)),...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 u of r)await this.log.append({type:"parent_change",id:u.id,payload:{from:u.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 u=this.tree.get(t.id),p=this.tree.get(e.id);u?.file&&await this.app.fileManager.processFrontMatter(u.file,f=>{n==null||n===k?(delete f.parent,f.parent=k):f.parent=n}),p?.file&&await this.app.fileManager.processFrontMatter(p.file,f=>{f.parent=t.id});for(let f of r){let I=this.app.vault.getAbstractFileByPath(f.path);I&&await this.app.fileManager.processFrontMatter(I,m=>{f.was==null?m.parent=k:m.parent=f.was})}this.order.setOrder(s,i,l),this.order.setOrder(s,e.id,c),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??k;if(o(n)===o(e)){if(!i.quiet){let l=this.titleForNode(t),c=e===k?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${l}" is already under ${c}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==k&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let r=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),c=l?this.titleForNode(l):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${c}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:r,folder:this.noteFolder,actions:e===k?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let l=this.noteFolder,c=s.path,d=t.id;this.plugin.getUndoStack(l).push({label:"Move note",undo:async()=>{let h=this.app.vault.getAbstractFileByPath(c);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,u=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(f=>f.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(u,120),setTimeout(u,400)}}},redo:async()=>{let h=this.app.vault.getAbstractFileByPath(c);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,u=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(f=>f.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(u,120),setTimeout(u,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===k?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=l=>i.get(l.id)??0,r;if(t.length===1){let l=this.titleForNode(t[0]),c=o(t[0]);r=c>0?`Moved "${l}" and its ${c} ${c===1?"child":"children"} \u2192 ${n}`:`Moved "${l}" \u2192 ${n}`}else{let l=t.reduce((c,d)=>c+o(d),0);r=l>0?`Moved ${t.length} notes (${l} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:r,kind:"success",category:"move",duration:e===k?void 0:0,affectedIds:t.map(l=>l.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===k?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};ts.AIMED_TAP_WINDOW_MS=600;var nn=ts,No=class extends F.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)}},on=class extends F.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 ie=require("obsidian");rt();kt();var Gc=ie.moment,rn=class extends ie.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 Je}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,ie.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,ie.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 r=new Set(n.map(d=>d.blob));for(let d of[...this.selected])r.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 u=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Clear"});u.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 c=[...l.keys()].sort((d,h)=>d===" hidden"?1:h===" hidden"?-1:d.localeCompare(h));this.order=[];for(let d of c){let h=d===" hidden",g=e.createDiv({cls:"stashpad-trash-group"}),u=g.createDiv({cls:"stashpad-trash-group-head"});(0,ie.setIcon)(u.createSpan({cls:"stashpad-trash-group-icon"}),h?"lock":"folder"),u.createSpan({text:h?"Hidden (title obscured)":d.split("/").pop()||d}),u.createSpan({cls:"stashpad-trash-group-count",text:String(l.get(d).length)});for(let p of l.get(d)){let f=this.order.length;this.order.push(p.blob);let I=g.createDiv({cls:"stashpad-trash-row"});this.selected.has(p.blob)&&I.addClass("is-selected"),I.addEventListener("click",Q=>{Q.target.closest("button")||this.onRowClick(f,p.blob,Q)});let m=I.createDiv({cls:"stashpad-trash-row-main"});m.createSpan({cls:"stashpad-trash-title",text:h?"Locked note":p.meta?.title||"Locked note"});let C=p.meta?.deletedAt?`deleted ${Gc(p.meta.deletedAt).fromNow()}`:"deleted",B=p.meta&&p.meta.count>1?` \xB7 ${p.meta.count} ${p.meta.kind==="rawtrash"?"files":"notes"}`:"";m.createSpan({cls:"stashpad-trash-sub",text:C+B});let w=I.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,ie.setIcon)(w.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),w.onclick=async()=>{w.disabled=!0,await this.plugin.restoreDeletedAt(p.blob)?await this.render():w.disabled=!1};let y=I.createEl("button",{cls:"stashpad-trash-delete",attr:{"aria-label":"Delete permanently"}});(0,ie.setIcon)(y,"trash-2"),y.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 it(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 Oa(A){let{workspace:a}=A.app,t=a.getLeavesOfType(Je);if(t.length>0){a.revealLeaf(t[0]);return}let e=a.getLeaf("tab");await e.setViewState({type:Je,active:!0}),a.revealLeaf(e)}var se=require("obsidian");rt();var Ya=se.moment,an=class extends se.ItemView{constructor(t,e){super(t);this.plugin=e;this.mode="encrypted";this.renderPending=!1}getViewType(){return Oe}getDisplayText(){return this.mode==="archived"?"All archived":"All encrypted"}getIcon(){return this.mode==="archived"?"archive":"lock"}getState(){return{...super.getState(),mode:this.mode}}async setState(t,e){(t?.mode==="archived"||t?.mode==="encrypted")&&(this.mode=t.mode),await super.setState(t,e),await this.render()}async onOpen(){this.containerEl.addClass("stashpad-aggregate-view");let t=e=>e.endsWith(".stashenc")&&!e.startsWith("_deleted/");this.registerEvent(this.app.vault.on("create",e=>{t(e.path)&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",e=>{t(e.path)&&this.scheduleRender()})),await this.render()}scheduleRender(){this.renderPending||(this.renderPending=!0,window.setTimeout(()=>{this.renderPending=!1,this.render()},150))}cleanFolder(t){return(t||"").replace(/\/+$/,"")}archiveFolders(){let t=new Set((this.plugin.settings.archiveFolders??[]).map(i=>this.cleanFolder(i))),e=this.plugin.settings.folderEncPrefs??{};for(let[i,s]of Object.entries(e))s?.archive&&t.add(this.cleanFolder(i));return[...t].sort((i,s)=>i.localeCompare(s))}async render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-aggregate-body");let e=t.createDiv({cls:"stashpad-aggregate-header"});e.createEl("h3",{text:this.getDisplayText()});let i=e.createEl("button",{cls:"stashpad-trash-iconbtn"});if((0,se.setIcon)(i,"refresh-cw"),i.setAttr("aria-label","Refresh"),i.onclick=()=>void this.render(),this.mode==="archived"){this.renderArchived(t);return}this.renderEncrypted(t)}renderEncrypted(t){let e=this.plugin.settings.lockedSubtrees??[];if(e.length===0){t.createDiv({cls:"stashpad-trash-empty",text:"Nothing is encrypted yet. Lock a note or folder and it shows up here."});return}let i=new Map;for(let n of e){let o=this.cleanFolder(n.folder)||"(vault root)";(i.get(o)??i.set(o,[]).get(o)).push(n)}let s=[...i.keys()].sort((n,o)=>n.localeCompare(o));t.createDiv({cls:"stashpad-aggregate-sub",text:`${e.length} locked ${e.length===1?"item":"items"} in ${s.length} ${s.length===1?"folder":"folders"}.`});for(let n of s){let o=t.createDiv({cls:"stashpad-trash-group"}),r=o.createDiv({cls:"stashpad-trash-group-head"});(0,se.setIcon)(r.createSpan({cls:"stashpad-trash-group-icon"}),"folder"),r.createSpan({text:n.split("/").pop()||n}),r.createSpan({cls:"stashpad-trash-group-count",text:String(i.get(n).length)});let l=r.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Open"});l.onclick=()=>void this.plugin.activateViewForFolder(n);for(let c of i.get(n)){let d=o.createDiv({cls:"stashpad-trash-row"}),h=d.createDiv({cls:"stashpad-trash-row-main"});h.createSpan({cls:"stashpad-trash-title",text:c.title||"Locked note"});let g=c.created?`locked ${Ya(c.created).fromNow()}`:"locked",u=c.count>1?` \xB7 ${c.count} notes`:"";h.createSpan({cls:"stashpad-trash-sub",text:g+u});let p=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Export"});p.setAttr("aria-label","Export to .stash (encrypted with a password you choose)"),p.onclick=()=>void this.plugin.exportLockedSubtree(c.blob);let f=d.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,se.setIcon)(f,"lock")}}}renderArchived(t){let e=this.archiveFolders();if(e.length===0){t.createDiv({cls:"stashpad-trash-empty",text:"No archive folders yet. Toggle Archive on a folder to collect it here."});return}let i=new Set(e),s=this.plugin.settings.lockedSubtrees??[],n=new Map;for(let r of s){let l=this.cleanFolder(r.folder);i.has(l)&&(n.get(l)??n.set(l,[]).get(l)).push(r)}let o=[...n.values()].reduce((r,l)=>r+l.length,0);t.createDiv({cls:"stashpad-aggregate-sub",text:`${e.length} archive ${e.length===1?"folder":"folders"}, ${o} archived ${o===1?"item":"items"}.`});for(let r of e){let l=n.get(r)??[],c=t.createDiv({cls:"stashpad-trash-group"}),d=c.createDiv({cls:"stashpad-trash-group-head"});(0,se.setIcon)(d.createSpan({cls:"stashpad-trash-group-icon"}),"archive"),d.createSpan({text:r.split("/").pop()||r}),d.createSpan({cls:"stashpad-trash-group-count",text:String(l.length)});let h=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Open"});if(h.onclick=()=>void this.plugin.activateViewForFolder(r),l.length===0){c.createDiv({cls:"stashpad-trash-sub",text:"No archived (locked) items."});continue}for(let g of l){let u=c.createDiv({cls:"stashpad-trash-row"}),p=u.createDiv({cls:"stashpad-trash-row-main"});p.createSpan({cls:"stashpad-trash-title",text:g.title||"Locked note"});let f=g.created?`archived ${Ya(g.created).fromNow()}`:"archived",I=g.count>1?` \xB7 ${g.count} notes`:"";p.createSpan({cls:"stashpad-trash-sub",text:f+I});let m=u.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Export"});m.setAttr("aria-label","Export to .stash (encrypted with a password you choose)"),m.onclick=()=>void this.plugin.exportLockedSubtree(g.blob);let C=u.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,se.setIcon)(C,"lock")}}}async onClose(){this.contentEl.empty()}};async function Mo(A,a){let{workspace:t}=A.app,e=t.getLeavesOfType(Oe).find(s=>s.view?.getState?.().mode===a);if(e){t.revealLeaf(e);return}let i=t.getLeaf("tab");await i.setViewState({type:Oe,active:!0,state:{mode:a}}),t.revealLeaf(i)}rt();var Y=require("obsidian");rt();kt();var ln=class A 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 ge}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()))}refresh(){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 r=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-folders"});r.setCssStyles({flex:"1 1 0"});let l=r.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"}),c=l.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});c.setAttr("aria-label","Open folder switcher"),c.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(r.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=r=>{let l=t.getBoundingClientRect();if(l.height<=0)return;let c=this.clampFrac((r.clientY-l.top)/l.height);s=c,e.style.flex=`0 0 ${(c*100).toFixed(2)}%`},o=r=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(r.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",r=>{r.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(r.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,c)=>{let d=n.get(l.folder);d||(d=[],n.set(l.folder,d)),d.push({...l,idx:c})});let o=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,r=Array.from(n.keys());o&&n.has(o)&&(r.splice(r.indexOf(o),1),r.unshift(o));for(let l of r){let c=t.createDiv({cls:"stashpad-pinned-group-header"});l===o&&c.addClass("is-active-folder"),c.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)),r=n[o-1],l=n[o],c;!r&&!l?c=Date.now():r?l?c=(r.pinnedAt+l.pinnedAt)/2:c=r.pinnedAt+1e3:c=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=c})}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??{},r=typeof o.color=="string"?o.color:null,l=o.completed===!0,c=this.childrenOf(e,i),d=c.length>0,h=`${e}|${i}`,g=this.pinExpanded.has(h),u=t.createDiv({cls:"stashpad-pinned-row"});r&&(u.addClass("has-color"),u.style.setProperty("--stashpad-note-color",r)),l&&u.addClass("is-completed"),u.draggable=!0,u.dataset.pinIdx=String(n),u.addEventListener("dragstart",m=>{m.dataTransfer?.setData("text/plain",String(n)),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="move");let C=u.getBoundingClientRect(),B=m.clientY-C.top<C.height/2;u.toggleClass("drop-before",B),u.toggleClass("drop-after",!B)}),u.addEventListener("dragleave",()=>{u.removeClass("drop-before"),u.removeClass("drop-after")}),u.addEventListener("drop",m=>{m.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let C=parseInt(m.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===n)return;let B=u.getBoundingClientRect(),w=m.clientY-B.top<B.height/2;this.reorderPin(C,w?n:n+1)});let p=u.createSpan({cls:"stashpad-pinned-toggle"});d&&(Ie(p,c.length,g),p.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(h)?this.pinExpanded.delete(h):this.pinExpanded.add(h),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(f,d?"folder-tree":"file-text"),r&&(f.style.color=r);let I=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(I.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},u.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),u.oncontextmenu=m=>{m.preventDefault();let C=new Y.Menu;C.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),C.showAtMouseEvent(m)},d&&g){let m=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(m,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},r=typeof o.id=="string"?o.id:null;if(!r)continue;let l=typeof o.color=="string"?o.color:null,c=o.completed===!0,d=this.childrenOf(e,r),h=d.length>0,g=`${e}|${r}`,u=this.pinExpanded.has(g),p=t.createDiv({cls:"stashpad-pinned-subrow"});c&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let f=p.createSpan({cls:"stashpad-pinned-toggle"});h&&(Ie(f,d.length,u),f.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(I,"file-text"),l&&(I.style.color=l);let m=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});m.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},h&&u&&this.renderPinSubtree(t,e,r,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 r=o.parent;if(r===e||e===k&&(r==null||r===k)){if(o.id===k)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",r=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(r))}),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(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=A.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=A.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(A.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!==k||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=[],r=[];for(let c of e)switch(this.folderState(c)){case"pinned":s.push(c);break;case"downranked":o.push(c);break;case"hidden":r.push(c);break;default:n.push(c)}let l=[...s,...n,...o];if(l.length===0&&r.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let c of l)this.renderFolderRow(t,c,i);r.length>0&&this.renderHiddenSection(t,r)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(A.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 r=o.createSpan({cls:"stashpad-folderpanel-dot"});if(r.setAttr("aria-label",n?"Open in a tab":"Not open"),n&&r.setAttr("title","Open in a tab"),s==="pinned"){let m=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,Y.setIcon)(m,"pin"),m.setAttr("aria-label","Pinned")}let l=this.folderHomePinnedNotes(e),c=A.clean(e),d=this.folderPinExpanded.has(c);if(l.length>0){let m=o.createSpan({cls:"stashpad-folderpanel-pinreveal"});Ie(m,l.length,d),m.setAttr("aria-label",d?"Hide pinned notes":`${l.length} pinned note${l.length===1?"":"s"}`),m.addEventListener("mousedown",C=>{C.stopPropagation(),C.preventDefault()}),m.onclick=C=>{C.stopPropagation(),this.folderPinExpanded.has(c)?this.folderPinExpanded.delete(c):this.folderPinExpanded.add(c),this.render()}}let h=this.plugin.isArchiveFolder(e),g=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,Y.setIcon)(g,this.plugin.getFolderIcon(e)??(h?"archive":"folder")),h&&g.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let u=this.folderHomeColor(e);u&&(g.style.color=u);let p=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:p});let I=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});if((0,Y.setIcon)(I,"plus-square"),I.setAttr("aria-label","Open in new tab"),I.onmousedown=m=>{m.button===0&&(m.preventDefault(),m.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",m=>{m.button===0&&(m.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=m=>{m.preventDefault(),this.openFolderMenu(m,e)},l.length>0&&d){let m=t.createDiv({cls:"stashpad-folderpanel-pinlist"});for(let C of l){let B=m.createDiv({cls:"stashpad-folderpanel-pinrow"}),w=this.app.metadataCache.getFileCache(C)?.frontmatter??{},y=B.createSpan({cls:"stashpad-folderpanel-pinrow-icon"});(0,Y.setIcon)(y,"arrow-up-to-line"),typeof w.color=="string"&&(y.style.color=w.color),B.createSpan({cls:"stashpad-folderpanel-pinrow-label",text:this.titleFromFile(C)}),B.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(C)}}}}folderHomePinnedNotes(t){return this.childrenOf(t,k).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 r=o.style.display!=="none";o.setCssStyles({display:r?"none":""}),(0,Y.setIcon)(n,r?"chevron-right":"chevron-down")};for(let r of e){let l=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),c=r.split("/").pop()||r;l.createSpan({cls:"stashpad-folderpanel-row-label",text:c});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(r,"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(r=>r.setTitle("Encrypt (lock) all notes in folder").setIcon("lock").onClick(()=>void this.plugin.lockFolder(e))),this.app.vault.getFiles().some(r=>r.extension==="stashenc"&&(r.parent?.path?.replace(/\/+$/,"")??"")===e.replace(/\/+$/,""))&&i.addItem(r=>r.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(r=>r.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 it(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(r=>r.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 To(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(c){console.warn("[Stashpad] folder rename failed",c),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 it(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()}},To=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 cn(A){let a=A.workspace.getLeavesOfType(ge);if(a.length>0){A.workspace.revealLeaf(a[0]);return}let t=A.workspace.getLeftLeaf(!1);if(!t){new Y.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ge,active:!0}),A.workspace.revealLeaf(t)}kt();je();rt();var Po="OKF Template.md",Lc=`--- +`).find(w=>w.trim())??"note").trim().slice(0,60);i.deferUndo||this.plugin.notifications.show({message:`"${B}" landed in \`${C}\``,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(m,C=>{for(let[B,w]of Object.entries(a))ue.includes(B)||Sn.includes(B)||C[B]===void 0&&(C[B]=w)})}catch(C){console.warn("[Stashpad] template fm overlay failed",C)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:d,parent:h}}),i.record!==!1&&!i.deferUndo){let m=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let C=this.app.vault.getAbstractFileByPath(d);if(C)try{await this.app.fileManager.trashFile(C)}catch{}if(this.composerDraft=m,this.saveDraft(m),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=m;let B=m.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,I),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(m),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(I){return new F.Notice(`Stashpad: failed to create note (${I.message})`),null}}async createNotesBatch(t,e,i,s,n){let o=t.length,a=[],l=!!i?.targetFolder&&i.targetFolder!==this.noteFolder,c=8,d=null;if(o>=c){let h=new F.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"}),f=g.createDiv({cls:"stashpad-split-progress-label",text:`0 / ${o}`});d={notice:h,fill:p,label:f}}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(u=>window.setTimeout(u,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 u=this.app.vault.getAbstractFileByPath(g);if(u)try{await this.app.fileManager.trashFile(u)}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:u}of h)await this.app.vault.adapter.exists(g)||await this.app.vault.create(g,u);this.composerDraft="",this.saveDraft(""),this.composerInputEl&&(this.composerInputEl.value=""),l||this.tree.rebuild(this.noteFolder),this.render()}})}o>=c&&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 F.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}/${fs(s,n)}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:k,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 F.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,c=i.showContributors&&o.length>0,d=i.showLastEdit&&!!a;if(!l&&!c&&!d)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),g=(p,f)=>{let I=f.replace(/^\[\[/,"").replace(/\]\]$/,""),m=I.indexOf("|"),C=m>=0?I.slice(0,m):I,B=m>=0?I.slice(m+1):I.split("/").pop()??I,w=p.createEl("a",{cls:"internal-link",text:B});w.setAttribute("data-href",C),w.setAttribute("href",C)},u=[];l&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"by "}),g(p,n)}),c&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((f,I)=>{I>0&&p.createSpan({text:", "}),g(p,f)})}),d&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"edited "}),p.createSpan({text:this.formatTimeInline(a)})}),u.forEach((p,f)=>{f>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let I=h.createSpan({cls:"stashpad-authorship-piece"});p(I)}),h.addEventListener("click",p=>this.handleRenderedClick(p,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Vt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,F.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=me(t.basename);if(!e||e===k)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=St(s,this.activeStopwords()),o=bt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let 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,F.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=>be(d));if(a.length===s.length&&a.every((d,h)=>d===s[h]))return;let c=s.map(d=>$t(d));await this.app.fileManager.processFrontMatter(t,d=>{d.attachments=c})}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,F.moment)(t);if(!e.isValid())return"";let i=X();if(i.useTemplatesFormat){let n=Ts(this.app);if(n)return`${e.format(n.dateFormat)} +${e.format(n.timeFormat)}`}let s=e.valueOf();return`${ls(s,i)} +${cs(s,i)}`}formatTimeInline(t){if(!t)return"";let e=(0,F.moment)(t);if(!e.isValid())return"";if(X().useTemplatesFormat){let s=Ts(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,F.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 F.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??k),g=h.indexOf(e.id),u=g>0?h[g-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,u)&&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,k),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==k&&this.navigateTo(k)}));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)},c=d=>{let h=this.isTask(e);if(h){let g=this.isCompleted(e);d.addItem(u=>u.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"?c(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 f of this.tree.getChildren(p.id))i(f),e.push(f)};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 f=n[p];a.push(...this.extractAttachments(this.stripFrontmatter(o[p])));let I=this.app.metadataCache.getFileCache(f.file)?.frontmatter;if(Array.isArray(I?.attachments))for(let m of I.attachments)typeof m=="string"&&m.trim()&&a.push(be(m))}let l=[...new Set(a)],c=this.authorship.collectAuthorIds(s),d=async p=>{let f=await this.snapshotNotes(s,p),I=0;if(p)for(let D of l){let H=this.app.metadataCache.getFirstLinkpathDest(D,"");if(H)try{await this.app.fileManager.trashFile(H),await this.log.append({type:"attachment_remove",id:k,payload:{path:H.path}}),this.plugin.notifications.show({message:`Deleted attachment "${H.name}"`,kind:"warning",category:"attachment",affectedPaths:[H.path],folder:this.noteFolder}),I+=1}catch{}}let m=new Set;for(let D of s)D.parent&&m.add(D.parent);let C=this.currentChildren.findIndex(D=>D.id===t.id),B=null;if(C>=0){for(let D=C+1;D<this.currentChildren.length;D++)if(this.currentChildren[D].id!==t.id){B=this.currentChildren[D].id;break}if(!B){for(let D=C-1;D>=0;D--)if(this.currentChildren[D].id!==t.id){B=this.currentChildren[D].id;break}}}for(let D of s)if(D.file){try{await this.app.fileManager.trashFile(D.file)}catch{}await this.log.append({type:"delete",id:D.id,payload:{path:D.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 D of m)s.some(H=>H.id===D)||this.fmSync.scheduleParentOfDeleted(D);let w=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,Q=t.id,v=I>0?` with ${I} attachment${I===1?"":"s"}`:"",E=!1,S=async()=>{E||(E=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(f,[Q]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${v}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:c,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void S()}]}),this.plugin.getUndoStack(w).push({label:y,undo:async()=>{await S()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,E=!1,await this.trashNotesAndAttachments(f)}})},h=X(),g=e.length>0&&h.confirmBulkDelete,u=l.length>0&&h.confirmAttachmentDelete;if(!g&&!u){await d(!1),this.focusView();return}new We(this.app,this.titleForNode(t),e.length,l.length,u,async p=>{await d(p),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new F.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===k){new F.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new F.Notice("Couldn't find the parent note.");return}let i=e.parent??k,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 it(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 it(this.app,"Confirm Note Swap",a.join(` +`),"Swap",async l=>{if(!l)return;let c=t.parent??k;await this.swapParentChild(t,i,c)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new F.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(u=>u.id!==e.id).filter(u=>!!u.file),a=o.map(u=>({id:u.id,path:u.file.path,was:u.parent})),l=this.order.getOrder(s,i).slice(),c=this.order.getOrder(s,e.id).slice(),d=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,u=>{u.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,u=>{u.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let u of o)await this.app.fileManager.processFrontMatter(u.file,p=>{p.parent=e.id}),this.fmSync.scheduleParentChange(u.id,t.id,e.id);if(l.length>0){let u=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,u)}let h=o.map(u=>u.id),g=[t.id,...c.filter(u=>u!==t.id&&!h.includes(u)),...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 u of a)await this.log.append({type:"parent_change",id:u.id,payload:{from:u.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 u=this.tree.get(t.id),p=this.tree.get(e.id);u?.file&&await this.app.fileManager.processFrontMatter(u.file,f=>{n==null||n===k?(delete f.parent,f.parent=k):f.parent=n}),p?.file&&await this.app.fileManager.processFrontMatter(p.file,f=>{f.parent=t.id});for(let f of a){let I=this.app.vault.getAbstractFileByPath(f.path);I&&await this.app.fileManager.processFrontMatter(I,m=>{f.was==null?m.parent=k:m.parent=f.was})}this.order.setOrder(s,i,l),this.order.setOrder(s,e.id,c),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??k;if(o(n)===o(e)){if(!i.quiet){let l=this.titleForNode(t),c=e===k?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${l}" is already under ${c}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==k&&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),c=l?this.titleForNode(l):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${c}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===k?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let l=this.noteFolder,c=s.path,d=t.id;this.plugin.getUndoStack(l).push({label:"Move note",undo:async()=>{let h=this.app.vault.getAbstractFileByPath(c);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,u=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(f=>f.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(u,120),setTimeout(u,400)}}},redo:async()=>{let h=this.app.vault.getAbstractFileByPath(c);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,u=()=>{if(this.selectionGuardKey!==g||this.selection.has(d))return;let p=this.currentChildren.findIndex(f=>f.id===d);p<0||(this.selection.add(d),this.cursorIdx=p,this.render({kind:"follow-cursor"}))};setTimeout(u,120),setTimeout(u,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===k?"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]),c=o(t[0]);a=c>0?`Moved "${l}" and its ${c} ${c===1?"child":"children"} \u2192 ${n}`:`Moved "${l}" \u2192 ${n}`}else{let l=t.reduce((c,d)=>c+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===k?void 0:0,affectedIds:t.map(l=>l.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===k?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};es.AIMED_TAP_WINDOW_MS=600;var ln=es,Ho=class extends F.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)}},cn=class extends F.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 ie=require("obsidian");at();kt();var Kc=ie.moment,An=class extends ie.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 Je}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,ie.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,ie.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 u=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Clear"});u.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 c=[...l.keys()].sort((d,h)=>d===" hidden"?1:h===" hidden"?-1:d.localeCompare(h));this.order=[];for(let d of c){let h=d===" hidden",g=e.createDiv({cls:"stashpad-trash-group"}),u=g.createDiv({cls:"stashpad-trash-group-head"});(0,ie.setIcon)(u.createSpan({cls:"stashpad-trash-group-icon"}),h?"lock":"folder"),u.createSpan({text:h?"Hidden (title obscured)":d.split("/").pop()||d}),u.createSpan({cls:"stashpad-trash-group-count",text:String(l.get(d).length)});for(let p of l.get(d)){let f=this.order.length;this.order.push(p.blob);let I=g.createDiv({cls:"stashpad-trash-row"});this.selected.has(p.blob)&&I.addClass("is-selected"),I.addEventListener("click",Q=>{Q.target.closest("button")||this.onRowClick(f,p.blob,Q)});let m=I.createDiv({cls:"stashpad-trash-row-main"});m.createSpan({cls:"stashpad-trash-title",text:h?"Locked note":p.meta?.title||"Locked note"});let C=p.meta?.deletedAt?`deleted ${Kc(p.meta.deletedAt).fromNow()}`:"deleted",B=p.meta&&p.meta.count>1?` \xB7 ${p.meta.count} ${p.meta.kind==="rawtrash"?"files":"notes"}`:"";m.createSpan({cls:"stashpad-trash-sub",text:C+B});let w=I.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,ie.setIcon)(w.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),w.onclick=async()=>{w.disabled=!0,await this.plugin.restoreDeletedAt(p.blob)?await this.render():w.disabled=!1};let y=I.createEl("button",{cls:"stashpad-trash-delete",attr:{"aria-label":"Delete permanently"}});(0,ie.setIcon)(y,"trash-2"),y.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 it(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 $r(A){let{workspace:r}=A.app,t=r.getLeavesOfType(Je);if(t.length>0){r.revealLeaf(t[0]);return}let e=r.getLeaf("tab");await e.setViewState({type:Je,active:!0}),r.revealLeaf(e)}var se=require("obsidian");at();var Vr=se.moment,dn=class extends se.ItemView{constructor(t,e){super(t);this.plugin=e;this.mode="encrypted";this.renderPending=!1}getViewType(){return Oe}getDisplayText(){return this.mode==="archived"?"All archived":"All encrypted"}getIcon(){return this.mode==="archived"?"archive":"lock"}getState(){return{...super.getState(),mode:this.mode}}async setState(t,e){(t?.mode==="archived"||t?.mode==="encrypted")&&(this.mode=t.mode),await super.setState(t,e),await this.render()}async onOpen(){this.containerEl.addClass("stashpad-aggregate-view");let t=e=>e.endsWith(".stashenc")&&!e.startsWith("_deleted/");this.registerEvent(this.app.vault.on("create",e=>{t(e.path)&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",e=>{t(e.path)&&this.scheduleRender()})),await this.render()}scheduleRender(){this.renderPending||(this.renderPending=!0,window.setTimeout(()=>{this.renderPending=!1,this.render()},150))}cleanFolder(t){return(t||"").replace(/\/+$/,"")}archiveFolders(){let t=new Set((this.plugin.settings.archiveFolders??[]).map(i=>this.cleanFolder(i))),e=this.plugin.settings.folderEncPrefs??{};for(let[i,s]of Object.entries(e))s?.archive&&t.add(this.cleanFolder(i));return[...t].sort((i,s)=>i.localeCompare(s))}async render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-aggregate-body");let e=t.createDiv({cls:"stashpad-aggregate-header"});e.createEl("h3",{text:this.getDisplayText()});let i=e.createEl("button",{cls:"stashpad-trash-iconbtn"});if((0,se.setIcon)(i,"refresh-cw"),i.setAttr("aria-label","Refresh"),i.onclick=()=>void this.render(),this.mode==="archived"){this.renderArchived(t);return}this.renderEncrypted(t)}renderEncrypted(t){let e=this.plugin.settings.lockedSubtrees??[];if(e.length===0){t.createDiv({cls:"stashpad-trash-empty",text:"Nothing is encrypted yet. Lock a note or folder and it shows up here."});return}let i=new Map;for(let n of e){let o=this.cleanFolder(n.folder)||"(vault root)";(i.get(o)??i.set(o,[]).get(o)).push(n)}let s=[...i.keys()].sort((n,o)=>n.localeCompare(o));t.createDiv({cls:"stashpad-aggregate-sub",text:`${e.length} locked ${e.length===1?"item":"items"} in ${s.length} ${s.length===1?"folder":"folders"}.`});for(let n of s){let o=t.createDiv({cls:"stashpad-trash-group"}),a=o.createDiv({cls:"stashpad-trash-group-head"});(0,se.setIcon)(a.createSpan({cls:"stashpad-trash-group-icon"}),"folder"),a.createSpan({text:n.split("/").pop()||n}),a.createSpan({cls:"stashpad-trash-group-count",text:String(i.get(n).length)});let l=a.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Open"});l.onclick=()=>void this.plugin.activateViewForFolder(n);for(let c of i.get(n)){let d=o.createDiv({cls:"stashpad-trash-row"}),h=d.createDiv({cls:"stashpad-trash-row-main"});h.createSpan({cls:"stashpad-trash-title",text:c.title||"Locked note"});let g=c.created?`locked ${Vr(c.created).fromNow()}`:"locked",u=c.count>1?` \xB7 ${c.count} notes`:"";h.createSpan({cls:"stashpad-trash-sub",text:g+u});let p=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Export"});p.setAttr("aria-label","Export to .stash (encrypted with a password you choose)"),p.onclick=()=>void this.plugin.exportLockedSubtree(c.blob);let f=d.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,se.setIcon)(f,"lock")}}}renderArchived(t){let e=this.archiveFolders();if(e.length===0){t.createDiv({cls:"stashpad-trash-empty",text:"No archive folders yet. Toggle Archive on a folder to collect it here."});return}let i=new Set(e),s=this.plugin.settings.lockedSubtrees??[],n=new Map;for(let a of s){let l=this.cleanFolder(a.folder);i.has(l)&&(n.get(l)??n.set(l,[]).get(l)).push(a)}let o=[...n.values()].reduce((a,l)=>a+l.length,0);t.createDiv({cls:"stashpad-aggregate-sub",text:`${e.length} archive ${e.length===1?"folder":"folders"}, ${o} archived ${o===1?"item":"items"}.`});for(let a of e){let l=n.get(a)??[],c=t.createDiv({cls:"stashpad-trash-group"}),d=c.createDiv({cls:"stashpad-trash-group-head"});(0,se.setIcon)(d.createSpan({cls:"stashpad-trash-group-icon"}),"archive"),d.createSpan({text:a.split("/").pop()||a}),d.createSpan({cls:"stashpad-trash-group-count",text:String(l.length)});let h=d.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Open"});if(h.onclick=()=>void this.plugin.activateViewForFolder(a),l.length===0){c.createDiv({cls:"stashpad-trash-sub",text:"No archived (locked) items."});continue}for(let g of l){let u=c.createDiv({cls:"stashpad-trash-row"}),p=u.createDiv({cls:"stashpad-trash-row-main"});p.createSpan({cls:"stashpad-trash-title",text:g.title||"Locked note"});let f=g.created?`archived ${Vr(g.created).fromNow()}`:"archived",I=g.count>1?` \xB7 ${g.count} notes`:"";p.createSpan({cls:"stashpad-trash-sub",text:f+I});let m=u.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Export"});m.setAttr("aria-label","Export to .stash (encrypted with a password you choose)"),m.onclick=()=>void this.plugin.exportLockedSubtree(g.blob);let C=u.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,se.setIcon)(C,"lock")}}}async onClose(){this.contentEl.empty()}};async function Uo(A,r){let{workspace:t}=A.app,e=t.getLeavesOfType(Oe).find(s=>s.view?.getState?.().mode===r);if(e){t.revealLeaf(e);return}let i=t.getLeaf("tab");await i.setViewState({type:Oe,active:!0,state:{mode:r}}),t.revealLeaf(i)}at();var Y=require("obsidian");at();kt();var hn=class A 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 ge}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()))}refresh(){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"}),c=l.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});c.setAttr("aria-label","Open folder switcher"),c.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 c=this.clampFrac((a.clientY-l.top)/l.height);s=c,e.style.flex=`0 0 ${(c*100).toFixed(2)}%`},o=a=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(a.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",a=>{a.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(a.pointerId)}catch{}document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)})}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new 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,c)=>{let d=n.get(l.folder);d||(d=[],n.set(l.folder,d)),d.push({...l,idx:c})});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 c=t.createDiv({cls:"stashpad-pinned-group-header"});l===o&&c.addClass("is-active-folder"),c.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],c;!a&&!l?c=Date.now():a?l?c=(a.pinnedAt+l.pinnedAt)/2:c=a.pinnedAt+1e3:c=l.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,d=>{d.pinnedAt=c})}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,c=this.childrenOf(e,i),d=c.length>0,h=`${e}|${i}`,g=this.pinExpanded.has(h),u=t.createDiv({cls:"stashpad-pinned-row"});a&&(u.addClass("has-color"),u.style.setProperty("--stashpad-note-color",a)),l&&u.addClass("is-completed"),u.draggable=!0,u.dataset.pinIdx=String(n),u.addEventListener("dragstart",m=>{m.dataTransfer?.setData("text/plain",String(n)),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="move");let C=u.getBoundingClientRect(),B=m.clientY-C.top<C.height/2;u.toggleClass("drop-before",B),u.toggleClass("drop-after",!B)}),u.addEventListener("dragleave",()=>{u.removeClass("drop-before"),u.removeClass("drop-after")}),u.addEventListener("drop",m=>{m.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let C=parseInt(m.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===n)return;let B=u.getBoundingClientRect(),w=m.clientY-B.top<B.height/2;this.reorderPin(C,w?n:n+1)});let p=u.createSpan({cls:"stashpad-pinned-toggle"});d&&(Ie(p,c.length,g),p.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(h)?this.pinExpanded.delete(h):this.pinExpanded.add(h),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(f,d?"folder-tree":"file-text"),a&&(f.style.color=a);let I=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(I.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},u.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),u.oncontextmenu=m=>{m.preventDefault();let C=new Y.Menu;C.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),C.showAtMouseEvent(m)},d&&g){let m=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(m,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,c=o.completed===!0,d=this.childrenOf(e,a),h=d.length>0,g=`${e}|${a}`,u=this.pinExpanded.has(g),p=t.createDiv({cls:"stashpad-pinned-subrow"});c&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let f=p.createSpan({cls:"stashpad-pinned-toggle"});h&&(Ie(f,d.length,u),f.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(I,"file-text"),l&&(I.style.color=l);let m=p.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});m.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},h&&u&&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===k&&(a==null||a===k)){if(o.id===k)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(q)){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=A.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=A.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(A.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!==k||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let c of e)switch(this.folderState(c)){case"pinned":s.push(c);break;case"downranked":o.push(c);break;case"hidden":a.push(c);break;default:n.push(c)}let 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 c of l)this.renderFolderRow(t,c,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(A.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 m=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,Y.setIcon)(m,"pin"),m.setAttr("aria-label","Pinned")}let l=this.folderHomePinnedNotes(e),c=A.clean(e),d=this.folderPinExpanded.has(c);if(l.length>0){let m=o.createSpan({cls:"stashpad-folderpanel-pinreveal"});Ie(m,l.length,d),m.setAttr("aria-label",d?"Hide pinned notes":`${l.length} pinned note${l.length===1?"":"s"}`),m.addEventListener("mousedown",C=>{C.stopPropagation(),C.preventDefault()}),m.onclick=C=>{C.stopPropagation(),this.folderPinExpanded.has(c)?this.folderPinExpanded.delete(c):this.folderPinExpanded.add(c),this.render()}}let h=this.plugin.isArchiveFolder(e),g=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,Y.setIcon)(g,this.plugin.getFolderIcon(e)??(h?"archive":"folder")),h&&g.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let u=this.folderHomeColor(e);u&&(g.style.color=u);let p=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:p});let I=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});if((0,Y.setIcon)(I,"plus-square"),I.setAttr("aria-label","Open in new tab"),I.onmousedown=m=>{m.button===0&&(m.preventDefault(),m.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",m=>{m.button===0&&(m.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=m=>{m.preventDefault(),this.openFolderMenu(m,e)},l.length>0&&d){let m=t.createDiv({cls:"stashpad-folderpanel-pinlist"});for(let C of l){let B=m.createDiv({cls:"stashpad-folderpanel-pinrow"}),w=this.app.metadataCache.getFileCache(C)?.frontmatter??{},y=B.createSpan({cls:"stashpad-folderpanel-pinrow-icon"});(0,Y.setIcon)(y,"arrow-up-to-line"),typeof w.color=="string"&&(y.style.color=w.color),B.createSpan({cls:"stashpad-folderpanel-pinrow-label",text:this.titleFromFile(C)}),B.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(C)}}}}folderHomePinnedNotes(t){return this.childrenOf(t,k).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"}),c=a.split("/").pop()||a;l.createSpan({cls:"stashpad-folderpanel-row-label",text:c});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 it(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 Ro(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(c){console.warn("[Stashpad] folder rename failed",c),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 it(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()}},Ro=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 pn(A){let r=A.workspace.getLeavesOfType(ge);if(r.length>0){A.workspace.revealLeaf(r[0]);return}let t=A.workspace.getLeftLeaf(!1);if(!t){new Y.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ge,active:!0}),A.workspace.revealLeaf(t)}kt();je();at();var Go="OKF Template.md",qc=`--- okfType: concept --- {{body}} -`,Ho=["> 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 es(A){return A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||A.basename}function $a(A){return`[${es(A)}](${encodeURI(A.name)})`}async function Va(A,a=Po){try{await A.vault.adapter.exists(a)||await A.vault.create(a,Lc)}catch{}return a}function za(A,a){if(!a)return[];let t=a.replace(/^\/+/,"");return Object.entries(A??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function Uo(A,a){let t=a.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of A.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let r;try{r=dt(await A.vault.read(o)).fm}catch{continue}let l=typeof r.id=="string"?r.id:null;if(!l)continue;let c=typeof r.parent=="string"?r.parent:k;e.set(l,{file:o,id:l,parent:c,modified:typeof r.modified=="string"?r.modified:"",created:typeof r.created=="string"?r.created:""});let d=i.get(c)??[];d.push(l),i.set(c,d)}let s=0,n=0;for(let o of e.values()){if(o.id===k)continue;s+=1;let r=o.parent&&o.parent!==k&&e.get(o.parent)?$a(e.get(o.parent).file):null,l=(i.get(o.id)??[]).map(c=>e.get(c)).filter(c=>!!c).map(c=>$a(c.file));try{let c=!1;await A.fileManager.processFrontMatter(o.file,d=>{r?d.okfParent!==r&&(d.okfParent=r,c=!0):d.okfParent!==void 0&&(delete d.okfParent,c=!0);let h=Array.isArray(d.okfChildren)?d.okfChildren:[],g=h.length===l.length&&h.every((u,p)=>u===l[p]);if(l.length?g||(d.okfChildren=l,c=!0):d.okfChildren!==void 0&&(delete d.okfChildren,c=!0),d.okfType===void 0&&(d.okfType="concept",c=!0),d.okfTitle===void 0&&(d.okfTitle=es(o.file),c=!0),d.okfTimestamp===void 0){let u=o.modified||o.created;u&&(d.okfTimestamp=u,c=!0)}}),c&&(n+=1,await new Promise(d=>setTimeout(d,50)))}catch(c){console.warn("[Stashpad] OKF rebuild failed",o.file.path,c)}}try{await A.vault.adapter.write(`${t}/index.md`,await Ro(A,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function Ro(A,a,t){let e=a.replace(/\/+$/,""),i=new Map,s=new Map;for(let d of A.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e||d.name==="index.md")continue;let h;try{h=dt(await A.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===k||t&&!t.has(g)||i.set(g,{id:g,file:d,parent:typeof h.parent=="string"?h.parent:k,title:typeof h.okfTitle=="string"&&h.okfTitle?h.okfTitle:es(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 u of s.get(d.id)??[])o(u,h+1,g)}},r=new Set,l=[...i.values()].filter(d=>d.parent===k||!i.has(d.parent)).sort((d,h)=>d.position-h.position||d.created.localeCompare(h.created));for(let d of l)o(d,0,r);let c=e.split("/").pop()||e;return["---","type: index",`title: ${c} (OKF index)`,"---","",`# ${c}`,"",Ho,"","## Concepts",n.length?n.join(` +`,Lo=["> 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 is(A){return A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||A.basename}function zr(A){return`[${is(A)}](${encodeURI(A.name)})`}async function Wr(A,r=Go){try{await A.vault.adapter.exists(r)||await A.vault.create(r,qc)}catch{}return r}function Xr(A,r){if(!r)return[];let t=r.replace(/^\/+/,"");return Object.entries(A??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function Ko(A,r){let t=r.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of A.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let a;try{a=dt(await A.vault.read(o)).fm}catch{continue}let l=typeof a.id=="string"?a.id:null;if(!l)continue;let c=typeof a.parent=="string"?a.parent:k;e.set(l,{file:o,id:l,parent:c,modified:typeof a.modified=="string"?a.modified:"",created:typeof a.created=="string"?a.created:""});let d=i.get(c)??[];d.push(l),i.set(c,d)}let s=0,n=0;for(let o of e.values()){if(o.id===k)continue;s+=1;let a=o.parent&&o.parent!==k&&e.get(o.parent)?zr(e.get(o.parent).file):null,l=(i.get(o.id)??[]).map(c=>e.get(c)).filter(c=>!!c).map(c=>zr(c.file));try{let c=!1;await A.fileManager.processFrontMatter(o.file,d=>{a?d.okfParent!==a&&(d.okfParent=a,c=!0):d.okfParent!==void 0&&(delete d.okfParent,c=!0);let h=Array.isArray(d.okfChildren)?d.okfChildren:[],g=h.length===l.length&&h.every((u,p)=>u===l[p]);if(l.length?g||(d.okfChildren=l,c=!0):d.okfChildren!==void 0&&(delete d.okfChildren,c=!0),d.okfType===void 0&&(d.okfType="concept",c=!0),d.okfTitle===void 0&&(d.okfTitle=is(o.file),c=!0),d.okfTimestamp===void 0){let u=o.modified||o.created;u&&(d.okfTimestamp=u,c=!0)}}),c&&(n+=1,await new Promise(d=>setTimeout(d,50)))}catch(c){console.warn("[Stashpad] OKF rebuild failed",o.file.path,c)}}try{await A.vault.adapter.write(`${t}/index.md`,await qo(A,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function qo(A,r,t){let e=r.replace(/\/+$/,""),i=new Map,s=new Map;for(let d of A.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e||d.name==="index.md")continue;let h;try{h=dt(await A.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===k||t&&!t.has(g)||i.set(g,{id:g,file:d,parent:typeof h.parent=="string"?h.parent:k,title:typeof h.okfTitle=="string"&&h.okfTitle?h.okfTitle:is(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 u of s.get(d.id)??[])o(u,h+1,g)}},a=new Set,l=[...i.values()].filter(d=>d.parent===k||!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 c=e.split("/").pop()||e;return["---","type: index",`title: ${c} (OKF index)`,"---","",`# ${c}`,"",Lo,"","## Concepts",n.length?n.join(` `):"_No concepts yet._",""].join(` -`)}var qc=new TextEncoder,An=A=>qc.encode(A);function is(A){if(typeof A=="number"||typeof A=="boolean")return String(A);let a=String(A??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(a)?JSON.stringify(a):a}function Kc(A,a){let{fm:t}=dt(A),e=[];e.push(`type: ${is(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${is(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:es(a))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${is(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let r of i)e.push(` - ${is(r)}`)}let s=typeof t.okfTimestamp=="string"&&t.okfTimestamp||typeof t.modified=="string"&&t.modified||typeof t.created=="string"&&t.created||"";s&&e.push(`timestamp: ${is(s)}`);let n=e.join(` +`)}var Jc=new TextEncoder,gn=A=>Jc.encode(A);function ss(A){if(typeof A=="number"||typeof A=="boolean")return String(A);let r=String(A??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(r)?JSON.stringify(r):r}function Oc(A,r){let{fm:t}=dt(A),e=[];e.push(`type: ${ss(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${ss(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:is(r))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${ss(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let a of i)e.push(` - ${ss(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: ${ss(s)}`);let n=e.join(` `),o=A.match(/^---\r?\n/);return o?A.slice(0,o[0].length)+n+` `+A.slice(o[0].length):`--- ${n} --- -${A}`}async function Wa(A,a,t,e){let i=[],s=new Map;for(let n of a){let o=await A.vault.read(n);i.push({name:n.name,data:An(Kc(o,n))});for(let r of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let l=r.slice(3,-2).split("|")[0].split("#")[0].trim(),c=A.metadataCache.getFirstLinkpathDest(l,n.path);c&&!s.has(c.name)&&s.set(c.name,c)}}for(let[n,o]of s)i.push({name:`_attachments/${n}`,data:new Uint8Array(await A.vault.readBinary(o))});return i.push({name:"index.md",data:An(await Ro(A,t,e))}),i.push({name:"_okf.md",data:An(`# About this bundle +${A}`}async function Zr(A,r,t,e){let i=[],s=new Map;for(let n of r){let o=await A.vault.read(n);i.push({name:n.name,data:gn(Oc(o,n))});for(let a of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let l=a.slice(3,-2).split("|")[0].split("#")[0].trim(),c=A.metadataCache.getFirstLinkpathDest(l,n.path);c&&!s.has(c.name)&&s.set(c.name,c)}}for(let[n,o]of s)i.push({name:`_attachments/${n}`,data:new Uint8Array(await A.vault.readBinary(o))});return i.push({name:"index.md",data:gn(await qo(A,t,e))}),i.push({name:"_okf.md",data:gn(`# About this bundle -${Ho.replace(/^> /gm,"")} -`)}),i}async function Xa(A){let{zipFiles:a}=await Promise.resolve().then(()=>(Vs(),ga));return a(A.map(t=>({name:t.name,data:t.data})))}function gi(A,a){return A.toString(8).padStart(a-1,"0")+"\0"}function Jc(A,a){let t=new Uint8Array(512),e=(s,n,o)=>{let r=An(s);t.set(r.subarray(0,o),n)};e(A.slice(0,100),0,100),e(gi(420,8),100,8),e(gi(0,8),108,8),e(gi(0,8),116,8),e(gi(a,12),124,12),e(gi(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(gi(i,8),148,8),t}function Oc(A){let a=[],t=0;for(let s of A){let n=Jc(s.name,s.data.length);a.push(n,s.data),t+=512+s.data.length;let o=(512-s.data.length%512)%512;o&&(a.push(new Uint8Array(o)),t+=o)}a.push(new Uint8Array(1024)),t+=1024;let e=new Uint8Array(t),i=0;for(let s of a)e.set(s,i),i+=s.length;return e}async function Yc(A){let a=new CompressionStream("gzip"),t=new Response(A).body.pipeThrough(a);return new Uint8Array(await new Response(t).arrayBuffer())}async function Za(A){return Yc(Oc(A))}var dn=class{constructor(a,t,e){this.app=a;this.dirOk=!1;this.writeChain=Promise.resolve();this.baseDir=t.replace(/\/+$/,""),this.logPath=`${this.baseDir}/log.jsonl`,this.statePath=`${this.baseDir}/state.json`,this.getAuthor=e??(()=>"")}getLogPath(){return this.logPath}getDir(){return this.baseDir}async ensureDir(){if(this.dirOk)return;let a=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let i of t)e=e?`${e}/${i}`:i,await a.exists(e)||await a.mkdir(e);this.dirOk=!0}append(a){let t=a.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...a};t?e.author=t:delete e.author;let i=JSON.stringify(e)+` -`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let s=this.app.vault.adapter;if(typeof s.append=="function")await s.append(this.logPath,i);else{let n=await s.exists(this.logPath)?await s.read(this.logPath):"";await s.write(this.logPath,n+i)}}catch(s){console.warn("Stashpad: log append failed",s)}}),Promise.resolve()}async readState(){let a=this.app.vault.adapter;if(!await a.exists(this.statePath))return{};try{return JSON.parse(await a.read(this.statePath))}catch{return{}}}async writeState(a){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(a,null,2))}};rt();var hn=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(a){for(this.undoStack.push(a),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let a=this.undoStack.pop();if(!a)return null;try{await a.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(a),a}async redo(){let a=this.redoStack.pop();if(!a)return null;if(a.redo)try{await a.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(a),a}peekUndoLabel(){return this.undoStack[this.undoStack.length-1]?.label??null}peekRedoLabel(){return this.redoStack[this.redoStack.length-1]?.label??null}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}clear(){this.undoStack=[],this.redoStack=[]}};var pn=class{constructor(a,t){this.app=a;this.data={version:1,authors:{}};this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/authors.json`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let a=this.app.vault.adapter;if(await a.exists(this.path)){let t=JSON.parse(await a.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(a){console.warn("[Stashpad] author registry load failed; starting empty",a),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((a,t)=>(t.lastSeen??"").localeCompare(a.lastSeen??""))}get(a){return this.data.authors[a]??null}record(a){let t=(a.id??"").trim();if(!t)return!1;let e=a.at??new Date().toISOString(),i=(a.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:a.role?.trim()||void 0,department:a.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(i&&i!==s.name&&(s.renames.push({from:s.name,to:i,at:e}),s.name=i,n=!0),a.role!==void 0){let o=a.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(a.department!==void 0){let o=a.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(a,t){let e=t??new Date().toISOString(),i={};for(let s of a){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],r=(s.name??"").trim()||o?.name||"",l=o?.renames?[...o.renames]:[];o&&r&&r!==o.name&&l.push({from:o.name,to:r,at:e}),i[n]={id:n,name:r,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 a=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await a.exists(i)||await a.mkdir(i);this.dirOk=!0}save(){return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.write(this.path,JSON.stringify(this.data,null,2))}catch(a){console.warn("[Stashpad] author registry save failed",a)}}),this.writeChain}};var et=require("obsidian");rt();Gt();je();ls();kt();var gn=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),ja="_archive",_a=new Set([te,"edtz","stashenc","stashmeta"]),ui=class ui{constructor(a){this.plugin=a;this.pending=new Map;this.pendingFolders=new Map;this.suppressed=new Set;this.armed=!1;this.drainTimer=null;this.draining=!1;this.pendingEncryptedStashes=new Set;this.encryptedNotifySnoozeUntil=0}setArmed(a){this.armed=a}isArmed(){return this.armed}get app(){return this.plugin.app}enqueue(a){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(a)&&(this.pending.set(a.path,Date.now()),this.arm())}enqueueFolder(a){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(a.path))return;let t=a.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(gn.has(a.name)||(this.pendingFolders.set(a.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),ui.DEBOUNCE_MS)}suppress(a,t=4e3){this.suppressed.add(a),window.setTimeout(()=>this.suppressed.delete(a),t)}async createNote(a,t){this.suppress(a,6e4),await this.app.vault.create(a,t)}isEligiblePath(a){if(this.suppressed.has(a.path)||_a.has(a.extension))return!1;let t=a.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return gn.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(a){if(!this.isEligiblePath(a))return!1;if(a.extension==="md")try{let{fm:t}=dt(await this.app.vault.read(a));if(t&&typeof t.id=="string"&&t.id)return!1}catch{}return!0}async drain(){if(this.drainTimer=null,!this.draining){this.draining=!0;try{let a=[...this.pending.keys()];this.pending.clear();let t=a.map(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 r=e,l=[],c=e.filter(h=>this.plugin.importLog.findDuplicate(h.name,h.stat?.size??null));if(c.length>0){let h=c.slice(0,5).map(p=>`\u2022 ${p.name}`).join(` +${Lo.replace(/^> /gm,"")} +`)}),i}async function jr(A){let{zipFiles:r}=await Promise.resolve().then(()=>(Zs(),fr));return r(A.map(t=>({name:t.name,data:t.data})))}function ui(A,r){return A.toString(8).padStart(r-1,"0")+"\0"}function Yc(A,r){let t=new Uint8Array(512),e=(s,n,o)=>{let a=gn(s);t.set(a.subarray(0,o),n)};e(A.slice(0,100),0,100),e(ui(420,8),100,8),e(ui(0,8),108,8),e(ui(0,8),116,8),e(ui(r,12),124,12),e(ui(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(ui(i,8),148,8),t}function $c(A){let r=[],t=0;for(let s of A){let n=Yc(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 Vc(A){let r=new CompressionStream("gzip"),t=new Response(A).body.pipeThrough(r);return new Uint8Array(await new Response(t).arrayBuffer())}async function _r(A){return Vc($c(A))}var un=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))}};at();var fn=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 In=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");at();Gt();je();ds();kt();var mn=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),tl="_archive",el=new Set([te,"edtz","stashenc","stashmeta"]),fi=class fi{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)&&(mn.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(),fi.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)||el.has(r.extension))return!1;let t=r.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return mn.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}=dt(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=[],c=e.filter(h=>this.plugin.importLog.findDuplicate(h.name,h.stat?.size??null));if(c.length>0){let h=c.slice(0,5).map(p=>`\u2022 ${p.name}`).join(` `),g=c.length>5?` \u2026and ${c.length-5} more`:"",u=await this.dupChoice(`${c.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(u==="skip"){let p=new Set(c.map(f=>f.path));if(r=e.filter(f=>!p.has(f.path)),r.length===0&&s.length===0){new et.Notice(`Skipped ${c.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(u==="replace")for(let p of c){let f=this.plugin.importLog.findDuplicate(p.name,p.stat?.size??null);for(let I of f?.notePaths??[]){let m=this.app.vault.getAbstractFileByPath(I);if(m instanceof et.TFile)try{l.push({path:I,content:await this.app.vault.read(m)}),await this.app.fileManager.trashFile(m)}catch(C){console.warn("[Stashpad] replace: couldn't remove prior note",I,C)}}}}if(o=r.length+n,o>=ui.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 r)try{let g=h.stat?.size??null,u=h.extension==="md"?await this.importMarkdown(h):await this.importOtherFile(h);u&&(d.push(u),this.plugin.importLog.append({ts:new Date().toISOString(),folder:u.folder,kind:u.kind,originalName:h.name,size:g,sourcePath:h.path,notePaths:u.kind==="folder"?u.notePaths:[u.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(a){let t=a.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(a),{fm:i,body:s}=dt(e),n=`${t}/${ja}`;await this.ensureFolder(n);let o=await this.uniquePath(n,a.name);if(await this.app.fileManager.renameFile(a,o),!(this.app.vault.getAbstractFileByPath(o)instanceof et.TFile))throw new Error(`archive move failed for ${a.path} \u2014 import aborted to avoid data loss`);let r={};for(let[h,g]of Object.entries(i))ue.includes(h)||(r[h]=g);r.id=W(),r.parent=k;let l=this.preservedTimes(i,a);r.created=l.created,l.modified&&(r.modified=l.modified),r.attachments=Array.isArray(i.attachments)?i.attachments:[],i.author!==void 0&&(r.author=i.author),i.contributors!==void 0&&(r.contributors=i.contributors),r.imported=!0;let c=St(s)||a.basename,d=await this.uniquePath(t,bt(c,r.id));return await this.createNote(d,ve(r,s)),{kind:"md",folder:t,archivePath:o,notePath:d,originalName:a.name}}async importOtherFile(a){let t=a.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,a.name);await this.app.fileManager.renameFile(a,i);let s=a.basename,n=W(),o={id:n,parent:k,created:new Date().toISOString(),attachments:[$t(i)],imported:!0},r=`${s} +Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(u==="skip"){let p=new Set(c.map(f=>f.path));if(a=e.filter(f=>!p.has(f.path)),a.length===0&&s.length===0){new et.Notice(`Skipped ${c.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(u==="replace")for(let p of c){let f=this.plugin.importLog.findDuplicate(p.name,p.stat?.size??null);for(let I of f?.notePaths??[]){let m=this.app.vault.getAbstractFileByPath(I);if(m instanceof et.TFile)try{l.push({path:I,content:await this.app.vault.read(m)}),await this.app.fileManager.trashFile(m)}catch(C){console.warn("[Stashpad] replace: couldn't remove prior note",I,C)}}}}if(o=a.length+n,o>=fi.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,u=h.extension==="md"?await this.importMarkdown(h):await this.importOtherFile(h);u&&(d.push(u),this.plugin.importLog.append({ts:new Date().toISOString(),folder:u.folder,kind:u.kind,originalName:h.name,size:g,sourcePath:h.path,notePaths:u.kind==="folder"?u.notePaths:[u.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}=dt(e),n=`${t}/${tl}`;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))ue.includes(h)||(a[h]=g);a.id=W(),a.parent=k;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 c=St(s)||r.basename,d=await this.uniquePath(t,bt(c,a.id));return await this.createNote(d,ve(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=W(),o={id:n,parent:k,created:new Date().toISOString(),attachments:[$t(i)],imported:!0},a=`${s} ![[${i}]] -`,l=St(s)||s,c=await this.uniquePath(t,bt(l,n));return await this.createNote(c,ve(o,r)),{kind:"file",folder:t,attachmentPath:i,notePath:c,originalName:a.name}}preservedTimes(a,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(a.created)?a.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(a.modified)?a.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(a){let t=a.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(a){let t=a.parent.path.replace(/\/+$/,""),e=a.name,i=`${t}/${ja}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(a,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let 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 r=[],l=[],c=await this.createFolderNote(t,e,k,l,o);return n instanceof et.TFolder&&await this.buildNotesFromArchive(n,t,c,l,o,r),r.length&&new et.Notice(`Stashpad: ${r.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(a,t,e,i,s){let n=W();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},r=St(t)||t,l=await this.uniquePath(a,bt(r,n));return await this.createNote(l,ve(o,`${t} -`)),i.push(l),n}async mergeReservedFolder(a,t,e){await this.ensureFolder(t);for(let i of[...a.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(a,t,e,i,s,n){for(let o of[...a.children])if(o instanceof et.TFolder)if(gn.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let r=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,r,i,s,n)}else if(o instanceof et.TFile)if(o.extension==="md"){let r=await this.app.vault.read(o),{fm:l,body:c}=dt(r),d={};for(let[I,m]of Object.entries(l))ue.includes(I)||(d[I]=m);let h=typeof l.id=="string"&&l.id?l.id:null,g=h&&!s.has(h)?h:W();s.add(g),d.id=g,d.parent=e;let u=this.preservedTimes(l,o);d.created=u.created,u.modified&&(d.modified=u.modified),d.attachments=Array.isArray(l.attachments)?l.attachments:[];let p=St(c)||o.basename,f=await this.uniquePath(t,bt(p,d.id));await this.createNote(f,ve(d,c)),i.push(f)}else{if(_a.has(o.extension))continue;{let r=W(),l={id:r,parent:e,created:new Date().toISOString(),attachments:[$t(o.path)]},c=`${o.basename} +`,l=St(s)||s,c=await this.uniquePath(t,bt(l,n));return await this.createNote(c,ve(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:c,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}/${tl}`;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=[],c=await this.createFolderNote(t,e,k,l,o);return n instanceof et.TFolder&&await this.buildNotesFromArchive(n,t,c,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=W();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=St(t)||t,l=await this.uniquePath(r,bt(a,n));return await this.createNote(l,ve(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(mn.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:c}=dt(a),d={};for(let[I,m]of Object.entries(l))ue.includes(I)||(d[I]=m);let h=typeof l.id=="string"&&l.id?l.id:null,g=h&&!s.has(h)?h:W();s.add(g),d.id=g,d.parent=e;let u=this.preservedTimes(l,o);d.created=u.created,u.modified&&(d.modified=u.modified),d.attachments=Array.isArray(l.attachments)?l.attachments:[];let p=St(c)||o.basename,f=await this.uniquePath(t,bt(p,d.id));await this.createNote(f,ve(d,c)),i.push(f)}else{if(el.has(o.extension))continue;{let a=W(),l={id:a,parent:e,created:new Date().toISOString(),attachments:[$t(o.path)]},c=`${o.basename} ![[${o.path}]] -`,d=St(o.basename)||o.basename,h=await this.uniquePath(t,bt(d,r));await this.createNote(h,ve(l,c)),i.push(h)}}}recordNotePaths(a){return a.kind==="folder"?a.notePaths:[a.notePath]}announce(a,t=[]){let e=a[0]?.folder??"",i=a.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(a,t))};this.plugin.notifications.show({message:`Imported ${i} file${i===1?"":"s"}${s} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:a.flatMap(r=>this.recordNotePaths(r)),actions:[{label:"Undo import",onClick:()=>void o()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${i} file${i===1?"":"s"}`,undo:async()=>{await o()},redo:async()=>{}})}async undo(a,t=[]){for(let e of a)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof 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 ${a.length} file(s).`)}pickFilesInto(a){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(),r=await this.uniquePath(a,n.name);this.suppress(r,6e4),await this.app.vault.createBinary(r,o);let l=this.app.vault.getAbstractFileByPath(r);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,r=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);r&&(s.push(r),this.plugin.importLog.append({ts:new Date().toISOString(),folder:r.folder,kind:r.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:r.kind==="folder"?r.notePaths:[r.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(a){let t=a.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),i=[];for(let n of e)await this.isStillImportable(n)&&i.push(n);if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i)try{let o=n.stat?.size??null,r=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);r&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:r.folder,kind:r.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:r.kind==="folder"?r.notePaths:[r.notePath]}))}catch(o){console.warn("[Stashpad] loose-file import failed",n.path,o)}return s}async importLooseFoldersIn(a){let t=a.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof et.TFolder))return 0;let i=e.children.filter(n=>n instanceof et.TFolder&&!gn.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 r=await this.importFolder(n);r&&r.kind==="folder"&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:r.folder,kind:r.kind,originalName:n.name,size:null,sourcePath:o,notePaths:r.notePaths}))}catch(r){console.warn("[Stashpad] loose-folder import failed",o,r)}}return s}pendingEncryptedPaths(){for(let a of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(a)instanceof et.TFile||this.pendingEncryptedStashes.delete(a);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(a){this.pendingEncryptedStashes.delete(a)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(a){this.encryptedNotifySnoozeUntil=a===1/0?Number.MAX_SAFE_INTEGER:Date.now()+a}parkEncrypted(a){return this.pendingEncryptedStashes.has(a)?!1:(this.pendingEncryptedStashes.add(a),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let a=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof 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)}})&&a++,t)break}return{imported:a,rescheduled:t}}liveRootIds(a){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==a)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(a,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(a));if(i&&xt(n))return this.pendingEncryptedStashes.add(a.path),!1;let o=await ii(this.app,n,{...s,secretId:Ve(a.basename)});if(!o)return!1;let r=await ee(this.app,o,t,e);if(r.colorAliases)for(let[l,c]of Object.entries(r.colorAliases))try{await this.plugin.setColorAlias(t,l,c)}catch{}try{await this.app.fileManager.trashFile(a)}catch{}this.pendingEncryptedStashes.delete(a.path);try{await this.plugin.newLog().append({type:"stash_import",id:k,payload:{from:a.path,into:t,noteCount:r.notesWritten,attachmentsWritten:r.attachmentsWritten,collisionsRenamed:r.collisionsRenamed,loose:!0}})}catch{}return!0}catch(n){return console.warn("[Stashpad] loose .stash import failed",a.path,n),!1}}async importLooseStashesIn(a,t={}){let e=a.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===te);if(i.length===0)return 0;let s=this.liveRootIds(e),n=0;for(let o of i)await this.importOneStash(o,e,s,!!t.auto)&&n++;return n}async importLooseInto(a,t={}){let e=await this.importLooseFilesIn(a),i=await this.importLooseFoldersIn(a),s=await this.importLooseStashesIn(a,t);return{files:e,folders:i,stashes:s}}defaultDestination(){let t=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder;return t&&this.plugin.discoverStashpadFolders().includes(t)?t:this.plugin.discoverStashpadFolders()[0]??null}confirm(a,t,e){return new Promise(i=>{new it(this.app,a,t,e,i).open()})}dupChoice(a){return new Promise(t=>{new Mi(this.app,a,t).open()})}async ensureFolder(a){let t=this.app.vault.adapter,e=a.split("/").filter(Boolean),i="";for(let s of e){i=i?`${i}/${s}`:s;try{await t.exists(i)||await t.mkdir(i)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(a,t){let e=this.app.vault.adapter,i=t.lastIndexOf("."),s=i>0?t.slice(0,i):t,n=i>0?t.slice(i):"",o=`${a}/${t}`,r=0;for(;await e.exists(o);)r+=1,o=`${a}/${s}-${r}${n}`;return o}};ui.DEBOUNCE_MS=900,ui.BATCH_CONFIRM_AT=8;var un=ui;var fn=class{constructor(a,t){this.app=a;this.entries=[];this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/import-log.jsonl`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let a=this.app.vault.adapter;if(await a.exists(this.path)){let t=await a.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(a){console.warn("[Stashpad] import log load failed",a)}}}recent(){return[...this.entries].reverse()}findDuplicate(a,t){for(let e=this.entries.length-1;e>=0;e--){let i=this.entries[e];if(i.originalName===a&&(t==null||i.size==null||i.size===t))return i}return null}append(a){this.entries.push(a),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(a)+` -`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let a=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await a.exists(i)||await a.mkdir(i);this.dirOk=!0}};var mn=class mn{constructor(a,t){this.app=a;this.map=new Map;this.loaded=!1;this.dirty=!1;this.saveTimer=null;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/render-cache.json`}async load(){if(!this.loaded){this.loaded=!0;try{let a=this.app.vault.adapter;if(await a.exists(this.path)){let t=JSON.parse(await a.read(this.path));if(t?.schema===1&&t.entries){for(let[e,i]of Object.entries(t.entries))this.map.set(e,i);for(let e of[...this.map.keys()])this.app.vault.getAbstractFileByPath(e)||(this.map.delete(e),this.dirty=!0)}}}catch(a){console.warn("[Stashpad] render cache load failed; starting empty",a),this.map.clear()}}}evict(a){this.map.delete(a)&&(this.dirty=!0,this.save())}get(a){return this.map.get(a)}has(a){return this.map.has(a)}set(a,t){this.map.set(a,t),this.dirty=!0,this.scheduleSave()}scheduleSave(){this.saveTimer==null&&(this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},mn.SAVE_DEBOUNCE_MS))}save(){return this.saveTimer!=null&&(window.clearTimeout(this.saveTimer),this.saveTimer=null),this.dirty?(this.dirty=!1,this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let a={schema:1,entries:Object.fromEntries(this.map)};await this.app.vault.adapter.write(this.path,JSON.stringify(a))}catch(a){console.warn("[Stashpad] render cache save failed",a)}}),this.writeChain):this.writeChain}async ensureDir(){if(this.dirOk)return;let a=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await a.exists(i)||await a.mkdir(i);this.dirOk=!0}};mn.SAVE_DEBOUNCE_MS=8e3;var In=mn;var Go="stashpad:unghost-after-reload",ss=class ss extends M.Plugin{constructor(){super(...arguments);this.settings={...Be};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>ss.DEBUG_BUFFER_MAX&&this.debugBuffer.splice(0,this.debugBuffer.length-ss.DEBUG_BUFFER_MAX)}getDebugTrace(){return this.debugBuffer.join(` -`)}clearDebugTrace(){this.debugBuffer=[]}get notifications(){return this._notifications||(this._notifications=new ms(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new pn(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new un(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new fn(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 In(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 dn(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),i=async()=>{let r=e.split("/").filter(Boolean),l="";for(let c of r)l=l?`${l}/${c}`:c,await t.exists(l)||await t.mkdir(l)},s=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(n))try{let r=await t.read(n);await t.write(s,r),await t.write(`${n}.bak`,r),await t.remove(n),console.debug("[Stashpad] relocated data.json \u2192 standard path (for Obsidian Sync)")}catch(r){console.warn("Stashpad: data.json relocation failed",r)}let o=".stashpad";if(await t.exists(o))try{await i();let r=await t.list(o);for(let l of r.files){let c=l.replace(/^.*\//,""),d=this.pluginPrivatePath(c);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(r){console.warn("Stashpad: .stashpad migration scan failed",r)}}async createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let c of s)n=n?`${n}/${c}`:c,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let c=this.app.vault.getAbstractFileByPath(o);c&&await this.app.fileManager.processFrontMatter(c,d=>{(typeof d.id!="string"||!d.id)&&(d.id=k),"parent"in d||(d.parent=null),(typeof d.created!="string"||!d.created)&&(d.created=new Date().toISOString())});return}let r=new Date().toISOString(),l=["---",`id: ${k}`,"parent: null",`created: ${r}`,"---","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 r=this.app.metadataCache.getFileCache(n)?.frontmatter,l=typeof r?.color=="string"?r.color.trim():"";if(!l||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(l))continue;let c=l.toLowerCase();e.set(c,(e.get(c)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let l of this.app.vault.getMarkdownFiles()){let c=l.parent?.path?.replace(/\/+$/,"")??"";if(c!==s&&!c.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 r=this.settings.colorAliases?.[s];if(r){let l=r[n];l&&(delete r[n],i&&(r[i.toLowerCase()]=l),Object.keys(r).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],r=i.trim();r?o[n]=r: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))}}importExcludePrefixList(){return(this.settings.importExcludePrefixes??"_").split(",").map(t=>t.trim()).filter(Boolean)}pathHasExcludedSegment(t){let e=this.importExcludePrefixList();return e.length?t.replace(/\/+$/,"").split("/").some(i=>e.some(s=>i.startsWith(s))):!1}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&&!this.pathHasExcludedSegment(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(r=>r!==t&&!r.startsWith(t+"/")),s=(e.folderPanelPinned?.length??0)+(e.folderPanelDownranked?.length??0)+(e.folderPanelHidden?.length??0);e.folderPanelPinned=i(e.folderPanelPinned),e.folderPanelDownranked=i(e.folderPanelDownranked),e.folderPanelHidden=i(e.folderPanelHidden),e.folderPanelPinned.length+e.folderPanelDownranked.length+e.folderPanelHidden.length!==s&&await this.saveSettings()}async deleteStashpadFolderWithUndo(t){let e=t.path.replace(/\/+$/,""),i=t.name,s=this.app.vault.adapter,n=".trash";try{await s.exists(n)||await s.mkdir(n)}catch(c){console.warn("[Stashpad] couldn't ensure .trash",c)}let o=`${n}/${i}`;for(let c=1;await s.exists(o);c++)o=`${n}/${i} (${c})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let r=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(c){console.warn("[Stashpad] folder delete failed",c),this.suppressedFolderDeletes.delete(e),new M.Notice("Delete failed (see console).");return}let l=r>0?`Deleted \u201C${i}\u201D \u2014 closed ${r} open tab${r===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(c){console.warn("[Stashpad] folder undo failed",c),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(c=>(c??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(c=>s.has(c)?!1:e.size>0?e.has(c):!i.has(c)),r=(t||"").trim().replace(/\/+$/,""),l=o.filter(c=>c!==r);return r&&l.unshift(r),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(c=>c.path===t||c.path.startsWith(t+"/"));for(let c of n){let d=this.app.metadataCache.getFileCache(c)?.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:c.path}}let o=await i.readState(),r=c=>c===t||c.startsWith(t+"/");if(!e.silent){for(let[c,d]of Object.entries(s)){let h=o[c];h?h.parent!==d.parent?await i.append({type:"parent_change",id:c,payload:{from:h.parent,to:d.parent}}):h.path!==d.path&&await i.append({type:"rename",id:c,payload:{from:h.path,to:d.path}}):await i.append({type:"create",id:c,payload:{path:d.path,parent:d.parent}})}for(let[c,d]of Object.entries(o))!s[c]&&r(d.path)&&await i.append({type:"missing",id:c,payload:{lastPath:d.path}})}let l={};for(let[c,d]of Object.entries(o))r(d.path)||(l[c]=d);for(let[c,d]of Object.entries(s))l[c]=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 hn,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),vt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new vs(this.app,()=>({...Yi(),...this.settings.encryption??{}}),async p=>{this.settings.encryption=p,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.app.workspace.onLayoutReady(()=>{this.resumeRotations()}),this.settingTab=new bs(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,f)=>this.renderCacheStore.evict(f)));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,f)=>{this.onOkfFileEvent(p.path),this.onOkfFileEvent(f)})),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(K,p=>new nn(p,this)),this.registerView(Se,p=>new xs(p,this)),this.registerView(pe,p=>new ds(p,this)),this.registerView(Je,p=>new rn(p,this)),this.registerView(Oe,p=>new an(p,this)),this.registerView(ge,p=>new ln(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(Se).length===0&&setTimeout(()=>{Ns(this.app)},0),this.notifyStashpadSelectionChanged())}));let e=()=>{let p=ce(),f=!!p&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===p,I=!!f&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",I),document.body.classList.toggle("stashpad-active",!!f)};this.register(Rr(e)),this.registerEvent(this.app.workspace.on("active-leaf-change",e));let i=p=>{try{let f=Array.from(document.querySelectorAll("style")).filter(I=>(I.textContent??"").includes(".stashpad-"));for(let I of f){let m=I.id||"",C=m?`style[data-stashpad-source="${m}"]`:null;if(C&&p.head.querySelector(C))continue;let B=p.createElement("style");m?B.setAttribute("data-stashpad-source",m):B.setAttribute("data-stashpad-source","anon"),B.textContent=I.textContent??"",p.head.appendChild(B)}}catch(f){console.warn("[Stashpad] inject popout styles failed",f)}};this.registerEvent(this.app.workspace.on("window-open",p=>{let f=p?.doc??p?.win?.document??null;f&&i(f)})),this.registerEvent(this.app.workspace.on("file-menu",(p,f)=>{if(!(f instanceof M.TFolder))return;let I=f.path.replace(/\/+$/,"");p.addItem(C=>C.setTitle("\u{1F512} Encrypt with Stashpad").setIcon("lock").onClick(()=>void this.encryptFolderFromExplorer(I))),f.children?.some(C=>C instanceof M.TFile&&C.extension==="stashenc")&&!this.folderHasStashpadNotes(I)&&p.addItem(C=>C.setTitle("\u{1F513} Decrypt with Stashpad").setIcon("unlock").onClick(()=>void this.decryptFolderFromExplorer(I))),this.discoverStashpadFolders().includes(I)&&p.addItem(C=>{C.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(I))})})),setTimeout(()=>{try{let p=this.app.workspace;typeof p.iterateAllLeaves=="function"&&p.iterateAllLeaves(f=>{let I=f?.view?.containerEl?.ownerDocument;I&&I!==document&&i(I)})}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"),f=p&&p.isConnected?p.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${f}px`);let I=0;s&&(I=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${I}px`),document.body.classList.toggle("stashpad-keyboard-open",I>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)",()=>{hs(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{cn(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{Ns(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 r=p=>{let f=ce();f&&typeof f[p]=="function"&&f[p]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>r("toggleSplit")}),this.addCommand({id:"stashpad-fork-version",name:"Fork as a version (alternate draft in this sheet)",callback:()=>r("cmdForkVersion")}),this.addCommand({id:"stashpad-mark-version-final",name:"Mark version as final (sheet)",callback:()=>r("cmdMarkVersionFinal")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>r("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-lock-selection",name:"Encrypt (lock) selection (notes + children)",callback:()=>r("cmdLockSelection")}),this.addCommand({id:"stashpad-unlock-all",name:"Decrypt (unlock) locked notes in view",callback:()=>r("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:()=>r("cmdCopyNotes")}),this.addCommand({id:"stashpad-cut-notes",name:"Cut notes (paste in list to move, in composer to extract text)",callback:()=>r("cmdCutNotes")}),this.addCommand({id:"stashpad-paste-notes",name:"Paste notes (from the note clipboard)",callback:()=>r("cmdPasteNotes")}),this.addCommand({id:"stashpad-move-to-archive",name:"Move selection to archive (encrypt)",callback:()=>r("cmdMoveToArchive")}),this.addCommand({id:"stashpad-encrypt-delete",name:"Encrypt & delete selection (to encrypted trash)",callback:()=>r("cmdEncryptDelete")}),this.addCommand({id:"stashpad-restore-trash",name:"Open encrypted trash (restore deleted)\u2026",callback:()=>this.openEncryptedTrash()}),this.addCommand({id:"stashpad-open-all-encrypted",name:"Open \u201CAll encrypted\u201D (every locked note, by folder)",callback:()=>void Mo(this,"encrypted")}),this.addCommand({id:"stashpad-open-all-archived",name:"Open \u201CAll archived\u201D (every archive folder)",callback:()=>void Mo(this,"archived")}),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:()=>r("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>r("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>r("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>r("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>r("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>r("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>r("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>r("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>r("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>r("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>r("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>r("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>r("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>r("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>r("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>r("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>r("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>r("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>r("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>r("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>r("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>r("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>r("cmdClone")}),this.addCommand({id:"stashpad-fork-note",name:"Fork into a separate note (copy under a chosen parent)",callback:()=>r("cmdForkNote")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>r("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>r("cmdToggleExpand")}),this.addCommand({id:"stashpad-expand-all",name:"Expand all (show every note's full body)",callback:()=>r("cmdExpandAll")}),this.addCommand({id:"stashpad-collapse-all",name:"Collapse all (clamp every note's body)",callback:()=>r("cmdCollapseAll")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>r("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>r("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>r("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>r("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>r("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new M.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let p=vt.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:()=>{vt.reset(),new M.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>r("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>r("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>r("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:p}=await Promise.resolve().then(()=>(kt(),Pi));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 f=this.importService.defaultDestination();return p?!!f:(f&&this.runImportLooseFiles(f),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:p=>{let f=this.importService.defaultDestination();return p?!!f:(f&&this.runFolderSlugPass(f),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:p=>{let f=this.importService.defaultDestination();return p?!!f:(f&&this.runFolderFrontmatterBackfill(f),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>r("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>r("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void hs(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void cn(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void Ns(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:p=>{let f=this.app.workspace.getActiveFile(),I=!!f&&f.extension==="md"&&this.isStashpadNoteFile(f);return p||I&&f&&this.revealNoteInStashpad(f),I}});let l=Object.keys(Hi);for(let p of l){let f=Hi[p];this.addCommand({id:`stashpad-open-panels-${p}`,name:`Open Stashpad panel: ${f.label}`,callback:async()=>{await hs(this.app),this.app.workspace.getLeavesOfType(pe)[0]?.view?.setActivePanel?.(p)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>r("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>r("cmdTogglePin")}),this.addCommand({id:"stashpad-list-pin",name:"Pin / unpin to top of list",callback:()=>r("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:()=>r("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>r("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>r("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>r("cmdExportStash")}),this.addCommand({id:"stashpad-export-okf",name:"Export selection as OKF bundle (.zip / .tar.gz / .stash)",callback:()=>r("cmdExportOkf")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>r("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Stashpad: open / switch / create folder\u2026",callback:()=>this.openFolderPicker()}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:p=>{let f=ce(),I=f&&f.noteFolder;return I?(p||(new M.Notice(`Running integrity check on "${I}"\u2026`),this.runIntegrityCheckOnFolder(I).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:()=>{this.runRebootstrapWithUI().catch(()=>{})}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:p=>{let f=this.app.workspace.getActiveFile();return!f||f.extension!=="md"?!1:(p||this.adoptNote(f),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(kt(),Pi)).then(({NotificationHistoryModal:p,LogModal:f})=>{new p(this.app,this.notifications,async()=>{let I=this.app.vault.adapter,m=this.pluginPrivatePath("log.jsonl");if(!await I.exists(m)){new M.Notice("No log yet \u2014 make some changes first.");return}let C=await I.read(m);new f(this.app,C,m).open()},this.settings.authorId||null,I=>this.lookupNoteAuthorIds(I)).open()})}});let c=[{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 c){let f=`stashpad-toggle-${String(p.key).replace(/[A-Z]/g,I=>`-${I.toLowerCase()}`)}`;this.addCommand({id:f,name:`Toggle: ${p.label}`,callback:async()=>{let I=!this.settings[p.key];this.settings[p.key]=I,await this.saveSettings(),new M.Notice(`${p.label}: ${I?"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 Ss)this.addCommand({id:`stashpad-open-settings-${p.id}`,name:`Open Stashpad settings: ${p.label}`,callback:()=>{let f=this.app.setting;!f?.open||!f?.openTabById||(f.open(),f.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(()=>(Ri(),fs)),f=await p(this.app,this,this.settings);if(f.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(f.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:I}=await Promise.resolve().then(()=>(Ri(),fs));I(this.app,f)}catch(p){console.error("[stashpad] preview failed",p),new M.Notice(`Preview failed: ${p?.message??p}`,8e3)}}}),this.addCommand({id:"stashpad-decrypt-folder-bundle",name:"Decrypt a folder bundle (encrypted non-Stashpad folder)\u2026",callback:async()=>{if(!this.encryption.isConfigured()){new M.Notice("Stashpad encryption isn't set up.");return}let p=await Ha(this.app);if(!p.length){new M.Notice("No encrypted folder bundles found in this vault.");return}new qo(this.app,p,f=>void this.decryptFolderFromExplorer(f.folder)).open()}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:p,scanForJdNotes:f,JdBuildConfirmModal:I}=await Promise.resolve().then(()=>(Ri(),fs));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}let C=f(this.app,this,this.settings);new I(this.app,this,this.settings,C.indexed.length,async()=>{try{let w=await p(this.app,this,this.settings);if(w.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(w.error==="dest-not-stashpad"){new M.Notice(`"${w.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: ${w.created} created, ${w.updated} updated, ${w.skipped} skipped \u2192 ${w.destFolder}`,6e3)}catch(w){console.error("[stashpad] build failed",w),new M.Notice(`Build failed: ${w?.message??w}`,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!==te)return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),I=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),m=p.parent?.path||"",C=m.split("/").pop()??"";if(f&&C===f){if(I&&m.endsWith(`/${I}`))return;let B=m.slice(0,m.length-f.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(p,B);return}this.settings.autoImport&&this.importService.isArmed()&&($e(p.path)||this.discoverStashpadFolders().includes(m)&&this.autoImportStash(p,m))};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 f=p.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(f)&&setTimeout(()=>{this.fixOrphanParentForFile(p)},800)},u=p=>{if(p.extension!=="md")return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!f)return;let I=p.parent?.path?.replace(/\/+$/,"")??"";if((I.split("/").pop()??"")!==f)return;let C=I.slice(0,I.length-f.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(p,C)},200)};this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile&&(g(p),u(p))})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile&&(g(p),u(p))})),this.registerEvent(this.app.vault.on("delete",p=>{if(!(p instanceof M.TFolder))return;let f=p.path.replace(/\/+$/,"");this.knownStashpadFolders.has(f)&&this.handleStashpadFolderDeleted(f)})),this.registerEvent(this.app.vault.on("rename",(p,f)=>{p instanceof M.TFile&&this.maybeReHomeOnCrossFolderMove(p,f)})),this.registerEvent(this.app.vault.on("rename",(p,f)=>{p instanceof M.TFile&&this.maybeArchiveOnMoveIn(p,f)})),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,f)=>{p instanceof M.TFile&&this.maybeAdoptAuthorRename(p,f)})),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(Go,"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(Go)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Go)}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 r=i[o]??0,l=s[o]??0;if(r!==l)return r>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 r=this.parseAuthorFilePath(o.path);if(!r||r.id!==t)continue;let l=`${n}/${i}-${t}.md`,c=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&&(c=d)}catch(d){console.warn("[Stashpad] author file rename failed",d);continue}try{await this.refreshAuthorStub(c)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,r=>{r.aliases=[e],delete r.name,i?r.role=i:delete r.role,s?r.department=s:delete r.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,r=n>0?s.slice(n):"",l=0;for(;await i.exists(`${e}/${s}`);)l+=1,s=`${o}-${l}${r}`;let c=`${e}/${s}`;await this.app.fileManager.renameFile(t,c);let d=this.app.vault.getAbstractFileByPath(c);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:[c]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",r=!i,l=!n,c=!o;if(!r&&!l&&!c)return;let{newId:d}=await Promise.resolve().then(()=>(Gt(),cs)),h,g=!1,u=!1;if(await this.app.fileManager.processFrontMatter(t,I=>{if(r&&(typeof I.id=="string"&&I.id.trim()||(h=d(),I.id=h)),l){let m=I.parent;(typeof m=="string"?m.trim()!=="":m!=null)||(I.parent=k,g=!0)}c&&(typeof I.created=="string"&&I.created.trim()||(I.created=new Date(t.stat.ctime).toISOString(),u=!0))}),!h&&!g&&!u)return;let p=this.newLog(),f=h||i;f&&await p.append({type:"parent_change",id:f,payload:{from:null,to:k,reason:"orphan_auto_fix",path:t.path,addedId:!!h,addedParent:g,addedCreated:u}}),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===k||this.app.vault.getMarkdownFiles().some(r=>(r.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(r)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,r=>{let l=typeof r.parent=="string"?r.parent.trim():"";l&&l!==k&&(r.parent=k)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:k,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(xt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await ii(this.app,i);if(!s)return;let n=ce(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let c of n.collectExistingIds())o.add(c);else for(let c of this.app.vault.getMarkdownFiles()){if(!c.path.startsWith(e+"/"))continue;let d=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof d=="string"&&o.add(d)}let r=await ee(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:k,payload:{from:t.path,into:e,noteCount:r.notesWritten,attachmentsWritten:r.attachmentsWritten,collisionsRenamed:r.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let l=[`Auto-imported ${r.notesWritten} note${r.notesWritten===1?"":"s"} from ${t.name}`];r.attachmentsWritten&&l.push(`+ ${r.attachmentsWritten} attachment${r.attachmentsWritten===1?"":"s"}`),r.collisionsRenamed&&l.push(`(${r.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=St(o.basename)||o.basename,h=await this.uniquePath(t,bt(d,a));await this.createNote(h,ve(l,c)),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&&!mn.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&&xt(n))return this.pendingEncryptedStashes.add(r.path),!1;let o=await si(this.app,n,{...s,secretId:Ve(r.basename)});if(!o)return!1;let a=await ee(this.app,o,t,e);if(a.colorAliases)for(let[l,c]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,l,c)}catch{}try{await this.app.fileManager.trashFile(r)}catch{}this.pendingEncryptedStashes.delete(r.path);try{await this.plugin.newLog().append({type:"stash_import",id:k,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===te);if(i.length===0)return 0;let s=this.liveRootIds(e),n=0;for(let o of i)await this.importOneStash(o,e,s,!!t.auto)&&n++;return n}async importLooseInto(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 it(this.app,r,t,e,i).open()})}dupChoice(r){return new Promise(t=>{new Ti(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}};fi.DEBOUNCE_MS=900,fi.BATCH_CONFIRM_AT=8;var Cn=fi;var Bn=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 wn=class wn{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()},wn.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}};wn.SAVE_DEBOUNCE_MS=8e3;var yn=wn;var Jo="stashpad:unghost-after-reload",ns=class ns extends M.Plugin{constructor(){super(...arguments);this.settings={...Be};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>ns.DEBUG_BUFFER_MAX&&this.debugBuffer.splice(0,this.debugBuffer.length-ns.DEBUG_BUFFER_MAX)}getDebugTrace(){return this.debugBuffer.join(` +`)}clearDebugTrace(){this.debugBuffer=[]}get notifications(){return this._notifications||(this._notifications=new ws(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new In(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new Cn(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new Bn(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 yn(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 un(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 c of a)l=l?`${l}/${c}`:c,await t.exists(l)||await t.mkdir(l)},s=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(n))try{let a=await t.read(n);await t.write(s,a),await t.write(`${n}.bak`,a),await t.remove(n),console.debug("[Stashpad] relocated data.json \u2192 standard path (for Obsidian Sync)")}catch(a){console.warn("Stashpad: data.json relocation 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 c=l.replace(/^.*\//,""),d=this.pluginPrivatePath(c);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 createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let c of s)n=n?`${n}/${c}`:c,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let c=this.app.vault.getAbstractFileByPath(o);c&&await this.app.fileManager.processFrontMatter(c,d=>{(typeof d.id!="string"||!d.id)&&(d.id=k),"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: ${k}`,"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 c=l.toLowerCase();e.set(c,(e.get(c)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let l of this.app.vault.getMarkdownFiles()){let c=l.parent?.path?.replace(/\/+$/,"")??"";if(c!==s&&!c.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))}}importExcludePrefixList(){return(this.settings.importExcludePrefixes??"_").split(",").map(t=>t.trim()).filter(Boolean)}pathHasExcludedSegment(t){let e=this.importExcludePrefixList();return e.length?t.replace(/\/+$/,"").split("/").some(i=>e.some(s=>i.startsWith(s))):!1}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&&!this.pathHasExcludedSegment(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(q)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(a=>a!==t&&!a.startsWith(t+"/")),s=(e.folderPanelPinned?.length??0)+(e.folderPanelDownranked?.length??0)+(e.folderPanelHidden?.length??0);e.folderPanelPinned=i(e.folderPanelPinned),e.folderPanelDownranked=i(e.folderPanelDownranked),e.folderPanelHidden=i(e.folderPanelHidden),e.folderPanelPinned.length+e.folderPanelDownranked.length+e.folderPanelHidden.length!==s&&await this.saveSettings()}async deleteStashpadFolderWithUndo(t){let e=t.path.replace(/\/+$/,""),i=t.name,s=this.app.vault.adapter,n=".trash";try{await s.exists(n)||await s.mkdir(n)}catch(c){console.warn("[Stashpad] couldn't ensure .trash",c)}let o=`${n}/${i}`;for(let c=1;await s.exists(o);c++)o=`${n}/${i} (${c})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let a=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(c){console.warn("[Stashpad] folder delete failed",c),this.suppressedFolderDeletes.delete(e),new 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(c){console.warn("[Stashpad] folder undo failed",c),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(c=>(c??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(c=>s.has(c)?!1:e.size>0?e.has(c):!i.has(c)),a=(t||"").trim().replace(/\/+$/,""),l=o.filter(c=>c!==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(c=>c.path===t||c.path.startsWith(t+"/"));for(let c of n){let d=this.app.metadataCache.getFileCache(c)?.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:c.path}}let o=await i.readState(),a=c=>c===t||c.startsWith(t+"/");if(!e.silent){for(let[c,d]of Object.entries(s)){let h=o[c];h?h.parent!==d.parent?await i.append({type:"parent_change",id:c,payload:{from:h.parent,to:d.parent}}):h.path!==d.path&&await i.append({type:"rename",id:c,payload:{from:h.path,to:d.path}}):await i.append({type:"create",id:c,payload:{path:d.path,parent:d.parent}})}for(let[c,d]of Object.entries(o))!s[c]&&a(d.path)&&await i.append({type:"missing",id:c,payload:{lastPath:d.path}})}let l={};for(let[c,d]of Object.entries(o))a(d.path)||(l[c]=d);for(let[c,d]of Object.entries(s))l[c]=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 fn,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),vt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new bs(this.app,()=>({...$i(),...this.settings.encryption??{}}),async p=>{this.settings.encryption=p,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.app.workspace.onLayoutReady(()=>{this.resumeRotations()}),this.settingTab=new Ms(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,f)=>this.renderCacheStore.evict(f)));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,f)=>{this.onOkfFileEvent(p.path),this.onOkfFileEvent(f)})),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(q,p=>new ln(p,this)),this.registerView(Se,p=>new Ps(p,this)),this.registerView(pe,p=>new gs(p,this)),this.registerView(Je,p=>new An(p,this)),this.registerView(Oe,p=>new dn(p,this)),this.registerView(ge,p=>new hn(p,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",p=>{p&&p.view.getViewType()===q&&(this.lastActiveStashpadLeaf=p,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(Se).length===0&&setTimeout(()=>{Hs(this.app)},0),this.notifyStashpadSelectionChanged())}));let e=()=>{let p=ce(),f=!!p&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===p,I=!!f&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",I),document.body.classList.toggle("stashpad-active",!!f)};this.register(La(e)),this.registerEvent(this.app.workspace.on("active-leaf-change",e));let i=p=>{try{let f=Array.from(document.querySelectorAll("style")).filter(I=>(I.textContent??"").includes(".stashpad-"));for(let I of f){let m=I.id||"",C=m?`style[data-stashpad-source="${m}"]`:null;if(C&&p.head.querySelector(C))continue;let B=p.createElement("style");m?B.setAttribute("data-stashpad-source",m):B.setAttribute("data-stashpad-source","anon"),B.textContent=I.textContent??"",p.head.appendChild(B)}}catch(f){console.warn("[Stashpad] inject popout styles failed",f)}};this.registerEvent(this.app.workspace.on("window-open",p=>{let f=p?.doc??p?.win?.document??null;f&&i(f)})),this.registerEvent(this.app.workspace.on("file-menu",(p,f)=>{if(!(f instanceof M.TFolder))return;let I=f.path.replace(/\/+$/,"");p.addItem(C=>C.setTitle("\u{1F512} Encrypt with Stashpad").setIcon("lock").onClick(()=>void this.encryptFolderFromExplorer(I))),f.children?.some(C=>C instanceof M.TFile&&C.extension==="stashenc")&&!this.folderHasStashpadNotes(I)&&p.addItem(C=>C.setTitle("\u{1F513} Decrypt with Stashpad").setIcon("unlock").onClick(()=>void this.decryptFolderFromExplorer(I))),this.discoverStashpadFolders().includes(I)&&p.addItem(C=>{C.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(I))})})),setTimeout(()=>{try{let p=this.app.workspace;typeof p.iterateAllLeaves=="function"&&p.iterateAllLeaves(f=>{let I=f?.view?.containerEl?.ownerDocument;I&&I!==document&&i(I)})}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"),f=p&&p.isConnected?p.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${f}px`);let I=0;s&&(I=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${I}px`),document.body.classList.toggle("stashpad-keyboard-open",I>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)",()=>{us(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{pn(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 f=ce();f&&typeof f[p]=="function"&&f[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-open-all-encrypted",name:"Open \u201CAll encrypted\u201D (every locked note, by folder)",callback:()=>void Uo(this,"encrypted")}),this.addCommand({id:"stashpad-open-all-archived",name:"Open \u201CAll archived\u201D (every archive folder)",callback:()=>void Uo(this,"archived")}),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=vt.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:()=>{vt.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(()=>(kt(),Hi));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 f=this.importService.defaultDestination();return p?!!f:(f&&this.runImportLooseFiles(f),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:p=>{let f=this.importService.defaultDestination();return p?!!f:(f&&this.runFolderSlugPass(f),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:p=>{let f=this.importService.defaultDestination();return p?!!f:(f&&this.runFolderFrontmatterBackfill(f),!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 us(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void pn(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 f=this.app.workspace.getActiveFile(),I=!!f&&f.extension==="md"&&this.isStashpadNoteFile(f);return p||I&&f&&this.revealNoteInStashpad(f),I}});let l=Object.keys(Ui);for(let p of l){let f=Ui[p];this.addCommand({id:`stashpad-open-panels-${p}`,name:`Open Stashpad panel: ${f.label}`,callback:async()=>{await us(this.app),this.app.workspace.getLeavesOfType(pe)[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 f=ce(),I=f&&f.noteFolder;return I?(p||(new M.Notice(`Running integrity check on "${I}"\u2026`),this.runIntegrityCheckOnFolder(I).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:()=>{this.runRebootstrapWithUI().catch(()=>{})}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:p=>{let f=this.app.workspace.getActiveFile();return!f||f.extension!=="md"?!1:(p||this.adoptNote(f),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(kt(),Hi)).then(({NotificationHistoryModal:p,LogModal:f})=>{new p(this.app,this.notifications,async()=>{let I=this.app.vault.adapter,m=this.pluginPrivatePath("log.jsonl");if(!await I.exists(m)){new M.Notice("No log yet \u2014 make some changes first.");return}let C=await I.read(m);new f(this.app,C,m).open()},this.settings.authorId||null,I=>this.lookupNoteAuthorIds(I)).open()})}});let c=[{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 c){let f=`stashpad-toggle-${String(p.key).replace(/[A-Z]/g,I=>`-${I.toLowerCase()}`)}`;this.addCommand({id:f,name:`Toggle: ${p.label}`,callback:async()=>{let I=!this.settings[p.key];this.settings[p.key]=I,await this.saveSettings(),new M.Notice(`${p.label}: ${I?"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 f=this.app.setting;!f?.open||!f?.openTabById||(f.open(),f.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(()=>(Gi(),Cs)),f=await p(this.app,this,this.settings);if(f.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(f.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:I}=await Promise.resolve().then(()=>(Gi(),Cs));I(this.app,f)}catch(p){console.error("[stashpad] preview failed",p),new M.Notice(`Preview failed: ${p?.message??p}`,8e3)}}}),this.addCommand({id:"stashpad-decrypt-folder-bundle",name:"Decrypt a folder bundle (encrypted non-Stashpad folder)\u2026",callback:async()=>{if(!this.encryption.isConfigured()){new M.Notice("Stashpad encryption isn't set up.");return}let p=await Rr(this.app);if(!p.length){new M.Notice("No encrypted folder bundles found in this vault.");return}new Yo(this.app,p,f=>void this.decryptFolderFromExplorer(f.folder)).open()}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:p,scanForJdNotes:f,JdBuildConfirmModal:I}=await Promise.resolve().then(()=>(Gi(),Cs));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}let C=f(this.app,this,this.settings);new I(this.app,this,this.settings,C.indexed.length,async()=>{try{let w=await p(this.app,this,this.settings);if(w.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),d();return}if(w.error==="dest-not-stashpad"){new M.Notice(`"${w.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: ${w.created} created, ${w.updated} updated, ${w.skipped} skipped \u2192 ${w.destFolder}`,6e3)}catch(w){console.error("[stashpad] build failed",w),new M.Notice(`Build failed: ${w?.message??w}`,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!==te)return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),I=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),m=p.parent?.path||"",C=m.split("/").pop()??"";if(f&&C===f){if(I&&m.endsWith(`/${I}`))return;let B=m.slice(0,m.length-f.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(p,B);return}this.settings.autoImport&&this.importService.isArmed()&&($e(p.path)||this.discoverStashpadFolders().includes(m)&&this.autoImportStash(p,m))};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 f=p.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(f)&&setTimeout(()=>{this.fixOrphanParentForFile(p)},800)},u=p=>{if(p.extension!=="md")return;let f=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!f)return;let I=p.parent?.path?.replace(/\/+$/,"")??"";if((I.split("/").pop()??"")!==f)return;let C=I.slice(0,I.length-f.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(p,C)},200)};this.registerEvent(this.app.vault.on("create",p=>{p instanceof M.TFile&&(g(p),u(p))})),this.registerEvent(this.app.vault.on("rename",p=>{p instanceof M.TFile&&(g(p),u(p))})),this.registerEvent(this.app.vault.on("delete",p=>{if(!(p instanceof M.TFolder))return;let f=p.path.replace(/\/+$/,"");this.knownStashpadFolders.has(f)&&this.handleStashpadFolderDeleted(f)})),this.registerEvent(this.app.vault.on("rename",(p,f)=>{p instanceof M.TFile&&this.maybeReHomeOnCrossFolderMove(p,f)})),this.registerEvent(this.app.vault.on("rename",(p,f)=>{p instanceof M.TFile&&this.maybeArchiveOnMoveIn(p,f)})),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,f)=>{p instanceof M.TFile&&this.maybeAdoptAuthorRename(p,f)})),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(Jo,"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(Jo)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Jo)}catch{}for(let e of this.app.workspace.getLeavesOfType(q))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`,c=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&&(c=d)}catch(d){console.warn("[Stashpad] author file rename failed",d);continue}try{await this.refreshAuthorStub(c)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,i?a.role=i:delete a.role,s?a.department=s:delete a.department})}catch(n){console.warn("[Stashpad] refreshAuthorStub failed",n)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let i=this.parseAuthorFilePath(t.path);if(!i)return;let s=(this.settings.authorId??"").trim();if(!s||i.id!==s)return;let n=i.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let i=this.app.vault.adapter,s=t.name,n=s.lastIndexOf("."),o=n>0?s.slice(0,n):s,a=n>0?s.slice(n):"",l=0;for(;await i.exists(`${e}/${s}`);)l+=1,s=`${o}-${l}${a}`;let c=`${e}/${s}`;await this.app.fileManager.renameFile(t,c);let d=this.app.vault.getAbstractFileByPath(c);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:[c]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",a=!i,l=!n,c=!o;if(!a&&!l&&!c)return;let{newId:d}=await Promise.resolve().then(()=>(Gt(),hs)),h,g=!1,u=!1;if(await this.app.fileManager.processFrontMatter(t,I=>{if(a&&(typeof I.id=="string"&&I.id.trim()||(h=d(),I.id=h)),l){let m=I.parent;(typeof m=="string"?m.trim()!=="":m!=null)||(I.parent=k,g=!0)}c&&(typeof I.created=="string"&&I.created.trim()||(I.created=new Date(t.stat.ctime).toISOString(),u=!0))}),!h&&!g&&!u)return;let p=this.newLog(),f=h||i;f&&await p.append({type:"parent_change",id:f,payload:{from:null,to:k,reason:"orphan_auto_fix",path:t.path,addedId:!!h,addedParent:g,addedCreated:u}}),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===k||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!==k&&(a.parent=k)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:k,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(xt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await si(this.app,i);if(!s)return;let n=ce(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let c of n.collectExistingIds())o.add(c);else for(let c of this.app.vault.getMarkdownFiles()){if(!c.path.startsWith(e+"/"))continue;let d=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof d=="string"&&o.add(d)}let a=await ee(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:k,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 r=n?.contributors;if(Array.isArray(r))for(let l of r){let c=i(l);c&&e.add(c)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async runRebootstrapWithUI(){let e=new M.Notice("",0).noticeEl;e.empty(),e.addClass("stashpad-progress-notice"),e.createDiv({cls:"stashpad-progress-title",text:"Rebootstrapping Stashpad folders\u2026"});let s=e.createDiv({cls:"stashpad-progress-bar"}).createDiv({cls:"stashpad-progress-fill"}),n=e.createDiv({cls:"stashpad-progress-sub",text:"Counting notes\u2026"}),o=(r,l,c)=>{let d=l>0?Math.min(100,Math.round(r/l*100)):0;s.style.width=`${d}%`,n.setText(c?`${c} \xB7 ${d}%`:`${d}%`)};try{let r=await this.rebootstrapAllFolders(o),l=r.imported+r.attachmentsLinked+r.attachmentsRenamed+r.fmWritten+r.slugsRenamed,c=[];return c.push(`Checked ${r.touched.length} folder${r.touched.length===1?"":"s"} (${r.fmChecked} note${r.fmChecked===1?"":"s"})`),l===0?c.push("everything already in sync \u2014 no changes needed"):(r.fmWritten>0&&c.push(`updated frontmatter on ${r.fmWritten} note${r.fmWritten===1?"":"s"}`),r.slugsRenamed>0&&c.push(`renamed ${r.slugsRenamed} note${r.slugsRenamed===1?"":"s"} to match body`),r.imported>0&&c.push(`imported ${r.imported} loose file${r.imported===1?"":"s"}`),r.attachmentsLinked>0&&c.push(`linked attachments on ${r.attachmentsLinked} note${r.attachmentsLinked===1?"":"s"}`),r.attachmentsRenamed>0&&c.push(`renamed ${r.attachmentsRenamed} attachment${r.attachmentsRenamed===1?"":"s"}`)),r.authors>0&&c.push(`${r.authors} author${r.authors===1?"":"s"} in registry`),e.empty(),e.removeClass("stashpad-progress-notice"),e.addClass("stashpad-progress-done"),e.createDiv({cls:"stashpad-progress-title",text:"\u2713 Rebootstrap complete"}),e.createDiv({cls:"stashpad-progress-sub",text:`${c.join("; ")}.`}),r.attachmentsSkipped>0&&new M.Notice(`Stashpad: ${r.attachmentsSkipped} attachment${r.attachmentsSkipped===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D, then rebootstrap again.`,12e3),r}catch(r){throw e.empty(),e.removeClass("stashpad-progress-notice"),e.addClass("stashpad-progress-error"),e.createDiv({cls:"stashpad-progress-title",text:"Rebootstrap failed"}),e.createDiv({cls:"stashpad-progress-sub",text:r.message}),r}}async rebootstrapAllFolders(t){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner(t)}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1;for(let e of this.app.workspace.getLeavesOfType(K))e.view?.forceReconcileRender?.()},2500)}}async rebootstrapAllFoldersInner(t){let e="__root__",i=new Set;for(let y of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(y)?.frontmatter?.id!==e)continue;let v=y.parent?.path;v&&i.add(v)}let s=new Map;for(let y of this.app.vault.getMarkdownFiles()){let Q=y.parent?.path;Q&&i.has(Q)&&s.set(Q,(s.get(Q)??0)+1)}let n=Math.max(1,[...s.values()].reduce((y,Q)=>y+Q,0)),o=0;t?.(0,n,"Starting\u2026");let r=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),l=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),c=[],d=async y=>{if(y&&!await this.app.vault.adapter.exists(y))try{await this.app.vault.createFolder(y)}catch(Q){let v=Q?.message??"";if(!/already exists/i.test(v))throw Q}},h=0,g=0,u=0,p=0,f=0,I=0,m=!!this.app.vault.getConfig?.("alwaysUpdateLinks"),C=new Set(this.okfActiveFolders());for(let y of i){let Q=s.get(y)??1;t?.(o,n,`Processing \u201C${y.split("/").pop()||y}\u201D (${Q} note${Q===1?"":"s"})`);try{if(r&&await d(`${y}/${r}`),l&&await d(`${y}/${l}`),this.settings.autoImport)try{let S=await this.importService.importLooseInto(y);p+=S.files+S.folders+S.stashes}catch(S){console.warn("Stashpad: loose sweep failed",y,S)}let v=await li(this.app,y);h+=v.checked,g+=v.written,u+=await this.rebootstrapFolderSlugs(y);let E=await this.rebootstrapFolderAttachments(y,m);if(f+=E.renamed,I+=E.skipped,C.has(y.replace(/\/+$/,"")))try{await Uo(this.app,y)}catch(S){console.warn("Stashpad: OKF rebuild during rebootstrap failed",y,S)}c.push(y)}catch(v){console.warn(`Stashpad: rebootstrap skipped ${y}`,v)}finally{o+=Q,t?.(o,n,`Processing \u201C${y.split("/").pop()||y}\u201D`)}}t?.(n,n,"Finalizing\u2026");let B=0;try{B=(await this.rebuildAuthorRegistry()).total}catch(y){console.warn("Stashpad: rebootstrap author-registry rebuild failed",y)}let w=0;try{w=await this.convertAttachmentsToLinks()}catch(y){console.warn("Stashpad: attachment-link conversion failed",y)}return{touched:c,fmChecked:h,fmWritten:g,slugsRenamed:u,authors:B,imported:p,attachmentsLinked:w,attachmentsRenamed:f,attachmentsSkipped:I}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Vt,n=0,o=this.app.vault.getMarkdownFiles().filter(r=>(r.parent?.path?.replace(/\/+$/,"")??"")===i);for(let r of o){let l=me(r.basename);if(!(!l||l===e||this.app.metadataCache.getFileCache(r)?.frontmatter?.id!==l))try{let d=await this.app.vault.cachedRead(r),h=d.startsWith("---")?d.slice(d.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):d,g=St(h,s),u=bt(g,l);if(r.name===u)continue;let p=r.parent?`${r.parent.path}/${u}`:u;if(this.app.vault.getAbstractFileByPath(p))continue;await this.app.fileManager.renameFile(r,p),n+=1}catch(d){console.warn(`Stashpad: slug rebootstrap skipped ${r.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,r=0;for(let l of n){let c=dr(l.name);if(!c)continue;let d=ps(c.rest,c.stamp);if(l.name===d)continue;if(!e){r+=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:r}}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(r=>r.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(pe);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()}}refreshFolderPanels(){for(let t of this.app.workspace.getLeavesOfType(ge)){let e=t.view;e&&typeof e.refresh=="function"&&e.refresh()}}getFolderIcon(t){let e=(t||"").replace(/\/+$/,""),i=this.settings.folderIcons?.[e];return i&&i.trim()?i.trim():void 0}async setFolderIcon(t,e){let i=(t||"").replace(/\/+$/,""),s={...this.settings.folderIcons??{}};e&&e.trim()?s[i]=e.trim():delete s[i],this.settings.folderIcons=s,await this.saveSettings(),this.refreshFolderIconFor(i)}refreshFolderIconFor(t){let e=(t||"").replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(K)){let s=i.view;if(s&&(s.noteFolder||"").replace(/\/+$/,"")===e){try{i.updateHeader?.()}catch{}try{s.refreshFolderSwitcherIcon?.()}catch{}}}this.refreshFolderPanels()}openFolderPicker(){let t=I=>{let C=I.getViewState().state?.folderOverride;return typeof C=="string"&&C.trim()?C.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(K),i=this.discoverStashpadFolders(),s=ce(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let I of this.app.vault.getAllLoadedFiles())if(I.children){let m=I.path;m&&m!=="/"&&!m.startsWith(".")&&o.add(m)}let r=I=>{let m=I.split("/").filter(Boolean).pop()??"";return m?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(B=>(B??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(m):!1},l=new Set,c=[],d=[],h=new Set;for(let I of e){let m=t(I);if(h.has(m))continue;h.add(m),l.add(m);let C=m.split("/").pop()||m;c.push({kind:"reveal",folder:m,label:`Reveal "${C}" tab`,leaf:I,icon:this.isArchiveFolder(m)?"archive":"layout-grid"}),d.push({kind:"open-anyway",folder:m,label:`Open "${C}" in another new tab`,icon:"layout-template"})}for(let I of i.filter(m=>!l.has(m))){let m=I.split("/").pop()||I;c.push({kind:"open",folder:I,label:`Open "${m}" in new tab`,icon:this.isArchiveFolder(I)?"archive":"layout-template"})}let g=I=>I.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||I.basename,u=this.settings.folderSwitcherIncludePinned?this.listPinnedNotes().map(I=>({kind:"pinned",folder:I.folder,file:I.file,label:g(I.file),icon:"pin"})):[],p=this,f=new class extends M.SuggestModal{getSuggestions(I){let m=I.trim().toLowerCase(),C=m?m.split(/\s+/).filter(Boolean):[],B=v=>{if(!C.length)return!0;let E=v.toLowerCase();for(let S of C)if(!E.includes(S))return!1;return!0},w=m?c.filter(v=>{let E="folder"in v?v.folder:"";return B(v.label)||B(E)}):c.slice();if(m&&s&&n)for(let v of i){if(v.toLowerCase()===n.toLowerCase())continue;let E=v.split("/").pop()??v,S=`${v} ${E}`;B(S)&&w.push({kind:"switch-current",folder:v,label:`Switch this tab to "${E}"`,icon:"folder-input"})}for(let v of u)(B(v.label)||B("folder"in v?v.folder:""))&&w.push(v);let y=I.trim().replace(/^\/+|\/+$/g,"");if(y&&!r(y)){let v=Array.from(o).find(S=>S.toLowerCase()===y.toLowerCase()),E=i.some(S=>S.toLowerCase()===y.toLowerCase());if(v&&!E)w.push({kind:"convert",folder:v,label:`Convert \u201C${vi(v)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!v){let S=vi(y);w.push({kind:"create",folder:y,label:`+ Create new Stashpad \u201C${S}\u201D`,icon:"folder-plus"})}}let Q=d.filter(v=>B(v.label)||B("folder"in v?v.folder:""));return w.push(...Q),p.encryption?.isConfigured?.()&&B("trash deleted encrypted")&&w.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),w}renderSuggestion(I,m){m.addClass("stashpad-suggest-item"),m.addClass("stashpad-ribbon-suggest-item"),I.kind==="create"&&m.addClass("stashpad-suggest-create");let C=m.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,M.setIcon)(C,I.icon);let B=m.createDiv({cls:"stashpad-ribbon-suggest-body"});B.createDiv({cls:"stashpad-suggest-title",text:I.label}),"folder"in I&&I.folder&&I.label!==I.folder&&B.createDiv({cls:"stashpad-suggest-preview",text:I.folder})}async onChooseSuggestion(I){if(I.kind==="trash"){p.openEncryptedTrash();return}if(I.kind==="pinned"){await p.revealNoteInStashpad(I.file);return}if(I.kind==="reveal"){p.app.workspace.revealLeaf(I.leaf);return}if(I.kind==="open"||I.kind==="open-anyway"){await p.activateViewForFolder(I.folder);return}if(I.kind==="switch-current"){let m=s;m&&typeof m.setFolderOverride=="function"&&(await m.setFolderOverride(I.folder),p.app.workspace.revealLeaf(m.leaf));return}if(I.kind==="create"){try{let m=vi(I.folder);await p.app.vault.adapter.exists(m)||await p.app.vault.createFolder(m),await p.activateViewForFolder(m)}catch(m){new M.Notice(`Stashpad: couldn't create folder (${m.message})`)}return}if(I.kind==="convert"){let{ConfirmModal:m}=await Promise.resolve().then(()=>(kt(),Pi)),C=I.folder,B=[`\u201C${C}\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 m(p.app,"Convert into a Stashpad?",B.join(` -`),"Convert & import",async w=>{if(w)try{await p.activateViewForFolder(C),await p.runImportLooseFiles(C)}catch(y){new M.Notice(`Stashpad: couldn't convert folder (${y.message})`)}}).open();return}}}(this.app);f.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"),f.open()}async openTinyWindow(){let t=ce(),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 cn(this.app);let t=this.app.workspace.getLeavesOfType(ge)[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 r=await js(this.app,n.path);r&&(e.push({folder:o,blob:n.path,parentId:r.parentId,title:r.title,count:r.count,created:r.created,rootId:r.rootId,prevSibling:r.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??k)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??k,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 r=o.parent?.path?.replace(/\/+$/,"")??"";r!==i||r==="_deleted"||r.startsWith("_deleted/")||e===k&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:k,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new ct(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 Stashpad \u2192 Encryption)."),!1)}async ensureFolderUnlocked(t){if(!this.encryption.isConfigured())return new M.Notice("Set up encryption first (Settings \u2192 Stashpad \u2192 Encryption)."),null;if(this.encryption.hasFolderKey(t)){if(this.encryption.isFolderUnlocked(t))return this.encryption.getFolderKey(t);if(await this.encryption.tryAutoUnlockFolder(t))return this.encryption.getFolderKey(t);let e=t.split("/").pop()||t;return await new Promise(s=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,title:`Unlock \u201C${e}\u201D`,intro:"Enter this folder's password.",onSubmit:async({current:n,remember:o})=>await this.encryption.unlockFolder(t,n,o)?(s(!0),null):"Wrong password. Try again.",onCancel:()=>s(!1)}).open()})?this.encryption.getFolderKey(t):null}return await this.ensureEncryptionUnlocked()?this.encryption.getSessionKey():null}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 sn(this.app)).length>0}catch{}if(!e)try{e=(await this.app.vault.adapter.list(Ut)).files.some(s=>s.endsWith(".stashenc"))}catch{}return{live:t.live,trash:e}}async lockNoteSubtree(t,e,i=null,s={}){let n=(s.blobFolder??t).replace(/\/+$/,""),o=await this.ensureFolderUnlocked(n);if(!o)return null;try{let r=!!s.blobFolder&&s.blobFolder.replace(/\/+$/,"")!==t.replace(/\/+$/,""),l=(this.settings.folderEncPrefs??{})[n]??{},c=(r?l.archiveEncryptFilenames:l.encryptFilenames)??this.settings.hideLockedTitles??!1,d=await wa(this.app,t,e,o,i,c,s.blobFolder);this.pendingEncBlobs.add(d.blobPath);let h=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(g=>g.blob!==d.blobPath),{folder:h,blob:d.blobPath,parentId:d.parentId,title:d.title,count:d.noteCount,created:d.created,rootId:d.rootId,prevSibling:i}],await this.saveSettings(),d.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Locked, but ${d.unpurged.length} file${d.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:Qs(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 c=i(l);c&&e.add(c)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async runRebootstrapWithUI(){let e=new M.Notice("",0).noticeEl;e.empty(),e.addClass("stashpad-progress-notice"),e.createDiv({cls:"stashpad-progress-title",text:"Rebootstrapping Stashpad folders\u2026"});let s=e.createDiv({cls:"stashpad-progress-bar"}).createDiv({cls:"stashpad-progress-fill"}),n=e.createDiv({cls:"stashpad-progress-sub",text:"Counting notes\u2026"}),o=(a,l,c)=>{let d=l>0?Math.min(100,Math.round(a/l*100)):0;s.style.width=`${d}%`,n.setText(c?`${c} \xB7 ${d}%`:`${d}%`)};try{let a=await this.rebootstrapAllFolders(o),l=a.imported+a.attachmentsLinked+a.attachmentsRenamed+a.fmWritten+a.slugsRenamed,c=[];return c.push(`Checked ${a.touched.length} folder${a.touched.length===1?"":"s"} (${a.fmChecked} note${a.fmChecked===1?"":"s"})`),l===0?c.push("everything already in sync \u2014 no changes needed"):(a.fmWritten>0&&c.push(`updated frontmatter on ${a.fmWritten} note${a.fmWritten===1?"":"s"}`),a.slugsRenamed>0&&c.push(`renamed ${a.slugsRenamed} note${a.slugsRenamed===1?"":"s"} to match body`),a.imported>0&&c.push(`imported ${a.imported} loose file${a.imported===1?"":"s"}`),a.attachmentsLinked>0&&c.push(`linked attachments on ${a.attachmentsLinked} note${a.attachmentsLinked===1?"":"s"}`),a.attachmentsRenamed>0&&c.push(`renamed ${a.attachmentsRenamed} attachment${a.attachmentsRenamed===1?"":"s"}`)),a.authors>0&&c.push(`${a.authors} author${a.authors===1?"":"s"} in registry`),e.empty(),e.removeClass("stashpad-progress-notice"),e.addClass("stashpad-progress-done"),e.createDiv({cls:"stashpad-progress-title",text:"\u2713 Rebootstrap complete"}),e.createDiv({cls:"stashpad-progress-sub",text:`${c.join("; ")}.`}),a.attachmentsSkipped>0&&new M.Notice(`Stashpad: ${a.attachmentsSkipped} attachment${a.attachmentsSkipped===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D, then rebootstrap again.`,12e3),a}catch(a){throw e.empty(),e.removeClass("stashpad-progress-notice"),e.addClass("stashpad-progress-error"),e.createDiv({cls:"stashpad-progress-title",text:"Rebootstrap failed"}),e.createDiv({cls:"stashpad-progress-sub",text:a.message}),a}}async rebootstrapAllFolders(t){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner(t)}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1;for(let e of this.app.workspace.getLeavesOfType(q))e.view?.forceReconcileRender?.()},2500)}}async rebootstrapAllFoldersInner(t){let e="__root__",i=new Set;for(let y of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(y)?.frontmatter?.id!==e)continue;let v=y.parent?.path;v&&i.add(v)}let s=new Map;for(let y of this.app.vault.getMarkdownFiles()){let Q=y.parent?.path;Q&&i.has(Q)&&s.set(Q,(s.get(Q)??0)+1)}let n=Math.max(1,[...s.values()].reduce((y,Q)=>y+Q,0)),o=0;t?.(0,n,"Starting\u2026");let a=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),l=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),c=[],d=async y=>{if(y&&!await this.app.vault.adapter.exists(y))try{await this.app.vault.createFolder(y)}catch(Q){let v=Q?.message??"";if(!/already exists/i.test(v))throw Q}},h=0,g=0,u=0,p=0,f=0,I=0,m=!!this.app.vault.getConfig?.("alwaysUpdateLinks"),C=new Set(this.okfActiveFolders());for(let y of i){let Q=s.get(y)??1;t?.(o,n,`Processing \u201C${y.split("/").pop()||y}\u201D (${Q} note${Q===1?"":"s"})`);try{if(a&&await d(`${y}/${a}`),l&&await d(`${y}/${l}`),this.settings.autoImport)try{let S=await this.importService.importLooseInto(y);p+=S.files+S.folders+S.stashes}catch(S){console.warn("Stashpad: loose sweep failed",y,S)}let v=await ci(this.app,y);h+=v.checked,g+=v.written,u+=await this.rebootstrapFolderSlugs(y);let E=await this.rebootstrapFolderAttachments(y,m);if(f+=E.renamed,I+=E.skipped,C.has(y.replace(/\/+$/,"")))try{await Ko(this.app,y)}catch(S){console.warn("Stashpad: OKF rebuild during rebootstrap failed",y,S)}c.push(y)}catch(v){console.warn(`Stashpad: rebootstrap skipped ${y}`,v)}finally{o+=Q,t?.(o,n,`Processing \u201C${y.split("/").pop()||y}\u201D`)}}t?.(n,n,"Finalizing\u2026");let B=0;try{B=(await this.rebuildAuthorRegistry()).total}catch(y){console.warn("Stashpad: rebootstrap author-registry rebuild failed",y)}let w=0;try{w=await this.convertAttachmentsToLinks()}catch(y){console.warn("Stashpad: attachment-link conversion failed",y)}return{touched:c,fmChecked:h,fmWritten:g,slugsRenamed:u,authors:B,imported:p,attachmentsLinked:w,attachmentsRenamed:f,attachmentsSkipped:I}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Vt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let l=me(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=St(h,s),u=bt(g,l);if(a.name===u)continue;let p=a.parent?`${a.parent.path}/${u}`:u;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 c=pa(l.name);if(!c)continue;let d=fs(c.rest,c.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?.()!==q)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(pe);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(q)){let e=t.view;e&&typeof e.render=="function"&&e.render()}}refreshFolderPanels(){for(let t of this.app.workspace.getLeavesOfType(ge)){let e=t.view;e&&typeof e.refresh=="function"&&e.refresh()}}getFolderIcon(t){let e=(t||"").replace(/\/+$/,""),i=this.settings.folderIcons?.[e];return i&&i.trim()?i.trim():void 0}async setFolderIcon(t,e){let i=(t||"").replace(/\/+$/,""),s={...this.settings.folderIcons??{}};e&&e.trim()?s[i]=e.trim():delete s[i],this.settings.folderIcons=s,await this.saveSettings(),this.refreshFolderIconFor(i)}refreshFolderIconFor(t){let e=(t||"").replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(q)){let s=i.view;if(s&&(s.noteFolder||"").replace(/\/+$/,"")===e){try{i.updateHeader?.()}catch{}try{s.refreshFolderSwitcherIcon?.()}catch{}}}this.refreshFolderPanels()}openFolderPicker(){let t=I=>{let C=I.getViewState().state?.folderOverride;return typeof C=="string"&&C.trim()?C.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(q),i=this.discoverStashpadFolders(),s=ce(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let I of this.app.vault.getAllLoadedFiles())if(I.children){let m=I.path;m&&m!=="/"&&!m.startsWith(".")&&o.add(m)}let a=I=>{let m=I.split("/").filter(Boolean).pop()??"";return m?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(B=>(B??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(m):!1},l=new Set,c=[],d=[],h=new Set;for(let I of e){let m=t(I);if(h.has(m))continue;h.add(m),l.add(m);let C=m.split("/").pop()||m;c.push({kind:"reveal",folder:m,label:`Reveal "${C}" tab`,leaf:I,icon:this.isArchiveFolder(m)?"archive":"layout-grid"}),d.push({kind:"open-anyway",folder:m,label:`Open "${C}" in another new tab`,icon:"layout-template"})}for(let I of i.filter(m=>!l.has(m))){let m=I.split("/").pop()||I;c.push({kind:"open",folder:I,label:`Open "${m}" in new tab`,icon:this.isArchiveFolder(I)?"archive":"layout-template"})}let g=I=>I.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||I.basename,u=this.settings.folderSwitcherIncludePinned?this.listPinnedNotes().map(I=>({kind:"pinned",folder:I.folder,file:I.file,label:g(I.file),icon:"pin"})):[],p=this,f=new class extends M.SuggestModal{getSuggestions(I){let m=I.trim().toLowerCase(),C=m?m.split(/\s+/).filter(Boolean):[],B=v=>{if(!C.length)return!0;let E=v.toLowerCase();for(let S of C)if(!E.includes(S))return!1;return!0},w=m?c.filter(v=>{let E="folder"in v?v.folder:"";return B(v.label)||B(E)}):c.slice();if(m&&s&&n)for(let v of i){if(v.toLowerCase()===n.toLowerCase())continue;let E=v.split("/").pop()??v,S=`${v} ${E}`;B(S)&&w.push({kind:"switch-current",folder:v,label:`Switch this tab to "${E}"`,icon:"folder-input"})}for(let v of u)(B(v.label)||B("folder"in v?v.folder:""))&&w.push(v);let y=I.trim().replace(/^\/+|\/+$/g,"");if(y&&!a(y)){let v=Array.from(o).find(S=>S.toLowerCase()===y.toLowerCase()),E=i.some(S=>S.toLowerCase()===y.toLowerCase());if(v&&!E)w.push({kind:"convert",folder:v,label:`Convert \u201C${Fi(v)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!v){let S=Fi(y);w.push({kind:"create",folder:y,label:`+ Create new Stashpad \u201C${S}\u201D`,icon:"folder-plus"})}}let Q=d.filter(v=>B(v.label)||B("folder"in v?v.folder:""));return w.push(...Q),p.encryption?.isConfigured?.()&&B("trash deleted encrypted")&&w.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),w}renderSuggestion(I,m){m.addClass("stashpad-suggest-item"),m.addClass("stashpad-ribbon-suggest-item"),I.kind==="create"&&m.addClass("stashpad-suggest-create");let C=m.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,M.setIcon)(C,I.icon);let B=m.createDiv({cls:"stashpad-ribbon-suggest-body"});B.createDiv({cls:"stashpad-suggest-title",text:I.label}),"folder"in I&&I.folder&&I.label!==I.folder&&B.createDiv({cls:"stashpad-suggest-preview",text:I.folder})}async onChooseSuggestion(I){if(I.kind==="trash"){p.openEncryptedTrash();return}if(I.kind==="pinned"){await p.revealNoteInStashpad(I.file);return}if(I.kind==="reveal"){p.app.workspace.revealLeaf(I.leaf);return}if(I.kind==="open"||I.kind==="open-anyway"){await p.activateViewForFolder(I.folder);return}if(I.kind==="switch-current"){let m=s;m&&typeof m.setFolderOverride=="function"&&(await m.setFolderOverride(I.folder),p.app.workspace.revealLeaf(m.leaf));return}if(I.kind==="create"){try{let m=Fi(I.folder);await p.app.vault.adapter.exists(m)||await p.app.vault.createFolder(m),await p.activateViewForFolder(m)}catch(m){new M.Notice(`Stashpad: couldn't create folder (${m.message})`)}return}if(I.kind==="convert"){let{ConfirmModal:m}=await Promise.resolve().then(()=>(kt(),Hi)),C=I.folder,B=[`\u201C${C}\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 m(p.app,"Convert into a Stashpad?",B.join(` +`),"Convert & import",async w=>{if(w)try{await p.activateViewForFolder(C),await p.runImportLooseFiles(C)}catch(y){new M.Notice(`Stashpad: couldn't convert folder (${y.message})`)}}).open();return}}}(this.app);f.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"),f.open()}async openTinyWindow(){let t=ce(),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:q,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(q);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:q,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(q),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 pn(this.app);let t=this.app.workspace.getLeavesOfType(ge)[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 sn(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??k)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??k,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===k&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:k,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new ct(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 Stashpad \u2192 Encryption)."),!1)}async ensureFolderUnlocked(t){if(!this.encryption.isConfigured())return new M.Notice("Set up encryption first (Settings \u2192 Stashpad \u2192 Encryption)."),null;if(this.encryption.hasFolderKey(t)){if(this.encryption.isFolderUnlocked(t))return this.encryption.getFolderKey(t);if(await this.encryption.tryAutoUnlockFolder(t))return this.encryption.getFolderKey(t);let e=t.split("/").pop()||t;return await new Promise(s=>{new ct(this.app,{mode:"unlock",offerKeychain:!0,title:`Unlock \u201C${e}\u201D`,intro:"Enter this folder's password.",onSubmit:async({current:n,remember:o})=>await this.encryption.unlockFolder(t,n,o)?(s(!0),null):"Wrong password. Try again.",onCancel:()=>s(!1)}).open()})?this.encryption.getFolderKey(t):null}return await this.ensureEncryptionUnlocked()?this.encryption.getSessionKey():null}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 rn(this.app)).length>0}catch{}if(!e)try{e=(await this.app.vault.adapter.list(Ut)).files.some(s=>s.endsWith(".stashenc"))}catch{}return{live:t.live,trash:e}}async lockNoteSubtree(t,e,i=null,s={}){let n=(s.blobFolder??t).replace(/\/+$/,""),o=await this.ensureFolderUnlocked(n);if(!o)return null;try{let a=!!s.blobFolder&&s.blobFolder.replace(/\/+$/,"")!==t.replace(/\/+$/,""),l=(this.settings.folderEncPrefs??{})[n]??{},c=(a?l.archiveEncryptFilenames:l.encryptFilenames)??this.settings.hideLockedTitles??!1,d=await Er(this.app,t,e,o,i,c,s.blobFolder);this.pendingEncBlobs.add(d.blobPath);let h=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(g=>g.blob!==d.blobPath),{folder:h,blob:d.blobPath,parentId:d.parentId,title:d.title,count:d.noteCount,created:d.created,rootId:d.rootId,prevSibling:i}],await this.saveSettings(),d.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Locked, but ${d.unpurged.length} file${d.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): ${d.unpurged.join(` -`)}`,0):s.silent||this.notifications.show({message:`Locked ${d.title?`\u201C${d.title}\u201D`:"a note"} (${d.noteCount} note${d.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),d}catch(r){return console.warn("[Stashpad] lock failed",r),new M.Notice(`Couldn't lock: ${r.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 r=dt(await this.app.vault.read(o)).fm.id;typeof r=="string"&&n.add(r)}catch{}return Qa(this.app,t,e,n,i)}async unlockBundleAt(t,e={}){let i=t.replace(/\/[^/]*$/,"").replace(/\/+$/,""),s=await this.ensureFolderUnlocked(i);if(!s)return!1;let n=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,"");try{let o=await this.unlockBundleCore(t,s,e.destFolder);return this.pendingEncBlobs.delete(t),this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(r=>r.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${o.notesWritten} note${o.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:n}),!0}catch(o){return console.warn("[Stashpad] unlock failed",o),new M.Notice(`Couldn't unlock: ${o.message}`),!1}}async lockFolder(t){let e=t.replace(/\/+$/,"");if(!await this.ensureFolderUnlocked(e))return 0;let i=[];for(let d of this.app.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let h;try{h=dt(await this.app.vault.read(d)).fm}catch{continue}let g=h.id;typeof g!="string"||g===k||(typeof h.parent=="string"?h.parent:k)!==k||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 r=(await new oi(this.app).load(e))[k]??[],l=n.length>3?new M.Notice("",0):null,c=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=r.indexOf(h),u=g>0?r[g-1]:null;await this.lockNoteSubtree(e,h,u,{silent:!0})&&c++}return l?.hide(),c>0&&this.notifications.show({message:`Locked ${c} note${c===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),c}async unlockFolder(t){let e=t.replace(/\/+$/,"");if(!await this.ensureFolderUnlocked(e))return 0;let 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(r){console.warn("[Stashpad] folder unlock skipped",i[o],r)}}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(!this.encryption.isConfigured())return new M.Notice("Set up encryption first (Settings \u2192 Stashpad \u2192 Encryption)."),0;let t=this.app.vault.getFiles().filter(d=>d.extension==="stashenc"&&(d.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(d=>d.path);if(t.length===0)return new M.Notice("No locked notes anywhere in the vault."),0;let e=t.length>3?new M.Notice("",0):null,i=new Map,s=!1,n=async d=>{if(i.has(d))return i.get(d);let h=null;return this.encryption.hasFolderKey(d)?(this.encryption.isFolderUnlocked(d)||await this.encryption.tryAutoUnlockFolder(d))&&(h=this.encryption.getFolderKey(d)):(s||(s=!0,await this.ensureEncryptionUnlocked()),h=this.encryption.getSessionKey()),i.set(d,h),h},o=0,r=[],l=new Set;for(let d=0;d<t.length;d++){e?.setMessage(`\u{1F513} Decrypting ${d+1}/${t.length}\u2026`);let h=t[d].replace(/\/[^/]*$/,"").replace(/\/+$/,""),g=await n(h);if(!g){l.add(h||"(vault root)");continue}try{let u=await this.unlockBundleCore(t[d],g);o+=u.notesWritten,r.push(t[d])}catch(u){console.warn("[Stashpad] vault unlock skipped",t[d],u)}}if(r.length>0){let d=new Set(r);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(h=>!d.has(h.blob)),await this.saveSettings()}e?.hide();for(let d of i.values())try{d?.fill(0)}catch{}let c=t[0].replace(/\/[^/]*$/,"");return o>0&&this.notifications.show({message:`Unlocked ${o} note${o===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:c}),l.size>0&&new M.Notice(`Skipped ${l.size} locked folder${l.size===1?"":"s"} (no key unlocked): ${[...l].map(d=>d.split("/").pop()||d).join(", ")}. Open each to unlock it, then run this again.`,0),o}exportLockedSubtree(t){return Ga(this,t)}folderHasStashpadNotes(t){let e=t.replace(/\/+$/,"");return this.discoverStashpadFolders().some(i=>e===i||e.startsWith(i+"/")||i.startsWith(e+"/"))}encStamp(){let t=new Date,e=i=>String(i).padStart(2,"0");return`${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}-${e(t.getHours())}${e(t.getMinutes())}`}folderKeyLabelFor(t){let e=(this.settings.authorName||"").trim(),i=e?e.split(/\s+/).map(s=>s[0]).join(""):(this.settings.authorId||"anon").slice(0,4);return`${this.encStamp()} - ${t} - ${i}`}async encryptFolderFromExplorer(t){if(!this.encryption.isConfigured()){new M.Notice("Set up Stashpad vault encryption first (Settings \u2192 Stashpad \u2192 Encryption), then try again.");return}let e=t.split("/").pop()||t;if(this.folderHasStashpadNotes(t)){await this.encryptStashpadFolder(t,e);return}if(await Do(this.app,t)){new M.Notice(`\u201C${e}\u201D is already encrypted as a Stashpad bundle. Use \u201CDecrypt with Stashpad\u201D to open it.`);return}await this.encryptRawFolder(t,e)}async encryptStashpadFolder(t,e){if(this.encryption.hasOwnFolderKey(t)){await this.ensureFolderUnlocked(t)&&await this.lockFolder(t);return}let i=this.folderKeyLabelFor(e);new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Encrypt \u201C${e}\u201D with Stashpad`,intro:"Give this folder its own password. Any Stashpad notes inside it get encrypted under it; you'll re-enter the password to unlock.",onSubmit:async({next:s,remember:n})=>{if(!s)return"Enter a password.";try{await this.encryption.setupFolderKey(t,s,i,n)}catch(r){return r.message}let o=await this.lockFolder(t);return new M.Notice(o>0?`Encrypted ${o} note${o===1?"":"s"} in \u201C${e}\u201D.`:`\u201C${e}\u201D now has a Stashpad password \u2014 notes added here will use it.`),this.refreshFolderPanels?.(),null}}).open()}async encryptRawFolder(t,e){let i=async s=>{let n=this.encryption.folderKeyEntry(t)?.keyId;try{let o=await Ta(this.app,t,s,n,this.encStamp());o.unpurged.length?new M.Notice(`Encrypted \u201C${e}\u201D (${o.fileCount} files) \u2014 but ${o.unpurged.length} file(s) changed mid-encrypt and were left in place.`):new M.Notice(`Encrypted \u201C${e}\u201D \u2014 ${o.fileCount} file(s) bundled into one encrypted file.`)}catch(o){return o.message}return this.refreshFolderPanels?.(),null};new it(this.app,`Encrypt \u201C${e}\u201D \u2014 non-Stashpad folder`,`This isn't a Stashpad folder, so its files can't be locked individually. +`)}`,0):s.silent||this.notifications.show({message:`Locked ${d.title?`\u201C${d.title}\u201D`:"a note"} (${d.noteCount} note${d.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),d}catch(a){return console.warn("[Stashpad] lock failed",a),new M.Notice(`Couldn't lock: ${a.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=dt(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}return vr(this.app,t,e,n,i)}async unlockBundleAt(t,e={}){let i=t.replace(/\/[^/]*$/,"").replace(/\/+$/,""),s=await this.ensureFolderUnlocked(i);if(!s)return!1;let n=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,"");try{let o=await this.unlockBundleCore(t,s,e.destFolder);return this.pendingEncBlobs.delete(t),this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(a=>a.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${o.notesWritten} note${o.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:n}),!0}catch(o){return console.warn("[Stashpad] unlock failed",o),new M.Notice(`Couldn't unlock: ${o.message}`),!1}}async lockFolder(t){let e=t.replace(/\/+$/,"");if(!await this.ensureFolderUnlocked(e))return 0;let i=[];for(let d of this.app.vault.getMarkdownFiles()){if((d.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let h;try{h=dt(await this.app.vault.read(d)).fm}catch{continue}let g=h.id;typeof g!="string"||g===k||(typeof h.parent=="string"?h.parent:k)!==k||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 ai(this.app).load(e))[k]??[],l=n.length>3?new M.Notice("",0):null,c=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),u=g>0?a[g-1]:null;await this.lockNoteSubtree(e,h,u,{silent:!0})&&c++}return l?.hide(),c>0&&this.notifications.show({message:`Locked ${c} note${c===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),c}async unlockFolder(t){let e=t.replace(/\/+$/,"");if(!await this.ensureFolderUnlocked(e))return 0;let 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(!this.encryption.isConfigured())return new M.Notice("Set up encryption first (Settings \u2192 Stashpad \u2192 Encryption)."),0;let t=this.app.vault.getFiles().filter(d=>d.extension==="stashenc"&&(d.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(d=>d.path);if(t.length===0)return new M.Notice("No locked notes anywhere in the vault."),0;let e=t.length>3?new M.Notice("",0):null,i=new Map,s=!1,n=async d=>{if(i.has(d))return i.get(d);let h=null;return this.encryption.hasFolderKey(d)?(this.encryption.isFolderUnlocked(d)||await this.encryption.tryAutoUnlockFolder(d))&&(h=this.encryption.getFolderKey(d)):(s||(s=!0,await this.ensureEncryptionUnlocked()),h=this.encryption.getSessionKey()),i.set(d,h),h},o=0,a=[],l=new Set;for(let d=0;d<t.length;d++){e?.setMessage(`\u{1F513} Decrypting ${d+1}/${t.length}\u2026`);let h=t[d].replace(/\/[^/]*$/,"").replace(/\/+$/,""),g=await n(h);if(!g){l.add(h||"(vault root)");continue}try{let u=await this.unlockBundleCore(t[d],g);o+=u.notesWritten,a.push(t[d])}catch(u){console.warn("[Stashpad] vault unlock skipped",t[d],u)}}if(a.length>0){let d=new Set(a);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(h=>!d.has(h.blob)),await this.saveSettings()}e?.hide();for(let d of i.values())try{d?.fill(0)}catch{}let c=t[0].replace(/\/[^/]*$/,"");return o>0&&this.notifications.show({message:`Unlocked ${o} note${o===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:c}),l.size>0&&new M.Notice(`Skipped ${l.size} locked folder${l.size===1?"":"s"} (no key unlocked): ${[...l].map(d=>d.split("/").pop()||d).join(", ")}. Open each to unlock it, then run this again.`,0),o}exportLockedSubtree(t){return Kr(this,t)}folderHasStashpadNotes(t){let e=t.replace(/\/+$/,"");return this.discoverStashpadFolders().some(i=>e===i||e.startsWith(i+"/")||i.startsWith(e+"/"))}encStamp(){let t=new Date,e=i=>String(i).padStart(2,"0");return`${t.getFullYear()}${e(t.getMonth()+1)}${e(t.getDate())}-${e(t.getHours())}${e(t.getMinutes())}`}folderKeyLabelFor(t){let e=(this.settings.authorName||"").trim(),i=e?e.split(/\s+/).map(s=>s[0]).join(""):(this.settings.authorId||"anon").slice(0,4);return`${this.encStamp()} - ${t} - ${i}`}async encryptFolderFromExplorer(t){if(!this.encryption.isConfigured()){new M.Notice("Set up Stashpad vault encryption first (Settings \u2192 Stashpad \u2192 Encryption), then try again.");return}let e=t.split("/").pop()||t;if(this.folderHasStashpadNotes(t)){await this.encryptStashpadFolder(t,e);return}if(await To(this.app,t)){new M.Notice(`\u201C${e}\u201D is already encrypted as a Stashpad bundle. Use \u201CDecrypt with Stashpad\u201D to open it.`);return}await this.encryptRawFolder(t,e)}async encryptStashpadFolder(t,e){if(this.encryption.hasOwnFolderKey(t)){await this.ensureFolderUnlocked(t)&&await this.lockFolder(t);return}let i=this.folderKeyLabelFor(e);new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Encrypt \u201C${e}\u201D with Stashpad`,intro:"Give this folder its own password. Any Stashpad notes inside it get encrypted under it; you'll re-enter the password to unlock.",onSubmit:async({next:s,remember:n})=>{if(!s)return"Enter a password.";try{await this.encryption.setupFolderKey(t,s,i,n)}catch(a){return a.message}let o=await this.lockFolder(t);return new M.Notice(o>0?`Encrypted ${o} note${o===1?"":"s"} in \u201C${e}\u201D.`:`\u201C${e}\u201D now has a Stashpad password \u2014 notes added here will use it.`),this.refreshFolderPanels?.(),null}}).open()}async encryptRawFolder(t,e){let i=async s=>{let n=this.encryption.folderKeyEntry(t)?.keyId;try{let o=await Hr(this.app,t,s,n,this.encStamp());o.unpurged.length?new M.Notice(`Encrypted \u201C${e}\u201D (${o.fileCount} files) \u2014 but ${o.unpurged.length} file(s) changed mid-encrypt and were left in place.`):new M.Notice(`Encrypted \u201C${e}\u201D \u2014 ${o.fileCount} file(s) bundled into one encrypted file.`)}catch(o){return o.message}return this.refreshFolderPanels?.(),null};new it(this.app,`Encrypt \u201C${e}\u201D \u2014 non-Stashpad folder`,`This isn't a Stashpad folder, so its files can't be locked individually. Stashpad will bundle EVERY file in this folder into one encrypted file and permanently delete the originals (no copy left in Obsidian's trash \u2014 that would defeat encryption). -This can't be undone with Cmd+Z; the only way back is \u201CDecrypt with Stashpad\u201D + the password. Continue?`,"Bundle & encrypt",s=>{if(!s)return;if(this.encryption.hasOwnFolderKey(t)){(async()=>{let o=await this.ensureFolderUnlocked(t);if(!o)return;let r=await i(o);r&&new M.Notice(r)})();return}let n=this.folderKeyLabelFor(e);new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Encrypt \u201C${e}\u201D with Stashpad`,intro:"Set a password for this bundle. You'll re-enter it to decrypt the whole folder.",onSubmit:async({next:o,remember:r})=>{if(!o)return"Enter a password.";try{await this.encryption.setupFolderKey(t,o,n,r)}catch(c){return c.message}let l=this.encryption.getFolderKey(t);return l?await i(l):"Couldn't derive the folder key."}}).open()}).open()}async decryptFolderFromExplorer(t){let e=await Do(this.app,t);if(!e){new M.Notice("No Stashpad bundle found in this folder.");return}let i=t.split("/").pop()||t,s=await this.ensureFolderUnlocked(t);if(s){try{let n=await Pa(this.app,e,s);new M.Notice(`Decrypted \u201C${i}\u201D \u2014 restored ${n.filesWritten} file(s).`)}catch(n){new M.Notice(`Couldn't decrypt: ${n.message}`)}this.refreshFolderPanels?.()}}rotationLockPath(t){let e=t.replace(/\/+$/,""),i=e.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,40)||"root",s=0;for(let n=0;n<e.length;n++)s=s*31+e.charCodeAt(n)|0;return`.stashpad/rotating-${i}-${(s>>>0).toString(36)}.lock`}async commitRotTemps(t){for(let e of await Ma(this.app,t))try{await tn(this.app,e)}catch(i){console.warn("[Stashpad] rot-commit failed",e,i)}}async rotateFolderKey(t,e,i=!1){let s=t.replace(/\/+$/,"");if(!e)return new M.Notice("A new password is required to rotate."),-1;let n=await this.ensureFolderUnlocked(s);if(!n)return-1;let o=this.encryption.folderKeyEntry(s)?.folderPath??s,r=this.rotationLockPath(o);if(await this.app.vault.adapter.exists(r))return new M.Notice("A rotation is already in progress for this folder (or one was interrupted \u2014 reload to recover)."),-1;let l=I=>I===o||I.startsWith(o+"/"),c=this.app.vault.getFiles().filter(I=>I.extension==="stashenc"&&l(I.parent?.path?.replace(/\/+$/,"")??"")).map(I=>I.path),d=this.encryption.folderKeyEntry(o)?.keyId,h=d?await bo(this.app,d):[],g=[...c,...h],u=crypto.getRandomValues(new Uint8Array(32)),p=[...crypto.getRandomValues(new Uint8Array(8))].map(I=>I.toString(16).padStart(2,"0")).join(""),f=g.length>0?new M.Notice("",0):null;try{await this.app.vault.adapter.write(r,JSON.stringify({folder:o,phase:"encrypting",at:new Date().toISOString()}));for(let I=0;I<g.length;I++)f?.setMessage(`\u{1F504} Re-encrypting ${I+1}/${g.length}\u2026`),await xa(this.app,g[I],n,u);await this.app.vault.adapter.write(r,JSON.stringify({folder:o,phase:"committing",rotId:p,at:new Date().toISOString()})),await this.encryption.commitFolderRotation(o,e,u,p,void 0,i),f?.setMessage("\u{1F504} Finalizing\u2026"),await this.commitRotTemps(o);for(let I of h){await tn(this.app,I);try{await Na(this.app,I,n,u)}catch(m){console.warn("[Stashpad] trash sidecar rewrap failed",I,m)}}try{await this.app.vault.adapter.remove(r)}catch{}return f?.hide(),new M.Notice(`\u{1F511} Rotated the key for \u201C${o.split("/").pop()}\u201D \u2014 ${g.length} item${g.length===1?"":"s"} re-encrypted. The OLD password no longer unlocks it; share the new one with anyone who should keep access.`,0),g.length}catch(I){f?.hide();try{await en(this.app,o)}catch{}for(let m of h)try{await this.app.vault.adapter.remove(`${m}.rot`)}catch{}try{await this.app.vault.adapter.remove(r)}catch{}return console.warn("[Stashpad] rotation failed",I),new M.Notice(`Rotation failed: ${I.message}. Nothing was changed (originals intact).`,0),-1}finally{u.fill(0)}}async resumeRotations(){let t=[];try{t=(await this.app.vault.adapter.list(".stashpad")).files.filter(e=>/\/rotating-[^/]+\.lock$/.test(e))}catch{return}if(t.length!==0){await this.encryption.refresh();for(let e of t){let i={};try{i=JSON.parse(await this.app.vault.adapter.read(e))}catch{}let s=(i.folder??"").replace(/\/+$/,"");if(!s){try{await this.app.vault.adapter.remove(e)}catch{}continue}let n=this.encryption.folderKeyEntry(s);if(!!i.rotId&&n?.rotId===i.rotId){if(await this.commitRotTemps(s),n?.keyId)for(let r of await bo(this.app,n.keyId))try{await tn(this.app,r)}catch(l){console.warn("[Stashpad] resume trash-commit failed",r,l)}new M.Notice(`Finished an interrupted key rotation for \u201C${s.split("/").pop()}\u201D.`,0)}else{try{await en(this.app,s)}catch{}try{await en(this.app,"_deleted")}catch{}}try{await this.app.vault.adapter.remove(e)}catch{}}}}async encryptDeleteSubtree(t,e){let i=await this.ensureFolderUnlocked(t);if(!i)return null;try{let s=new Date().toISOString(),o=(((this.settings.folderEncPrefs??{})[t.replace(/\/+$/,"")]??{}).trashEncryptFilenames??!1)||(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),r=this.encryption.folderKeyEntry(t)?.keyId,l=await Fa(this.app,t,e,i,s,o,r);return this.pendingEncBlobs.add(l.blobPath),l.unpurged.length>0&&new M.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${l.unpurged.length} file${l.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): +This can't be undone with Cmd+Z; the only way back is \u201CDecrypt with Stashpad\u201D + the password. Continue?`,"Bundle & encrypt",s=>{if(!s)return;if(this.encryption.hasOwnFolderKey(t)){(async()=>{let o=await this.ensureFolderUnlocked(t);if(!o)return;let a=await i(o);a&&new M.Notice(a)})();return}let n=this.folderKeyLabelFor(e);new ct(this.app,{mode:"setup",offerKeychain:!0,title:`Encrypt \u201C${e}\u201D with Stashpad`,intro:"Set a password for this bundle. You'll re-enter it to decrypt the whole folder.",onSubmit:async({next:o,remember:a})=>{if(!o)return"Enter a password.";try{await this.encryption.setupFolderKey(t,o,n,a)}catch(c){return c.message}let l=this.encryption.getFolderKey(t);return l?await i(l):"Couldn't derive the folder key."}}).open()}).open()}async decryptFolderFromExplorer(t){let e=await To(this.app,t);if(!e){new M.Notice("No Stashpad bundle found in this folder.");return}let i=t.split("/").pop()||t,s=await this.ensureFolderUnlocked(t);if(s){try{let n=await Ur(this.app,e,s);new M.Notice(`Decrypted \u201C${i}\u201D \u2014 restored ${n.filesWritten} file(s).`)}catch(n){new M.Notice(`Couldn't decrypt: ${n.message}`)}this.refreshFolderPanels?.()}}rotationLockPath(t){let e=t.replace(/\/+$/,""),i=e.replace(/[^a-zA-Z0-9]+/g,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,40)||"root",s=0;for(let n=0;n<e.length;n++)s=s*31+e.charCodeAt(n)|0;return`.stashpad/rotating-${i}-${(s>>>0).toString(36)}.lock`}async commitRotTemps(t){for(let e of await Pr(this.app,t))try{await on(this.app,e)}catch(i){console.warn("[Stashpad] rot-commit failed",e,i)}}async rotateFolderKey(t,e,i=!1){let s=t.replace(/\/+$/,"");if(!e)return new M.Notice("A new password is required to rotate."),-1;let n=await this.ensureFolderUnlocked(s);if(!n)return-1;let o=this.encryption.folderKeyEntry(s)?.folderPath??s,a=this.rotationLockPath(o);if(await this.app.vault.adapter.exists(a))return new M.Notice("A rotation is already in progress for this folder (or one was interrupted \u2014 reload to recover)."),-1;let l=I=>I===o||I.startsWith(o+"/"),c=this.app.vault.getFiles().filter(I=>I.extension==="stashenc"&&l(I.parent?.path?.replace(/\/+$/,"")??"")).map(I=>I.path),d=this.encryption.folderKeyEntry(o)?.keyId,h=d?await Mo(this.app,d):[],g=[...c,...h],u=crypto.getRandomValues(new Uint8Array(32)),p=[...crypto.getRandomValues(new Uint8Array(8))].map(I=>I.toString(16).padStart(2,"0")).join(""),f=g.length>0?new M.Notice("",0):null;try{await this.app.vault.adapter.write(a,JSON.stringify({folder:o,phase:"encrypting",at:new Date().toISOString()}));for(let I=0;I<g.length;I++)f?.setMessage(`\u{1F504} Re-encrypting ${I+1}/${g.length}\u2026`),await Mr(this.app,g[I],n,u);await this.app.vault.adapter.write(a,JSON.stringify({folder:o,phase:"committing",rotId:p,at:new Date().toISOString()})),await this.encryption.commitFolderRotation(o,e,u,p,void 0,i),f?.setMessage("\u{1F504} Finalizing\u2026"),await this.commitRotTemps(o);for(let I of h){await on(this.app,I);try{await Tr(this.app,I,n,u)}catch(m){console.warn("[Stashpad] trash sidecar rewrap failed",I,m)}}try{await this.app.vault.adapter.remove(a)}catch{}return f?.hide(),new M.Notice(`\u{1F511} Rotated the key for \u201C${o.split("/").pop()}\u201D \u2014 ${g.length} item${g.length===1?"":"s"} re-encrypted. The OLD password no longer unlocks it; share the new one with anyone who should keep access.`,0),g.length}catch(I){f?.hide();try{await an(this.app,o)}catch{}for(let m of h)try{await this.app.vault.adapter.remove(`${m}.rot`)}catch{}try{await this.app.vault.adapter.remove(a)}catch{}return console.warn("[Stashpad] rotation failed",I),new M.Notice(`Rotation failed: ${I.message}. Nothing was changed (originals intact).`,0),-1}finally{u.fill(0)}}async resumeRotations(){let t=[];try{t=(await this.app.vault.adapter.list(".stashpad")).files.filter(e=>/\/rotating-[^/]+\.lock$/.test(e))}catch{return}if(t.length!==0){await this.encryption.refresh();for(let e of t){let i={};try{i=JSON.parse(await this.app.vault.adapter.read(e))}catch{}let s=(i.folder??"").replace(/\/+$/,"");if(!s){try{await this.app.vault.adapter.remove(e)}catch{}continue}let n=this.encryption.folderKeyEntry(s);if(!!i.rotId&&n?.rotId===i.rotId){if(await this.commitRotTemps(s),n?.keyId)for(let a of await Mo(this.app,n.keyId))try{await on(this.app,a)}catch(l){console.warn("[Stashpad] resume trash-commit failed",a,l)}new M.Notice(`Finished an interrupted key rotation for \u201C${s.split("/").pop()}\u201D.`,0)}else{try{await an(this.app,s)}catch{}try{await an(this.app,"_deleted")}catch{}}try{await this.app.vault.adapter.remove(e)}catch{}}}}async encryptDeleteSubtree(t,e){let i=await this.ensureFolderUnlocked(t);if(!i)return null;try{let s=new Date().toISOString(),o=(((this.settings.folderEncPrefs??{})[t.replace(/\/+$/,"")]??{}).trashEncryptFilenames??!1)||(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),a=this.encryption.folderKeyEntry(t)?.keyId,l=await Sr(this.app,t,e,i,s,o,a);return this.pendingEncBlobs.add(l.blobPath),l.unpurged.length>0&&new M.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${l.unpurged.length} file${l.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): ${l.unpurged.join(` -`)}`,0),l.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={}){let i=await he(this.app,t),s;if(i?.keyId){let n=this.encryption.folderPathByKeyId(i.keyId);if(s=n?await this.ensureFolderUnlocked(n):null,!s)return e.silent||new M.Notice("Couldn't unlock the folder key this trashed note was encrypted with."),!1}else{if(!await this.ensureEncryptionUnlocked())return!1;s=this.encryption.getSessionKey()}if(!s)return!1;if(i?.kind==="rawtrash")try{let n=await Da(this.app,t,s);return this.pendingEncBlobs.delete(t),e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Ut}/).`,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 ko(this.app,t,i,s),o=new Set;for(let l of this.app.vault.getMarkdownFiles())if((l.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let c=dt(await this.app.vault.read(l)).fm.id;typeof c=="string"&&o.add(c)}catch{}let r=await ka(this.app,t,s,o);return this.pendingEncBlobs.delete(t),e.silent||this.notifications.show({message:`Restored ${r.notesWritten} note${r.notesWritten===1?"":"s"} to \u201C${r.restoredTo.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:r.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 So(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 So(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 sn(this.app),e=[];for(let i of t)e.push({blob:i,meta:await he(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 ba(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),l.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={}){let i=await he(this.app,t),s;if(i?.keyId){let n=this.encryption.folderPathByKeyId(i.keyId);if(s=n?await this.ensureFolderUnlocked(n):null,!s)return e.silent||new M.Notice("Couldn't unlock the folder key this trashed note was encrypted with."),!1}else{if(!await this.ensureEncryptionUnlocked())return!1;s=this.encryption.getSessionKey()}if(!s)return!1;if(i?.kind==="rawtrash")try{let n=await Nr(this.app,t,s);return this.pendingEncBlobs.delete(t),e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Ut}/).`,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 xo(this.app,t,i,s),o=new Set;for(let l of this.app.vault.getMarkdownFiles())if((l.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let c=dt(await this.app.vault.read(l)).fm.id;typeof c=="string"&&o.add(c)}catch{}let a=await br(this.app,t,s,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 No(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 No(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 rn(this.app),e=[];for(let i of t)e.push({blob:i,meta:await he(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 xr(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 ${Ut}/.`,kind:"success",category:"system",folder:""}),!0):(new M.Notice(`Obsidian's vault trash (${Ut}/) 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 Stashpad \u2192 Encryption).");return}Oa(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new M.Notice("Set up encryption first (Settings \u2192 Stashpad \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 on(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)?!0:!!(this.settings.folderEncPrefs??{})[e]?.archive}async ensureOkfTemplate(){let t=await Va(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||Po}okfActiveFolders(){return this.settings.okfEnabled?za(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}async rebuildOkfSuppressed(t){this.okfRebuildingFolders.add(t);try{return await Uo(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=[],r=[],l=[],c=new Set;for(let I of e){let m=await Fe(this.app,n,I);if(m){o.push({id:m.rootNote.id,file:m.rootNote.file}),l.push(m.rootNote.file),c.add(m.rootNote.id);for(let C of m.descendants)r.push({id:C.id,file:C.file}),l.push(C.file),c.add(C.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,""),u=`${n}/${g}`;for(let I of[n,u])try{await this.app.vault.adapter.exists(I)||await this.app.vault.adapter.mkdir(I)}catch{}let p=[],f=async(I,m)=>{let C=`${u}/${I}`;await this.app.vault.createBinary(C,m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)),p.push(C)};if(s.zip||s.targz){let I=await Wa(this.app,l,n,c);s.zip&&await f(`${d}-${h}.okf.zip`,await Xa(I)),s.targz&&await f(`${d}-${h}.okf.tar.gz`,await Za(I))}if(s.stash){let I=await Ee(this.app,{rootNotes:o,allDescendants:r,sourceFolder:n});await f(`${d}-${h}.${te}`,I)}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=dt(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 r=[],l=[],c=[],d=[];for(let E of e){let S=await Fe(this.app,t,E);if(S){c.push(S.rootNote.id),r.push({id:S.rootNote.id,file:S.rootNote.file}),d.push(S.rootNote.file);for(let D of S.descendants)l.push({id:D.id,file:D.file}),d.push(D.file)}}if(!r.length)return null;let h=r.length+l.length,g=[],u=[];n==="cut"&&(g=await this.exclusiveAttachmentsOf(d),u=await this.snapshotPaths([...d.map(E=>E.path),...g.map(E=>E.path)]));let p=await Ee(this.app,{rootNotes:r,allDescendants:l,sourceFolder:t}),f=await this.idsInFolder(o),I=new Set(this.filesUnder(o)),m=await ee(this.app,p,o,f,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),C=this.filesUnder(o).filter(E=>!I.has(E)),B=await this.snapshotPaths(C),w=c.map(E=>m.idRemap[E]).filter(E=>!!E);if(n==="cut"){for(let E of d)try{await this.app.fileManager.trashFile(E)}catch(S){console.warn("[Stashpad] cross-folder move: couldn't trash source note",E.path,S)}for(let E of g)try{await this.app.fileManager.trashFile(E)}catch(S){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",E.path,S)}}let y=async()=>{for(let E of[...C].reverse()){let S=this.app.vault.getAbstractFileByPath(E);if(S)try{await this.app.fileManager.trashFile(S)}catch{}}};return{rootIds:w,noteCount:h,undo:n==="cut"?async()=>{await y(),await this.restoreSnapshot(u)}:async()=>{await y()},redo:n==="cut"?async()=>{await this.restoreSnapshot(B);for(let E of u){let S=this.app.vault.getAbstractFileByPath(E.path);if(S)try{await this.app.fileManager.trashFile(S)}catch{}}}:async()=>{await this.restoreSnapshot(B)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let r=await Fe(this.app,t,o);r&&i.push(r.rootNote.file,...r.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(r){console.warn("[Stashpad] trashSubtrees: couldn't trash",o.path,r)}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 Ws(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 Fe(this.app,t,n);o&&i.push(o.rootNote.file,...o.descendants.map(r=>r.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 r=this.app.metadataCache.getFileCache(o)?.frontmatter?.position;return typeof r=="number"?r:Number.MAX_SAFE_INTEGER};for(let o of e){let r=await Fe(this.app,t,o);if(!r)continue;let l=new Map;for(let d of r.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 c=(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)??[])c(g,h+1)}};c({id:r.rootNote.id,file:r.rootNote.file,created:r.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(/\/+$/,"");if(!((this.settings.folderEncPrefs??{})[i]?.archiveEncryptContent??!0))return;let s=[];for(let c of e){let d=this.app.vault.getAbstractFileByPath(c);if(!(d instanceof M.TFile)||(d.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let h;try{h=dt(await this.app.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===k||s.push({id:g,parent:typeof h.parent=="string"?h.parent:null})}if(s.length===0)return;let n=new Set(s.map(c=>c.id)),o=new Set((this.settings.lockedSubtrees??[]).map(c=>c.rootId).filter(c=>!!c)),r=s.filter(c=>!o.has(c.id)&&!(c.parent&&n.has(c.parent)));if(r.length===0)return;if(!await this.ensureEncryptionUnlocked()){new M.Notice(`\u26A0\uFE0F Archive folder "${i.split("/").pop()}": ${r.length} arriving note${r.length===1?"":"s"} NOT encrypted (vault is locked). Unlock encryption and lock them manually.`,0);return}let l=0;for(let c of r)await this.lockNoteSubtree(i,c.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 f=i(p);return(p.isDeferred?f.folderOverride??"":p.view?.noteFolder??f.folderOverride??"").replace(/\/+$/,"")},n=p=>{let f=i(p);return(p.isDeferred?f.focusId:p.view?.focusId??f.focusId)||k},o=p=>{let f=p.view;return!!f&&f.getViewType?.()===K&&typeof f.navigateTo=="function"&&typeof f.noteFolder=="string"},r=new Map;for(let p of this.app.vault.getMarkdownFiles()){let f=(p.parent?.path??"").replace(/\/+$/,""),I=this.app.metadataCache.getFileCache(p)?.frontmatter?.id;typeof I=="string"&&I&&(r.get(f)??r.set(f,new Set).get(f)).add(I)}let l=0,c=[];for(let p of t){let f=s(p),I=n(p);if(f&&I&&I!==k){let m=!p.isDeferred&&!!p.view?.tree?.get?.(I),C=r.get(f)?.has(I)??!1;if(!m&&!C){p.detach(),l++;continue}}c.push(p)}let d=new Map;for(let p of c){let f=s(p);if(!f)continue;let I=f+" "+n(p);(d.get(I)??d.set(I,[]).get(I)).push(p)}let h=0;for(let p of d.values()){if(p.length<=1)continue;p.sort((I,m)=>{let C=B=>B===e?2:B.isDeferred?0:1;return C(m)-C(I)});let f=null;for(let I of p){try{await I.loadIfDeferred?.()}catch{}if(o(I)){f=I;break}}f||(f=p[0]);for(let I of p)I!==f&&(I.detach(),h++)}let g=this.app.workspace.getLeavesOfType(K).length,u=document.createDocumentFragment();return u.createEl("div",{text:h+l>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),u.createEl("div",{text:`\u2022 ${h} duplicate tab${h===1?"":"s"} closed`}),u.createEl("div",{text:`\u2022 ${l} orphaned tab${l===1?"":"s"} pruned (note no longer exists)`}),u.createEl("div",{text:`\u2022 ${g} Stashpad tab${g===1?"":"s"} remaining`}),new M.Notice(u,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 r=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],c=r.includes(e),d=l.some(p=>p.includes(e));if(!c&&!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 u=s.get(g);c&&u.authored++,d&&u.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return fe(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(c=>c.path.startsWith(s+"/")&&this.parseAuthorFilePath(c.path)?.id===e))return!1;let o=this.authorRegistry.get(e),r=this.authorNameToSafe(i),l=`${s}/${r}-${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(c){return console.warn("[Stashpad] ensureAuthorStubFor failed",l,c),!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 r=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!r||r.due==null)continue;let l=typeof r.id=="string"?r.id:"";if(!l)continue;let c=String(r.due),d=typeof r.due=="number"?r.due:Date.parse(c);if(!Number.isFinite(d)||d>t)continue;let h=De(r);if(h.length>0&&!(i&&h.some(u=>u.id===i)))continue;let g=`${l}@${c}`;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=dt(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(c=>c.trim()).find(c=>c.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 r=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${r}\u201D (${re(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(c=>typeof c=="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 r=[];if(typeof o.author=="string"&&r.push(o.author),Array.isArray(o.contributors))for(let l of o.contributors)typeof l=="string"&&r.push(l);for(let l of r){let c=this.parseAuthorRef(l);if(c)if(!e.has(c.id))e.set(c.id,{id:c.id,name:c.name,fromStub:!1}),i++;else{let d=e.get(c.id);!d.name&&c.name&&(d.name=c.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let r of this.app.vault.getMarkdownFiles()){if(!r.path.startsWith(o+"/"))continue;let l=this.parseAuthorFilePath(r.path);if(!l)continue;let c=this.app.metadataCache.getFileCache(r)?.frontmatter,h=((Array.isArray(c?.aliases)?c.aliases.find(f=>typeof f=="string")??"":typeof c?.aliases=="string"?c.aliases:"")||(typeof c?.name=="string"?c.name:"")||l.name).trim(),g=typeof c?.role=="string"?c.role:void 0,u=typeof c?.department=="string"?c.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:u??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=r=>r.replace(/[\r\n]+/g," ").trim(),s=r=>i(r).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`,r=new Set;for(let l of i){if(!l.path.startsWith(o+"/"))continue;let c=this.parseAuthorFilePath(l.path)?.id;c&&r.add(c)}for(let l of t){if(r.has(l.id))continue;let c=this.authorNameToSafe(l.name),d=`${o}/${c}-${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+"/")||$e(n.path))continue;let r=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!r||typeof r.id!="string"||!r.id)continue;let l=r.attachments,c=Array.isArray(l),d=typeof l=="string"&&l.trim().length>0;if(!(!c&&!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(u=>typeof u=="string"&&u.trim()?$t(u):u):typeof g.attachments=="string"&&g.attachments.trim()&&(g.attachments=[$t(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 Lo(this.app,e,t,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(c){this.notifications.show({message:`Stashpad: import failed in \`${e}\` -Error: ${c.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,c);return}let o=i+s+n,r=this.lastActiveStashpadLeaf?.view;o>0&&r?.noteFolder===t&&r?.tree&&(r.tree.rebuild(t),r.render?.());let l;if(o===0)l=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let c=[];i&&c.push(`${i} loose file${i===1?"":"s"}`),s&&c.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&c.push(`${n} .stash bundle${n===1?"":"s"}`),l=`Imported ${c.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 li(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),r=`${s}/${o}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(r)?!1:(await this.app.vault.create(r,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",r,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={...Be,...t,shortcuts:{...Be.shortcuts,...t?.shortcuts??{}},mod:{...Be.mod,...t?.mod??{}},bindings:$c(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:Vc(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Vt]},oo(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(r=>typeof r=="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?.[Ot];if(Array.isArray(i)&&i.some(s=>t.has(ns(s)??"")))try{await this.app.fileManager.processFrontMatter(e,s=>{let o=(Array.isArray(s[Ot])?s[Ot]:[]).filter(r=>!t.has(ns(r)??""));o.length?s[Ot]=o:delete s[Ot]})}catch{}}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),oo(this.settings),vt.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,u=typeof g?.id=="string"?g.id.trim():"";u&&e.add(u)}let{newId:s}=await Promise.resolve().then(()=>(Gt(),cs)),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 u=this.app.metadataCache.getFileCache(h)?.frontmatter,p=typeof u?.id=="string"?u.id.trim():"",f=u?.parent,I=typeof f=="string"?f.trim()!=="":f!=null,m=typeof u?.created=="string"&&u.created.trim()!=="",C=!p,B=!I,w=!m;!C&&!B&&!w||o.push({file:h,addId:C,addParent:B,addCreated:w})}if(o.length===0){new M.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let r=0,l=0,c=this.newLog();for(let h of o)try{let g;await this.app.fileManager.processFrontMatter(h.file,f=>{if(h.addId&&(typeof f.id=="string"&&f.id.trim()||(g=n(),f.id=g)),h.addParent){let I=f.parent;(typeof I=="string"?I.trim()!=="":I!=null)||(f.parent=k)}h.addCreated&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(h.file.stat.ctime).toISOString()))});let u=this.app.metadataCache.getFileCache(h.file)?.frontmatter,p=g??u?.id??"";p&&await c.append({type:"parent_change",id:p,payload:{from:null,to:k,reason:"orphan_fix",path:h.file.path,addedId:h.addId,addedParent:h.addParent,addedCreated:h.addCreated}}),r++}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 ${r} note${r===1?"":"s"} in Stashpad folders${d}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Gt(),cs)),i=new Set;for(let c of this.app.vault.getMarkdownFiles()){if(c.path===t.path)continue;let d=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof d?.id=="string"?d.id.trim():"";h&&i.add(h)}let s=()=>{for(let c=0;c<50;c++){let d=e();if(!i.has(d))return d}for(let c=8;c<=16;c+=2){let d=e(c);if(!i.has(d))return d}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,c=>{let d=typeof c.id=="string"?c.id.trim():"";!d||/\s/.test(d)||i.has(d)?(c.id=s(),n.push("id")):o.push("id"),c.parent!==void 0&&c.parent!==null&&String(c.parent).trim()!==""?o.push("parent"):(c.parent=k,n.push("parent")),typeof c.created=="string"&&c.created.trim()!==""?o.push("created"):(c.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(c){new M.Notice(`Adopt failed: ${c.message}`);return}let r=!1;try{let c=this.app.metadataCache.getFileCache(t)?.frontmatter,d=typeof c?.id=="string"?c.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),r=!0)}}catch(c){console.warn("Stashpad: adopt rename failed",c)}if(n.length===0&&!r){new M.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let l=[];n.length&&l.push(`added: ${n.join(", ")}`),r&&l.push("renamed with id"),new M.Notice(`Adopted into Stashpad \u2014 ${l.join("; ")}.`);try{let c=this.newLog(),d=this.app.metadataCache.getFileCache(t)?.frontmatter,h=d?.id??"";h&&await c.append({type:"create",id:h,payload:{path:t.path,parent:d?.parent??k,source:"adopt",added:n}})}catch{}}};ss.DEBUG_BUFFER_MAX=300;var Cn=ss;function $c(A,a,t){let e=no();for(let i of si){let s=a&&typeof a[i.id]=="string"?a[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(A&&typeof A=="object")for(let i of si){let s=A[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 si){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 Vc(A){let a={};if(!A||typeof A!="object")return a;for(let[t,e]of Object.entries(A))if(typeof e=="string")a[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){a[t]=i;break}}return a}var Lo=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)}},qo=class extends M.SuggestModal{constructor(t,e,i){super(t);this.bundles=e;this.onPick=i;this.setPlaceholder("Choose an encrypted folder bundle to decrypt\u2026")}getSuggestions(t){let e=t.toLowerCase();return this.bundles.filter(i=>i.folder.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.folder||"(vault root)"}),e.createDiv({cls:"stashpad-suggest-note",text:t.blobPath})}onChooseSuggestion(t){this.onPick(t)}}; +`)}`,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 ${Ut}/.`,kind:"success",category:"system",folder:""}),!0):(new M.Notice(`Obsidian's vault trash (${Ut}/) 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 Stashpad \u2192 Encryption).");return}$r(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new M.Notice("Set up encryption first (Settings \u2192 Stashpad \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 cn(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)?!0:!!(this.settings.folderEncPrefs??{})[e]?.archive}async ensureOkfTemplate(){let t=await Wr(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||Go}okfActiveFolders(){return this.settings.okfEnabled?Xr(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}async rebuildOkfSuppressed(t){this.okfRebuildingFolders.add(t);try{return await Ko(this.app,t)}finally{window.setTimeout(()=>{this.okfRebuildingFolders.delete(t);for(let e of this.app.workspace.getLeavesOfType(q)){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=[],c=new Set;for(let I of e){let m=await Fe(this.app,n,I);if(m){o.push({id:m.rootNote.id,file:m.rootNote.file}),l.push(m.rootNote.file),c.add(m.rootNote.id);for(let C of m.descendants)a.push({id:C.id,file:C.file}),l.push(C.file),c.add(C.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,""),u=`${n}/${g}`;for(let I of[n,u])try{await this.app.vault.adapter.exists(I)||await this.app.vault.adapter.mkdir(I)}catch{}let p=[],f=async(I,m)=>{let C=`${u}/${I}`;await this.app.vault.createBinary(C,m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)),p.push(C)};if(s.zip||s.targz){let I=await Zr(this.app,l,n,c);s.zip&&await f(`${d}-${h}.okf.zip`,await jr(I)),s.targz&&await f(`${d}-${h}.okf.tar.gz`,await _r(I))}if(s.stash){let I=await Ee(this.app,{rootNotes:o,allDescendants:a,sourceFolder:n});await f(`${d}-${h}.${te}`,I)}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=dt(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=[],c=[],d=[];for(let E of e){let S=await Fe(this.app,t,E);if(S){c.push(S.rootNote.id),a.push({id:S.rootNote.id,file:S.rootNote.file}),d.push(S.rootNote.file);for(let D of S.descendants)l.push({id:D.id,file:D.file}),d.push(D.file)}}if(!a.length)return null;let h=a.length+l.length,g=[],u=[];n==="cut"&&(g=await this.exclusiveAttachmentsOf(d),u=await this.snapshotPaths([...d.map(E=>E.path),...g.map(E=>E.path)]));let p=await Ee(this.app,{rootNotes:a,allDescendants:l,sourceFolder:t}),f=await this.idsInFolder(o),I=new Set(this.filesUnder(o)),m=await ee(this.app,p,o,f,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),C=this.filesUnder(o).filter(E=>!I.has(E)),B=await this.snapshotPaths(C),w=c.map(E=>m.idRemap[E]).filter(E=>!!E);if(n==="cut"){for(let E of d)try{await this.app.fileManager.trashFile(E)}catch(S){console.warn("[Stashpad] cross-folder move: couldn't trash source note",E.path,S)}for(let E of g)try{await this.app.fileManager.trashFile(E)}catch(S){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",E.path,S)}}let y=async()=>{for(let E of[...C].reverse()){let S=this.app.vault.getAbstractFileByPath(E);if(S)try{await this.app.fileManager.trashFile(S)}catch{}}};return{rootIds:w,noteCount:h,undo:n==="cut"?async()=>{await y(),await this.restoreSnapshot(u)}:async()=>{await y()},redo:n==="cut"?async()=>{await this.restoreSnapshot(B);for(let E of u){let S=this.app.vault.getAbstractFileByPath(E.path);if(S)try{await this.app.fileManager.trashFile(S)}catch{}}}:async()=>{await this.restoreSnapshot(B)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let a=await Fe(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 _s(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 Fe(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 Fe(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 c=(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)??[])c(g,h+1)}};c({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(q)){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(/\/+$/,"");if(!((this.settings.folderEncPrefs??{})[i]?.archiveEncryptContent??!0))return;let s=[];for(let c of e){let d=this.app.vault.getAbstractFileByPath(c);if(!(d instanceof M.TFile)||(d.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let h;try{h=dt(await this.app.vault.read(d)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===k||s.push({id:g,parent:typeof h.parent=="string"?h.parent:null})}if(s.length===0)return;let n=new Set(s.map(c=>c.id)),o=new Set((this.settings.lockedSubtrees??[]).map(c=>c.rootId).filter(c=>!!c)),a=s.filter(c=>!o.has(c.id)&&!(c.parent&&n.has(c.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 c of a)await this.lockNoteSubtree(i,c.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:q,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(q),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(q),e=this.app.workspace.activeLeaf;for(let p of t)try{await p.loadIfDeferred?.()}catch{}let i=p=>p.getViewState()?.state??{},s=p=>{let f=i(p);return(p.isDeferred?f.folderOverride??"":p.view?.noteFolder??f.folderOverride??"").replace(/\/+$/,"")},n=p=>{let f=i(p);return(p.isDeferred?f.focusId:p.view?.focusId??f.focusId)||k},o=p=>{let f=p.view;return!!f&&f.getViewType?.()===q&&typeof f.navigateTo=="function"&&typeof f.noteFolder=="string"},a=new Map;for(let p of this.app.vault.getMarkdownFiles()){let f=(p.parent?.path??"").replace(/\/+$/,""),I=this.app.metadataCache.getFileCache(p)?.frontmatter?.id;typeof I=="string"&&I&&(a.get(f)??a.set(f,new Set).get(f)).add(I)}let l=0,c=[];for(let p of t){let f=s(p),I=n(p);if(f&&I&&I!==k){let m=!p.isDeferred&&!!p.view?.tree?.get?.(I),C=a.get(f)?.has(I)??!1;if(!m&&!C){p.detach(),l++;continue}}c.push(p)}let d=new Map;for(let p of c){let f=s(p);if(!f)continue;let I=f+" "+n(p);(d.get(I)??d.set(I,[]).get(I)).push(p)}let h=0;for(let p of d.values()){if(p.length<=1)continue;p.sort((I,m)=>{let C=B=>B===e?2:B.isDeferred?0:1;return C(m)-C(I)});let f=null;for(let I of p){try{await I.loadIfDeferred?.()}catch{}if(o(I)){f=I;break}}f||(f=p[0]);for(let I of p)I!==f&&(I.detach(),h++)}let g=this.app.workspace.getLeavesOfType(q).length,u=document.createDocumentFragment();return u.createEl("div",{text:h+l>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),u.createEl("div",{text:`\u2022 ${h} duplicate tab${h===1?"":"s"} closed`}),u.createEl("div",{text:`\u2022 ${l} orphaned tab${l===1?"":"s"} pruned (note no longer exists)`}),u.createEl("div",{text:`\u2022 ${g} Stashpad tab${g===1?"":"s"} remaining`}),new M.Notice(u,7e3),h+l}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(q).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"):[],c=a.includes(e),d=l.some(p=>p.includes(e));if(!c&&!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 u=s.get(g);c&&u.authored++,d&&u.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return fe(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(c=>c.path.startsWith(s+"/")&&this.parseAuthorFilePath(c.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(c){return console.warn("[Stashpad] ensureAuthorStubFor failed",l,c),!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 c=String(a.due),d=typeof a.due=="number"?a.due:Date.parse(c);if(!Number.isFinite(d)||d>t)continue;let h=De(a);if(h.length>0&&!(i&&h.some(u=>u.id===i)))continue;let g=`${l}@${c}`;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=dt(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(c=>c.trim()).find(c=>c.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 (${ae(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(c=>typeof c=="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 c=this.parseAuthorRef(l);if(c)if(!e.has(c.id))e.set(c.id,{id:c.id,name:c.name,fromStub:!1}),i++;else{let d=e.get(c.id);!d.name&&c.name&&(d.name=c.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let l=this.parseAuthorFilePath(a.path);if(!l)continue;let c=this.app.metadataCache.getFileCache(a)?.frontmatter,h=((Array.isArray(c?.aliases)?c.aliases.find(f=>typeof f=="string")??"":typeof c?.aliases=="string"?c.aliases:"")||(typeof c?.name=="string"?c.name:"")||l.name).trim(),g=typeof c?.role=="string"?c.role:void 0,u=typeof c?.department=="string"?c.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:u??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 c=this.parseAuthorFilePath(l.path)?.id;c&&a.add(c)}for(let l of t){if(a.has(l.id))continue;let c=this.authorNameToSafe(l.name),d=`${o}/${c}-${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+"/")||$e(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let l=a.attachments,c=Array.isArray(l),d=typeof l=="string"&&l.trim().length>0;if(!(!c&&!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(u=>typeof u=="string"&&u.trim()?$t(u):u):typeof g.attachments=="string"&&g.attachments.trim()&&(g.attachments=[$t(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 Oo(this.app,e,t,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(c){this.notifications.show({message:`Stashpad: import failed in \`${e}\` +Error: ${c.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,c);return}let o=i+s+n,a=this.lastActiveStashpadLeaf?.view;o>0&&a?.noteFolder===t&&a?.tree&&(a.tree.rebuild(t),a.render?.());let l;if(o===0)l=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let c=[];i&&c.push(`${i} loose file${i===1?"":"s"}`),s&&c.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&c.push(`${n} .stash bundle${n===1?"":"s"}`),l=`Imported ${c.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 ci(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={...Be,...t,shortcuts:{...Be.shortcuts,...t?.shortcuts??{}},mod:{...Be.mod,...t?.mod??{}},bindings:zc(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:Wc(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Vt]},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?.[Ot];if(Array.isArray(i)&&i.some(s=>t.has(os(s)??"")))try{await this.app.fileManager.processFrontMatter(e,s=>{let o=(Array.isArray(s[Ot])?s[Ot]:[]).filter(a=>!t.has(os(a)??""));o.length?s[Ot]=o:delete s[Ot]})}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),vt.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,u=typeof g?.id=="string"?g.id.trim():"";u&&e.add(u)}let{newId:s}=await Promise.resolve().then(()=>(Gt(),hs)),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 u=this.app.metadataCache.getFileCache(h)?.frontmatter,p=typeof u?.id=="string"?u.id.trim():"",f=u?.parent,I=typeof f=="string"?f.trim()!=="":f!=null,m=typeof u?.created=="string"&&u.created.trim()!=="",C=!p,B=!I,w=!m;!C&&!B&&!w||o.push({file:h,addId:C,addParent:B,addCreated:w})}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,c=this.newLog();for(let h of o)try{let g;await this.app.fileManager.processFrontMatter(h.file,f=>{if(h.addId&&(typeof f.id=="string"&&f.id.trim()||(g=n(),f.id=g)),h.addParent){let I=f.parent;(typeof I=="string"?I.trim()!=="":I!=null)||(f.parent=k)}h.addCreated&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(h.file.stat.ctime).toISOString()))});let u=this.app.metadataCache.getFileCache(h.file)?.frontmatter,p=g??u?.id??"";p&&await c.append({type:"parent_change",id:p,payload:{from:null,to:k,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(()=>(Gt(),hs)),i=new Set;for(let c of this.app.vault.getMarkdownFiles()){if(c.path===t.path)continue;let d=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof d?.id=="string"?d.id.trim():"";h&&i.add(h)}let s=()=>{for(let c=0;c<50;c++){let d=e();if(!i.has(d))return d}for(let c=8;c<=16;c+=2){let d=e(c);if(!i.has(d))return d}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,c=>{let d=typeof c.id=="string"?c.id.trim():"";!d||/\s/.test(d)||i.has(d)?(c.id=s(),n.push("id")):o.push("id"),c.parent!==void 0&&c.parent!==null&&String(c.parent).trim()!==""?o.push("parent"):(c.parent=k,n.push("parent")),typeof c.created=="string"&&c.created.trim()!==""?o.push("created"):(c.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(c){new M.Notice(`Adopt failed: ${c.message}`);return}let a=!1;try{let c=this.app.metadataCache.getFileCache(t)?.frontmatter,d=typeof c?.id=="string"?c.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(c){console.warn("Stashpad: adopt rename failed",c)}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 c=this.newLog(),d=this.app.metadataCache.getFileCache(t)?.frontmatter,h=d?.id??"";h&&await c.append({type:"create",id:h,payload:{path:t.path,parent:d?.parent??k,source:"adopt",added:n}})}catch{}}};ns.DEBUG_BUFFER_MAX=300;var Qn=ns;function zc(A,r,t){let e=lo();for(let i of ni){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(A&&typeof A=="object")for(let i of ni){let s=A[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 ni){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 Wc(A){let r={};if(!A||typeof A!="object")return r;for(let[t,e]of Object.entries(A))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 Oo=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)}},Yo=class extends M.SuggestModal{constructor(t,e,i){super(t);this.bundles=e;this.onPick=i;this.setPlaceholder("Choose an encrypted folder bundle to decrypt\u2026")}getSuggestions(t){let e=t.toLowerCase();return this.bundles.filter(i=>i.folder.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.folder||"(vault root)"}),e.createDiv({cls:"stashpad-suggest-note",text:t.blobPath})}onChooseSuggestion(t){this.onPick(t)}}; /*! Bundled license information: hash-wasm/dist/index.esm.js: diff --git a/manifest.json b/manifest.json index feacb8c..ccf1e98 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.121.1", + "version": "0.121.13", "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 24f74fc..9d79ac0 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.121.1", + "version": "0.121.13", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.121.13.md b/release-notes/0.121.13.md new file mode 100644 index 0000000..6ce4c63 --- /dev/null +++ b/release-notes/0.121.13.md @@ -0,0 +1,51 @@ +# 0.121.13 β€” Settings overhaul: clearer structure, polish, and a date-format fix + +A settings-focused release: the tabs are reorganized, long-standing alignment +and padding issues are fixed, the per-folder icon picker becomes searchable, the +hotkey UI is reworked, and a date-format bug is fixed. + +## Reorganized settings tabs +- **Behavior** β€” the six toggle-only sections (List & Display, Moving Notes, + Composer & Copying, Deleting, Windows & Tabs, Misc) are now one **πŸŽ›οΈ Behavior** + tab, each kept as a labelled sub-heading. +- **Organization Systems** β€” **JD Index** and **Open Knowledge Format (OKF)** are + folded into one **πŸ—‚οΈ Organization Systems** tab. +- **Note Titles** is no longer its own tab β€” the "Slug stop-words" setting moves + to the end of **Folders & Storage** under a "Note Titles" heading. + +## Per-folder icon picker is now searchable +- The **Folder tab icon** box is type-ahead: start typing and matching Lucide + icons appear with live previews β€” no need to know icon ids by heart. + +## Date & time +- **Fix:** with "Use Templates plugin date/time formats" OFF, the notes-list + timestamps now follow the **Date display format** dropdown (and timezone) like + the Tasks/detail panels do β€” previously the list ignored the dropdown and was + hardcoded to `YYYY.MM.DD`. +- The Dates & Time section is reordered (display format first, then the Templates + toggle) with clearer descriptions. + +## Hotkeys +- The two key slots now **stack vertically** with the active-binding control on + the left, so the binding inputs sit at the right edge. +- The old L/R pill + "Use both" checkbox are replaced by a single + **Left | Both | Right** segmented control (disabled until both slots are bound). +- Chord slots are styled as compact rounded key-chips; the clear/revert buttons + stack on mobile. + +## Layout & padding polish +- Settings sections that previously sat flush against the modal edge are now + inset to align with the rest: the Cross-Stashpad Search Scope and Folder Panel + Placement lists, the JD Index description, the live date sample, and the + "Folders you've worked in" / Known Authors lists (the authored-folders list + also gains a heading). +- Each settings page gets breathing room at the bottom; folded-tab sub-headings + get top padding so the first one isn't cramped under the page title. +- The encryption no-recovery advice banner gets more padding. +- The JD "Actions" buttons wrap on mobile instead of running off the edge. + +## Internal +- The JD Index description is now built with safe DOM calls instead of an HTML + string (clears the last `no-inner-html` lint the store review flags). +- Clarified OKF copy to point at **Stashpad's own Templates section**, not + Obsidian's core Templates plugin. diff --git a/src/icon-suggest.ts b/src/icon-suggest.ts new file mode 100644 index 0000000..8d54d91 --- /dev/null +++ b/src/icon-suggest.ts @@ -0,0 +1,58 @@ +import { AbstractInputSuggest, App, getIconIds, setIcon } from "obsidian"; + +/** Lucide icon-name autocomplete for a settings text input β€” type a few letters + * and pick from matching icons (each shown WITH its preview) instead of having + * to know icon ids by heart. Mirrors {@link FolderSuggest}. + * + * Stores the bare name (strips the internal "lucide-" prefix) since that's what + * `setIcon` + the rest of the plugin already use (`rocket`, not `lucide-rocket`). + * + * Wire it up: + * ``` + * .addText((t) => { + * new IconSuggest(this.app, t.inputEl); + * t.setValue(...).onChange(...); + * }) + * ``` + * 0.121.10. */ +export class IconSuggest extends AbstractInputSuggest<string> { + constructor(app: App, private inputEl: HTMLInputElement) { + super(app, inputEl); + } + + private static norm(id: string): string { + return id.replace(/^lucide-/, ""); + } + + protected getSuggestions(query: string): string[] { + // all-tokens, any-order match so "arrow up" finds "arrow-up", "move-up", etc. + const tokens = query.toLowerCase().split(/\s+/).filter(Boolean); + const seen = new Set<string>(); + const ids: string[] = []; + for (const raw of getIconIds()) { + const id = IconSuggest.norm(raw); + if (seen.has(id)) continue; + seen.add(id); + ids.push(id); + } + const match = (id: string): boolean => tokens.every((t) => id.toLowerCase().includes(t)); + const out = tokens.length ? ids.filter(match) : ids; + // Cap the list β€” the popover only renders a window anyway, and an unfiltered + // getIconIds() is ~1.5k entries. + return out.sort().slice(0, 50); + } + + renderSuggestion(id: string, el: HTMLElement): void { + el.addClass("stashpad-icon-suggest-item"); + const ic = el.createSpan({ cls: "stashpad-icon-suggest-icon" }); + setIcon(ic, id); + el.createSpan({ cls: "stashpad-icon-suggest-label", text: id }); + } + + selectSuggestion(id: string): void { + this.setValue(id); + // Fire `input` so the caller's onChange listener persists + repaints. + this.inputEl.dispatchEvent(new Event("input", { bubbles: true })); + this.close(); + } +} diff --git a/src/settings.ts b/src/settings.ts index 9f8d620..fb5c929 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -6,6 +6,7 @@ function osFileManagerName(): string { } import { buildJdIndexPreview, buildJdIndexNotes, scanForJdNotes, JdBuildConfirmModal, buildJdPreviewNotice } from "./index-builder"; import { FolderSuggest } from "./folder-suggest"; +import { IconSuggest } from "./icon-suggest"; import type StashpadPlugin from "./main"; import { RESERVED_FRONTMATTER, type ViewMode } from "./types"; import { type SplitMode } from "./view-helpers"; @@ -650,29 +651,25 @@ export function getTemplatesFormats(app: App): { dateFormat: string; timeFormat: * is the source of truth for both the bar at the top and the * search-mode group order. Order here = display order. */ export type SettingsTabId = - | "foldersStorage" | "importExport" | "noteTitles" | "datesTime" | "listDisplay" - | "movingNotes" | "deleting" | "composerCopy" | "windowsTabs" | "notifications" - | "encryption" | "authorship" | "templates" | "jdindex" | "okf" - | "maintenance" | "diagnostics" | "misc" | "hotkeys"; + | "foldersStorage" | "importExport" | "datesTime" | "behaviors" + | "notifications" | "encryption" | "authorship" | "templates" + | "organizationSystems" | "maintenance" | "diagnostics" | "hotkeys"; export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = ([ { 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" }, + // 0.121.9: the six toggle-only sections (List & Display, Moving Notes, + // Deleting, Composer & Copying, Windows & Tabs, Misc) are folded into one + // "Behavior" tab as sub-headings (see itemsForTab). + { id: "behaviors", label: "πŸŽ›οΈ Behavior" }, { 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)" }, + // 0.121.9: JD Index + OKF folded into one "Organization Systems" tab. + { id: "organizationSystems", label: "πŸ—‚οΈ Organization Systems" }, { id: "maintenance", label: "πŸ› οΈ Maintenance" }, { 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. @@ -792,23 +789,32 @@ export class StashpadSettingTab extends PluginSettingTab { // General split into focused categories (0.110.0) β€” each pulls its bucket. 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; + // 0.121.9: "Behavior" merges the six toggle-only sections, each kept as a + // labelled sub-heading so the groupings still read clearly. + case "behaviors": { + const c = this.buildGeneralCategories(); + return [ + this.headingDef("πŸ“‹ List & Display"), ...c.listDisplay, + this.headingDef("↕️ Moving Notes"), ...c.movingNotes, + this.headingDef("✍️ Composer & Copying"), ...c.composerCopy, + this.headingDef("πŸ—‘οΈ Deleting"), ...c.deleting, + this.headingDef("πŸͺŸ Windows & Tabs"), ...c.windowsTabs, + this.headingDef("βš™οΈ Misc"), ...c.misc, + ]; + } + // 0.121.9: "Organization Systems" merges JD Index + OKF as sub-sections. + case "organizationSystems": return [ + this.headingDef("πŸ”’ JD Index (Johnny Decimal)"), ...this.jdIndexItems(), + this.headingDef("πŸ“š Open Knowledge Format (OKF)"), ...this.okfItems(), + ]; case "encryption": return this.encryptionItems(); // 0.99.15: authorship/templates/jdindex decomposed too β€” static fields as // per-setting items, the per-folder editors as sectionDefs (rendered fresh // at display) β€” so individual settings are searchable, not just page names. case "authorship": return this.authorshipItems(); case "templates": return this.templatesItems(); - case "jdindex": return this.jdIndexItems(); - case "okf": return this.okfItems(); default: return null; } } @@ -820,8 +826,8 @@ export class StashpadSettingTab extends PluginSettingTab { switch (tab) { case "authorship": this.renderAuthorshipSection(parent); break; case "templates": this.renderTemplatesTab(parent); break; - case "jdindex": this.renderJdIndexSection(parent); break; - // hotkeys migrated to declarative items (itemsForTab) β€” never routed here. + // jdindex/okf now live under the "Organization Systems" tab (declarative + // items via itemsForTab); hotkeys are declarative too β€” neither routed here. } } @@ -1192,7 +1198,7 @@ export class StashpadSettingTab extends PluginSettingTab { * bucket to its own settings page. Anything that doesn't fit a precise * category goes to `misc`. */ private buildGeneralCategories(): Record< - "foldersStorage" | "importExport" | "datesTime" | "noteTitles" | "listDisplay" + "foldersStorage" | "importExport" | "datesTime" | "listDisplay" | "movingNotes" | "deleting" | "composerCopy" | "windowsTabs" | "maintenance" | "misc", SettingDefinitionItem[] > { @@ -1206,7 +1212,6 @@ export class StashpadSettingTab extends PluginSettingTab { foldersStorage: [] as SettingDefinitionItem[], importExport: [] as SettingDefinitionItem[], datesTime: [] as SettingDefinitionItem[], - noteTitles: [] as SettingDefinitionItem[], listDisplay: [] as SettingDefinitionItem[], movingNotes: [] as SettingDefinitionItem[], deleting: [] as SettingDefinitionItem[], @@ -1250,7 +1255,7 @@ export class StashpadSettingTab extends PluginSettingTab { // 0.118.6: per-folder tab icon β€” moved here from the Encryption tab's // per-folder panel so it's searchable. Pick a folder, then enter a Lucide // icon id; a live preview shows whether it's valid. - cats.foldersStorage.push(this.renderDef("Folder tab icon", "Give a folder its own Lucide icon (e.g. rocket, star, book-open) shown on its tab, the folder switcher, and its folder-panel row. Pick a folder, then enter an icon id (browse at lucide.dev). Blank = the default icon. Set per folder.", (s) => { + cats.foldersStorage.push(this.renderDef("Folder tab icon", "Give a folder its own Lucide icon (e.g. rocket, star, book-open) shown on its tab, the folder switcher, and its folder-panel row. Pick a folder, then start typing in the icon box β€” matching icons appear with previews; pick one. Blank = the default icon. Set per folder.", (s) => { const folders = this.plugin.discoverStashpadFolders(); if (folders.length === 0) { s.setDesc("No Stashpad folders found yet."); return; } if (!this.iconPickFolder || !folders.includes(this.iconPickFolder)) this.iconPickFolder = folders[0]; @@ -1264,9 +1269,11 @@ export class StashpadSettingTab extends PluginSettingTab { }); s.addText((t) => { textComp = t; - t.setPlaceholder("list-tree"); + t.setPlaceholder("type to search… (e.g. rocket)"); + // 0.121.10: type-ahead icon search with previews β€” no need to know ids. + new IconSuggest(this.app, t.inputEl); t.setValue(this.plugin.getFolderIcon(this.iconPickFolder!) ?? ""); - t.onChange(async (v) => { paint(v); await this.plugin.setFolderIcon(this.iconPickFolder!, v); }); + t.onChange(async (v) => { paint(v); await this.plugin.setFolderIcon(this.iconPickFolder!, v.trim()); }); }); paint(this.plugin.getFolderIcon(this.iconPickFolder) ?? ""); }, ["icon", "folder", "tab", "lucide", "emoji", "switcher"])); @@ -1306,24 +1313,16 @@ export class StashpadSettingTab extends PluginSettingTab { this.plugin.settings.writeRecoveryLinks = v; await set(); })), ["recovery", "parentlink", "children", "frontmatter"])); - cats.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((t) => t.setValue(this.plugin.settings.useTemplatesFormat).onChange(async (v) => { - this.plugin.settings.useTemplatesFormat = v; await set(); - })); - const fmt = getTemplatesFormats(this.app); - s.descEl.createDiv({ cls: "stashpad-settings-note" }).setText(fmt - ? `Templates plugin: date = "${fmt.dateFormat}", time = "${fmt.timeFormat}"` - : "Templates plugin not enabled."); - }, ["templates", "date", "time", "format"])); - - // Date display block β€” dropdown + timezone share a live sample element. + // Date display block β€” dropdown leads (it now drives EVERY timestamp surface: + // notes list, Tasks, detail panel), then the Templates-format toggle, the + // timezone, and a live sample. 0.121.7: reordered + copy updated. { let sampleEl: HTMLElement | null = null; const refreshSample = () => { if (!sampleEl) return; sampleEl.setText(`Sample: ${formatDateTime(Date.now(), this.plugin.settings)}`); }; - cats.datesTime.push(this.renderDef("Date display format", "How due dates and created/modified times are shown in the Tasks and detail panels.", (s) => { + cats.datesTime.push(this.renderDef("Date display format", "How created / edited timestamps and due dates are shown β€” in the notes list, the Tasks panel, and the detail panel. Overridden by the Templates-plugin formats when the option below is on.", (s) => { s.addDropdown((d) => { d.addOption("locale", "Locale, short (Mar 5, 9:00 AM)"); d.addOption("long", "Locale, long (Thursday, March 5…)"); @@ -1334,6 +1333,15 @@ export class StashpadSettingTab extends PluginSettingTab { d.onChange(async (v) => { this.plugin.settings.dateDisplayFormat = v as any; await set(); refreshSample(); }); }); }, ["date", "format", "display"])); + cats.datesTime.push(this.renderDef("Use Templates plugin date/time formats", "Use the date/time formats configured in the core Templates plugin instead of the Date display format above. Off = the Date display format above is used everywhere.", (s) => { + s.addToggle((t) => t.setValue(this.plugin.settings.useTemplatesFormat).onChange(async (v) => { + this.plugin.settings.useTemplatesFormat = v; await set(); refreshSample(); + })); + const fmt = getTemplatesFormats(this.app); + s.descEl.createDiv({ cls: "stashpad-settings-note" }).setText(fmt + ? `Templates plugin: date = "${fmt.dateFormat}", time = "${fmt.timeFormat}"` + : "Templates plugin not enabled."); + }, ["templates", "date", "time", "format"])); cats.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.", (s) => { s.addText((t) => { t.setPlaceholder("(system timezone)"); @@ -1344,8 +1352,10 @@ export class StashpadSettingTab extends PluginSettingTab { cats.datesTime.push({ name: "Date sample", searchable: false, render: (s: Setting) => { - const host = s.settingEl; host.empty(); host.removeClass("setting-item"); - sampleEl = host.createDiv({ cls: "setting-item-description stashpad-settings-note" }); + // 0.121.5: mark the host as a settings-section so the sample picks up + // the standard 14px inset (otherwise it sits flush against the edge). + const host = s.settingEl; host.empty(); host.removeClass("setting-item"); host.addClass("stashpad-settings-section"); + sampleEl = host.createDiv({ cls: "setting-item-description stashpad-settings-note stashpad-date-sample" }); refreshSample(); }, }); @@ -1372,26 +1382,6 @@ export class StashpadSettingTab extends PluginSettingTab { cats.deleting.push(toggle("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 ![[…]] 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, (v) => { this.plugin.settings.confirmAttachmentDelete = v; }, ["delete", "attachment", "orphan"])); - cats.noteTitles.push(this.renderDef("Slug stop-words", "Words removed from auto-generated note titles (filenames). One per line.", (s) => { - let textarea: HTMLTextAreaElement | null = null; - const initial = (this.plugin.settings.slugStopWords?.length ? this.plugin.settings.slugStopWords : DEFAULT_STOPWORDS).join("\n"); - s.addTextArea((t) => { - t.setValue(initial); - textarea = (t as any).inputEl as HTMLTextAreaElement; - textarea.rows = 6; - textarea.setCssStyles({ fontFamily: "var(--font-monospace)" }); - t.onChange(async (v) => { - this.plugin.settings.slugStopWords = (v || "").split(/\r?\n/).map((x) => x.trim().toLowerCase()).filter(Boolean); - await set(); - }); - }).addExtraButton((b) => - b.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async () => { - this.plugin.settings.slugStopWords = [...DEFAULT_STOPWORDS]; - if (textarea) textarea.value = DEFAULT_STOPWORDS.join("\n"); - await set(); - })); - }, ["slug", "stopwords", "filename", "title"])); - cats.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.", (host) => { const folders = this.plugin.discoverStashpadFolders(); new Setting(host) @@ -1433,6 +1423,29 @@ export class StashpadSettingTab extends PluginSettingTab { this.renderFolderPlacementList(host); }, ["folder", "panel", "pin", "pinned", "downrank", "hide", "hidden", "restore", "placement"])); + // 0.121.6: Note Titles folded into Folders & Storage as a trailing + // sub-section (was its own tab). Keep the labelled "🏷️ Note Titles" header. + cats.foldersStorage.push(this.headingDef("🏷️ Note Titles")); + cats.foldersStorage.push(this.renderDef("Slug stop-words", "Words removed from auto-generated note titles (filenames). One per line.", (s) => { + let textarea: HTMLTextAreaElement | null = null; + const initial = (this.plugin.settings.slugStopWords?.length ? this.plugin.settings.slugStopWords : DEFAULT_STOPWORDS).join("\n"); + s.addTextArea((t) => { + t.setValue(initial); + textarea = (t as any).inputEl as HTMLTextAreaElement; + textarea.rows = 6; + textarea.setCssStyles({ fontFamily: "var(--font-monospace)" }); + t.onChange(async (v) => { + this.plugin.settings.slugStopWords = (v || "").split(/\r?\n/).map((x) => x.trim().toLowerCase()).filter(Boolean); + await set(); + }); + }).addExtraButton((b) => + b.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async () => { + this.plugin.settings.slugStopWords = [...DEFAULT_STOPWORDS]; + if (textarea) textarea.value = DEFAULT_STOPWORDS.join("\n"); + await set(); + })); + }, ["slug", "stopwords", "filename", "title", "note titles"])); + cats.composerCopy.push(toggle("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 β€” useful if you want arrow keys to work without an extra click.", () => this.plugin.settings.autofocusComposerAfterSend, (v) => { this.plugin.settings.autofocusComposerAfterSend = v; }, ["composer", "focus", "send"])); cats.windowsTabs.push(toggle("Open in new window β€” duplicate tab", "ON: the new-window button (in the time-filter row) duplicates the current Stashpad tab β€” original stays open in the main window. OFF: the leaf is MOVED to the new window, closing the original tab.", @@ -1845,12 +1858,29 @@ export class StashpadSettingTab extends PluginSettingTab { private renderJdIndexSection(containerEl: HTMLElement): void { const header = new Setting(containerEl).setName("JD Index Builder").setHeading(); header.settingEl.id = "stashpad-jd-index-section"; - const blurb = containerEl.createEl("p", { cls: "setting-item-description" }); - blurb.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β†’parent 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.'; + // 0.121.2: render the description into a .stashpad-settings-section host so + // it picks up the standard 14px inset (a bare <p> on containerEl sits flush + // against the modal edge β€” it's not a Setting row and not a section child). + const blurb = containerEl.createEl("div", { cls: "stashpad-settings-section" }) + .createEl("p", { cls: "setting-item-description" }); + // 0.121.4: built with safe DOM helpers instead of innerHTML (the Obsidian + // store linter flags raw HTML strings). Same rendered output: <br> breaks, + // <strong> command names, <code> prefix examples. + blurb.appendText("Builds a Johnny-Decimal-style index inside a designated Stashpad folder. Two commands:"); + blurb.createEl("br"); + blurb.createEl("strong", { text: "Preview" }); + blurb.appendText(" 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."); + blurb.createEl("br"); + blurb.createEl("strong", { text: "Build" }); + blurb.appendText(" creates an actual hierarchy of Stashpad notes (one per prefix), with childβ†’parent relationships matching the dotted segments."); + blurb.createEl("br"); + blurb.appendText("Matches strict prefixes only: all-digits ("); + blurb.createEl("code", { text: "10 Life" }); + blurb.appendText(") or alphanumeric-with-dots ("); + blurb.createEl("code", { text: "1.2 Family" }); + blurb.appendText(", "); + blurb.createEl("code", { text: "animal.duck.yellow Eggs" }); + blurb.appendText("). Mixed schemes sort numbers first, then alphabetically."); const stashpadFolders = this.plugin.discoverStashpadFolders(); @@ -1923,7 +1953,8 @@ export class StashpadSettingTab extends PluginSettingTab { // Preview line: shows current counts before building. const scan = scanForJdNotes(this.app, this.plugin, this.plugin.settings); - const previewEl = containerEl.createEl("p", { cls: "setting-item-description" }); + const previewEl = containerEl.createEl("div", { cls: "stashpad-settings-section" }) + .createEl("p", { cls: "setting-item-description" }); const skippedSuffix = scan.skippedStashpadNotes.length > 0 ? ` (${scan.skippedStashpadNotes.length} Stashpad-folder note${scan.skippedStashpadNotes.length === 1 ? "" : "s"} excluded by default)` : ""; @@ -1934,6 +1965,7 @@ export class StashpadSettingTab extends PluginSettingTab { new Setting(containerEl) .setName("Actions") + .setClass("stashpad-jd-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((b) => { b.setButtonText("Preview"); @@ -2158,6 +2190,8 @@ export class StashpadSettingTab extends PluginSettingTab { /** The "folders you've worked in" list, extracted so the authorship sectionDef * can render it fresh at display time. */ private renderAuthoredFolders(parent: HTMLElement): void { + // 0.121.5: this sectionDef renders no heading of its own, so label the list. + new Setting(parent).setName("Folders you've worked in").setHeading(); const folders = this.plugin.collectAuthoredFolders(); if (folders.length === 0) { parent.createEl("p", { cls: "setting-item-description", text: "No authored or contributed folders yet." }); return; } const list = parent.createDiv({ cls: "stashpad-authored-folders-list" }); @@ -2227,7 +2261,7 @@ export class StashpadSettingTab extends PluginSettingTab { new Setting(parent) .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 β†’ Templates (all / some / none β€” 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.")) + .setDesc(this.codeDesc("Master switch. When on, you choose which folders use OKF by assigning the OKF template to them in Stashpad's own Templates section (the πŸ“„ Templates settings here β€” NOT Obsidian's core Templates plugin) β€” all / some / none, 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((t) => t.setValue(this.plugin.settings.okfEnabled).onChange(async (v) => { this.plugin.settings.okfEnabled = v; await this.plugin.saveSettings(); @@ -2244,7 +2278,7 @@ export class StashpadSettingTab extends PluginSettingTab { const steps = parent.createEl("div", { cls: "setting-item-description stashpad-okf-howto" }); steps.createEl("p", { text: "How to use OKF in a folder:" }); const ol = steps.createEl("ol"); - this.appendCode(ol.createEl("li"), `Open Templates and set a folder's template to \`${okfPath}\` (archive folders are skipped).`); + this.appendCode(ol.createEl("li"), `Open Stashpad's πŸ“„ Templates section (here in Stashpad's settings β€” not Obsidian's core Templates plugin) and set a folder's template to \`${okfPath}\` (archive folders are skipped).`); this.appendCode(ol.createEl("li"), "Hit Rebuild below to write OKF frontmatter (`okfParent`/`okfChildren` + `okfType`/`okfTitle`/`okfTimestamp`) and generate that folder's `index.md`."); this.appendCode(ol.createEl("li"), "Right-click a note (or a selection) β†’ β€œExport as OKF…” to save a `.zip` / `.tar.gz` bundle (or `.stash`)."); steps.createEl("p", { cls: "stashpad-okf-soon", text: "OKF frontmatter + index.md refresh automatically a few seconds after you add, move, or delete notes β€” NOT instantly. Use Rebuild for an immediate pass." }); @@ -2817,15 +2851,28 @@ export class StashpadSettingTab extends PluginSettingTab { /** One settings row: label + 2 chord recorders + active-slot toggle. */ private renderBindingRow(row: Setting, meta: CommandMeta): void { row.setName(meta.label).setDesc(meta.desc); + row.settingEl.addClass("stashpad-binding-row"); const get = () => this.plugin.settings.bindings[meta.id]; let primaryInput: HTMLInputElement; let secondaryInput: HTMLInputElement; - // Late-bound: assigned once the pill toggle is built below. let refreshToggle = (): void => {}; + // 0.121.11 (#8/#9): a tri-state segmented control (Left | Both | Right) on + // the LEFT, then the two key slots STACKED on the right β€” replacing the old + // L/R pill + separate "Use both" checkbox. `setState` is assigned once the + // slots exist (below); the buttons just call it. + let setState = async (_s: "left" | "both" | "right"): Promise<void> => {}; + const seg = row.controlEl.createDiv({ cls: "stashpad-binding-seg", attr: { role: "group", "aria-label": "Active binding" } }); + const segBtns = { + left: seg.createEl("button", { cls: "stashpad-binding-seg-btn", text: "Left" }), + both: seg.createEl("button", { cls: "stashpad-binding-seg-btn", text: "Both" }), + right: seg.createEl("button", { cls: "stashpad-binding-seg-btn", text: "Right" }), + }; + (["left", "both", "right"] as const).forEach((k) => { segBtns[k].onclick = () => void setState(k); }); + const slotsCol = row.controlEl.createDiv({ cls: "stashpad-binding-slots" }); const renderSlot = (which: "primary" | "secondary"): HTMLInputElement => { - const wrap = row.controlEl.createDiv({ cls: "stashpad-binding-slot" }); + const wrap = slotsCol.createDiv({ cls: "stashpad-binding-slot" }); const input = wrap.createEl("input", { type: "text" }); input.readOnly = true; input.placeholder = "Click & press a key"; @@ -2850,7 +2897,10 @@ export class StashpadSettingTab extends PluginSettingTab { syncRevert(); }); }; - const clearBtn = wrap.createEl("button", { cls: "stashpad-binding-clear", text: "Γ—" }); + // 0.121.12 (#4): clear (Γ—) + revert (β†Ί) share a wrapper so they can stack + // vertically on mobile instead of widening the row. + const slotBtns = wrap.createDiv({ cls: "stashpad-binding-slot-btns" }); + const clearBtn = slotBtns.createEl("button", { cls: "stashpad-binding-clear", text: "Γ—" }); clearBtn.title = "Clear this slot"; clearBtn.onclick = async () => { this.plugin.settings.bindings[meta.id][which] = ""; @@ -2866,7 +2916,7 @@ export class StashpadSettingTab extends PluginSettingTab { // one click. Hidden when the slot already matches its default (nothing to // revert). A slot with no default ("") only shows it after the user binds // something, and reverting then clears the slot. - const revertBtn = wrap.createEl("button", { cls: "stashpad-binding-revert" }); + const revertBtn = slotBtns.createEl("button", { cls: "stashpad-binding-revert" }); setIcon(revertBtn, "rotate-ccw"); const syncRevert = (): void => { const cur = get()[which]; @@ -2892,23 +2942,14 @@ export class StashpadSettingTab extends PluginSettingTab { secondaryInput = renderSlot("secondary"); void primaryInput; void secondaryInput; - // Active-slot pill toggle: a rounded track with a sliding knob whose - // label is "L" when on the left (primary active) and "R" when on the - // right (secondary active). Greyed out unless BOTH slots are bound. - const pill = row.controlEl.createDiv({ cls: "stashpad-binding-pill" }); - pill.setAttribute("role", "switch"); - pill.setAttribute("tabindex", "0"); - const knob = pill.createDiv({ cls: "stashpad-binding-pill-knob" }); - - // 0.59.1: "Use both" checkbox β€” when checked, both bindings fire and - // the L/R pill becomes a no-op (visually greyed). Only meaningful - // when both slots are filled. - const bothWrap = row.controlEl.createDiv({ cls: "stashpad-binding-useboth" }); - const bothCb = bothWrap.createEl("input", { type: "checkbox" }); - bothCb.title = "Use both bindings simultaneously (overrides the L/R toggle)"; - bothWrap.createSpan({ text: "Use both" }); - bothCb.onchange = async () => { - this.plugin.settings.bindings[meta.id].useBoth = bothCb.checked; + // 0.121.11: tri-state behaviour. Left = primary only, Right = secondary + // only, Both = both fire. Only meaningful once BOTH slots are bound (until + // then the lone bound slot just fires and the control is disabled). + setState = async (state: "left" | "both" | "right"): Promise<void> => { + const b = this.plugin.settings.bindings[meta.id]; + if (!(b.primary && b.secondary)) return; + if (state === "both") { b.useBoth = true; } + else { b.useBoth = false; b.preferRight = state === "right"; } await this.plugin.saveSettings(); refreshToggle(); }; @@ -2916,36 +2957,15 @@ export class StashpadSettingTab extends PluginSettingTab { refreshToggle = (): void => { const b = get(); const both = !!(b.primary && b.secondary); - bothCb.checked = !!b.useBoth; - bothCb.disabled = !both; - bothWrap.toggleClass("is-disabled", !both); - const useBoth = !!b.useBoth && both; - // L/R pill: disabled when fewer than two slots OR when useBoth wins. - pill.toggleClass("is-disabled", !both || useBoth); - pill.toggleClass("is-right", b.preferRight); - pill.setAttribute("aria-checked", String(b.preferRight)); - pill.setAttribute("aria-disabled", String(!both || useBoth)); - knob.setText(b.preferRight ? "R" : "L"); - pill.title = !both - ? "Set both slots to enable the toggle" - : useBoth - ? "Overridden by \"Use both\"" - : (b.preferRight ? "Right slot active β€” click for left" : "Left slot active β€” click for right"); - }; - - const flip = async () => { - const b = get(); - if (!b.primary || !b.secondary) return; - this.plugin.settings.bindings[meta.id].preferRight = !b.preferRight; - refreshToggle(); - await this.plugin.saveSettings(); - }; - pill.onclick = () => void flip(); - pill.onkeydown = (e) => { - if (e.key === " " || e.key === "Enter") { - e.preventDefault(); - void flip(); - } + const active: "left" | "both" | "right" = b.useBoth ? "both" : (b.preferRight ? "right" : "left"); + (["left", "both", "right"] as const).forEach((k) => { + segBtns[k].toggleClass("is-active", both && k === active); + segBtns[k].disabled = !both; + }); + seg.toggleClass("is-disabled", !both); + seg.title = both + ? "Which binding is active β€” Left, Both, or Right" + : "Bind both slots to choose Left / Both / Right"; }; refreshToggle(); diff --git a/src/view.ts b/src/view.ts index 282c856..34522e2 100644 --- a/src/view.ts +++ b/src/view.ts @@ -9,7 +9,7 @@ import { } from "./types"; import { TreeIndex } from "./tree-index"; import { perf } from "./perf"; -import { formatDateTime } from "./format"; +import { formatDateTime, formatDateOnly, formatTimeOnly } from "./format"; import { OrderStore } from "./order-store"; import { SortStore, SORT_MODE_LABELS, SORT_MODES_ORDER } from "./sort-store"; import { FrontmatterSyncQueue, rebootstrapFolderFrontmatter } from "./frontmatter-sync"; @@ -11021,7 +11021,12 @@ export class StashpadView extends ItemView { const fmt = getTemplatesFormats(this.app); if (fmt) return `${d.format(fmt.dateFormat)}\n${d.format(fmt.timeFormat)}`; } - return `${d.format("YYYY.MM.DD")}\n${d.format("HH:mm A")}`; + // 0.121.7: when NOT using the Templates plugin format, honour the user's + // "Date display format" dropdown (+ timezone) for the two-line list + // timestamp β€” previously this ignored the dropdown and was hardcoded to + // YYYY.MM.DD / HH:mm A, so the dropdown only affected the detail/tasks panels. + const ms = d.valueOf(); + return `${formatDateOnly(ms, settings)}\n${formatTimeOnly(ms, settings)}`; } /** public: read by extracted command modules (commands/*.ts). */ formatTimeInline(iso: string): string { diff --git a/styles.css b/styles.css index bd5cf50..d7c6546 100644 --- a/styles.css +++ b/styles.css @@ -893,6 +893,27 @@ flex: 0 0 auto; } /* 0.118.0: live preview swatch next to the per-folder icon input in settings. */ +/* 0.121.10: icon-search suggestion rows (IconSuggest) β€” preview + id label. */ +.stashpad-icon-suggest-item { + display: flex; + align-items: center; + gap: 10px; +} +.stashpad-icon-suggest-icon { + display: inline-flex; + align-items: center; + justify-content: center; + flex: 0 0 auto; + width: 20px; + height: 20px; + color: var(--text-normal); +} +.stashpad-icon-suggest-icon .svg-icon { width: 18px; height: 18px; } +.stashpad-icon-suggest-label { + font-family: var(--font-monospace); + font-size: var(--font-ui-smaller); + color: var(--text-muted); +} .stashpad-folder-icon-preview { display: inline-flex; align-items: center; @@ -1411,7 +1432,10 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { display: flex; flex-direction: column; gap: 4px; - padding: 4px 0 12px; + /* 0.121.5: inset to align with the section heading + Setting rows. + 0.121.7: bumped 14β†’20px per feedback that 14 read under-indented vs the + rest. (Approximate β€” verify against the live settings.) */ + padding: 4px 20px 12px; } .stashpad-authored-folder-row { display: flex; @@ -1997,11 +2021,17 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { .stashpad-folder-list { display: flex; flex-direction: column; - padding: 4px 0 12px; + /* 0.121.2: 14px left/right inset so these custom rows align with the Setting + rows + section text (PROVISION insets text element types, not custom divs, + so the list was sitting flush against the modal edge). */ + padding: 4px 14px 12px; } /* 0.95.2: placement overview group heading in settings */ .stashpad-folder-placement-group { margin-top: 10px; + /* 0.121.2: match the 14px inset of its rows + the section text above. */ + padding-left: 14px; + padding-right: 14px; font-size: var(--font-ui-smaller); font-weight: var(--font-semibold); color: var(--text-muted); @@ -2269,7 +2299,10 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { display: flex; flex-direction: column; gap: 6px; + /* 0.121.5: 14px left/right inset so the author cards align with the rest. */ margin: 8px 0 4px; + padding-left: 14px; + padding-right: 14px; } .stashpad-known-author-row { padding: 6px 10px; @@ -2497,18 +2530,12 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { text-align: center; font-family: var(--font-monospace); cursor: pointer; -} -.stashpad-binding-useboth { - display: inline-flex; - align-items: center; - gap: 4px; - margin-right: 8px; - font-size: 0.85em; - color: var(--text-muted); -} -.stashpad-binding-useboth.is-disabled { - opacity: 0.45; - pointer-events: none; + /* 0.121.12 (#4): compact rounded key-chip look (desktop + mobile). */ + height: 26px; + padding: 2px 8px; + border: 1px solid var(--background-modifier-border); + border-radius: 5px; + background: var(--background-secondary); } .stashpad-binding-input.is-recording { background: var(--background-modifier-active-hover); @@ -2559,49 +2586,77 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { /* Pill toggle: a rounded track with a knob that slides L↔R. The knob shows "L" when on the left (primary active) or "R" when on the right (secondary active). Disabled state dims the whole pill. */ -.stashpad-binding-pill { - position: relative; - display: inline-block; - width: 48px; - height: 22px; - margin-left: 8px; - border-radius: 11px; - background: var(--background-modifier-border); - cursor: pointer; - transition: background 0.15s ease; - vertical-align: middle; - outline: none; -} -.stashpad-binding-pill:focus-visible { - box-shadow: 0 0 0 2px var(--interactive-accent); -} -.stashpad-binding-pill.is-right { - background: var(--interactive-accent); -} -.stashpad-binding-pill.is-disabled { - opacity: 0.4; - cursor: not-allowed; -} -.stashpad-binding-pill-knob { - position: absolute; - top: 2px; - left: 2px; - width: 18px; - height: 18px; - border-radius: 50%; - background: var(--background-primary); - color: var(--text-normal); - font-size: 11px; - font-weight: 700; - display: flex; +/* 0.121.11 (#8): hotkey row β€” tri-state control on the LEFT, the two key slots + STACKED on the right so the binding controls sit at the right end. */ +.stashpad-binding-row .setting-item-control { align-items: center; - justify-content: center; - transition: left 0.15s ease, transform 0.15s ease; - user-select: none; - pointer-events: none; + gap: 12px; + flex-wrap: nowrap; } -.stashpad-binding-pill.is-right .stashpad-binding-pill-knob { - left: calc(100% - 20px); +.stashpad-binding-slots { + display: flex; + flex-direction: column; + gap: 4px; + align-items: flex-end; +} +.stashpad-binding-slots .stashpad-binding-slot { margin-right: 0; } +/* 0.121.11 (#9): Left | Both | Right segmented control β€” replaces the old L/R + pill + separate "Use both" checkbox. */ +.stashpad-binding-seg { + display: inline-flex; + flex: 0 0 auto; + border: 1px solid var(--background-modifier-border); + border-radius: 6px; + overflow: hidden; +} +.stashpad-binding-seg-btn { + padding: 3px 10px; + font-size: var(--font-ui-smaller); + background: transparent; + border: none; + border-radius: 0; + box-shadow: none; + color: var(--text-muted); + cursor: pointer; +} +.stashpad-binding-seg-btn:not(:last-child) { + border-right: 1px solid var(--background-modifier-border); +} +.stashpad-binding-seg-btn:hover:not(:disabled) { + background: var(--background-modifier-hover); + color: var(--text-normal); +} +.stashpad-binding-seg-btn.is-active { + background: var(--interactive-accent); + color: var(--text-on-accent); +} +.stashpad-binding-seg.is-disabled { opacity: 0.45; } +.stashpad-binding-seg-btn:disabled { cursor: not-allowed; } +/* 0.121.12 (#4): the clear (Γ—) + revert (β†Ί) buttons sit side-by-side on desktop, + stacked vertically on mobile to keep the (stacked) slots narrow. */ +.stashpad-binding-slot-btns { display: inline-flex; gap: 4px; align-items: center; } +body.is-mobile .stashpad-binding-slot-btns { flex-direction: column; gap: 3px; } + +/* 0.121.12 (#1/#3): give each folded-tab sub-heading top breathing room β€” the + first one (e.g. "List & Display", "JD Index") was cramped right under the + page title with no separation. */ +.stashpad-settings-section .setting-item-heading { + margin-top: 16px; + padding-top: 4px; +} +/* 0.121.13: the FIRST sub-heading of a folded tab (top of Behavior / Org + Systems) gets extra top room so it doesn't crowd the page title. */ +.stashpad-settings-section:first-child .setting-item-heading { + margin-top: 28px; + padding-top: 6px; +} + +/* 0.121.12 (#2): the JD "Actions" buttons spilled off the right on mobile β€” + let them wrap instead. */ +body.is-mobile .stashpad-jd-actions .setting-item-control { + flex-wrap: wrap; + justify-content: flex-end; + gap: 6px; } /* Color picker modal */ .stashpad-color-modal { width: min(360px, 90vw); } @@ -2743,7 +2798,16 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { /* Per-folder encryption: filename sub-toggles sit indented under their content toggle, dimmed when disabled. */ -.stashpad-subsetting { padding-left: 22px; opacity: 0.85; } +/* 0.121.2: sub-settings (e.g. the encryption filename sub-toggle under its + content toggle) get a left guide-line so the nesting reads structurally, not + just by indent + dim. Additive + stashpad-scoped (never touches global + .setting-item). */ +.stashpad-subsetting { + padding-left: 18px; + margin-left: 6px; + border-left: 2px solid var(--background-modifier-border); + opacity: 0.85; +} .stashpad-subsetting .setting-item-name { font-size: var(--font-ui-smaller); color: var(--text-muted); } .stashpad-trash-iconbtn { flex: 0 0 auto; display: inline-flex; align-items: center; justify-content: center; padding: 4px 6px; cursor: pointer; --icon-size: 15px; background: transparent; border: none; box-shadow: none; color: var(--text-muted); } .stashpad-trash-iconbtn:hover { color: var(--text-normal); } @@ -2810,6 +2874,17 @@ body.is-phone .modal.stashpad-compact-modal.stashpad-breadcrumb-modal { padding-left: 14px; padding-right: 14px; } +/* 0.121.7 (#2): the live date sample read under-indented vs the rest β€” bump it + a touch past the standard 14px. (Approximate β€” verify against live settings.) */ +.stashpad-settings-section .stashpad-date-sample { + padding-left: 20px; +} +/* 0.121.7 (#1): give each settings page some breathing room at the very bottom + so the last section isn't flush against the modal edge (e.g. the encryption + page's trailing advice text). Only the last section in a tab is affected. */ +.stashpad-settings-section:last-child { + padding-bottom: 16px; +} .stashpad-ai-disclaimer { margin: 4px 14px 12px; padding: 10px 12px; border-radius: var(--radius-m, 6px); border: 1px solid var(--color-red, #e24b4a); @@ -5072,7 +5147,9 @@ body.stashpad-folderpanel-resizing { cursor: row-resize; user-select: none; } color: var(--text-normal); background: rgba(var(--color-red-rgb, 224, 49, 49), 0.12); border-left: 3px solid var(--color-red, #e03131); - padding: 8px 12px; + /* 0.121.5: a touch more vertical padding + more bottom breathing room so the + advice banner doesn't feel cramped (L/R stays at the section's 14px inset). */ + padding: 11px 12px; border-radius: 4px; - margin: 4px 0 12px; + margin: 4px 0 18px; }