From 60b7634519fb2152ab752faaa554775e15747f2b Mon Sep 17 00:00:00 2001 From: Human Date: Sat, 20 Jun 2026 19:53:15 -0700 Subject: [PATCH] 0.115.6: per-folder encryption polish + subfolders, plaintext archives, encrypt-from-explorer --- main.js | 160 +++++++++++++++++++------------------- manifest.json | 2 +- package.json | 2 +- release-notes/0.115.6.md | 36 +++++++++ src/encryption-ops.ts | 55 +++++++++---- src/encryption-service.ts | 86 ++++++++++++++------ src/main.ts | 110 +++++++++++++++++++++----- src/settings.ts | 119 +++++++++++++++++++--------- src/view.ts | 26 ++++++- 9 files changed, 419 insertions(+), 177 deletions(-) create mode 100644 release-notes/0.115.6.md diff --git a/main.js b/main.js index 55a456e..22b65a5 100644 --- a/main.js +++ b/main.js @@ -1,147 +1,147 @@ -"use strict";var In=Object.defineProperty;var qr=Object.getOwnPropertyDescriptor;var Jr=Object.getOwnPropertyNames;var Kr=Object.prototype.hasOwnProperty;var qt=(d,a)=>()=>(d&&(a=d(d=0)),a);var gi=(d,a)=>{for(var t in a)In(d,t,{get:a[t],enumerable:!0})},Or=(d,a,t,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let i of Jr(a))!Kr.call(d,i)&&i!==t&&In(d,i,{get:()=>a[i],enumerable:!(e=qr(a,i))||e.enumerable});return d};var Yr=d=>Or(In({},"__esModule",{value:!0}),d);function Cn(d){return Array.isArray(d)?d.filter(a=>typeof a=="string"):typeof d=="string"?d.split(/[,\s]+/).filter(Boolean):[]}function Ye(d,a){let t=a.replace(/^#/,"");return Cn(d?.tags).some(e=>e.replace(/^#/,"")===t)}function Bn(d,a){let t=a.replace(/^#/,""),e=Cn(d.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),d.tags=e}function yn(d,a){let t=a.replace(/^#/,""),e=Cn(d.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?d.tags=e:delete d.tags}function $e(d){return d.split("/").some(a=>fi.has(a))}function qo(d){return d.split("/").some(a=>a==="_archive"||a===".archive")}function Yt(d){let a=(d??"").trim();return!a||/^\[\[.*\]\]$/.test(a)?a:`[[${a}]]`}function Se(d){let a=(d??"").trim(),t=a.match(/^\[\[(.*)\]\]$/);return t&&(a=t[1]),a.split("|")[0].split("#")[0].split("^")[0].trim()}function Jo(d){let a=d.match(/\.([^./]+)$/);return!!a&&zr.has(a[1].toLowerCase())}function Ko(d,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(d))return!0}catch{}else if(d===e||d.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function is(d,a){let t=d.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=a.toLowerCase();return t.every(i=>e.includes(i))}function ue(d){if(typeof d!="string")return null;let a=d.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(d){let a=d?.assignedTo,t=Array.isArray(a)?a:a!=null?[a]:[],e=[];for(let i of t){let s=ue(i);s&&e.push(s)}return e}var J,pe,ge,ke,Ke,Oe,F,se,fi,zr,at=qt(()=>{"use strict";J="stashpad-view",pe="stashpad-panels",ge="stashpad-folder-panel",ke="stashpad-detail",Ke="stashpad-trash",Oe="stashpad-aggregate",F="__root__";se=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","listPinned","listPinnedAt","imported","okfParent","okfChildren"],fi=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);zr=new Set(["edtz"])});function Ci(d,a){let t=d.replace(/\r\n/g,` +"use strict";var Cn=Object.defineProperty;var $r=Object.getOwnPropertyDescriptor;var Vr=Object.getOwnPropertyNames;var zr=Object.prototype.hasOwnProperty;var qt=(d,a)=>()=>(d&&(a=d(d=0)),a);var ui=(d,a)=>{for(var t in a)Cn(d,t,{get:a[t],enumerable:!0})},Wr=(d,a,t,e)=>{if(a&&typeof a=="object"||typeof a=="function")for(let i of Vr(a))!zr.call(d,i)&&i!==t&&Cn(d,i,{get:()=>a[i],enumerable:!(e=$r(a,i))||e.enumerable});return d};var Xr=d=>Wr(Cn({},"__esModule",{value:!0}),d);function Qn(d){return Array.isArray(d)?d.filter(a=>typeof a=="string"):typeof d=="string"?d.split(/[,\s]+/).filter(Boolean):[]}function $e(d,a){let t=a.replace(/^#/,"");return Qn(d?.tags).some(e=>e.replace(/^#/,"")===t)}function En(d,a){let t=a.replace(/^#/,""),e=Qn(d.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),d.tags=e}function wn(d,a){let t=a.replace(/^#/,""),e=Qn(d.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?d.tags=e:delete d.tags}function Ve(d){return d.split("/").some(a=>mi.has(a))}function Oo(d){return d.split("/").some(a=>a==="_archive"||a===".archive")}function Yt(d){let a=(d??"").trim();return!a||/^\[\[.*\]\]$/.test(a)?a:`[[${a}]]`}function Se(d){let a=(d??"").trim(),t=a.match(/^\[\[(.*)\]\]$/);return t&&(a=t[1]),a.split("|")[0].split("#")[0].split("^")[0].trim()}function Yo(d){let a=d.match(/\.([^./]+)$/);return!!a&&_r.has(a[1].toLowerCase())}function $o(d,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(d))return!0}catch{}else if(d===e||d.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function ss(d,a){let t=d.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=a.toLowerCase();return t.every(i=>e.includes(i))}function ue(d){if(typeof d!="string")return null;let a=d.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(d){let a=d?.assignedTo,t=Array.isArray(a)?a:a!=null?[a]:[],e=[];for(let i of t){let s=ue(i);s&&e.push(s)}return e}var J,pe,ge,ke,Oe,Ye,F,ne,mi,_r,at=qt(()=>{"use strict";J="stashpad-view",pe="stashpad-panels",ge="stashpad-folder-panel",ke="stashpad-detail",Oe="stashpad-trash",Ye="stashpad-aggregate",F="__root__";ne=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","listPinned","listPinnedAt","imported","okfParent","okfChildren"],mi=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);_r=new Set(["edtz"])});function Bi(d,a){let t=d.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(` `))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 Ht(d,a,t){d.empty();try{(0,Vo.setIcon)(d,a)}catch{}let e=d.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(d.empty(),d.createSpan({cls:"stashpad-icon-fallback",text:t}))}function zo(d){if(d instanceof Element&&d.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let a=new Set([document]);d instanceof Element&&d.ownerDocument&&a.add(d.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 Wo(d){let a=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(d))!=null;)a.push({lang:e[3].trim(),code:e[4]});return a}function Bi(d){return d.split("/").map(a=>a.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function Xo(d,a,t){let e=new Set(a),i=d.filter(n=>!e.has(n)),s=d.findIndex(n=>e.has(n));if(s<0)return d.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 d.forEach((A,h)=>{e.has(A)&&(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:Wr(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 Vo,mi,be,Ne,yi=qt(()=>{"use strict";Vo=require("obsidian"),mi={lines:"Each line",paragraphs:"Paragraphs (blank line)",headings:"Headings"};be="__stashpad:tagged__",Ne="__stashpad:untagged__"});function Xr(d,a){return d>12?d>=24?0:d:a==="am"?d===12?0:d:d===12?12:d+12}function ns(d,a){d.addClass("stashpad-when-pop-time");let t=a.seedPeriod,e=d.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 A=()=>{let Q=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",Q),r.toggleClass("is-disabled",Q),o.disabled=Q,r.disabled=Q},h=B=>{let Q=B.value.replace(/\D/g,"").slice(0,2);if(Q===""){B.value="",B===i&&A();return}let y=parseInt(Q,10);B===i?y>24&&(y=24):y>59&&(y=59),B.value=String(y),B===i&&A()};for(let B of[i,s])B.addEventListener("input",()=>h(B));A();let p=()=>{let B=parseInt(i.value||"12",10)||12,Q=parseInt(s.value||"0",10)||0,y=B>12;a.onFinalize({hours24:Xr(B,t),minutes:Q,raw:{hh:B,mm:Q,period:t,is24:y}}),a.close()};a.setOnEnter?.(p);let u=[i,s,o,r],g=(B,Q)=>{let y=u.indexOf(B);if(y===-1)return;let E=(y+Q+u.length)%u.length;u[E].focus()},I=B=>{B.addEventListener("keydown",Q=>{Q.key==="Enter"?(Q.preventDefault(),Q.stopPropagation(),p()):Q.key==="Escape"?(Q.preventDefault(),Q.stopPropagation(),a.close()):Q.key==="Tab"&&(Q.preventDefault(),Q.stopPropagation(),g(B,Q.shiftKey?-1:1))})},m=d.createDiv({cls:"stashpad-when-time-pad"}),f=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],C=null;for(let B of f){let Q=m.createEl("button",{cls:"stashpad-when-time-padbtn"});Q.type="button",B==="backspace"?(0,jo.setIcon)(Q,"delete"):B==="insert"?(Q.setText("OK"),C=Q):Q.setText(B),B==="insert"&&Q.addClass("is-go"),Q.addEventListener("mousedown",y=>y.preventDefault()),Q.addEventListener("click",y=>{if(y.preventDefault(),B==="insert"){p();return}if(B==="backspace"){c.value=c.value.slice(0,-1),h(c),c.focus();return}let E=c.selectionStart===0&&c.selectionEnd===c.value.length&&c.value.length>0,v=2,w=E||c.value.length>=v?B:c.value+B;c.value=w,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)I(B);i.focus(),i.select()}function _o(d){let{hh:a,mm:t,period:e,is24:i}=d.raw;return i?`${a}:${String(t).padStart(2,"0")}`:`${a}:${String(t).padStart(2,"0")}${e}`}var jo,En=qt(()=>{"use strict";jo=require("obsidian")});function ea(d){let a=Math.floor(4294967296/d)*d,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=a);return e%d}function wn(d=5){let a=[];for(let t=0;t=1&&s.every(r=>/^[a-zA-Z]+$/.test(r))&&(i=Math.min(i,s.length*11)),Zr.has(d.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 jr(d){let a=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function Ve(d){let a="stashpad-",t=jr(d),e=64-a.length-1-t.length,i=d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${a}${i}-${t}`}var ta,Zr,os=qt(()=>{"use strict";ta="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((d,a,t)=>t.indexOf(d)===a);Zr=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 as={};gi(as,{newId:()=>W});function W(d=6){let a="",t=new Uint8Array(d);crypto.getRandomValues(t);for(let e=0;e{"use strict";ia="abcdefghijkmnpqrstuvwxyz23456789"});var Di={};gi(Di,{ColorPickerModal:()=>Te,ConfirmDeleteModal:()=>We,ConfirmModal:()=>nt,CustomColorModal:()=>rs,DueDatePickerModal:()=>Ze,EncryptionPasswordModal:()=>At,ExportStashModal:()=>Xe,ImportDupChoiceModal:()=>ki,ImportLogModal:()=>Fn,LogModal:()=>ze,NotificationHistoryModal:()=>Fi,OkfExportModal:()=>Si,SplitNoteModal:()=>Ei,StashPasswordModal:()=>wi,TypeToConfirmModal:()=>vi,buildAssigneePicker:()=>sa});function sa(d,a){let t=[...a.initial],e=a.knownAuthors,i=d.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 p of t){let u=s.createSpan({cls:"stashpad-assign-chip"});u.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let g=u.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});g.title=`Remove ${p.name}`,g.onclick=()=>{t=t.filter(I=>I.id!==p.id),l(),c()}}},A=p=>{p.name.trim()&&(t.some(u=>u.id===p.id)||t.push(p),o.value="",r.setCssStyles({display:"none"}),l(),c(),o.focus())},h=()=>{let p=o.value.trim();r.empty();let u=new Set(t.map(m=>m.id)),I=e.filter(m=>!u.has(m.id)&&is(p,m.name)).slice(0,6).map(m=>({label:m.name,onPick:()=>A(m)}));if(p&&!e.some(m=>m.name.toLowerCase()===p.toLowerCase())&&I.push({label:`Create \u201C${p}\u201D`,onPick:()=>A({id:W(6),name:p})}),I.length===0){r.setCssStyles({display:"none"});return}r.setCssStyles({display:""});for(let m of I){let f=r.createDiv({cls:"stashpad-assign-suggest-item",text:m.label});f.onmousedown=C=>{C.preventDefault(),m.onPick()}}};o.addEventListener("input",h),o.addEventListener("focus",h),o.addEventListener("keydown",p=>{if(p.key==="Enter"){p.preventDefault();let u=r.querySelector(".stashpad-assign-suggest-item");u&&u.dispatchEvent(new MouseEvent("mousedown"))}else p.key==="Escape"&&r.style.display!=="none"&&(p.stopPropagation(),r.setCssStyles({display:"none"}))}),o.addEventListener("blur",()=>{window.setTimeout(()=>{r.setCssStyles({display:"none"})},120)}),c()}var q,_r,xe,ze,We,Ei,Xe,wi,At,vi,rs,Qi,Te,nt,Ze,Me,Fi,Fn,ki,Si,kt=qt(()=>{"use strict";q=require("obsidian");yi();En();at();os();Ut();_r=q.moment,xe=class xe 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(xe.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(xe.PAGE),this.renderFooter()},t>xe.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 nt(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()}};xe.PAGE=100;ze=xe,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()}},Ei=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 Ht(d,a,t){d.empty();try{(0,Xo.setIcon)(d,a)}catch{}let e=d.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(d.empty(),d.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Zo(d){if(d instanceof Element&&d.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let a=new Set([document]);d instanceof Element&&d.ownerDocument&&a.add(d.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 jo(d){let a=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(d))!=null;)a.push({lang:e[3].trim(),code:e[4]});return a}function yi(d){return d.split("/").map(a=>a.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function _o(d,a,t){let e=new Set(a),i=d.filter(n=>!e.has(n)),s=d.findIndex(n=>e.has(n));if(s<0)return d.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 d.forEach((A,h)=>{e.has(A)&&(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:tl(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 Xo,Ci,be,Ne,Qi=qt(()=>{"use strict";Xo=require("obsidian"),Ci={lines:"Each line",paragraphs:"Paragraphs (blank line)",headings:"Headings"};be="__stashpad:tagged__",Ne="__stashpad:untagged__"});function el(d,a){return d>12?d>=24?0:d:a==="am"?d===12?0:d:d===12?12:d+12}function os(d,a){d.addClass("stashpad-when-pop-time");let t=a.seedPeriod,e=d.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 A=()=>{let Q=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",Q),r.toggleClass("is-disabled",Q),o.disabled=Q,r.disabled=Q},h=B=>{let Q=B.value.replace(/\D/g,"").slice(0,2);if(Q===""){B.value="",B===i&&A();return}let y=parseInt(Q,10);B===i?y>24&&(y=24):y>59&&(y=59),B.value=String(y),B===i&&A()};for(let B of[i,s])B.addEventListener("input",()=>h(B));A();let g=()=>{let B=parseInt(i.value||"12",10)||12,Q=parseInt(s.value||"0",10)||0,y=B>12;a.onFinalize({hours24:el(B,t),minutes:Q,raw:{hh:B,mm:Q,period:t,is24:y}}),a.close()};a.setOnEnter?.(g);let u=[i,s,o,r],p=(B,Q)=>{let y=u.indexOf(B);if(y===-1)return;let E=(y+Q+u.length)%u.length;u[E].focus()},I=B=>{B.addEventListener("keydown",Q=>{Q.key==="Enter"?(Q.preventDefault(),Q.stopPropagation(),g()):Q.key==="Escape"?(Q.preventDefault(),Q.stopPropagation(),a.close()):Q.key==="Tab"&&(Q.preventDefault(),Q.stopPropagation(),p(B,Q.shiftKey?-1:1))})},f=d.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 Q=f.createEl("button",{cls:"stashpad-when-time-padbtn"});Q.type="button",B==="backspace"?(0,ea.setIcon)(Q,"delete"):B==="insert"?(Q.setText("OK"),C=Q):Q.setText(B),B==="insert"&&Q.addClass("is-go"),Q.addEventListener("mousedown",y=>y.preventDefault()),Q.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 E=c.selectionStart===0&&c.selectionEnd===c.value.length&&c.value.length>0,v=2,w=E||c.value.length>=v?B:c.value+B;c.value=w,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)I(B);i.focus(),i.select()}function ia(d){let{hh:a,mm:t,period:e,is24:i}=d.raw;return i?`${a}:${String(t).padStart(2,"0")}`:`${a}:${String(t).padStart(2,"0")}${e}`}var ea,Fn=qt(()=>{"use strict";ea=require("obsidian")});function na(d){let a=Math.floor(4294967296/d)*d,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=a);return e%d}function kn(d=5){let a=[];for(let t=0;t=1&&s.every(r=>/^[a-zA-Z]+$/.test(r))&&(i=Math.min(i,s.length*11)),il.has(d.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 sl(d){let a=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function ze(d){let a="stashpad-",t=sl(d),e=64-a.length-1-t.length,i=d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${a}${i}-${t}`}var sa,il,as=qt(()=>{"use strict";sa="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((d,a,t)=>t.indexOf(d)===a);il=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 rs={};ui(rs,{newId:()=>W});function W(d=6){let a="",t=new Uint8Array(d);crypto.getRandomValues(t);for(let e=0;e{"use strict";oa="abcdefghijkmnpqrstuvwxyz23456789"});var bi={};ui(bi,{ColorPickerModal:()=>Te,ConfirmDeleteModal:()=>Xe,ConfirmModal:()=>nt,CustomColorModal:()=>ls,DueDatePickerModal:()=>je,EncryptionPasswordModal:()=>At,ExportStashModal:()=>Ze,ImportDupChoiceModal:()=>Si,ImportLogModal:()=>Dn,LogModal:()=>We,NotificationHistoryModal:()=>ki,OkfExportModal:()=>Di,SplitNoteModal:()=>wi,StashPasswordModal:()=>vi,TypeToConfirmModal:()=>Fi,buildAssigneePicker:()=>aa});function aa(d,a){let t=[...a.initial],e=a.knownAuthors,i=d.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(I=>I.id!==g.id),l(),c()}}},A=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(f=>f.id)),I=e.filter(f=>!u.has(f.id)&&ss(g,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>A(f)}));if(g&&!e.some(f=>f.name.toLowerCase()===g.toLowerCase())&&I.push({label:`Create \u201C${g}\u201D`,onPick:()=>A({id:W(6),name:g})}),I.length===0){r.setCssStyles({display:"none"});return}r.setCssStyles({display:""});for(let f of I){let m=r.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});m.onmousedown=C=>{C.preventDefault(),f.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,nl,xe,We,Xe,wi,Ze,vi,At,Fi,ls,Ei,Te,nt,je,Me,ki,Dn,Si,Di,kt=qt(()=>{"use strict";q=require("obsidian");Qi();Fn();at();as();Ut();nl=q.moment,xe=class xe 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(xe.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(xe.PAGE),this.renderFooter()},t>xe.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 nt(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()}};xe.PAGE=100;We=xe,Xe=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()}},wi=class extends q.Modal{constructor(t,e,i,s,n){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;this.onSplitMany=n;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` `).split(` -`),this.lineCursorIdx=Math.max(1,Math.min(this.lines.length-1,Math.floor(this.lines.length/2))),this.lines.length<2&&(this.mode="cursor")}onOpen(){this.titleEl.setText("Split note"),this.modalEl.addClass("stashpad-split-modal"),this.render(),this.scope.register([],"Tab",t=>{this.lines.length<2||(t.preventDefault(),this.mode=this.mode==="line"?"cursor":"line",this.render())}),this.scope.register([],"Enter",t=>{this.mode==="line"&&(t.preventDefault(),this.commitLine())}),this.scope.register(["Mod"],"Enter",t=>{this.mode==="cursor"&&(t.preventDefault(),this.commitCursor())}),this.scope.register([],"ArrowUp",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.max(1,this.lineCursorIdx-1),this.render())}),this.scope.register([],"ArrowDown",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.min(this.lines.length-1,this.lineCursorIdx+1),this.render())})}commitLine(){let t=this.lineCursorIdx;this.close(),this.onSplitAtLine(t)}commitCursor(){let t=this.cursorTextarea;if(!t)return;let e=t.selectionStart;if(e<=0||e>=t.value.length){new q.Notice("Move the cursor inside the text \u2014 neither end can be empty.");return}this.close(),this.onSplitAtChar(e)}render(){this.contentEl.empty();let t=this.contentEl.createDiv({cls:"stashpad-split-quick"});t.createSpan({cls:"stashpad-split-quick-label",text:"Split by:"}),["lines","paragraphs","headings"].forEach(o=>{let r=Ci(this.body,o),l=t.createEl("button",{cls:"stashpad-split-quick-btn",text:`${mi[o]} (${r.length})`});l.disabled=r.length<2,l.onmousedown=c=>c.preventDefault(),l.onclick=()=>{let c=Ci(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=[],A=L=>{let z=l.createDiv({cls:"stashpad-export-pw-row"}),K=z.createEl("input",{type:"password"});K.addClass("stashpad-export-name"),K.placeholder=L;let O=z.createEl("button",{cls:"stashpad-export-copy"}),it=()=>{let lt=K.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(),K.value.length===0)try{let tt=(await navigator.clipboard?.readText())?.trim();if(!tt){new q.Notice("Clipboard is empty.");return}K.value=tt,K.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(K.value).then(()=>new q.Notice("Passphrase copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},it(),c.push(it),K},h=A("Password"),p=A("Confirm password"),u=l.createDiv({cls:"stashpad-export-strength"}),g=u.createDiv({cls:"stashpad-strength-bar"}),I=[0,1,2,3].map(()=>g.createDiv({cls:"stashpad-strength-seg"})),m=u.createEl("span",{cls:"stashpad-strength-label"}),f=l.createDiv({cls:"stashpad-export-genrow"}),C=f.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),B=f.createEl("button",{cls:"stashpad-export-show",text:"Show"}),Q=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 E=this.app.secretStorage,v=l.createDiv({cls:"stashpad-export-remember"}),w=v.createEl("input",{type:"checkbox"});w.id="stashpad-export-remember-cb";let D=v.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});D.htmlFor=w.id;let b=l.createDiv({cls:"stashpad-export-remember-note"});b.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),b.setCssStyles({display:"none"}),w.onchange=()=>{b.setCssStyles({display:w.checked?"":"none"})},E||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 x=this.contentEl.createDiv({cls:"stashpad-export-footer"}),S=x.createEl("button",{text:"Cancel"});S.onclick=()=>this.close();let T=x.createEl("button",{cls:"mod-cta",text:"Export"}),P=()=>{let L=vn(h.value);u.style.visibility=h.value?"visible":"hidden",I.forEach((z,K)=>z.toggleClass("is-on",h.value!==""&&K<=L.level)),g.dataset.level=String(L.level),m.setText(L.label)},R=()=>{let L=o.checked;l.setCssStyles({display:L?"":"none"});let z=!0;L&&(h.value?h.value!==p.value?(Q.setText("Passwords don't match."),Q.addClass("is-error"),z=!1):(Q.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),Q.removeClass("is-error")):(Q.setText("Enter a password to encrypt this export."),Q.removeClass("is-error"),z=!1)),P(),c.forEach(K=>K()),T.disabled=!z,T.toggleClass("is-disabled",!z),U()},X=!1,$=L=>{X=L,h.type=p.type=L?"text":"password",B.setText(L?"Hide":"Show")};B.onclick=L=>{L.preventDefault(),$(!X)},C.onclick=L=>{L.preventDefault(),h.value=p.value=wn(),$(!1),new q.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),R()},o.onchange=R,h.oninput=R,p.oninput=R,R();let V=()=>this.commit(H(),o.checked?h.value:null,o.checked&&w.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()}},wi=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()}},At=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=I=>{let m=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),f=m.createEl("input",{type:"password"});f.addClass("stashpad-export-name","stashpad-encryption-field"),f.placeholder=I;let C=m.createEl("button",{cls:"stashpad-export-copy"}),B=()=>{let Q=f.value.length===0;C.setText(Q?"Paste":"Copy"),C.toggleClass("is-paste",Q),C.setAttr("aria-label",`${Q?"Paste into":"Copy"} ${I.toLowerCase()}`)};return C.onclick=async Q=>{if(Q.preventDefault(),f.value.length===0)try{let y=(await navigator.clipboard?.readText())?.trim();if(!y){new q.Notice("Clipboard is empty.");return}f.value=y,f.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(f.value).then(()=>new q.Notice("Copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},f.addEventListener("input",B),B(),e.push(B),f},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 I=this.contentEl.createDiv({cls:"stashpad-export-strength"}),m=I.createDiv({cls:"stashpad-strength-bar"}),f=[0,1,2,3].map(()=>m.createDiv({cls:"stashpad-strength-seg"})),C=I.createEl("span",{cls:"stashpad-strength-label"}),B=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),Q=()=>{let w=n.value,D=vn(w);f.forEach((b,H)=>b.toggleClass("is-on",H0&&w.length<6?" \u2014 use at least 6":""}`),B.toggleClass("is-weak",w.length>0&&w.length<6)};n.addEventListener("input",Q),Q();let y=this.contentEl.createDiv({cls:"stashpad-export-genrow"});y.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=w=>{w.preventDefault();let D=wn(5);n.value=D,o&&(o.value=D),Q(),e.forEach(b=>b()),new q.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(D).catch(()=>{})};let E=y.createEl("button",{cls:"stashpad-export-show",text:"Show"});E.onclick=w=>{w.preventDefault();let D=n.type==="password";n.type=D?"text":"password",o&&(o.type=D?"text":"password"),E.setText(D?"Hide":"Show")};let v=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});v.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(w=>{v.toggleClass("is-weak",!w),v.setText(w?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run here, so this will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>v.setText("Encryption: AES-256-GCM with a password-derived key.")):v.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let r=null,l=this.app.secretStorage;if(this.opts.offerKeychain&&l){let I=this.contentEl.createDiv({cls:"stashpad-export-remember"});r=I.createEl("input",{type:"checkbox"}),r.id="stashpad-enc-remember";let m=I.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});m.htmlFor=r.id;let f=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});f.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."),f.setCssStyles({display:"none"}),r.onchange=()=>{f.setCssStyles({display:r.checked?"":"none"})}}let c=this.contentEl.createEl("div",{cls:"stashpad-export-error"});c.setCssStyles({display:"none"});let A=I=>{c.setText(I),c.setCssStyles({display:""})},h=this.contentEl.createDiv({cls:"stashpad-export-footer"});h.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let p=h.createEl("button",{cls:"mod-cta",text:t==="setup"?"Set up":t==="change"?"Change":"Unlock"}),u=!1,g=async()=>{if(u)return;let I=s?.value??void 0,m=n?.value??void 0;if((t==="unlock"||t==="change")&&!I){A("Enter your current password.");return}if(t==="setup"||t==="change"){if(!m){A("Enter a password.");return}if(m.length<6){A("Use at least 6 characters.");return}if(m!==o?.value){A("Passwords don't match.");return}}u=!0,p.disabled=!0,c.setCssStyles({display:"none"});let f=p.textContent;p.setText("Working\u2026");try{let C=await this.opts.onSubmit({current:I,next:m,remember:!!r?.checked});if(C){A(C),u=!1,p.disabled=!1,p.setText(f??"OK");return}this.succeeded=!0,this.close()}catch(C){A(`Failed: ${C.message}`),u=!1,p.disabled=!1,p.setText(f??"OK")}};p.onclick=()=>void g(),this.scope.register([],"Enter",I=>{I.preventDefault(),g()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},vi=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",A=>{A.preventDefault(),c()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},rs=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=A=>{let h=A.startsWith("#")?A:"#"+A;/^#[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",A=>{A.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",A=>{A.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()}},Qi=class Qi 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=[...Qi.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=!Qi.DEFAULT_PALETTE.some(h=>h.toLowerCase()===r.toLowerCase()),A=this.items.length;if(l.onclick=()=>this.activate(A),c&&this.onDeleteCustom){let h=l.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});h.title="Remove from palette",h.onclick=p=>{p.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 rs(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))}};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 A=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=()=>{A.value="",A.focus()},n.onclick=()=>{try{o.showPicker?.()}catch{}},c.onclick=()=>this.openTimeNumpad(c,A),t&&(o.value=this.toDateValue(t),A.value=this.toTimeValue(t)),this.renderAssignSection(e);let p=e.createDiv({cls:"stashpad-due-grid"}),u=(C,B)=>{let Q=p.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:C});Q.onclick=()=>{let y=B();o.value=this.toDateValue(y),A.value||(A.value=this.toTimeValue(y))}},g=C=>(C.setHours(9,0,0,0),C);u("Today",()=>g(this.startOfTodayLocal())),u("Tomorrow",()=>{let C=this.startOfTodayLocal();return C.setDate(C.getDate()+1),g(C)}),u("Next week",()=>{let C=this.startOfTodayLocal();return C.setDate(C.getDate()+7),g(C)});let I=p.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});I.onclick=()=>{o.value="",A.value="",o.focus()};let m=p.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});m.onclick=()=>{this.didChoose=!0,this.close()};let f=p.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});f.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[C,B,Q]=o.value.split("-").map(w=>parseInt(w,10)),y=9,E=0;if(A.value){let[w,D]=A.value.split(":").map(b=>parseInt(b,10));y=w,E=D}let v=new Date(C,B-1,Q,y,E,0,0);this.didChoose=!0,this.close(),this.onPick({iso:v.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){sa(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,g]=e.value.split(":").map(I=>parseInt(I,10));Number.isFinite(u)&&(i=u),Number.isFinite(g)&&(s=g)}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",A,!0),document.removeEventListener("keydown",h,!0),this.tinyClosePopover===c&&(this.tinyClosePopover=null)},A=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,ns(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 p=t.getBoundingClientRect();r.setCssStyles({left:`${Math.max(8,Math.min(p.left,window.innerWidth-220))}px`,top:`${p.bottom+4}px`}),setTimeout(()=>{document.addEventListener("mousedown",A,!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}`}},Me=class Me 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 nt(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(Me.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 A of e.actionLabels){let h=c.createSpan({cls:"stashpad-notif-action-chip"});h.setText(A),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(Me.PAGE,t)} more`});if(e.onclick=()=>{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()}}}};Me.PAGE=100;Fi=Me,Fn=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()}},ki=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()}},Si=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 A=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),h=A.createEl("input",{type:"checkbox"});return h.checked=c,A.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 Et(d,a=$t){let t=a instanceof Set?a:new Set(a.map(o=>o.toLowerCase())),e=(d.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 wt(d,a){return`${d}-${a}.md`}function fe(d){let a=d.match(/-([a-z0-9]{4,12})$/);return a?a[1]:null}function As(d,a){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${a}${d.slice(t)}`:`${d}-${a}`}function na(d){let a=d.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 $t,je=qt(()=>{"use strict";$t=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var ps={};gi(ps,{JdBuildConfirmModal:()=>Ni,buildJdIndexNotes:()=>Sn,buildJdIndexPreview:()=>ds,buildJdPreviewNotice:()=>hs,scanForJdNotes:()=>_e});function kn(d,a){if(/^\d+-\d+$/.test(d))return null;if(d.includes(".")){let e=d.split(".").slice(0,-1).join(".");return a.has(e)?e:kn(e,a)}if(/^\d+$/.test(d)){let t=parseInt(d,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(d,a,t){let e=d.vault.getMarkdownFiles(),i=el(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(a.discoverStashpadFolders()),o=u=>s?!1:Array.from(n).some(g=>u===g||u.startsWith(g+"/")),r=[],l=[],c=[];for(let u of i){let g=u.parent?.path?.replace(/\/+$/,"")??"";if(o(g)){c.push(u);continue}let I=u.basename.match(oa);I?r.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:u,folder:null}):l.push(u)}let A=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",h=u=>{let g=u.path.replace(/\/+$/,"");if(!(A&&g&&g!==A&&!g.startsWith(A+"/"))){if(g&&!o(g)){let I=u.name.match(oa);I&&r.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:null,folder:u})}}for(let I of u.children)I instanceof ut.TFolder&&h(I)};h(d.vault.getRoot());let p=t.jdIndexSort??"natural";return r.sort((u,g)=>il(u,g,p)),{indexed:r,nonIndex:l,skippedStashpadNotes:c}}async function ds(d,a,t){let e=Dn(t.jdIndexStashpadFolder??"");if(!e)return{..._e(d,a,t),previewPath:null,error:"no-dest"};let i=_e(d,a,t),s=tl(d,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=sl(i.indexed,i.nonIndex,i.skippedStashpadNotes),r=(await d.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),l=r?`${r[0]}${n}`:n;return await d.vault.modify(s,l),{...i,previewPath:s.path}}function tl(d,a){let t=d.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((d.metadataCache.getFileCache(e)?.frontmatter??{}).id===F)return e}return null}async function Sn(d,a,t){let e=Dn(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(d,a,t),n=new Map;for(let m of s.indexed)n.set(m.prefix,m);for(let m of s.indexed)if(m.prefix.includes("."))for(let f=1;f{l.push(m);for(let f of r.get(m)??[])c(f)};for(let m of o)c(m);let A=new Map,h=d.vault.getAbstractFileByPath(e);if(h instanceof ut.TFolder)for(let m of h.children){if(!(m instanceof ut.TFile)||m.extension!=="md")continue;let f=d.metadataCache.getFileCache(m)?.frontmatter??{};typeof f.jdPrefix=="string"&&A.set(f.jdPrefix,m)}let p=new Map,u=0,g=0,I=0;for(let m of l){let f=n.get(m)??null,C=kn(m,new Set(n.keys())),B=C?p.get(C)??F:F,Q=f?`${m} ${f.title}`:m,y=f?.file?`[[${f.file.basename}]]`:"",E=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 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=Bi(this.body,o),l=t.createEl("button",{cls:"stashpad-split-quick-btn",text:`${Ci[o]} (${r.length})`});l.disabled=r.length<2,l.onmousedown=c=>c.preventDefault(),l.onclick=()=>{let c=Bi(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()}},Ze=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=[],A=L=>{let z=l.createDiv({cls:"stashpad-export-pw-row"}),K=z.createEl("input",{type:"password"});K.addClass("stashpad-export-name"),K.placeholder=L;let O=z.createEl("button",{cls:"stashpad-export-copy"}),it=()=>{let lt=K.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(),K.value.length===0)try{let tt=(await navigator.clipboard?.readText())?.trim();if(!tt){new q.Notice("Clipboard is empty.");return}K.value=tt,K.dispatchEvent(new Event("input")),new q.Notice("Pasted from clipboard.")}catch{new q.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(K.value).then(()=>new q.Notice("Passphrase copied to clipboard."),()=>new q.Notice("Couldn't access the clipboard."))},it(),c.push(it),K},h=A("Password"),g=A("Confirm password"),u=l.createDiv({cls:"stashpad-export-strength"}),p=u.createDiv({cls:"stashpad-strength-bar"}),I=[0,1,2,3].map(()=>p.createDiv({cls:"stashpad-strength-seg"})),f=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"}),Q=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 E=this.app.secretStorage,v=l.createDiv({cls:"stashpad-export-remember"}),w=v.createEl("input",{type:"checkbox"});w.id="stashpad-export-remember-cb";let D=v.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});D.htmlFor=w.id;let b=l.createDiv({cls:"stashpad-export-remember-note"});b.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),b.setCssStyles({display:"none"}),w.onchange=()=>{b.setCssStyles({display:w.checked?"":"none"})},E||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 x=this.contentEl.createDiv({cls:"stashpad-export-footer"}),S=x.createEl("button",{text:"Cancel"});S.onclick=()=>this.close();let T=x.createEl("button",{cls:"mod-cta",text:"Export"}),P=()=>{let L=Sn(h.value);u.style.visibility=h.value?"visible":"hidden",I.forEach((z,K)=>z.toggleClass("is-on",h.value!==""&&K<=L.level)),p.dataset.level=String(L.level),f.setText(L.label)},R=()=>{let L=o.checked;l.setCssStyles({display:L?"":"none"});let z=!0;L&&(h.value?h.value!==g.value?(Q.setText("Passwords don't match."),Q.addClass("is-error"),z=!1):(Q.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),Q.removeClass("is-error")):(Q.setText("Enter a password to encrypt this export."),Q.removeClass("is-error"),z=!1)),P(),c.forEach(K=>K()),T.disabled=!z,T.toggleClass("is-disabled",!z),U()},X=!1,$=L=>{X=L,h.type=g.type=L?"text":"password",B.setText(L?"Hide":"Show")};B.onclick=L=>{L.preventDefault(),$(!X)},C.onclick=L=>{L.preventDefault(),h.value=g.value=kn(),$(!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&&w.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()}},vi=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()}},At=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=I=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),m=f.createEl("input",{type:"password"});m.addClass("stashpad-export-name","stashpad-encryption-field"),m.placeholder=I;let C=f.createEl("button",{cls:"stashpad-export-copy"}),B=()=>{let Q=m.value.length===0;C.setText(Q?"Paste":"Copy"),C.toggleClass("is-paste",Q),C.setAttr("aria-label",`${Q?"Paste into":"Copy"} ${I.toLowerCase()}`)};return C.onclick=async Q=>{if(Q.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 I=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=I.createDiv({cls:"stashpad-strength-bar"}),m=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),C=I.createEl("span",{cls:"stashpad-strength-label"}),B=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),Q=()=>{let w=n.value,D=Sn(w);m.forEach((b,H)=>b.toggleClass("is-on",H0&&w.length<6?" \u2014 use at least 6":""}`),B.toggleClass("is-weak",w.length>0&&w.length<6)};n.addEventListener("input",Q),Q();let y=this.contentEl.createDiv({cls:"stashpad-export-genrow"});y.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=w=>{w.preventDefault();let D=kn(5);n.value=D,o&&(o.value=D),Q(),e.forEach(b=>b()),new q.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(D).catch(()=>{})};let E=y.createEl("button",{cls:"stashpad-export-show",text:"Show"});E.onclick=w=>{w.preventDefault();let D=n.type==="password";n.type=D?"text":"password",o&&(o.type=D?"text":"password"),E.setText(D?"Hide":"Show")};let v=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});v.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(w=>{v.toggleClass("is-weak",!w),v.setText(w?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run here, so this will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>v.setText("Encryption: AES-256-GCM with a password-derived key.")):v.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let r=null,l=this.app.secretStorage;if(this.opts.offerKeychain&&l){let I=this.contentEl.createDiv({cls:"stashpad-export-remember"});r=I.createEl("input",{type:"checkbox"}),r.id="stashpad-enc-remember";let f=I.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});f.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 A=I=>{c.setText(I),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 I=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!I){A("Enter your current password.");return}if(t==="setup"||t==="change"){if(!f){A("Enter a password.");return}if(f.length<6){A("Use at least 6 characters.");return}if(f!==o?.value){A("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:I,next:f,remember:!!r?.checked});if(C){A(C),u=!1,g.disabled=!1,g.setText(m??"OK");return}this.succeeded=!0,this.close()}catch(C){A(`Failed: ${C.message}`),u=!1,g.disabled=!1,g.setText(m??"OK")}};g.onclick=()=>void p(),this.scope.register([],"Enter",I=>{I.preventDefault(),p()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},Fi=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",A=>{A.preventDefault(),c()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},ls=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=A=>{let h=A.startsWith("#")?A:"#"+A;/^#[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",A=>{A.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",A=>{A.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()}},Ei=class Ei 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=[...Ei.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=!Ei.DEFAULT_PALETTE.some(h=>h.toLowerCase()===r.toLowerCase()),A=this.items.length;if(l.onclick=()=>this.activate(A),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 ls(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))}};je=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 A=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=()=>{A.value="",A.focus()},n.onclick=()=>{try{o.showPicker?.()}catch{}},c.onclick=()=>this.openTimeNumpad(c,A),t&&(o.value=this.toDateValue(t),A.value=this.toTimeValue(t)),this.renderAssignSection(e);let g=e.createDiv({cls:"stashpad-due-grid"}),u=(C,B)=>{let Q=g.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:C});Q.onclick=()=>{let y=B();o.value=this.toDateValue(y),A.value||(A.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 I=g.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});I.onclick=()=>{o.value="",A.value="",o.focus()};let f=g.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});f.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,Q]=o.value.split("-").map(w=>parseInt(w,10)),y=9,E=0;if(A.value){let[w,D]=A.value.split(":").map(b=>parseInt(b,10));y=w,E=D}let v=new Date(C,B-1,Q,y,E,0,0);this.didChoose=!0,this.close(),this.onPick({iso:v.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){aa(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(I=>parseInt(I,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",A,!0),document.removeEventListener("keydown",h,!0),this.tinyClosePopover===c&&(this.tinyClosePopover=null)},A=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,os(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",A,!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}`}},Me=class Me 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 nt(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(Me.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 A of e.actionLabels){let h=c.createSpan({cls:"stashpad-notif-action-chip"});h.setText(A),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(Me.PAGE,t)} more`});if(e.onclick=()=>{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()}}}};Me.PAGE=100;ki=Me,Dn=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()}},Si=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()}},Di=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 A=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),h=A.createEl("input",{type:"checkbox"});return h.checked=c,A.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 Et(d,a=$t){let t=a instanceof Set?a:new Set(a.map(o=>o.toLowerCase())),e=(d.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 wt(d,a){return`${d}-${a}.md`}function fe(d){let a=d.match(/-([a-z0-9]{4,12})$/);return a?a[1]:null}function ds(d,a){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${a}${d.slice(t)}`:`${d}-${a}`}function ra(d){let a=d.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 $t,_e=qt(()=>{"use strict";$t=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var gs={};ui(gs,{JdBuildConfirmModal:()=>xi,buildJdIndexNotes:()=>Nn,buildJdIndexPreview:()=>hs,buildJdPreviewNotice:()=>ps,scanForJdNotes:()=>ti});function bn(d,a){if(/^\d+-\d+$/.test(d))return null;if(d.includes(".")){let e=d.split(".").slice(0,-1).join(".");return a.has(e)?e:bn(e,a)}if(/^\d+$/.test(d)){let t=parseInt(d,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 ti(d,a,t){let e=d.vault.getMarkdownFiles(),i=al(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 I=u.basename.match(la);I?r.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:u,folder:null}):l.push(u)}let A=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",h=u=>{let p=u.path.replace(/\/+$/,"");if(!(A&&p&&p!==A&&!p.startsWith(A+"/"))){if(p&&!o(p)){let I=u.name.match(la);I&&r.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:null,folder:u})}}for(let I of u.children)I instanceof ut.TFolder&&h(I)};h(d.vault.getRoot());let g=t.jdIndexSort??"natural";return r.sort((u,p)=>rl(u,p,g)),{indexed:r,nonIndex:l,skippedStashpadNotes:c}}async function hs(d,a,t){let e=xn(t.jdIndexStashpadFolder??"");if(!e)return{...ti(d,a,t),previewPath:null,error:"no-dest"};let i=ti(d,a,t),s=ol(d,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=ll(i.indexed,i.nonIndex,i.skippedStashpadNotes),r=(await d.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),l=r?`${r[0]}${n}`:n;return await d.vault.modify(s,l),{...i,previewPath:s.path}}function ol(d,a){let t=d.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((d.metadataCache.getFileCache(e)?.frontmatter??{}).id===F)return e}return null}async function Nn(d,a,t){let e=xn(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=ti(d,a,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let m=1;m{l.push(f);for(let m of r.get(f)??[])c(m)};for(let f of o)c(f);let A=new Map,h=d.vault.getAbstractFileByPath(e);if(h instanceof ut.TFolder)for(let f of h.children){if(!(f instanceof ut.TFile)||f.extension!=="md")continue;let m=d.metadataCache.getFileCache(f)?.frontmatter??{};typeof m.jdPrefix=="string"&&A.set(m.jdPrefix,f)}let g=new Map,u=0,p=0,I=0;for(let f of l){let m=n.get(f)??null,C=bn(f,new Set(n.keys())),B=C?g.get(C)??F:F,Q=m?`${f} ${m.title}`:f,y=m?.file?`[[${m.file.basename}]]`:"",E=y?`${y} `:`${Q} -`,v=A.get(m);if(v){try{let w=null;await d.fileManager.processFrontMatter(v,U=>{U.jdPrefix=m,B&&(U.parent=B),(!U.id||typeof U.id!="string")&&(U.id=W()),U.created||(U.created=new Date().toISOString()),U.attachments||(U.attachments=[]),w=U.id});let b=(await d.vault.read(v)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),H=b?`${b[0]}${E}`:E;await d.vault.modify(v,H),w&&p.set(m,w),g++}catch(w){console.error("[stashpad] buildJdIndexNotes: update failed",w),I++}continue}try{let w=W();p.set(m,w);let D=Et(Q,t.slugStopWords),b=wt(D,w),H=`${e}/${b}`,U=["---",`id: ${w}`,`parent: ${B}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${m}"`,"---",""].join(` -`);await d.vault.create(H,U+E),u++}catch(w){console.error("[stashpad] buildJdIndexNotes: create failed for",m,w),I++}}return{created:u,updated:g,skipped:I,destFolder:e}}function Dn(d){return(d||"").trim().replace(/^\/+|\/+$/g,"")}function el(d,a){if((a.jdIndexScope??"vault")==="vault")return d;let t=Dn(a.jdIndexScopeFolder??"");return t?d.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):d}function il(d,a,t){if(t==="created"){let e=d.file?.stat?.ctime??0,i=a.file?.stat?.ctime??0;if(e!==i)return e-i}return ra(d.segments,a.segments)}function aa(d,a){let t=d.match(/^(\d+)-(\d+)$/),e=a.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:d.split("."),s=e?[e[1]]:a.split(".");return ra(i,s)}function ra(d,a){let t=Math.min(d.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 sl(d,a,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),d.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 d)s.set(c.prefix,c);for(let c of d)if(c.prefix.includes("."))for(let A=1;A{let A=s.get(c),h=r.get(c)??0,p=" ".repeat(h),u=i(h),g=A?.folder?` ${A.title} _(folder)_`:(A?.file,"");A?.file?e.push(`${p}- ${u} [[${A.file.basename}|${A.prefix} ${A.title}]]`):A?.folder?e.push(`${p}- ${u} ${A.prefix}${g}`):e.push(`${p}- ${u} ${c}`);for(let I of o.get(c)??[])l(I)};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(` +`,v=A.get(f);if(v){try{let w=null;await d.fileManager.processFrontMatter(v,U=>{U.jdPrefix=f,B&&(U.parent=B),(!U.id||typeof U.id!="string")&&(U.id=W()),U.created||(U.created=new Date().toISOString()),U.attachments||(U.attachments=[]),w=U.id});let b=(await d.vault.read(v)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),H=b?`${b[0]}${E}`:E;await d.vault.modify(v,H),w&&g.set(f,w),p++}catch(w){console.error("[stashpad] buildJdIndexNotes: update failed",w),I++}continue}try{let w=W();g.set(f,w);let D=Et(Q,t.slugStopWords),b=wt(D,w),H=`${e}/${b}`,U=["---",`id: ${w}`,`parent: ${B}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` +`);await d.vault.create(H,U+E),u++}catch(w){console.error("[stashpad] buildJdIndexNotes: create failed for",f,w),I++}}return{created:u,updated:p,skipped:I,destFolder:e}}function xn(d){return(d||"").trim().replace(/^\/+|\/+$/g,"")}function al(d,a){if((a.jdIndexScope??"vault")==="vault")return d;let t=xn(a.jdIndexScopeFolder??"");return t?d.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):d}function rl(d,a,t){if(t==="created"){let e=d.file?.stat?.ctime??0,i=a.file?.stat?.ctime??0;if(e!==i)return e-i}return Aa(d.segments,a.segments)}function ca(d,a){let t=d.match(/^(\d+)-(\d+)$/),e=a.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:d.split("."),s=e?[e[1]]:a.split(".");return Aa(i,s)}function Aa(d,a){let t=Math.min(d.length,a.length);for(let e=0;e<t;e++){let i=d[e],s=a[e],n=/^\d+$/.test(i),o=/^\d+$/.test(s);if(n&&o){let r=parseInt(i,10)-parseInt(s,10);if(r!==0)return r}else{if(n&&!o)return-1;if(!n&&o)return 1;{let r=i.localeCompare(s,void 0,{numeric:!0,sensitivity:"base"});if(r!==0)return r}}}return d.length-a.length}function da(d){let a=new Set(d.keys()),t=new Map,e=new Map;for(let o of a){let r=bn(o,a);if(t.set(o,r),r!==null){let l=e.get(r)??[];l.push(o),e.set(r,l)}}let i=[];for(let o of a)t.get(o)===null&&i.push(o);i.sort(ca);for(let o of e.values())o.sort(ca);let s=new Map,n=(o,r)=>{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 ll(d,a,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),d.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 d)s.set(c.prefix,c);for(let c of d)if(c.prefix.includes("."))for(let A=1;A<c.segments.length;A++){let h=c.segments.slice(0,A).join(".");s.has(h)||s.set(h,null)}let{roots:n,childrenOf:o,depthOf:r}=da(s),l=c=>{let A=s.get(c),h=r.get(c)??0,g=" ".repeat(h),u=i(h),p=A?.folder?` ${A.title} _(folder)_`:(A?.file,"");A?.file?e.push(`${g}- ${u} [[${A.file.basename}|${A.prefix} ${A.title}]]`):A?.folder?e.push(`${g}- ${u} ${A.prefix}${p}`):e.push(`${g}- ${u} ${c}`);for(let I of o.get(c)??[])l(I)};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 `<prefix> <title>` and re-run to include them._"),e.push("");for(let s of a)e.push(`- # [[${s.basename}]] \xB7 \`${s.path}\``)}if(t.length>0){let s=new Map;for(let o of t){let 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(` `)+` -`}function hs(d,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=d.vault.getAbstractFileByPath(a.previewPath);r instanceof ut.TFile&&await d.workspace.getLeaf("tab").openFile(r)}n?.hide()},n=new ut.Notice(t,0),n}var ut,oa,Ni,xi=qt(()=>{"use strict";ut=require("obsidian");Ut();je();at();oa=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ni=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 A=await ds(this.app,this.plugin,this.settings);if(A.error==="no-dest"){new ut.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(A.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=A.previewPath,hs(this.app,A),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(A){new ut.Notice(`Preview failed: ${A?.message??A}`,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 nc(d,a){return sc(d,a||{},0,0)}function oc(d,a){return jl(d,{i:2},a&&a.out,a&&a.dictionary)}function Ls(d,a){if(a){for(var t=new ct(d.length),e=0;e<d.length;++e)t[e]=d.charCodeAt(e);return t}if(za)return za.encode(d);for(var i=d.length,s=new ct(d.length+(d.length>>1)),n=0,o=function(c){s[n++]=c},e=0;e<i;++e){if(n+5>s.length){var r=new ct(n+8+(i-e<<1));r.set(s),s=r}var l=d.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)|d.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 $i(s,0,n)}function mo(d,a){if(a){for(var t="",e=0;e<d.length;e+=16384)t+=String.fromCharCode.apply(null,d.subarray(e,e+16384));return t}else{if(go)return go.decode(d);var i=rc(d),s=i.s,t=i.r;return t.length&&Ct(8),s}}function nr(d,a){a||(a={});var t={},e=[];sr(d,"",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,A=Ls(n),h=A.length,p=l.comment,u=p&&Ls(p),g=u&&u.length,I=uo(l.extra);h>65535&&Ct(11);var m=c?nc(r,l):r,f=m.length,C=ic();C.p(r),e.push(ir(l,{size:r.length,crc:C.d(),c:m,f:A,m:u,u:h!=n.length||u&&p.length!=g,o:i,compression:c})),i+=30+h+I+f,s+=76+2*(h+I)+(g||0)+f}for(var B=new ct(s+22),Q=i,y=s-i,E=0;E<e.length;++E){var A=e[E];Wa(B,A.o,A,A.f,A.u,A.c.length);var v=30+A.f.length+uo(A.extra);B.set(A.c,A.o+v),Wa(B,i,A,A.f,A.u,A.c.length,A.o,A.m),i+=16+v+(A.m?A.m.length:0)}return dc(B,i,e.length,y,Q),B}function or(d,a){for(var t={},e=d.length-22;Mt(d,e)!=101010256;--e)(!e||d.length-e>65558)&&Ct(13);var i=Zt(d,e+8);if(!i)return{};var s=Mt(d,e+16),n=Mt(d,e-20)==117853008;if(n){var o=Mt(d,e-12);n=Mt(d,o)==101075792,n&&(i=Mt(d,o+32),s=Mt(d,o+48))}for(var r=a&&a.filter,l=0;l<i;++l){var c=cc(d,s,n),A=c[0],h=c[1],p=c[2],u=c[3],g=c[4],I=c[5],m=lc(d,I);s=g,(!r||r({name:u,size:h,originalSize:p,compression:A}))&&(A?A==8?t[u]=oc(d.subarray(m,m+h),{out:new ct(p)}):Ct(14,"unknown compression type "+A):t[u]=$i(d,m,m+h))}return t}var ct,St,Io,qs,Js,co,Xa,Za,ja,Ao,_a,$l,Ya,ho,ce,_,jt,ye,_,_,_,_,Yi,_,Vl,zl,Wl,Xl,oo,Lt,ao,fo,$i,Zl,Ct,jl,Ae,Ki,ro,po,$a,Oi,tr,Va,_l,er,tc,ec,ic,sc,ir,Zt,Mt,lo,It,sr,za,go,ac,rc,lc,cc,Ac,uo,Wa,dc,ar=qt(()=>{ct=Uint8Array,St=Uint16Array,Io=Int32Array,qs=new ct([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]),Js=new ct([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]),co=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),Xa=function(d,a){for(var t=new St(31),e=0;e<31;++e)t[e]=a+=1<<d[e-1];for(var i=new Io(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}},Za=Xa(qs,2),ja=Za.b,Ao=Za.r;ja[28]=258,Ao[258]=28;_a=Xa(Js,0),$l=_a.b,Ya=_a.r,ho=new St(32768);for(_=0;_<32768;++_)ce=(_&43690)>>1|(_&21845)<<1,ce=(ce&52428)>>2|(ce&13107)<<2,ce=(ce&61680)>>4|(ce&3855)<<4,ho[_]=((ce&65280)>>8|(ce&255)<<8)>>1;jt=function(d,a,t){for(var e=d.length,i=0,s=new St(a);i<e;++i)d[i]&&++s[d[i]-1];var n=new St(a);for(i=1;i<a;++i)n[i]=n[i-1]+s[i-1]<<1;var o;if(t){o=new St(1<<a);var r=15-a;for(i=0;i<e;++i)if(d[i])for(var l=i<<4|d[i],c=a-d[i],A=n[d[i]-1]++<<c,h=A|(1<<c)-1;A<=h;++A)o[ho[A]>>r]=l}else for(o=new St(e),i=0;i<e;++i)d[i]&&(o[i]=ho[n[d[i]-1]++]>>15-d[i]);return o},ye=new ct(288);for(_=0;_<144;++_)ye[_]=8;for(_=144;_<256;++_)ye[_]=9;for(_=256;_<280;++_)ye[_]=7;for(_=280;_<288;++_)ye[_]=8;Yi=new ct(32);for(_=0;_<32;++_)Yi[_]=5;Vl=jt(ye,9,0),zl=jt(ye,9,1),Wl=jt(Yi,5,0),Xl=jt(Yi,5,1),oo=function(d){for(var a=d[0],t=1;t<d.length;++t)d[t]>a&&(a=d[t]);return a},Lt=function(d,a,t){var e=a/8|0;return(d[e]|d[e+1]<<8)>>(a&7)&t},ao=function(d,a){var t=a/8|0;return(d[t]|d[t+1]<<8|d[t+2]<<16)>>(a&7)},fo=function(d){return(d+7)/8|0},$i=function(d,a,t){return(a==null||a<0)&&(a=0),(t==null||t>d.length)&&(t=d.length),new ct(d.subarray(a,t))},Zl=["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(d,a,t){var e=new Error(a||Zl[d]);if(e.code=d,Error.captureStackTrace&&Error.captureStackTrace(e,Ct),!t)throw e;return e},jl=function(d,a,t,e){var i=d.length,s=e?e.length:0;if(!i||a.f&&!a.l)return t||new ct(0);var n=!t,o=n||a.i!=2,r=a.i;n&&(t=new ct(i*3));var l=function(ht){var Dt=t.length;if(ht>Dt){var st=new ct(Math.max(Dt*2,ht));st.set(t),t=st}},c=a.f||0,A=a.p||0,h=a.b||0,p=a.l,u=a.d,g=a.m,I=a.n,m=i*8;do{if(!p){c=Lt(d,A,1);var f=Lt(d,A+1,3);if(A+=3,f)if(f==1)p=zl,u=Xl,g=9,I=5;else if(f==2){var y=Lt(d,A,31)+257,E=Lt(d,A+10,15)+4,v=y+Lt(d,A+5,31)+1;A+=14;for(var w=new ct(v),D=new ct(19),b=0;b<E;++b)D[co[b]]=Lt(d,A+b*3,7);A+=E*3;for(var H=oo(D),U=(1<<H)-1,x=jt(D,H,1),b=0;b<v;){var S=x[Lt(d,A,U)];A+=S&15;var C=S>>4;if(C<16)w[b++]=C;else{var T=0,P=0;for(C==16?(P=3+Lt(d,A,3),A+=2,T=w[b-1]):C==17?(P=3+Lt(d,A,7),A+=3):C==18&&(P=11+Lt(d,A,127),A+=7);P--;)w[b++]=T}}var R=w.subarray(0,y),X=w.subarray(y);g=oo(R),I=oo(X),p=jt(R,g,1),u=jt(X,I,1)}else Ct(1);else{var C=fo(A)+4,B=d[C-4]|d[C-3]<<8,Q=C+B;if(Q>i){r&&Ct(0);break}o&&l(h+B),t.set(d.subarray(C,Q),h),a.b=h+=B,a.p=A=Q*8,a.f=c;continue}if(A>m){r&&Ct(0);break}}o&&l(h+131072);for(var $=(1<<g)-1,V=(1<<I)-1,L=A;;L=A){var T=p[ao(d,A)&$],z=T>>4;if(A+=T&15,A>m){r&&Ct(0);break}if(T||Ct(2),z<256)t[h++]=z;else if(z==256){L=A,p=null;break}else{var K=z-254;if(z>264){var b=z-257,O=qs[b];K=Lt(d,A,(1<<O)-1)+ja[b],A+=O}var it=u[ao(d,A)&V],lt=it>>4;it||Ct(3),A+=it&15;var X=$l[lt];if(lt>3){var O=Js[lt];X+=ao(d,A)&(1<<O)-1,A+=O}if(A>m){r&&Ct(0);break}o&&l(h+131072);var tt=h+K;if(h<X){var Z=s-X,yt=Math.min(X,tt);for(Z+h<0&&Ct(3);h<yt;++h)t[h]=e[Z+h]}for(;h<tt;++h)t[h]=t[h-X]}}a.l=p,a.p=L,a.b=h,a.f=c,p&&(c=1,a.m=g,a.d=u,a.n=I)}while(!c);return h!=t.length&&n?$i(t,0,h):t.subarray(0,h)},Ae=function(d,a,t){t<<=a&7;var e=a/8|0;d[e]|=t,d[e+1]|=t>>8},Ki=function(d,a,t){t<<=a&7;var e=a/8|0;d[e]|=t,d[e+1]|=t>>8,d[e+2]|=t>>16},ro=function(d,a){for(var t=[],e=0;e<d.length;++e)d[e]&&t.push({s:e,f:d[e]});var i=t.length,s=t.slice();if(!i)return{t:er,l:0};if(i==1){var n=new ct(t[0].s+1);return n[t[0].s]=1,{t:n,l:1}}t.sort(function(Q,y){return Q.f-y.f}),t.push({s:-1,f:25001});var o=t[0],r=t[1],l=0,c=1,A=2;for(t[0]={s:-1,f:o.f+r.f,l:o,r};c!=i-1;)o=t[t[l].f<t[A].f?l++:A++],r=t[l!=c&&t[l].f<t[A].f?l++:A++],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 p=new St(h+1),u=po(t[c-1],p,0);if(u>a){var e=0,g=0,I=u-a,m=1<<I;for(s.sort(function(y,E){return p[E.s]-p[y.s]||y.f-E.f});e<i;++e){var f=s[e].s;if(p[f]>a)g+=m-(1<<u-p[f]),p[f]=a;else break}for(g>>=I;g>0;){var C=s[e].s;p[C]<a?g-=1<<a-p[C]++-1:++e}for(;e>=0&&g;--e){var B=s[e].s;p[B]==a&&(--p[B],++g)}u=a}return{t:new ct(p),l:u}},po=function(d,a,t){return d.s==-1?Math.max(po(d.l,a,t+1),po(d.r,a,t+1)):a[d.s]=t},$a=function(d){for(var a=d.length;a&&!d[--a];);for(var t=new St(++a),e=0,i=d[0],s=1,n=function(r){t[e++]=r},o=1;o<=a;++o)if(d[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=d[o]}return{c:t.subarray(0,e),n:a}},Oi=function(d,a){for(var t=0,e=0;e<a.length;++e)t+=d[e]*a[e];return t},tr=function(d,a,t){var e=t.length,i=fo(a+2);d[i]=e&255,d[i+1]=e>>8,d[i+2]=d[i]^255,d[i+3]=d[i+1]^255;for(var s=0;s<e;++s)d[i+s+4]=t[s];return(i+4+e)*8},Va=function(d,a,t,e,i,s,n,o,r,l,c){Ae(a,c++,t),++i[256];for(var A=ro(i,15),h=A.t,p=A.l,u=ro(s,15),g=u.t,I=u.l,m=$a(h),f=m.c,C=m.n,B=$a(g),Q=B.c,y=B.n,E=new St(19),v=0;v<f.length;++v)++E[f[v]&31];for(var v=0;v<Q.length;++v)++E[Q[v]&31];for(var w=ro(E,7),D=w.t,b=w.l,H=19;H>4&&!D[co[H-1]];--H);var U=l+5<<3,x=Oi(i,ye)+Oi(s,Yi)+n,S=Oi(i,h)+Oi(s,g)+n+14+3*H+Oi(E,D)+2*E[16]+3*E[17]+7*E[18];if(r>=0&&U<=x&&U<=S)return tr(a,c,d.subarray(r,r+l));var T,P,R,X;if(Ae(a,c,1+(S<x)),c+=2,S<x){T=jt(h,p,0),P=h,R=jt(g,I,0),X=g;var $=jt(D,b,0);Ae(a,c,C-257),Ae(a,c+5,y-1),Ae(a,c+10,H-4),c+=14;for(var v=0;v<H;++v)Ae(a,c+3*v,D[co[v]]);c+=3*H;for(var V=[f,Q],L=0;L<2;++L)for(var z=V[L],v=0;v<z.length;++v){var K=z[v]&31;Ae(a,c,$[K]),c+=D[K],K>15&&(Ae(a,c,z[v]>>5&127),c+=z[v]>>12)}}else T=Vl,P=ye,R=Wl,X=Yi;for(var v=0;v<o;++v){var O=e[v];if(O>255){var K=O>>18&31;Ki(a,c,T[K+257]),c+=P[K+257],K>7&&(Ae(a,c,O>>23&31),c+=qs[K]);var it=O&31;Ki(a,c,R[it]),c+=X[it],it>3&&(Ki(a,c,O>>5&8191),c+=Js[it])}else Ki(a,c,T[O]),c+=P[O]}return Ki(a,c,T[256]),c+P[256]},_l=new Io([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),er=new ct(0),tc=function(d,a,t,e,i,s){var n=s.z||d.length,o=new ct(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 A=_l[a-1],h=A>>13,p=A&8191,u=(1<<t)-1,g=s.p||new St(32768),I=s.h||new St(u+1),m=Math.ceil(t/3),f=2*m,C=function(Qt){return(d[Qt]^d[Qt+1]<<m^d[Qt+2]<<f)&u},B=new Io(25e3),Q=new St(288),y=new St(32),E=0,v=0,w=s.i||0,D=0,b=s.w||0,H=0;w+2<n;++w){var U=C(w),x=w&32767,S=I[U];if(g[x]=S,I[U]=x,b<=w){var T=n-w;if((E>7e3||D>24576)&&(T>423||!l)){c=Va(d,r,0,B,Q,y,v,D,H,w-H,c),D=E=v=0,H=w;for(var P=0;P<286;++P)Q[P]=0;for(var P=0;P<30;++P)y[P]=0}var R=2,X=0,$=p,V=x-S&32767;if(T>2&&U==C(w-V))for(var L=Math.min(h,T)-1,z=Math.min(32767,w),K=Math.min(258,T);V<=z&&--$&&x!=S;){if(d[w+R]==d[w+R-V]){for(var O=0;O<K&&d[w+O]==d[w+O-V];++O);if(O>R){if(R=O,X=V,O>L)break;for(var it=Math.min(V,O-2),lt=0,P=0;P<it;++P){var tt=w-V+P&32767,Z=g[tt],yt=tt-Z&32767;yt>lt&&(lt=yt,S=tt)}}}x=S,S=g[x],V+=x-S&32767}if(X){B[D++]=268435456|Ao[R]<<18|Ya[X];var ht=Ao[R]&31,Dt=Ya[X]&31;v+=qs[ht]+Js[Dt],++Q[257+ht],++y[Dt],b=w+R,++E}else B[D++]=d[w],++Q[d[w]]}}for(w=Math.max(w,b);w<n;++w)B[D++]=d[w],++Q[d[w]];c=Va(d,r,l,B,Q,y,v,D,H,w-H,c),l||(s.r=c&7|r[c/8|0]<<3,c-=7,s.h=I,s.p=g,s.i=w,s.w=b)}else{for(var w=s.w||0;w<n+l;w+=65535){var st=w+65535;st>=n&&(r[c/8|0]=l,st=n),c=tr(r,c+1,d.subarray(w,st))}s.i=n}return $i(o,0,e+fo(c)+i)},ec=function(){for(var d=new Int32Array(256),a=0;a<256;++a){for(var t=a,e=9;--e;)t=(t&1&&-306674912)^t>>>1;d[a]=t}return d}(),ic=function(){var d=-1;return{p:function(a){for(var t=d,e=0;e<a.length;++e)t=ec[t&255^a[e]]^t>>>8;d=t},d:function(){return~d}}},sc=function(d,a,t,e,i){if(!i&&(i={l:1},a.dictionary)){var s=a.dictionary.subarray(-32768),n=new ct(s.length+d.length);n.set(s),n.set(d,s.length),d=n,i.w=s.length}return tc(d,a.level==null?6:a.level,a.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(d.length)))*1.5):20:12+a.mem,t,e,i)},ir=function(d,a){var t={};for(var e in d)t[e]=d[e];for(var e in a)t[e]=a[e];return t},Zt=function(d,a){return d[a]|d[a+1]<<8},Mt=function(d,a){return(d[a]|d[a+1]<<8|d[a+2]<<16|d[a+3]<<24)>>>0},lo=function(d,a){return Mt(d,a)+Mt(d,a+4)*4294967296},It=function(d,a,t){for(;t;++a)d[a]=t,t>>>=8};sr=function(d,a,t,e){for(var i in d){var s=d[i],n=a+i,o=e;Array.isArray(s)&&(o=ir(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[n]=[s,o]:(t[n+="/"]=[new ct(0),o],sr(s,n,t,e))}},za=typeof TextEncoder<"u"&&new TextEncoder,go=typeof TextDecoder<"u"&&new TextDecoder,ac=0;try{go.decode(er,{stream:!0}),ac=1}catch{}rc=function(d){for(var a="",t=0;;){var e=d[t++],i=(e>127)+(e>223)+(e>239);if(t+i>d.length)return{s:a,r:$i(d,t-1)};i?i==3?(e=((e&15)<<18|(d[t++]&63)<<12|(d[t++]&63)<<6|d[t++]&63)-65536,a+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?a+=String.fromCharCode((e&31)<<6|d[t++]&63):a+=String.fromCharCode((e&15)<<12|(d[t++]&63)<<6|d[t++]&63):a+=String.fromCharCode(e)}};lc=function(d,a){return a+30+Zt(d,a+26)+Zt(d,a+28)},cc=function(d,a,t){var e=Zt(d,a+28),i=Zt(d,a+30),s=mo(d.subarray(a+46,a+46+e),!(Zt(d,a+8)&2048)),n=a+46+e,o=Ac(d,n,i,t,Mt(d,a+20),Mt(d,a+24),Mt(d,a+42)),r=o[0],l=o[1],c=o[2];return[Zt(d,a+10),r,l,s,n+i+Zt(d,a+32),c]},Ac=function(d,a,t,e,i,s,n){var o=i==4294967295,r=s==4294967295,l=n==4294967295,c=a+t,A=o+r+l;if(e&&A){for(;a+4<c;a+=4+Zt(d,a+2))if(Zt(d,a)==1)return[o?lo(d,a+4+8*r):i,r?lo(d,a+4):s,l?lo(d,a+4+8*(r+o)):n,1];e<2&&Ct(13)}return[i,s,n,0]},uo=function(d){var a=0;if(d)for(var t in d){var e=d[t].length;e>65535&&Ct(9),a+=e+4}return a},Wa=function(d,a,t,e,i,s,n,o){var r=e.length,l=t.extra,c=o&&o.length,A=uo(l);It(d,a,n!=null?33639248:67324752),a+=4,n!=null&&(d[a++]=20,d[a++]=t.os),d[a]=20,a+=2,d[a++]=t.flag<<1|(s<0&&8),d[a++]=i&&8,d[a++]=t.compression&255,d[a++]=t.compression>>8;var h=new Date(t.mtime==null?Date.now():t.mtime),p=h.getFullYear()-1980;if((p<0||p>119)&&Ct(10),It(d,a,p<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),a+=4,s!=-1&&(It(d,a,t.crc),It(d,a+4,s<0?-s-2:s),It(d,a+8,t.size)),It(d,a+12,r),It(d,a+14,A),a+=16,n!=null&&(It(d,a,c),It(d,a+6,t.attrs),It(d,a+10,n),a+=14),d.set(e,a),a+=r,A)for(var u in l){var g=l[u],I=g.length;It(d,a,+u),It(d,a+2,I),d.set(g,a+4),a+=4+I}return c&&(d.set(o,a),a+=c),a},dc=function(d,a,t,e,i){It(d,a,101010256),It(d,a+8,t),It(d,a+10,t),It(d,a+12,e),It(d,a+16,i)}});var rr={};gi(rr,{bytesToStr:()=>Ks,unzipFiles:()=>zi,zipFiles:()=>Vi});function hc(d){return typeof d=="string"?Ls(d):d instanceof Uint8Array?d:new Uint8Array(d)}function Vi(d,a=6){let t={};for(let e of d)t[e.name]=[hc(e.data),{level:a}];return Promise.resolve(nr(t,{level:a}))}function Ks(d){return mo(d)}function zi(d){let a=d instanceof Uint8Array?d:new Uint8Array(d);return Promise.resolve(or(a))}var Os=qt(()=>{"use strict";ar()});var Gc={};gi(Gc,{default:()=>gn});module.exports=Yr(Gc);var M=require("obsidian");var Le="sheet-group",Jt="sheet-order",Fe="sheet-final",Po="sheet-label",qe="sheet-origin",Je="forked-from",Kt="fork-siblings",ts=[Le,Jt,Fe,Po,qe,Je,Kt];function Ot(d){if(!d)return null;let a=d[Le];return typeof a=="string"&&a.trim()?a:null}function fn(d){let a=d?.[Jt];return typeof a=="number"?a:null}function ui(d){return Ot(d)!==null&&fn(d)!==null}function Ii(d){return d?.[Fe]===!0}function Ho(d){return d?.[qe]===!0}function $r(d){let a=d?.[Je];return typeof a=="string"&&a.trim()?a:null}function es(d){return typeof d!="string"?null:d.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].split("#")[0].trim()||null}function Uo(d){return es($r(d))}function Vr(d){let a=d?.[Po];return typeof a=="string"&&a.trim()?a:null}function Ro(){let d=Date.now().toString(36),a=Math.floor(Math.random()*1e6).toString(36);return`s-${d}-${a}`}function ft(d,a){return a.file?d.metadataCache.getFileCache(a.file)?.frontmatter:null}function mn(d,a){return a.slice().sort((t,e)=>{let i=fn(ft(d,t)),s=fn(ft(d,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 Go(d,a){if(a.length===0)return null;let t=mn(d,a);return t.find(e=>Ii(ft(d,e)))??t[0]}function Lo(d,a,t){let e=Vr(ft(d,a));return e||t}at();var vt=require("obsidian");var rt=require("obsidian");at();function ss(d){let a=(d.dateDisplayTimezone||"").trim();return a?{timeZone:a}:{}}function ne(d,a){try{return new Intl.DateTimeFormat(void 0,a).format(new Date(d))}catch{let{timeZone:t,...e}=a;return new Intl.DateTimeFormat(void 0,e).format(new Date(d))}}function oe(d,a){let t=ss(a);switch(a.dateDisplayFormat??"locale"){case"iso":return $o(d,a,!0);case"us":return ne(d,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return ne(d,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return ne(d,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return ne(d,{...t,dateStyle:"medium",timeStyle:"short"})}}function Oo(d,a){let t=ss(a);switch(a.dateDisplayFormat??"locale"){case"iso":return $o(d,a,!1);case"us":return ne(d,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return ne(d,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return ne(d,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(d).getFullYear()===e.getFullYear();return ne(d,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Yo(d,a){let t=ss(a),e=a.dateDisplayFormat==="iso"||a.dateDisplayFormat==="eu";return ne(d,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function $o(d,a,t){let e=ss(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(d)),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(d,a,t){let e=d.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(a>99?"99+":String(a))}var bi={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},ls=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()===J&&this.scheduleRender()}))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},80))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-panels-root");let e=t.createDiv({cls:"stashpad-panels-globals"}),i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,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 r=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,rt.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 A of Object.keys(bi)){let h=bi[A],p=l.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,rt.setIcon)(p.createSpan({cls:"stashpad-panels-bar-btn-icon"}),h.icon),p.createSpan({cls:"stashpad-panels-bar-btn-text",text:h.label}),this.activePanel===A&&p.addClass("is-active"),p.onclick=()=>{this.activePanel!==A&&(this.activePanel=A,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=p=>{p.stopPropagation(),this.openPinnedOptionsMenu(p)};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((p,u)=>this.renderPinnedRow(e,p,u));return}let c=new Map;r.forEach((p,u)=>{let g=c.get(p.folder);g||(g=[],c.set(p.folder,g)),g.push({pin:p,idx:u})});let A=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,h=Array.from(c.keys());A&&c.has(A)&&(h.splice(h.indexOf(A),1),h.unshift(A));for(let p of h){let u=p.split("/").pop()||p,g=e.createDiv({cls:"stashpad-pinned-group-header"});p===A&&g.addClass("is-active-folder"),g.createSpan({cls:"stashpad-pinned-group-name",text:u});let I=c.get(p)??[];for(let{pin:m,idx:f}of I)this.renderPinnedRow(e,m,f)}}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,A=c>0,h=this.expanded.has(`${e.folder}|${e.id}`),p=t.createDiv({cls:"stashpad-pinned-row"});r&&p.addClass("has-color"),l&&p.addClass("is-completed"),p.draggable=!0,p.dataset.pinIdx=String(i),p.addEventListener("dragstart",f=>{f.dataTransfer?.setData("text/plain",String(i)),f.dataTransfer&&(f.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",f=>{f.preventDefault(),f.dataTransfer&&(f.dataTransfer.dropEffect="move");let C=p.getBoundingClientRect(),B=f.clientY-C.top<C.height/2;p.toggleClass("drop-before",B),p.toggleClass("drop-after",!B)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",f=>{f.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let C=parseInt(f.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===i)return;let B=p.getBoundingClientRect(),Q=f.clientY-B.top<B.height/2;this.reorderPin(C,Q?i:i+1)});let u=p.createSpan({cls:"stashpad-pinned-toggle"});A&&(Ie(u,c,h),u.onclick=f=>{f.stopPropagation();let C=`${e.folder}|${e.id}`;this.expanded.has(C)?this.expanded.delete(C):this.expanded.add(C),this.render()});let g=p.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(g,A?"folder-tree":"file-text"),r&&(g.style.color=r);let I=p.createSpan({cls:"stashpad-pinned-label",text:o});I.onclick=()=>this.openPinFromPanel(e);let m=e.folder.split("/").pop()||e.folder;if(p.createSpan({cls:"stashpad-pinned-folder",text:m}),p.oncontextmenu=f=>{f.preventDefault();let C=new rt.Menu;C.addItem(B=>B.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),C.showAtMouseEvent(f)},A&&h){let f=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(f,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((A,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,A=>{A.pinnedAt=c})}catch(A){console.warn("[Stashpad] pin reorder failed",A)}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,A=r.completed===!0,h=this.childrenOf(e,l).length,p=h>0,u=this.expanded.has(`${e}|${l}`),g=t.createDiv({cls:"stashpad-pinned-subrow"});A&&g.addClass("is-completed"),g.style.paddingLeft=`${s*16}px`;let I=g.createSpan({cls:"stashpad-pinned-toggle"});p&&(Ie(I,h,u),I.onclick=C=>{C.stopPropagation();let B=`${e}|${l}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),this.render()});let m=g.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(m,"file-text"),c&&(m.style.color=c);let f=g.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});f.onclick=()=>this.openPinFromPanel({folder:e,id:l}),p&&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===F&&(r==null||r===F)){if(o.id===F)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 rt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(kt(),Di));new s(this.app,i,e).open()}openNotificationsFromPanel(){this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")}async openHomeFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.navigateTo=="function"&&t.navigateTo(F)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===J)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(J);return i.length>0?(this.app.workspace.revealLeaf(i[0]),i[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===J?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let A of s){let h=A.authorId;h&&!n.has(h)&&n.set(h,A.authorDisplay||h)}let o=e.createDiv({cls:"stashpad-shared-filters"}),r=(A,h,p)=>{let u=o.createEl("button",{cls:"stashpad-shared-chip",text:A});return h&&u.addClass("is-active"),u.onclick=p,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 A=o.createEl("select",{cls:"stashpad-shared-author-select"}),h=A.createEl("option",{text:"Any author"});h.value="__any__";for(let[u,g]of n){let I=A.createEl("option",{text:g});I.value=u}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;A.value=p,A.onchange=()=>{let u=A.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(A=>{if(this.sharedContribOnly&&A.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return A.authorId===i;case"others":return A.authorId!==i;default:return A.authorId===this.sharedAuthorFilter}});if(c.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let A of c){let h=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),p=h.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(p,"users"),A.color&&(p.style.color=A.color);let u=h.createSpan({cls:"stashpad-pinned-label",text:A.title});u.onclick=()=>this.openSharedFromPanel(A.folder,A.id);let g=A.folder.split("/").pop()||A.folder;h.createSpan({cls:"stashpad-pinned-folder",text:g}),A.authorDisplay&&h.createSpan({cls:"stashpad-shared-meta"}).setText(A.authorId===i?`you \xB7 ${A.contributorCount} contributor${A.contributorCount===1?"":"s"}`:`by ${A.authorDisplay}${A.contributorCount>0?` \xB7 ${A.contributorCount} contributor${A.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===F&&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===F)continue;let c=this.extractAuthorId(l.author),A=Array.isArray(l.contributors)?l.contributors.filter(C=>typeof C=="string"):[],h=s.get(r)??null;if(!(A.length>0||h===t&&(c!==null&&c!==t)))continue;let m=this.titleFromFile(o),f=typeof l.color=="string"?l.color:null;n.push({file:o,folder:r,id:l.id,title:m,color:f,authorId:c,authorDisplay:this.extractAuthorDisplay(l.author)||(c??""),contributorCount:A.length})}return n.sort((o,r)=>{let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},c=this.app.metadataCache.getFileCache(r.file)?.frontmatter??{},A=l.modified??l.created??"";return(c.modified??c.created??"").localeCompare(A)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),i=this.collectTasks();if(i.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks yet \u2014 press H on a note to mark it a task, or D to give it a due date.");return}let s=(this.plugin.settings.authorId??"").trim(),n=S=>!!s&&S.assignedTo.some(T=>T.id===s),o=S=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let P=T.slice(7);return S.assignedTo.some(R=>R.id===P)}switch(T){case"mine":return n(S);case"others":return S.assignedTo.length>0&&!n(S);case"byme":return!!s&&S.assignedBy?.id===s;case"unassigned":return S.assignedTo.length===0;default:return!0}},r=new Map;for(let S of i){for(let T of S.assignedTo)T.id!==s&&r.set(T.id,T.name);S.assignedBy&&S.assignedBy.id!==s&&r.set(S.assignedBy.id,S.assignedBy.name)}let l=[...r.entries()].map(([S,T])=>({id:S,name:T})).sort((S,T)=>S.name.localeCompare(T.name)),c=e.createDiv({cls:"stashpad-task-assign-bar"});c.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let A=c.createEl("select",{cls:"stashpad-task-assign-select"}),h=S=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return S.startsWith("person:")?r.get(S.slice(7))??"Person":T[S]??S},p=S=>{let T=A.createEl("option",{text:h(S),value:S});this.taskAssignFilter===S&&(T.selected=!0)};for(let S of["all","mine","others","byme","unassigned"])p(S);if(l.length>0){let S=A.createEl("optgroup");S.setAttr("label","By person");for(let T of l){let P=S.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(P.selected=!0)}}A.onchange=()=>{this.taskAssignFilter=A.value,this.render()};let u=[...new Set(i.map(S=>S.folder))].sort((S,T)=>S.localeCompare(T));this.taskFolderFilter!=="all"&&!u.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let g=e.createDiv({cls:"stashpad-task-assign-bar"});g.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let I=g.createEl("select",{cls:"stashpad-task-assign-select"}),m=I.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(m.selected=!0);for(let S of u){let T=I.createEl("option",{text:S.split("/").pop()||S,value:S});this.taskFolderFilter===S&&(T.selected=!0)}I.onchange=()=>{this.taskFolderFilter=I.value,this.render()};let f=S=>this.taskFolderFilter==="all"||S.folder===this.taskFolderFilter,C=i.filter(S=>o(S)&&f(S));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 Q=B.getTime(),y=Q+24*60*60*1e3,E={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let S of C){if(S.completed){E.completed.push(S);continue}if(S.due==null){E.nodate.push(S);continue}S.due<Q?E.overdue.push(S):S.due<y?E.today.push(S):E.upcoming.push(S)}let v=(S,T)=>S.due==null&&T.due==null?S.title.localeCompare(T.title):S.due==null?1:T.due==null?-1:S.due-T.due,w=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],D=e.createDiv({cls:"stashpad-task-filters"}),b=C.length,H=(S,T,P)=>{let R=D.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===S&&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=S,this.render()}};H("all","All",b),H("overdue","Overdue",E.overdue.length),H("today","Today",E.today.length),H("upcoming","Upcoming",E.upcoming.length),H("nodate","No date",E.nodate.length),H("completed","Done",E.completed.length);let U=this.taskFilter==="all"?w:w.filter(S=>S.key===this.taskFilter),x=!1;for(let S of U){let T=E[S.key];if(T.length!==0){if(x=!0,T.sort(S.key==="completed"?(P,R)=>v(R,P):v),this.taskFilter==="all"){let P=e.createDiv({cls:`stashpad-task-section-header is-${S.key}`});(0,rt.setIcon)(P.createSpan({cls:"stashpad-task-section-icon"}),S.icon),P.createSpan({cls:"stashpad-task-section-name",text:S.label}),P.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let P of T)this.renderTaskRow(e,P,S.key==="today")}}if(!x&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${U[0]?.label??this.taskFilter}".`);return}x||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=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 A=l.createSpan({cls:"stashpad-task-assignee"});r&&c.id===r&&A.addClass("is-me"),A.setText(this.initials(c.name)),A.title=r&&c.id===r?`${c.name} (you)`:c.name}}s.oncontextmenu=r=>{r.preventDefault();let l=new rt.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?Yo(t,this.plugin.settings):Oo(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??{},r=typeof o.id=="string"?o.id:null;if(!r||r===F)continue;let l=o.completed===!0,c=Ye(o,"task")||o.task===!0||o.completed!==void 0,A=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,h=null;if(A){let p=Date.parse(A);Number.isNaN(p)||(h=p)}!c&&!l&&h==null&&!A||i.push({file:s,folder:n,id:r,title:this.titleFromFile(s),task:c,completed:l,due:h,dueRaw:A,color:typeof o.color=="string"?o.color:null,assignedTo:De(o),assignedBy:ue(o.assignedBy)})}return i}};async function cs(d){let a=d.workspace.getLeavesOfType(pe);if(a.length>0){d.workspace.revealLeaf(a[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new rt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:pe,active:!0}),d.workspace.revealLeaf(t)}var Ta=require("obsidian");at();var N=require("obsidian");xi();var gs=require("obsidian");at();var ti=class extends gs.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!=="/"&&fi.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let r of o.children)r instanceof gs.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()}};at();kt();var Pe=require("obsidian"),bn={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."}},nl={info:4e3,success:4e3,warning:6e3,error:1e4},ca=5e3,us=class{constructor(a){this.app=a;this.history=[];this.nextId=1;this.historyLimit=ca;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??nl[t];return new Pe.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:ca,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(A=>console.warn("[Stashpad] notification action failed",A)),!r.keepOpen){let A=l.closest(".notice");A&&A.parentElement&&A.parentElement.removeChild(A)}}),o.appendChild(l)}i.appendChild(o)}return e.appendChild(i),e}};function Is(d,a,t){let e=d.vault.getAbstractFileByPath(a);if(!(e instanceof Pe.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=d.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;d.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=Pe.Platform.isMacOS?"Finder":Pe.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,r=d.vault.adapter?.getFullPath?.(a);r&&n?.showItemInFolder&&n.showItemInFolder(r)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var Aa=require("obsidian"),Nn=Aa.Platform.isMacOS;function Mi(d){if(!d)return"(none)";let a=d.replace(/\bMod\b/g,Nn?"Cmd":"Ctrl");return Nn&&(a=a.replace(/\bAlt\b/g,"Option")),a}function da(d,a,t={allowSingleKey:!0}){let e=d.placeholder,i=d.value;d.placeholder="Press a key\u2026 (Backspace to cancel)",d.value="",d.classList.add("is-recording");let s=!1,n=()=>{d.placeholder=e,d.classList.remove("is-recording"),s||(d.value=i),d.removeEventListener("keydown",o,!0),d.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 A=[];Nn?(l.metaKey&&A.push("Mod"),l.ctrlKey&&A.push("Ctrl")):l.ctrlKey&&A.push("Mod"),l.altKey&&A.push("Alt"),l.shiftKey&&A.push("Shift");let h=ol(l.key,l.code);if(!h||A.length===0&&!t.allowSingleKey)return;A.push(h);let p=A.join("+");s=!0,n(),a(p)},r=()=>n();return d.addEventListener("keydown",o,!0),d.addEventListener("blur",r),n}function ol(d,a){if(!d)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 d.length===1?d.toUpperCase():d}je();Ut();function He(d,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(A){n(A)}}function r(c){try{l(e.throw(c))}catch(A){n(A)}}function l(c){c.done?s(c.value):i(c.value).then(o,r)}l((e=e.apply(d,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 He(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(a())}finally{t()}})}},xn;function al(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Hn=al(),Mn=(xn=Hn.Buffer)!==null&&xn!==void 0?xn:null,rl=Hn.TextEncoder?new Hn.TextEncoder:null;function fa(d,a){return(d&15)+(d>>6|d>>3&8)<<4|(a&15)+(a>>6|a>>3&8)}function ma(d,a){let t=a.length>>1;for(let e=0;e<t;e++){let i=e<<1;d[e]=fa(a.charCodeAt(i),a.charCodeAt(i+1))}}function ll(d,a){if(d.length!==a.length*2)return!1;for(let t=0;t<a.length;t++){let e=t<<1;if(a[t]!==fa(d.charCodeAt(e),d.charCodeAt(e+1)))return!1}return!0}var ha=87,pa=48;function Un(d,a,t){let e=0;for(let i=0;i<t;i++){let s=a[i]>>>4;d[e++]=s>9?s+ha:s+pa,s=a[i]&15,d[e++]=s>9?s+ha:s+pa}return String.fromCharCode.apply(null,d)}var re=Mn!==null?d=>{if(typeof d=="string"){let a=Mn.from(d,"utf8");return new Uint8Array(a.buffer,a.byteOffset,a.length)}if(Mn.isBuffer(d))return new Uint8Array(d.buffer,d.byteOffset,d.length);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")}:d=>{if(typeof d=="string")return rl.encode(d);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")},Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Pi=new Uint8Array(256);for(let d=0;d<Rt.length;d++)Pi[Rt.charCodeAt(d)]=d;function ga(d,a=!0){let t=d.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(d[n]<<16&16711680)+(d[n+1]<<8&65280)+(d[n+2]&255),r=Rt.charAt(o>>18&63)+Rt.charAt(o>>12&63)+Rt.charAt(o>>6&63)+Rt.charAt(o&63);i.push(r)}if(e===1){let n=d[t-1],o=Rt.charAt(n>>2),r=Rt.charAt(n<<4&63);i.push(`${o}${r}`),a&&i.push("==")}else if(e===2){let n=(d[t-2]<<8)+d[t-1],o=Rt.charAt(n>>10),r=Rt.charAt(n>>4&63),l=Rt.charAt(n<<2&63);i.push(`${o}${r}${l}`),a&&i.push("=")}return i.join("")}function cl(d){let a=Math.floor(d.length*.75),t=d.length;return d[t-1]==="="&&(a-=1,d[t-2]==="="&&(a-=1)),a}function Al(d){let a=cl(d),t=d.length,e=new Uint8Array(a),i=0;for(let s=0;s<t;s+=4){let n=Pi[d.charCodeAt(s)],o=Pi[d.charCodeAt(s+1)],r=Pi[d.charCodeAt(s+2)],l=Pi[d.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 fs=16*1024,Ti=4,dl=new ot,Tn=new Map;function Ca(d,a){return He(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,E=0)=>{e.set(y,E)},n=()=>e,o=()=>t.exports,r=y=>{t.exports.Hash_SetMemorySize(y);let E=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,E,y)},l=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),c=dl.dispatch(()=>He(this,void 0,void 0,function*(){if(!Tn.has(d.name)){let E=Al(d.data),v=WebAssembly.compile(E);Tn.set(d.name,v)}let y=yield Tn.get(d.name);t=yield WebAssembly.instantiate(y,{})})),A=()=>He(this,void 0,void 0,function*(){t||(yield c);let y=t.exports.Hash_GetBuffer(),E=t.exports.memory.buffer;e=new Uint8Array(E,y,fs)}),h=(y=null)=>{i=!0,t.exports.Hash_Init(y)},p=y=>{let E=0;for(;E<y.length;){let v=y.subarray(E,E+fs);E+=v.length,e.set(v),t.exports.Hash_Update(v.length)}},u=y=>{if(!i)throw new Error("update() called before init()");let E=re(y);p(E)},g=new Uint8Array(a*2),I=(y,E=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(E),y==="binary"?e.slice(0,a):Un(g,e,a)},m=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),E=l(),v=t.exports.memory.buffer,w=new Uint8Array(v,y,E),D=new Uint8Array(Ti+E);return ma(D,d.hash),D.set(w,Ti),D},f=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let E=t.exports.Hash_GetState(),v=l(),w=Ti+v,D=t.exports.memory.buffer;if(y.length!==w)throw new Error(`Bad state length (expected ${w} bytes, got ${y.length})`);if(!ll(d.hash,y.subarray(0,Ti)))throw new Error("This state was written by an incompatible hash implementation");let b=y.subarray(Ti);new Uint8Array(D,E,v).set(b),i=!0},C=y=>typeof y=="string"?y.length<fs/4:y.byteLength<fs,B=C;switch(d.name){case"argon2":case"scrypt":B=()=>!0;break;case"blake2b":case"blake2s":B=(y,E)=>E<=512&&C(y);break;case"blake3":B=(y,E)=>E===0&&C(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":B=()=>!1;break}let Q=(y,E=null,v=null)=>{if(!B(y,E))return h(E),u(y),I("hex",v);let w=re(y);return e.set(w),t.exports.Hash_Calculate(w.length,E,v),Un(g,e,a)};return yield A(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:r,init:h,update:u,digest:I,save:m,load:f,calculate:Q,hashLength:a}})}var uA=new ot;var hl="argon2",pl="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",gl="e4cdc523",ul={name:hl,data:pl,hash:gl},Il="blake2b",fl="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=",ml="c6f286e6",Cl={name:Il,data:fl,hash:ml},IA=new ot;function ua(d){return!Number.isInteger(d)||d<8||d>512||d%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function Bl(d,a){return d|a<<16}function Rn(d=512,a=null){if(ua(d))return Promise.reject(ua(d));let t=null,e=d;if(a!==null){if(t=re(a),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=Bl(d,t.length)}let i=d/8;return Ca(Cl,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 yl(d,a,t){let e=[`m=${a.memorySize}`,`t=${a.iterations}`,`p=${a.parallelism}`].join(",");return`$argon2${a.hashType}$v=19$${e}$${ga(d,!1)}$${ga(t,!1)}`}var Ia=new DataView(new ArrayBuffer(4));function ae(d){return Ia.setInt32(0,d,!0),new Uint8Array(Ia.buffer)}function Pn(d,a,t){return He(this,void 0,void 0,function*(){if(t<=64){let r=yield Rn(t*8);return r.update(ae(t)),r.update(a),r.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);d.init(),d.update(ae(t)),d.update(a);let s=d.digest("binary");i.set(s.subarray(0,32),0);for(let r=1;r<e;r++)d.init(),d.update(s),s=d.digest("binary"),i.set(s.subarray(0,32),r*32);let n=t-32*e,o;return n===64?(o=d,o.init()):o=yield Rn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function Ql(d){switch(d){case"d":return 0;case"i":return 1;default:return 2}}function El(d){return He(this,void 0,void 0,function*(){var a;let{parallelism:t,iterations:e,hashLength:i}=d,s=re(d.password),n=re(d.salt),o=19,r=Ql(d.hashType),{memorySize:l}=d,c=re((a=d.secret)!==null&&a!==void 0?a:""),[A,h]=yield Promise.all([Ca(ul,1024),Rn(512)]);A.setMemorySize(l*1024+1024);let p=new Uint8Array(24),u=new DataView(p.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),A.writeMemory(p,l*1024),h.init(),h.update(p),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 I=Math.floor(l/(t*4))*4,m=new Uint8Array(72),f=h.digest("binary");m.set(f);for(let Q=0;Q<t;Q++){m.set(ae(0),64),m.set(ae(Q),68);let y=Q*I,E=yield Pn(h,m,1024);A.writeMemory(E,y*1024),y+=1,m.set(ae(1),64),E=yield Pn(h,m,1024),A.writeMemory(E,y*1024)}let C=new Uint8Array(1024);ma(C,A.calculate(new Uint8Array([]),l));let B=yield Pn(h,C,i);if(d.outputType==="hex"){let Q=new Uint8Array(i*2);return Un(Q,B,i)}return d.outputType==="encoded"?yl(n,d,B):B})}var wl=d=>{var a;if(!d||typeof d!="object")throw new Error("Invalid options parameter. It requires an object.");if(!d.password)throw new Error("Password must be specified");if(d.password=re(d.password),d.password.length<1)throw new Error("Password must be specified");if(!d.salt)throw new Error("Salt must be specified");if(d.salt=re(d.salt),d.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(d.secret=re((a=d.secret)!==null&&a!==void 0?a:""),!Number.isInteger(d.iterations)||d.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(d.parallelism)||d.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(d.hashLength)||d.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(d.memorySize))throw new Error("Memory size should be specified.");if(d.memorySize<8*d.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(d.outputType===void 0&&(d.outputType="hex"),!["hex","binary","encoded"].includes(d.outputType))throw new Error(`Insupported output type ${d.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Gn(d){return He(this,void 0,void 0,function*(){return wl(d),El(Object.assign(Object.assign({},d),{hashType:"id"}))})}var fA=new ot;var mA=new ot;var CA=new ot;var BA=new ot;var yA=new Uint8Array(8);var QA=new ot;var EA=new ot;var wA=new ot;var vA=new ot;var FA=new ot;var kA=new ot;var SA=new ot;var DA=new ot;var bA=new ot;var NA=new ot;var xA=new ot;var MA=new Uint8Array(8);var TA=new ot;var PA=new Uint8Array(8);var HA=new ot;var UA=new Uint8Array(8);var RA=new ot;var GA=new ot;var LA=new ot;kt();var Gt=new Uint8Array([83,84,65,83,72,69,78,67]),Jn=2,Kn=1,On=2,Qa=3,vl=32,ei=12,Ln=32,Fl=6e5,kl=47104,Sl=3,Dl=1,pt=d=>d;function bt(d){if(d.length<Gt.length+1)return!1;for(let a=0;a<Gt.length;a++)if(d[a]!==Gt[a])return!1;return!0}function Ba(d,a,t){d[a]=t>>>24&255,d[a+1]=t>>>16&255,d[a+2]=t>>>8&255,d[a+3]=t&255}function ya(d,a){return d[a]*16777216+(d[a+1]<<16)+(d[a+2]<<8)+d[a+3]}async function qn(d,a,t){if(t.id===On)return await Gn({password:d,salt:a,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Ln,outputType:"binary"});if(t.id===Kn){let e=await crypto.subtle.importKey("raw",pt(new TextEncoder().encode(d)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:pt(a),iterations:t.a,hash:"SHA-256"},e,Ln*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function ms(d){return crypto.subtle.importKey("raw",pt(d),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var Yn={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function zt(d,a){let t=crypto.getRandomValues(new Uint8Array(vl)),e=crypto.getRandomValues(new Uint8Array(ei)),i,s,n;try{i={id:On,a:kl,b:Sl,c:Dl},n=await qn(a,t,i),s="argon2id"}catch(A){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",A),i={id:Kn,a:Fl,b:0,c:0},n=await qn(a,t,i),s="pbkdf2"}let o=Ea(i,t,e),r=await ms(n),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(e),additionalData:pt(o)},r,pt(d))),c=new Uint8Array(o.length+l.length);return c.set(o,0),c.set(l,o.length),{data:c,kdf:s}}var Hi=null;async function Ui(){if(Hi!==null)return Hi;try{await Gn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Hi=!0}catch{Hi=!1}return Hi}function Ea(d,a,t){let e=new Uint8Array(Gt.length+1+1+4+4+1+1+a.length+t.length),i=0;return e.set(Gt,i),i+=Gt.length,e[i++]=Jn,e[i++]=d.id,Ba(e,i,d.a),i+=4,Ba(e,i,d.b),i+=4,e[i++]=d.c,e[i++]=a.length,e.set(a,i),i+=a.length,e.set(t,i),i+=t.length,e}async function Vt(d,a){if(!bt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Gt.length];if(t===1)return bl(d,a);if(t!==Jn)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Gt.length+1,i={id:d[e++],a:0,b:0,c:0};if(i.a=ya(d,e),e+=4,i.b=ya(d,e),e+=4,i.c=d[e++],i.id===On){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===Kn&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=d[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=d.slice(e,e+s);e+=s;let o=d.slice(e,e+ei);e+=ei;let r=d.slice(0,e),l=d.slice(e),c=await qn(a,n,i),A=await ms(c),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(o),additionalData:pt(r)},A,pt(l));return new Uint8Array(h)}async function bl(d,a){let t=Gt.length+1,e=d.slice(t,t+16);t+=16;let i=d.slice(t,t+12);t+=12;let s=d.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 ii(d,a){if(a.length!==Ln)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(ei)),i=Ea({id:Qa,a:0,b:0,c:0},new Uint8Array(0),t),s=await ms(a),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(t),additionalData:pt(i)},s,pt(d))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function Nt(d,a){if(!bt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Gt.length];if(t!==Jn)throw new Error(`Unsupported encrypted version (${t}).`);let e=Gt.length+1;if(d[e++]!==Qa)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=d[e++];e+=s;let n=d.slice(e,e+ei);e+=ei;let o=d.slice(0,e),r=d.slice(e),l=await ms(a),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(n),additionalData:pt(o)},l,pt(r));return new Uint8Array(c)}async function si(d,a,t={}){if(!bt(a))return a;if(t.secretId){let i=d.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Vt(a,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new wi(d,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Vt(a,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Ut();var Cs={name:"ECDH",namedCurve:"P-256"},Nl="stashpad-vault-dek-wrap",xl=new TextEncoder;function $n(d){let a="";for(let t=0;t<d.length;t++)a+=String.fromCharCode(d[t]);return btoa(a)}function Vn(d){let a=atob(d),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}async function wa(){let d=await crypto.subtle.generateKey(Cs,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",d.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",d.privateKey))}}function va(d){return crypto.subtle.importKey("spki",d,Cs,!1,[])}function Ml(d){return crypto.subtle.importKey("pkcs8",d,Cs,!1,["deriveBits"])}async function Fa(d,a){let t=await crypto.subtle.deriveBits({name:"ECDH",public:a},d,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:xl.encode(Nl)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Bs(d,a,t){let e=await crypto.subtle.generateKey(Cs,!0,["deriveBits"]),i=await Fa(e.privateKey,await va(a)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,d)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:$n(o),iv:$n(s),ct:$n(n)}}async function ka(d,a){let t=await Fa(await Ml(a),await va(Vn(d.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Vn(d.iv)},t,Vn(d.ct)))}var Sa=".stashpad/keys.json",Tl=".stashpad",Ri="_keys";function zn(d){return{v:2,keyId:d,identities:[],slots:[],joinRequests:[]}}var ys=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(Sa);if(a)return a;try{let e=((await this.a.list(Ri)).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(Tl),await this.a.write(Sa,t),await this.ensureDir(Ri);for(let e=4;e>=1;e--){let i=`${Ri}/keys-${e}.json`,s=`${Ri}/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(`${Ri}/keys-1.json`,t)}catch{}}};var Ue="stashpad-vault-encryption";function Gi(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function Re(d){let a="";for(let t=0;t<d.length;t++)a+=String.fromCharCode(d[t]);return btoa(a)}function Wt(d){let a=atob(d),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}var Da=32,Qs=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 ys(a)}argonProbe(){return Ui()}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`${Ue}-${this.appTag()}`}legacyAppIdKeychainId(){let a=this.app.appId||"default";return`${Ue}-${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(Ue)||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(Ue)??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(Ue):await a?.setSecret(Ue,"")}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(Da)),s=await this.mintIdentity(a,e),n=zn(W(8));n.identities.push(this.identityRecord(s)),n.slots.push(await Bs(i,Wt(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 Vt(Wt(e.wrappedKey),a)}catch{return!1}let n=await this.mintIdentity(a,e.identityLabel??void 0),o=zn(W(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await Bs(s,Wt(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 Vt(Wt(e.identityPrivWrapped),a);try{let n=await ka(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 Vt(Wt(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 zt(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:Re(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))}folderKeyEntry(a){return this.kf?.folderKeys?.[this.cleanFolder(a)]??null}hasFolderKey(a){return!!this.folderKeyEntry(a)}folderActiveSlots(a){return a.passwordSlots.filter(t=>!t.label.startsWith("[deprecated]"))}isFolderUnlocked(a){return this.folderKeyEntry(a)?this.folderSessionKeys.has(this.cleanFolder(a)):this.isUnlocked()}getFolderKey(a){if(!this.folderKeyEntry(a))return this.getSessionKey();let e=this.folderSessionKeys.get(this.cleanFolder(a));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=crypto.getRandomValues(new Uint8Array(Da)),o=await zt(n,t),r=W(8),l={keyId:r,folderPath:s,label:e,kcId:this.folderKcId(e,r),passwordSlots:[{id:W(8),label:"Folder password",wrapped:Re(o.data),kdf:o.kdf,createdAt:new Date().toISOString()}],createdAt:new Date().toISOString()};this.kf.folderKeys={...this.kf.folderKeys??{},[s]:l},await this.keyfiles.save(this.kf),this.folderSessionKeys.set(s,n),i&&await this.rememberFolder(this.folderKcIdFor(l),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 Vt(Wt(n.wrapped),t);this.folderSessionKeys.set(i,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),s=this.folderSessionKeys.get(i);if(!s)throw new Error("Unlock this folder first.");await this.refresh();let n=this.folderKeyEntry(i);if(!n||!this.kf)throw new Error("This folder has no key.");let o=n.passwordSlots.filter(p=>!p.label.startsWith("[deprecated]")),r=this.folderKcIdFor(n),l=this.rememberedFolderPassword(r);if(l&&o[0])try{await this.secretStore()?.setSecret(`${r}-d-${o[0].id}`,l)}catch{}let c=await zt(s,t),A=n.passwordSlots.map(p=>p.label.startsWith("[deprecated]")?p:{...p,label:`[deprecated] ${p.label}`}),h={...n,kcId:n.kcId??this.folderKcId(n.label,n.keyId),passwordSlots:[{id:W(8),label:"Folder password",wrapped:Re(c.data),kdf:c.kdf,createdAt:new Date().toISOString()},...A]};this.kf.folderKeys={...this.kf.folderKeys??{},[i]:h},await this.keyfiles.save(this.kf),(e||this.isFolderRemembered(r))&&await this.rememberFolder(this.folderKcIdFor(h),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?.keyId??W(8),c=r?this.folderKcIdFor(r):null,A=(r?.passwordSlots??[]).filter(f=>!f.label.startsWith("[deprecated]")),h=c?this.rememberedFolderPassword(c):null;if(h&&A[0])try{await this.secretStore()?.setSecret(`${c}-d-${A[0].id}`,h)}catch{}let p=await zt(e,t),u=(r?.passwordSlots??[]).map(f=>f.label.startsWith("[deprecated]")?f:{...f,label:`[deprecated] ${f.label}`}),g=s??r?.label??`rotated - ${o.split("/").pop()||o}`,I={keyId:l,folderPath:o,label:g,kcId:this.folderKcId(g,l),rotId:i,passwordSlots:[{id:W(8),label:"Folder password",wrapped:Re(p.data),kdf:p.kdf,createdAt:new Date().toISOString()},...u],createdAt:r?.createdAt??new Date().toISOString()};this.kf.folderKeys={...this.kf.folderKeys??{},[o]:I},await this.keyfiles.save(this.kf);let m=this.folderSessionKeys.get(o);m&&m!==e&&m.fill(0),this.folderSessionKeys.set(o,e),(n||c&&this.isFolderRemembered(c))&&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||`${Ue}-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 Vt(Wt(t.identityPrivWrapped),a)).fill(0),!0;if(t.wrappedKey)return(await Vt(Wt(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 Vt(Wt(s.identityPrivWrapped),a)}catch{return!1}let o=await zt(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:Re(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 Bs(this.sessionKey,Wt(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.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(Gi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(a,t){let e=await wa(),i=await zt(e.privKeyPkcs8,a);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??W(8),o=t??s.identityLabel??"This device",r=Re(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:r,identityPrivWrapped:Re(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 Li=null,Es=new Set;function ws(d){if(Li!==d){Li=d;for(let a of Es)a()}}function le(){return Li}function ba(d){if(Li===d){Li=null;for(let a of Es)a()}}function Na(d){return Es.add(d),()=>Es.delete(d)}function Pl(){return N.Platform.isMacOS?"Finder":N.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 Zn(){let d={};for(let a of ni)d[a.id]={primary:a.defaultPrimary,secondary:a.defaultSecondary??"",preferRight:!1,useBoth:!!a.defaultUseBoth};return d}var Hl=!1,Ul=!1,me={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,debugTrace:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,splitMode:"lines",confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,encryption:Gi(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],folderEncPrefs:{},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:Zn()},xa=JSON.parse(JSON.stringify(me)),Xn=new Set;function j(){return xa}function jn(d){xa=d;for(let a of Xn)a()}function Ma(d){return Xn.add(d),()=>Xn.delete(d)}function ks(d){try{let a=d.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 vs=[{id:"foldersStorage",label:"Folders & storage"},{id:"importExport",label:"Import & export"},{id:"noteTitles",label:"Note titles"},{id:"datesTime",label:"Dates & time"},{id:"listDisplay",label:"List & display"},{id:"movingNotes",label:"Moving notes"},{id:"deleting",label:"Deleting"},{id:"composerCopy",label:"Composer & copying"},{id:"windowsTabs",label:"Windows & tabs"},{id:"notifications",label:"Notifications"},{id:"encryption",label:"Encryption"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"okf",label:"Open Knowledge Format (OKF)"},{id:"maintenance",label:"Maintenance"},{id:"diagnostics",label:"Diagnostics"},{id:"misc",label:"Misc"},{id:"hotkeys",label:"Hotkeys"}].sort((d,a)=>d.label.localeCompare(a.label)),Wn=null;function Rl(d,a){return Wn||(Wn=class extends N.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new Wn(d,a)}var Fs=class extends N.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.pfeSelected=null}display(){let{containerEl:t}=this;t.empty();for(let e of vs){new N.Setting(t).setName(e.label).setHeading();let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new N.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 vs.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>Rl(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 N.Notice("Debug trace is empty \u2014 enable it and reproduce the issue first.");return}try{await navigator.clipboard.writeText(i),new N.Notice("Debug trace copied.")}catch{new N.Notice("Couldn't access clipboard.")}})),t.addButton(e=>e.setButtonText("Clear").onClick(()=>{this.plugin.clearDebugTrace(),new N.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 N.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(bn);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=bn[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 Fi(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 N.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)}}}}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 At(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 N.Notice("Folder password set \u2014 share it securely."),this.update?.(),null}}).open()}promptChangeFolderPassword(t){new At(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 N.Notice("Folder password changed."),this.update?.(),null}}).open()}promptRotateFolderKey(t){let e=t.split("/").pop()||t;new nt(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 At(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 At(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 N.Notice("Folder unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()}encryptionOrOnboard(){return this.plugin.encryption?.isConfigured?.()?!0:(new N.Notice("That setting needs vault encryption, which isn't set up yet \u2014 let's set it up first.",6e3),new At(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 N.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}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 N.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.hasFolderKey(e),n=i.isFolderUnlocked(e),o=(this.plugin.settings.folderEncPrefs??{})[e]??{},r=s?n?"Has its own password \xB7 unlocked":"Has its own password \xB7 locked":"Uses the vault password",l=new N.Setting(t).setName("Password").setDesc(r);s?n?(l.addButton(h=>h.setButtonText("Lock (forget password)").onClick(()=>{this.plugin.encryption.lockFolder(e),new N.Notice("Folder locked \u2014 you'll re-enter its password next time."),this.update?.()})),l.addButton(h=>h.setButtonText("Change password\u2026").onClick(()=>this.promptChangeFolderPassword(e))),l.addButton(h=>{h.setButtonText("Rotate key\u2026").onClick(()=>this.promptRotateFolderKey(e)),h.buttonEl.addClass("mod-warning")})):l.addButton(h=>h.setButtonText("Unlock\u2026").setCta().onClick(()=>this.promptUnlockFolder(e))):l.addButton(h=>h.setButtonText("Set folder password\u2026").setCta().onClick(()=>this.promptSetFolderPassword(e)));let c=async h=>{this.plugin.settings.folderEncPrefs={...this.plugin.settings.folderEncPrefs??{},[e]:{...(this.plugin.settings.folderEncPrefs??{})[e]??{},...h}},await this.plugin.saveSettings()};new N.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(h=>h.setValue(!!o.archive).onChange(async p=>{await c({archive:p,...p&&o.archiveEncryptContent===void 0?{archiveEncryptContent:!0}:{}});let u=new Set((this.plugin.settings.archiveFolders??[]).map(g=>g.replace(/\/+$/,"")));p?u.add(e):u.delete(e),this.plugin.settings.archiveFolders=[...u],!p&&(this.plugin.settings.defaultArchiveFolder??"")===e&&(this.plugin.settings.defaultArchiveFolder=void 0),await this.plugin.saveSettings(),this.plugin.refreshFolderPanels(),this.update?.()})),new N.Setting(t).setName("Trash handling").setDesc("Where notes deleted from this folder go.").addDropdown(h=>h.addOption("","Use global default").addOption("stashpad","Stashpad encrypted trash").addOption("obsidian","Obsidian native trash").setValue(o.trashHandling??"").onChange(p=>c({trashHandling:p||void 0})));let A=(h,p,u,g)=>{new N.Setting(t).setName(h).addToggle(I=>I.setValue(!!o[p]).onChange(async m=>{let f={};f[p]=m,m||(f[u]=!1),await c(f),g&&await g(m),this.update?.()})),new N.Setting(t).setName(`\u21B3 ${h} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(I=>{I.setValue(!!o[u]),I.setDisabled(!o[p]),I.onChange(m=>{let f={};f[u]=m,c(f)})})};A("Encrypt this folder's notes","encryptContent","encryptFilenames",async h=>{h?await this.plugin.lockFolder(e):await this.plugin.unlockFolder(e);let p=(this.plugin.settings.lockedSubtrees??[]).some(u=>(u.folder||"").replace(/\/+$/,"")===e);await c({encryptContent:p,...p?{}:{encryptFilenames:!1}})}),A("Encrypt archived notes","archiveEncryptContent","archiveEncryptFilenames"),A("Encrypt trashed notes","trashEncryptContent","trashEncryptFilenames")}buildGeneralCategories(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,r,l)=>this.renderDef(s,n,c=>c.addToggle(A=>A.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,"")||me.folder,l=r.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(A=>(A??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(l)){new N.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.importExport.push(this.renderDef("Dedicated import subfolder (optional)","Optional. A subfolder (relative to each Stashpad folder) where dropped .stash files auto-import. Leave blank to just drop files into the Stashpad folder itself (recommended). Suggested name: _imports.",s=>s.addText(n=>n.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async o=>{this.plugin.settings.importDropFolder=(o||"").trim().replace(/^\/+|\/+$/g,""),await t()})),["import","subfolder"])),i.importExport.push(this.renderDef("Stash export subfolder","Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.",s=>s.addText(n=>n.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async o=>{this.plugin.settings.exportFolder=(o||"").trim().replace(/^\/+|\/+$/g,"")||me.exportFolder,await t()})),["export","stash","subfolder"])),i.maintenance.push(this.renderDef("Rebootstrap existing Stashpad folders","Walk every folder that has a home note: ensure infrastructure (_imports, _exports, drafts file), backfill the redundant parentLink + children frontmatter fields, rename any note whose filename slug no longer matches its body's first line, AND migrate legacy attachment filenames to the new name-first format (`photo-<id>.png`). Safe to run anytime; skip-if-equal means already-synced notes are no-op writes.",s=>s.addButton(n=>n.setButtonText("Rebootstrap now").onClick(async()=>{n.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:o,fmChecked:r,fmWritten:l,slugsRenamed:c,authors:A,imported:h,attachmentsLinked:p,attachmentsRenamed:u,attachmentsSkipped:g}=await this.plugin.rebootstrapAllFolders(),I=[];I.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),h>0&&I.push(`imported ${h} loose file${h===1?"":"s"}`),p>0&&I.push(`linked attachments on ${p} note${p===1?"":"s"}`),u>0&&I.push(`renamed ${u} attachment${u===1?"":"s"}`),l>0?I.push(`updated frontmatter on ${l} of ${r} notes`):r>0&&I.push(`frontmatter already in sync (${r} notes checked)`),c>0&&I.push(`renamed ${c} note${c===1?"":"s"} to match body`),A>0&&I.push(`rebuilt author registry (${A} author${A===1?"":"s"})`),new N.Notice(`Stashpad: ${I.join("; ")}.`),g>0&&new N.Notice(`Stashpad: ${g} attachment${g===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(o){new N.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.maintenance.push(this.renderDef("Write recovery navigation links","Maintain the redundant parentLink/children frontmatter so you can walk the hierarchy from raw Markdown if the index ever breaks. On a slow / network drive this is a big per-move cost (several round-trips each); turn it off there for snappier moves \u2014 Rebootstrap rebuilds the fields on demand, and your notes' canonical structure (id/parent) is unaffected either way.",s=>s.addToggle(n=>n.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async o=>{this.plugin.settings.writeRecoveryLinks=o,await t()})),["recovery","parentlink","children","frontmatter"])),i.datesTime.push(this.renderDef("Use Templates plugin date/time formats","When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.",s=>{s.addToggle(o=>o.setValue(this.plugin.settings.useTemplatesFormat).onChange(async r=>{this.plugin.settings.useTemplatesFormat=r,await t()}));let n=ks(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: ${oe(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:$t).join(` +`}function ps(d,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=d.vault.getAbstractFileByPath(a.previewPath);r instanceof ut.TFile&&await d.workspace.getLeaf("tab").openFile(r)}n?.hide()},n=new ut.Notice(t,0),n}var ut,la,xi,Mi=qt(()=>{"use strict";ut=require("obsidian");Ut();_e();at();la=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;xi=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 A=await hs(this.app,this.plugin,this.settings);if(A.error==="no-dest"){new ut.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(A.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=A.previewPath,ps(this.app,A),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(A){new ut.Notice(`Preview failed: ${A?.message??A}`,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 cc(d,a){return lc(d,a||{},0,0)}function Ac(d,a){return sc(d,{i:2},a&&a.out,a&&a.dictionary)}function qs(d,a){if(a){for(var t=new ct(d.length),e=0;e<d.length;++e)t[e]=d.charCodeAt(e);return t}if(Za)return Za.encode(d);for(var i=d.length,s=new ct(d.length+(d.length>>1)),n=0,o=function(c){s[n++]=c},e=0;e<i;++e){if(n+5>s.length){var r=new ct(n+8+(i-e<<1));r.set(s),s=r}var l=d.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)|d.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 Vi(s,0,n)}function yo(d,a){if(a){for(var t="",e=0;e<d.length;e+=16384)t+=String.fromCharCode.apply(null,d.subarray(e,e+16384));return t}else{if(fo)return fo.decode(d);var i=hc(d),s=i.s,t=i.r;return t.length&&Ct(8),s}}function rr(d,a){a||(a={});var t={},e=[];ar(d,"",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,A=qs(n),h=A.length,g=l.comment,u=g&&qs(g),p=u&&u.length,I=mo(l.extra);h>65535&&Ct(11);var f=c?cc(r,l):r,m=f.length,C=rc();C.p(r),e.push(or(l,{size:r.length,crc:C.d(),c:f,f:A,m:u,u:h!=n.length||u&&g.length!=p,o:i,compression:c})),i+=30+h+I+m,s+=76+2*(h+I)+(p||0)+m}for(var B=new ct(s+22),Q=i,y=s-i,E=0;E<e.length;++E){var A=e[E];ja(B,A.o,A,A.f,A.u,A.c.length);var v=30+A.f.length+mo(A.extra);B.set(A.c,A.o+v),ja(B,i,A,A.f,A.u,A.c.length,A.o,A.m),i+=16+v+(A.m?A.m.length:0)}return Ic(B,i,e.length,y,Q),B}function lr(d,a){for(var t={},e=d.length-22;Mt(d,e)!=101010256;--e)(!e||d.length-e>65558)&&Ct(13);var i=Zt(d,e+8);if(!i)return{};var s=Mt(d,e+16),n=Mt(d,e-20)==117853008;if(n){var o=Mt(d,e-12);n=Mt(d,o)==101075792,n&&(i=Mt(d,o+32),s=Mt(d,o+48))}for(var r=a&&a.filter,l=0;l<i;++l){var c=gc(d,s,n),A=c[0],h=c[1],g=c[2],u=c[3],p=c[4],I=c[5],f=pc(d,I);s=p,(!r||r({name:u,size:h,originalSize:g,compression:A}))&&(A?A==8?t[u]=Ac(d.subarray(f,f+h),{out:new ct(g)}):Ct(14,"unknown compression type "+A):t[u]=Vi(d,f,f+h))}return t}var ct,Dt,Co,Js,Ks,po,_a,tr,er,go,ir,Zl,za,uo,Ae,_,jt,ye,_,_,_,_,$i,_,jl,_l,tc,ec,lo,Lt,co,Bo,Vi,ic,Ct,sc,de,Oi,Ao,Io,Wa,Yi,sr,Xa,nc,nr,oc,ac,rc,lc,or,Zt,Mt,ho,It,ar,Za,fo,dc,hc,pc,gc,uc,mo,ja,Ic,cr=qt(()=>{ct=Uint8Array,Dt=Uint16Array,Co=Int32Array,Js=new ct([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]),Ks=new ct([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]),po=new ct([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),_a=function(d,a){for(var t=new Dt(31),e=0;e<31;++e)t[e]=a+=1<<d[e-1];for(var i=new Co(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}},tr=_a(Js,2),er=tr.b,go=tr.r;er[28]=258,go[258]=28;ir=_a(Ks,0),Zl=ir.b,za=ir.r,uo=new Dt(32768);for(_=0;_<32768;++_)Ae=(_&43690)>>1|(_&21845)<<1,Ae=(Ae&52428)>>2|(Ae&13107)<<2,Ae=(Ae&61680)>>4|(Ae&3855)<<4,uo[_]=((Ae&65280)>>8|(Ae&255)<<8)>>1;jt=function(d,a,t){for(var e=d.length,i=0,s=new Dt(a);i<e;++i)d[i]&&++s[d[i]-1];var n=new Dt(a);for(i=1;i<a;++i)n[i]=n[i-1]+s[i-1]<<1;var o;if(t){o=new Dt(1<<a);var r=15-a;for(i=0;i<e;++i)if(d[i])for(var l=i<<4|d[i],c=a-d[i],A=n[d[i]-1]++<<c,h=A|(1<<c)-1;A<=h;++A)o[uo[A]>>r]=l}else for(o=new Dt(e),i=0;i<e;++i)d[i]&&(o[i]=uo[n[d[i]-1]++]>>15-d[i]);return o},ye=new ct(288);for(_=0;_<144;++_)ye[_]=8;for(_=144;_<256;++_)ye[_]=9;for(_=256;_<280;++_)ye[_]=7;for(_=280;_<288;++_)ye[_]=8;$i=new ct(32);for(_=0;_<32;++_)$i[_]=5;jl=jt(ye,9,0),_l=jt(ye,9,1),tc=jt($i,5,0),ec=jt($i,5,1),lo=function(d){for(var a=d[0],t=1;t<d.length;++t)d[t]>a&&(a=d[t]);return a},Lt=function(d,a,t){var e=a/8|0;return(d[e]|d[e+1]<<8)>>(a&7)&t},co=function(d,a){var t=a/8|0;return(d[t]|d[t+1]<<8|d[t+2]<<16)>>(a&7)},Bo=function(d){return(d+7)/8|0},Vi=function(d,a,t){return(a==null||a<0)&&(a=0),(t==null||t>d.length)&&(t=d.length),new ct(d.subarray(a,t))},ic=["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(d,a,t){var e=new Error(a||ic[d]);if(e.code=d,Error.captureStackTrace&&Error.captureStackTrace(e,Ct),!t)throw e;return e},sc=function(d,a,t,e){var i=d.length,s=e?e.length:0;if(!i||a.f&&!a.l)return t||new ct(0);var n=!t,o=n||a.i!=2,r=a.i;n&&(t=new ct(i*3));var l=function(ht){var bt=t.length;if(ht>bt){var st=new ct(Math.max(bt*2,ht));st.set(t),t=st}},c=a.f||0,A=a.p||0,h=a.b||0,g=a.l,u=a.d,p=a.m,I=a.n,f=i*8;do{if(!g){c=Lt(d,A,1);var m=Lt(d,A+1,3);if(A+=3,m)if(m==1)g=_l,u=ec,p=9,I=5;else if(m==2){var y=Lt(d,A,31)+257,E=Lt(d,A+10,15)+4,v=y+Lt(d,A+5,31)+1;A+=14;for(var w=new ct(v),D=new ct(19),b=0;b<E;++b)D[po[b]]=Lt(d,A+b*3,7);A+=E*3;for(var H=lo(D),U=(1<<H)-1,x=jt(D,H,1),b=0;b<v;){var S=x[Lt(d,A,U)];A+=S&15;var C=S>>4;if(C<16)w[b++]=C;else{var T=0,P=0;for(C==16?(P=3+Lt(d,A,3),A+=2,T=w[b-1]):C==17?(P=3+Lt(d,A,7),A+=3):C==18&&(P=11+Lt(d,A,127),A+=7);P--;)w[b++]=T}}var R=w.subarray(0,y),X=w.subarray(y);p=lo(R),I=lo(X),g=jt(R,p,1),u=jt(X,I,1)}else Ct(1);else{var C=Bo(A)+4,B=d[C-4]|d[C-3]<<8,Q=C+B;if(Q>i){r&&Ct(0);break}o&&l(h+B),t.set(d.subarray(C,Q),h),a.b=h+=B,a.p=A=Q*8,a.f=c;continue}if(A>f){r&&Ct(0);break}}o&&l(h+131072);for(var $=(1<<p)-1,V=(1<<I)-1,L=A;;L=A){var T=g[co(d,A)&$],z=T>>4;if(A+=T&15,A>f){r&&Ct(0);break}if(T||Ct(2),z<256)t[h++]=z;else if(z==256){L=A,g=null;break}else{var K=z-254;if(z>264){var b=z-257,O=Js[b];K=Lt(d,A,(1<<O)-1)+er[b],A+=O}var it=u[co(d,A)&V],lt=it>>4;it||Ct(3),A+=it&15;var X=Zl[lt];if(lt>3){var O=Ks[lt];X+=co(d,A)&(1<<O)-1,A+=O}if(A>f){r&&Ct(0);break}o&&l(h+131072);var tt=h+K;if(h<X){var Z=s-X,yt=Math.min(X,tt);for(Z+h<0&&Ct(3);h<yt;++h)t[h]=e[Z+h]}for(;h<tt;++h)t[h]=t[h-X]}}a.l=g,a.p=L,a.b=h,a.f=c,g&&(c=1,a.m=p,a.d=u,a.n=I)}while(!c);return h!=t.length&&n?Vi(t,0,h):t.subarray(0,h)},de=function(d,a,t){t<<=a&7;var e=a/8|0;d[e]|=t,d[e+1]|=t>>8},Oi=function(d,a,t){t<<=a&7;var e=a/8|0;d[e]|=t,d[e+1]|=t>>8,d[e+2]|=t>>16},Ao=function(d,a){for(var t=[],e=0;e<d.length;++e)d[e]&&t.push({s:e,f:d[e]});var i=t.length,s=t.slice();if(!i)return{t:nr,l:0};if(i==1){var n=new ct(t[0].s+1);return n[t[0].s]=1,{t:n,l:1}}t.sort(function(Q,y){return Q.f-y.f}),t.push({s:-1,f:25001});var o=t[0],r=t[1],l=0,c=1,A=2;for(t[0]={s:-1,f:o.f+r.f,l:o,r};c!=i-1;)o=t[t[l].f<t[A].f?l++:A++],r=t[l!=c&&t[l].f<t[A].f?l++:A++],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 Dt(h+1),u=Io(t[c-1],g,0);if(u>a){var e=0,p=0,I=u-a,f=1<<I;for(s.sort(function(y,E){return g[E.s]-g[y.s]||y.f-E.f});e<i;++e){var m=s[e].s;if(g[m]>a)p+=f-(1<<u-g[m]),g[m]=a;else break}for(p>>=I;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 ct(g),l:u}},Io=function(d,a,t){return d.s==-1?Math.max(Io(d.l,a,t+1),Io(d.r,a,t+1)):a[d.s]=t},Wa=function(d){for(var a=d.length;a&&!d[--a];);for(var t=new Dt(++a),e=0,i=d[0],s=1,n=function(r){t[e++]=r},o=1;o<=a;++o)if(d[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=d[o]}return{c:t.subarray(0,e),n:a}},Yi=function(d,a){for(var t=0,e=0;e<a.length;++e)t+=d[e]*a[e];return t},sr=function(d,a,t){var e=t.length,i=Bo(a+2);d[i]=e&255,d[i+1]=e>>8,d[i+2]=d[i]^255,d[i+3]=d[i+1]^255;for(var s=0;s<e;++s)d[i+s+4]=t[s];return(i+4+e)*8},Xa=function(d,a,t,e,i,s,n,o,r,l,c){de(a,c++,t),++i[256];for(var A=Ao(i,15),h=A.t,g=A.l,u=Ao(s,15),p=u.t,I=u.l,f=Wa(h),m=f.c,C=f.n,B=Wa(p),Q=B.c,y=B.n,E=new Dt(19),v=0;v<m.length;++v)++E[m[v]&31];for(var v=0;v<Q.length;++v)++E[Q[v]&31];for(var w=Ao(E,7),D=w.t,b=w.l,H=19;H>4&&!D[po[H-1]];--H);var U=l+5<<3,x=Yi(i,ye)+Yi(s,$i)+n,S=Yi(i,h)+Yi(s,p)+n+14+3*H+Yi(E,D)+2*E[16]+3*E[17]+7*E[18];if(r>=0&&U<=x&&U<=S)return sr(a,c,d.subarray(r,r+l));var T,P,R,X;if(de(a,c,1+(S<x)),c+=2,S<x){T=jt(h,g,0),P=h,R=jt(p,I,0),X=p;var $=jt(D,b,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,D[po[v]]);c+=3*H;for(var V=[m,Q],L=0;L<2;++L)for(var z=V[L],v=0;v<z.length;++v){var K=z[v]&31;de(a,c,$[K]),c+=D[K],K>15&&(de(a,c,z[v]>>5&127),c+=z[v]>>12)}}else T=jl,P=ye,R=tc,X=$i;for(var v=0;v<o;++v){var O=e[v];if(O>255){var K=O>>18&31;Oi(a,c,T[K+257]),c+=P[K+257],K>7&&(de(a,c,O>>23&31),c+=Js[K]);var it=O&31;Oi(a,c,R[it]),c+=X[it],it>3&&(Oi(a,c,O>>5&8191),c+=Ks[it])}else Oi(a,c,T[O]),c+=P[O]}return Oi(a,c,T[256]),c+P[256]},nc=new Co([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),nr=new ct(0),oc=function(d,a,t,e,i,s){var n=s.z||d.length,o=new ct(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 A=nc[a-1],h=A>>13,g=A&8191,u=(1<<t)-1,p=s.p||new Dt(32768),I=s.h||new Dt(u+1),f=Math.ceil(t/3),m=2*f,C=function(Qt){return(d[Qt]^d[Qt+1]<<f^d[Qt+2]<<m)&u},B=new Co(25e3),Q=new Dt(288),y=new Dt(32),E=0,v=0,w=s.i||0,D=0,b=s.w||0,H=0;w+2<n;++w){var U=C(w),x=w&32767,S=I[U];if(p[x]=S,I[U]=x,b<=w){var T=n-w;if((E>7e3||D>24576)&&(T>423||!l)){c=Xa(d,r,0,B,Q,y,v,D,H,w-H,c),D=E=v=0,H=w;for(var P=0;P<286;++P)Q[P]=0;for(var P=0;P<30;++P)y[P]=0}var R=2,X=0,$=g,V=x-S&32767;if(T>2&&U==C(w-V))for(var L=Math.min(h,T)-1,z=Math.min(32767,w),K=Math.min(258,T);V<=z&&--$&&x!=S;){if(d[w+R]==d[w+R-V]){for(var O=0;O<K&&d[w+O]==d[w+O-V];++O);if(O>R){if(R=O,X=V,O>L)break;for(var it=Math.min(V,O-2),lt=0,P=0;P<it;++P){var tt=w-V+P&32767,Z=p[tt],yt=tt-Z&32767;yt>lt&&(lt=yt,S=tt)}}}x=S,S=p[x],V+=x-S&32767}if(X){B[D++]=268435456|go[R]<<18|za[X];var ht=go[R]&31,bt=za[X]&31;v+=Js[ht]+Ks[bt],++Q[257+ht],++y[bt],b=w+R,++E}else B[D++]=d[w],++Q[d[w]]}}for(w=Math.max(w,b);w<n;++w)B[D++]=d[w],++Q[d[w]];c=Xa(d,r,l,B,Q,y,v,D,H,w-H,c),l||(s.r=c&7|r[c/8|0]<<3,c-=7,s.h=I,s.p=p,s.i=w,s.w=b)}else{for(var w=s.w||0;w<n+l;w+=65535){var st=w+65535;st>=n&&(r[c/8|0]=l,st=n),c=sr(r,c+1,d.subarray(w,st))}s.i=n}return Vi(o,0,e+Bo(c)+i)},ac=function(){for(var d=new Int32Array(256),a=0;a<256;++a){for(var t=a,e=9;--e;)t=(t&1&&-306674912)^t>>>1;d[a]=t}return d}(),rc=function(){var d=-1;return{p:function(a){for(var t=d,e=0;e<a.length;++e)t=ac[t&255^a[e]]^t>>>8;d=t},d:function(){return~d}}},lc=function(d,a,t,e,i){if(!i&&(i={l:1},a.dictionary)){var s=a.dictionary.subarray(-32768),n=new ct(s.length+d.length);n.set(s),n.set(d,s.length),d=n,i.w=s.length}return oc(d,a.level==null?6:a.level,a.mem==null?i.l?Math.ceil(Math.max(8,Math.min(13,Math.log(d.length)))*1.5):20:12+a.mem,t,e,i)},or=function(d,a){var t={};for(var e in d)t[e]=d[e];for(var e in a)t[e]=a[e];return t},Zt=function(d,a){return d[a]|d[a+1]<<8},Mt=function(d,a){return(d[a]|d[a+1]<<8|d[a+2]<<16|d[a+3]<<24)>>>0},ho=function(d,a){return Mt(d,a)+Mt(d,a+4)*4294967296},It=function(d,a,t){for(;t;++a)d[a]=t,t>>>=8};ar=function(d,a,t,e){for(var i in d){var s=d[i],n=a+i,o=e;Array.isArray(s)&&(o=or(e,s[1]),s=s[0]),ArrayBuffer.isView(s)?t[n]=[s,o]:(t[n+="/"]=[new ct(0),o],ar(s,n,t,e))}},Za=typeof TextEncoder<"u"&&new TextEncoder,fo=typeof TextDecoder<"u"&&new TextDecoder,dc=0;try{fo.decode(nr,{stream:!0}),dc=1}catch{}hc=function(d){for(var a="",t=0;;){var e=d[t++],i=(e>127)+(e>223)+(e>239);if(t+i>d.length)return{s:a,r:Vi(d,t-1)};i?i==3?(e=((e&15)<<18|(d[t++]&63)<<12|(d[t++]&63)<<6|d[t++]&63)-65536,a+=String.fromCharCode(55296|e>>10,56320|e&1023)):i&1?a+=String.fromCharCode((e&31)<<6|d[t++]&63):a+=String.fromCharCode((e&15)<<12|(d[t++]&63)<<6|d[t++]&63):a+=String.fromCharCode(e)}};pc=function(d,a){return a+30+Zt(d,a+26)+Zt(d,a+28)},gc=function(d,a,t){var e=Zt(d,a+28),i=Zt(d,a+30),s=yo(d.subarray(a+46,a+46+e),!(Zt(d,a+8)&2048)),n=a+46+e,o=uc(d,n,i,t,Mt(d,a+20),Mt(d,a+24),Mt(d,a+42)),r=o[0],l=o[1],c=o[2];return[Zt(d,a+10),r,l,s,n+i+Zt(d,a+32),c]},uc=function(d,a,t,e,i,s,n){var o=i==4294967295,r=s==4294967295,l=n==4294967295,c=a+t,A=o+r+l;if(e&&A){for(;a+4<c;a+=4+Zt(d,a+2))if(Zt(d,a)==1)return[o?ho(d,a+4+8*r):i,r?ho(d,a+4):s,l?ho(d,a+4+8*(r+o)):n,1];e<2&&Ct(13)}return[i,s,n,0]},mo=function(d){var a=0;if(d)for(var t in d){var e=d[t].length;e>65535&&Ct(9),a+=e+4}return a},ja=function(d,a,t,e,i,s,n,o){var r=e.length,l=t.extra,c=o&&o.length,A=mo(l);It(d,a,n!=null?33639248:67324752),a+=4,n!=null&&(d[a++]=20,d[a++]=t.os),d[a]=20,a+=2,d[a++]=t.flag<<1|(s<0&&8),d[a++]=i&&8,d[a++]=t.compression&255,d[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),It(d,a,g<<25|h.getMonth()+1<<21|h.getDate()<<16|h.getHours()<<11|h.getMinutes()<<5|h.getSeconds()>>1),a+=4,s!=-1&&(It(d,a,t.crc),It(d,a+4,s<0?-s-2:s),It(d,a+8,t.size)),It(d,a+12,r),It(d,a+14,A),a+=16,n!=null&&(It(d,a,c),It(d,a+6,t.attrs),It(d,a+10,n),a+=14),d.set(e,a),a+=r,A)for(var u in l){var p=l[u],I=p.length;It(d,a,+u),It(d,a+2,I),d.set(p,a+4),a+=4+I}return c&&(d.set(o,a),a+=c),a},Ic=function(d,a,t,e,i){It(d,a,101010256),It(d,a+8,t),It(d,a+10,t),It(d,a+12,e),It(d,a+16,i)}});var Ar={};ui(Ar,{bytesToStr:()=>Os,unzipFiles:()=>Wi,zipFiles:()=>zi});function fc(d){return typeof d=="string"?qs(d):d instanceof Uint8Array?d:new Uint8Array(d)}function zi(d,a=6){let t={};for(let e of d)t[e.name]=[fc(e.data),{level:a}];return Promise.resolve(rr(t,{level:a}))}function Os(d){return yo(d)}function Wi(d){let a=d instanceof Uint8Array?d:new Uint8Array(d);return Promise.resolve(lr(a))}var Ys=qt(()=>{"use strict";cr()});var qc={};ui(qc,{default:()=>fn});module.exports=Xr(qc);var M=require("obsidian");var qe="sheet-group",Jt="sheet-order",Fe="sheet-final",Ro="sheet-label",Je="sheet-origin",Ke="forked-from",Kt="fork-siblings",es=[qe,Jt,Fe,Ro,Je,Ke,Kt];function Ot(d){if(!d)return null;let a=d[qe];return typeof a=="string"&&a.trim()?a:null}function Bn(d){let a=d?.[Jt];return typeof a=="number"?a:null}function Ii(d){return Ot(d)!==null&&Bn(d)!==null}function fi(d){return d?.[Fe]===!0}function Go(d){return d?.[Je]===!0}function Zr(d){let a=d?.[Ke];return typeof a=="string"&&a.trim()?a:null}function is(d){return typeof d!="string"?null:d.replace(/^\[\[/,"").replace(/\]\]$/,"").split("|")[0].split("#")[0].trim()||null}function Lo(d){return is(Zr(d))}function jr(d){let a=d?.[Ro];return typeof a=="string"&&a.trim()?a:null}function qo(){let d=Date.now().toString(36),a=Math.floor(Math.random()*1e6).toString(36);return`s-${d}-${a}`}function ft(d,a){return a.file?d.metadataCache.getFileCache(a.file)?.frontmatter:null}function yn(d,a){return a.slice().sort((t,e)=>{let i=Bn(ft(d,t)),s=Bn(ft(d,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 Jo(d,a){if(a.length===0)return null;let t=yn(d,a);return t.find(e=>fi(ft(d,e)))??t[0]}function Ko(d,a,t){let e=jr(ft(d,a));return e||t}at();var vt=require("obsidian");var rt=require("obsidian");at();function ns(d){let a=(d.dateDisplayTimezone||"").trim();return a?{timeZone:a}:{}}function oe(d,a){try{return new Intl.DateTimeFormat(void 0,a).format(new Date(d))}catch{let{timeZone:t,...e}=a;return new Intl.DateTimeFormat(void 0,e).format(new Date(d))}}function ae(d,a){let t=ns(a);switch(a.dateDisplayFormat??"locale"){case"iso":return Wo(d,a,!0);case"us":return oe(d,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return oe(d,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return oe(d,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return oe(d,{...t,dateStyle:"medium",timeStyle:"short"})}}function Vo(d,a){let t=ns(a);switch(a.dateDisplayFormat??"locale"){case"iso":return Wo(d,a,!1);case"us":return oe(d,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return oe(d,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return oe(d,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(d).getFullYear()===e.getFullYear();return oe(d,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function zo(d,a){let t=ns(a),e=a.dateDisplayFormat==="iso"||a.dateDisplayFormat==="eu";return oe(d,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Wo(d,a,t){let e=ns(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(d)),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(d,a,t){let e=d.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(a>99?"99+":String(a))}var Ni={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},cs=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()===J&&this.scheduleRender()}))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},80))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-panels-root");let e=t.createDiv({cls:"stashpad-panels-globals"}),i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,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 r=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,rt.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 A of Object.keys(Ni)){let h=Ni[A],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===A&&g.addClass("is-active"),g.onclick=()=>{this.activePanel!==A&&(this.activePanel=A,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 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 A=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,h=Array.from(c.keys());A&&c.has(A)&&(h.splice(h.indexOf(A),1),h.unshift(A));for(let g of h){let u=g.split("/").pop()||g,p=e.createDiv({cls:"stashpad-pinned-group-header"});g===A&&p.addClass("is-active-folder"),p.createSpan({cls:"stashpad-pinned-group-name",text:u});let I=c.get(g)??[];for(let{pin:f,idx:m}of I)this.renderPinnedRow(e,f,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,A=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(),Q=m.clientY-B.top<B.height/2;this.reorderPin(C,Q?i:i+1)});let u=g.createSpan({cls:"stashpad-pinned-toggle"});A&&(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,A?"folder-tree":"file-text"),r&&(p.style.color=r);let I=g.createSpan({cls:"stashpad-pinned-label",text:o});I.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(g.createSpan({cls:"stashpad-pinned-folder",text:f}),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)},A&&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((A,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,A=>{A.pinnedAt=c})}catch(A){console.warn("[Stashpad] pin reorder failed",A)}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,A=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"});A&&p.addClass("is-completed"),p.style.paddingLeft=`${s*16}px`;let I=p.createSpan({cls:"stashpad-pinned-toggle"});g&&(Ie(I,h,u),I.onclick=C=>{C.stopPropagation();let B=`${e}|${l}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),this.render()});let f=p.createSpan({cls:"stashpad-pinned-icon"});(0,rt.setIcon)(f,"file-text"),c&&(f.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===F&&(r==null||r===F)){if(o.id===F)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 rt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(kt(),bi));new s(this.app,i,e).open()}openNotificationsFromPanel(){this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")}async openHomeFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.navigateTo=="function"&&t.navigateTo(F)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===J)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(J);return i.length>0?(this.app.workspace.revealLeaf(i[0]),i[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===J?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let A of s){let h=A.authorId;h&&!n.has(h)&&n.set(h,A.authorDisplay||h)}let o=e.createDiv({cls:"stashpad-shared-filters"}),r=(A,h,g)=>{let u=o.createEl("button",{cls:"stashpad-shared-chip",text:A});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 A=o.createEl("select",{cls:"stashpad-shared-author-select"}),h=A.createEl("option",{text:"Any author"});h.value="__any__";for(let[u,p]of n){let I=A.createEl("option",{text:p});I.value=u}let g=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;A.value=g,A.onchange=()=>{let u=A.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(A=>{if(this.sharedContribOnly&&A.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return A.authorId===i;case"others":return A.authorId!==i;default:return A.authorId===this.sharedAuthorFilter}});if(c.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let A 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"),A.color&&(g.style.color=A.color);let u=h.createSpan({cls:"stashpad-pinned-label",text:A.title});u.onclick=()=>this.openSharedFromPanel(A.folder,A.id);let p=A.folder.split("/").pop()||A.folder;h.createSpan({cls:"stashpad-pinned-folder",text:p}),A.authorDisplay&&h.createSpan({cls:"stashpad-shared-meta"}).setText(A.authorId===i?`you \xB7 ${A.contributorCount} contributor${A.contributorCount===1?"":"s"}`:`by ${A.authorDisplay}${A.contributorCount>0?` \xB7 ${A.contributorCount} contributor${A.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===F&&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===F)continue;let c=this.extractAuthorId(l.author),A=Array.isArray(l.contributors)?l.contributors.filter(C=>typeof C=="string"):[],h=s.get(r)??null;if(!(A.length>0||h===t&&(c!==null&&c!==t)))continue;let f=this.titleFromFile(o),m=typeof l.color=="string"?l.color:null;n.push({file:o,folder:r,id:l.id,title:f,color:m,authorId:c,authorDisplay:this.extractAuthorDisplay(l.author)||(c??""),contributorCount:A.length})}return n.sort((o,r)=>{let l=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},c=this.app.metadataCache.getFileCache(r.file)?.frontmatter??{},A=l.modified??l.created??"";return(c.modified??c.created??"").localeCompare(A)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),i=this.collectTasks();if(i.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks yet \u2014 press H on a note to mark it a task, or D to give it a due date.");return}let s=(this.plugin.settings.authorId??"").trim(),n=S=>!!s&&S.assignedTo.some(T=>T.id===s),o=S=>{let T=this.taskAssignFilter;if(T.startsWith("person:")){let P=T.slice(7);return S.assignedTo.some(R=>R.id===P)}switch(T){case"mine":return n(S);case"others":return S.assignedTo.length>0&&!n(S);case"byme":return!!s&&S.assignedBy?.id===s;case"unassigned":return S.assignedTo.length===0;default:return!0}},r=new Map;for(let S of i){for(let T of S.assignedTo)T.id!==s&&r.set(T.id,T.name);S.assignedBy&&S.assignedBy.id!==s&&r.set(S.assignedBy.id,S.assignedBy.name)}let l=[...r.entries()].map(([S,T])=>({id:S,name:T})).sort((S,T)=>S.name.localeCompare(T.name)),c=e.createDiv({cls:"stashpad-task-assign-bar"});c.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let A=c.createEl("select",{cls:"stashpad-task-assign-select"}),h=S=>{let T={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return S.startsWith("person:")?r.get(S.slice(7))??"Person":T[S]??S},g=S=>{let T=A.createEl("option",{text:h(S),value:S});this.taskAssignFilter===S&&(T.selected=!0)};for(let S of["all","mine","others","byme","unassigned"])g(S);if(l.length>0){let S=A.createEl("optgroup");S.setAttr("label","By person");for(let T of l){let P=S.createEl("option",{text:T.name,value:`person:${T.id}`});this.taskAssignFilter===`person:${T.id}`&&(P.selected=!0)}}A.onchange=()=>{this.taskAssignFilter=A.value,this.render()};let u=[...new Set(i.map(S=>S.folder))].sort((S,T)=>S.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 I=p.createEl("select",{cls:"stashpad-task-assign-select"}),f=I.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let S of u){let T=I.createEl("option",{text:S.split("/").pop()||S,value:S});this.taskFolderFilter===S&&(T.selected=!0)}I.onchange=()=>{this.taskFolderFilter=I.value,this.render()};let m=S=>this.taskFolderFilter==="all"||S.folder===this.taskFolderFilter,C=i.filter(S=>o(S)&&m(S));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 Q=B.getTime(),y=Q+24*60*60*1e3,E={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let S of C){if(S.completed){E.completed.push(S);continue}if(S.due==null){E.nodate.push(S);continue}S.due<Q?E.overdue.push(S):S.due<y?E.today.push(S):E.upcoming.push(S)}let v=(S,T)=>S.due==null&&T.due==null?S.title.localeCompare(T.title):S.due==null?1:T.due==null?-1:S.due-T.due,w=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],D=e.createDiv({cls:"stashpad-task-filters"}),b=C.length,H=(S,T,P)=>{let R=D.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===S&&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=S,this.render()}};H("all","All",b),H("overdue","Overdue",E.overdue.length),H("today","Today",E.today.length),H("upcoming","Upcoming",E.upcoming.length),H("nodate","No date",E.nodate.length),H("completed","Done",E.completed.length);let U=this.taskFilter==="all"?w:w.filter(S=>S.key===this.taskFilter),x=!1;for(let S of U){let T=E[S.key];if(T.length!==0){if(x=!0,T.sort(S.key==="completed"?(P,R)=>v(R,P):v),this.taskFilter==="all"){let P=e.createDiv({cls:`stashpad-task-section-header is-${S.key}`});(0,rt.setIcon)(P.createSpan({cls:"stashpad-task-section-icon"}),S.icon),P.createSpan({cls:"stashpad-task-section-name",text:S.label}),P.createSpan({cls:"stashpad-task-section-count",text:String(T.length)})}for(let P of T)this.renderTaskRow(e,P,S.key==="today")}}if(!x&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${U[0]?.label??this.taskFilter}".`);return}x||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=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 A=l.createSpan({cls:"stashpad-task-assignee"});r&&c.id===r&&A.addClass("is-me"),A.setText(this.initials(c.name)),A.title=r&&c.id===r?`${c.name} (you)`:c.name}}s.oncontextmenu=r=>{r.preventDefault();let l=new rt.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?zo(t,this.plugin.settings):Vo(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??{},r=typeof o.id=="string"?o.id:null;if(!r||r===F)continue;let l=o.completed===!0,c=$e(o,"task")||o.task===!0||o.completed!==void 0,A=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,h=null;if(A){let g=Date.parse(A);Number.isNaN(g)||(h=g)}!c&&!l&&h==null&&!A||i.push({file:s,folder:n,id:r,title:this.titleFromFile(s),task:c,completed:l,due:h,dueRaw:A,color:typeof o.color=="string"?o.color:null,assignedTo:De(o),assignedBy:ue(o.assignedBy)})}return i}};async function As(d){let a=d.workspace.getLeavesOfType(pe);if(a.length>0){d.workspace.revealLeaf(a[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new rt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:pe,active:!0}),d.workspace.revealLeaf(t)}var Ua=require("obsidian");at();var N=require("obsidian");Mi();var us=require("obsidian");at();var ei=class extends us.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!=="/"&&mi.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let r of o.children)r instanceof us.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()}};at();kt();var Pe=require("obsidian"),Mn={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."}},cl={info:4e3,success:4e3,warning:6e3,error:1e4},ha=5e3,Is=class{constructor(a){this.app=a;this.history=[];this.nextId=1;this.historyLimit=ha;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??cl[t];return new Pe.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:ha,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(A=>console.warn("[Stashpad] notification action failed",A)),!r.keepOpen){let A=l.closest(".notice");A&&A.parentElement&&A.parentElement.removeChild(A)}}),o.appendChild(l)}i.appendChild(o)}return e.appendChild(i),e}};function fs(d,a,t){let e=d.vault.getAbstractFileByPath(a);if(!(e instanceof Pe.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=d.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;d.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=Pe.Platform.isMacOS?"Finder":Pe.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,r=d.vault.adapter?.getFullPath?.(a);r&&n?.showItemInFolder&&n.showItemInFolder(r)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var pa=require("obsidian"),Tn=pa.Platform.isMacOS;function Ti(d){if(!d)return"(none)";let a=d.replace(/\bMod\b/g,Tn?"Cmd":"Ctrl");return Tn&&(a=a.replace(/\bAlt\b/g,"Option")),a}function ga(d,a,t={allowSingleKey:!0}){let e=d.placeholder,i=d.value;d.placeholder="Press a key\u2026 (Backspace to cancel)",d.value="",d.classList.add("is-recording");let s=!1,n=()=>{d.placeholder=e,d.classList.remove("is-recording"),s||(d.value=i),d.removeEventListener("keydown",o,!0),d.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 A=[];Tn?(l.metaKey&&A.push("Mod"),l.ctrlKey&&A.push("Ctrl")):l.ctrlKey&&A.push("Mod"),l.altKey&&A.push("Alt"),l.shiftKey&&A.push("Shift");let h=Al(l.key,l.code);if(!h||A.length===0&&!t.allowSingleKey)return;A.push(h);let g=A.join("+");s=!0,n(),a(g)},r=()=>n();return d.addEventListener("keydown",o,!0),d.addEventListener("blur",r),n}function Al(d,a){if(!d)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 d.length===1?d.toUpperCase():d}_e();Ut();function He(d,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(A){n(A)}}function r(c){try{l(e.throw(c))}catch(A){n(A)}}function l(c){c.done?s(c.value):i(c.value).then(o,r)}l((e=e.apply(d,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 He(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(a())}finally{t()}})}},Pn;function dl(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Gn=dl(),Hn=(Pn=Gn.Buffer)!==null&&Pn!==void 0?Pn:null,hl=Gn.TextEncoder?new Gn.TextEncoder:null;function Ba(d,a){return(d&15)+(d>>6|d>>3&8)<<4|(a&15)+(a>>6|a>>3&8)}function ya(d,a){let t=a.length>>1;for(let e=0;e<t;e++){let i=e<<1;d[e]=Ba(a.charCodeAt(i),a.charCodeAt(i+1))}}function pl(d,a){if(d.length!==a.length*2)return!1;for(let t=0;t<a.length;t++){let e=t<<1;if(a[t]!==Ba(d.charCodeAt(e),d.charCodeAt(e+1)))return!1}return!0}var ua=87,Ia=48;function Ln(d,a,t){let e=0;for(let i=0;i<t;i++){let s=a[i]>>>4;d[e++]=s>9?s+ua:s+Ia,s=a[i]&15,d[e++]=s>9?s+ua:s+Ia}return String.fromCharCode.apply(null,d)}var le=Hn!==null?d=>{if(typeof d=="string"){let a=Hn.from(d,"utf8");return new Uint8Array(a.buffer,a.byteOffset,a.length)}if(Hn.isBuffer(d))return new Uint8Array(d.buffer,d.byteOffset,d.length);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")}:d=>{if(typeof d=="string")return hl.encode(d);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")},Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Hi=new Uint8Array(256);for(let d=0;d<Rt.length;d++)Hi[Rt.charCodeAt(d)]=d;function fa(d,a=!0){let t=d.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(d[n]<<16&16711680)+(d[n+1]<<8&65280)+(d[n+2]&255),r=Rt.charAt(o>>18&63)+Rt.charAt(o>>12&63)+Rt.charAt(o>>6&63)+Rt.charAt(o&63);i.push(r)}if(e===1){let n=d[t-1],o=Rt.charAt(n>>2),r=Rt.charAt(n<<4&63);i.push(`${o}${r}`),a&&i.push("==")}else if(e===2){let n=(d[t-2]<<8)+d[t-1],o=Rt.charAt(n>>10),r=Rt.charAt(n>>4&63),l=Rt.charAt(n<<2&63);i.push(`${o}${r}${l}`),a&&i.push("=")}return i.join("")}function gl(d){let a=Math.floor(d.length*.75),t=d.length;return d[t-1]==="="&&(a-=1,d[t-2]==="="&&(a-=1)),a}function ul(d){let a=gl(d),t=d.length,e=new Uint8Array(a),i=0;for(let s=0;s<t;s+=4){let n=Hi[d.charCodeAt(s)],o=Hi[d.charCodeAt(s+1)],r=Hi[d.charCodeAt(s+2)],l=Hi[d.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 ms=16*1024,Pi=4,Il=new ot,Un=new Map;function Qa(d,a){return He(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,E=0)=>{e.set(y,E)},n=()=>e,o=()=>t.exports,r=y=>{t.exports.Hash_SetMemorySize(y);let E=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,E,y)},l=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),c=Il.dispatch(()=>He(this,void 0,void 0,function*(){if(!Un.has(d.name)){let E=ul(d.data),v=WebAssembly.compile(E);Un.set(d.name,v)}let y=yield Un.get(d.name);t=yield WebAssembly.instantiate(y,{})})),A=()=>He(this,void 0,void 0,function*(){t||(yield c);let y=t.exports.Hash_GetBuffer(),E=t.exports.memory.buffer;e=new Uint8Array(E,y,ms)}),h=(y=null)=>{i=!0,t.exports.Hash_Init(y)},g=y=>{let E=0;for(;E<y.length;){let v=y.subarray(E,E+ms);E+=v.length,e.set(v),t.exports.Hash_Update(v.length)}},u=y=>{if(!i)throw new Error("update() called before init()");let E=le(y);g(E)},p=new Uint8Array(a*2),I=(y,E=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(E),y==="binary"?e.slice(0,a):Ln(p,e,a)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),E=l(),v=t.exports.memory.buffer,w=new Uint8Array(v,y,E),D=new Uint8Array(Pi+E);return ya(D,d.hash),D.set(w,Pi),D},m=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let E=t.exports.Hash_GetState(),v=l(),w=Pi+v,D=t.exports.memory.buffer;if(y.length!==w)throw new Error(`Bad state length (expected ${w} bytes, got ${y.length})`);if(!pl(d.hash,y.subarray(0,Pi)))throw new Error("This state was written by an incompatible hash implementation");let b=y.subarray(Pi);new Uint8Array(D,E,v).set(b),i=!0},C=y=>typeof y=="string"?y.length<ms/4:y.byteLength<ms,B=C;switch(d.name){case"argon2":case"scrypt":B=()=>!0;break;case"blake2b":case"blake2s":B=(y,E)=>E<=512&&C(y);break;case"blake3":B=(y,E)=>E===0&&C(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":B=()=>!1;break}let Q=(y,E=null,v=null)=>{if(!B(y,E))return h(E),u(y),I("hex",v);let w=le(y);return e.set(w),t.exports.Hash_Calculate(w.length,E,v),Ln(p,e,a)};return yield A(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:r,init:h,update:u,digest:I,save:f,load:m,calculate:Q,hashLength:a}})}var fA=new ot;var fl="argon2",ml="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",Cl="e4cdc523",Bl={name:fl,data:ml,hash:Cl},yl="blake2b",Ql="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=",El="c6f286e6",wl={name:yl,data:Ql,hash:El},mA=new ot;function ma(d){return!Number.isInteger(d)||d<8||d>512||d%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function vl(d,a){return d|a<<16}function qn(d=512,a=null){if(ma(d))return Promise.reject(ma(d));let t=null,e=d;if(a!==null){if(t=le(a),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=vl(d,t.length)}let i=d/8;return Qa(wl,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 Fl(d,a,t){let e=[`m=${a.memorySize}`,`t=${a.iterations}`,`p=${a.parallelism}`].join(",");return`$argon2${a.hashType}$v=19$${e}$${fa(d,!1)}$${fa(t,!1)}`}var Ca=new DataView(new ArrayBuffer(4));function re(d){return Ca.setInt32(0,d,!0),new Uint8Array(Ca.buffer)}function Rn(d,a,t){return He(this,void 0,void 0,function*(){if(t<=64){let r=yield qn(t*8);return r.update(re(t)),r.update(a),r.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);d.init(),d.update(re(t)),d.update(a);let s=d.digest("binary");i.set(s.subarray(0,32),0);for(let r=1;r<e;r++)d.init(),d.update(s),s=d.digest("binary"),i.set(s.subarray(0,32),r*32);let n=t-32*e,o;return n===64?(o=d,o.init()):o=yield qn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function kl(d){switch(d){case"d":return 0;case"i":return 1;default:return 2}}function Sl(d){return He(this,void 0,void 0,function*(){var a;let{parallelism:t,iterations:e,hashLength:i}=d,s=le(d.password),n=le(d.salt),o=19,r=kl(d.hashType),{memorySize:l}=d,c=le((a=d.secret)!==null&&a!==void 0?a:""),[A,h]=yield Promise.all([Qa(Bl,1024),qn(512)]);A.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),A.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 I=Math.floor(l/(t*4))*4,f=new Uint8Array(72),m=h.digest("binary");f.set(m);for(let Q=0;Q<t;Q++){f.set(re(0),64),f.set(re(Q),68);let y=Q*I,E=yield Rn(h,f,1024);A.writeMemory(E,y*1024),y+=1,f.set(re(1),64),E=yield Rn(h,f,1024),A.writeMemory(E,y*1024)}let C=new Uint8Array(1024);ya(C,A.calculate(new Uint8Array([]),l));let B=yield Rn(h,C,i);if(d.outputType==="hex"){let Q=new Uint8Array(i*2);return Ln(Q,B,i)}return d.outputType==="encoded"?Fl(n,d,B):B})}var Dl=d=>{var a;if(!d||typeof d!="object")throw new Error("Invalid options parameter. It requires an object.");if(!d.password)throw new Error("Password must be specified");if(d.password=le(d.password),d.password.length<1)throw new Error("Password must be specified");if(!d.salt)throw new Error("Salt must be specified");if(d.salt=le(d.salt),d.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(d.secret=le((a=d.secret)!==null&&a!==void 0?a:""),!Number.isInteger(d.iterations)||d.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(d.parallelism)||d.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(d.hashLength)||d.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(d.memorySize))throw new Error("Memory size should be specified.");if(d.memorySize<8*d.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(d.outputType===void 0&&(d.outputType="hex"),!["hex","binary","encoded"].includes(d.outputType))throw new Error(`Insupported output type ${d.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function Jn(d){return He(this,void 0,void 0,function*(){return Dl(d),Sl(Object.assign(Object.assign({},d),{hashType:"id"}))})}var CA=new ot;var BA=new ot;var yA=new ot;var QA=new ot;var EA=new Uint8Array(8);var wA=new ot;var vA=new ot;var FA=new ot;var kA=new ot;var SA=new ot;var DA=new ot;var bA=new ot;var NA=new ot;var xA=new ot;var MA=new ot;var TA=new ot;var PA=new Uint8Array(8);var HA=new ot;var UA=new Uint8Array(8);var RA=new ot;var GA=new Uint8Array(8);var LA=new ot;var qA=new ot;var JA=new ot;kt();var Gt=new Uint8Array([83,84,65,83,72,69,78,67]),Yn=2,$n=1,Vn=2,va=3,bl=32,ii=12,Kn=32,Nl=6e5,xl=47104,Ml=3,Tl=1,pt=d=>d;function Nt(d){if(d.length<Gt.length+1)return!1;for(let a=0;a<Gt.length;a++)if(d[a]!==Gt[a])return!1;return!0}function Ea(d,a,t){d[a]=t>>>24&255,d[a+1]=t>>>16&255,d[a+2]=t>>>8&255,d[a+3]=t&255}function wa(d,a){return d[a]*16777216+(d[a+1]<<16)+(d[a+2]<<8)+d[a+3]}async function On(d,a,t){if(t.id===Vn)return await Jn({password:d,salt:a,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:Kn,outputType:"binary"});if(t.id===$n){let e=await crypto.subtle.importKey("raw",pt(new TextEncoder().encode(d)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:pt(a),iterations:t.a,hash:"SHA-256"},e,Kn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function Cs(d){return crypto.subtle.importKey("raw",pt(d),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var zn={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function zt(d,a){let t=crypto.getRandomValues(new Uint8Array(bl)),e=crypto.getRandomValues(new Uint8Array(ii)),i,s,n;try{i={id:Vn,a:xl,b:Ml,c:Tl},n=await On(a,t,i),s="argon2id"}catch(A){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",A),i={id:$n,a:Nl,b:0,c:0},n=await On(a,t,i),s="pbkdf2"}let o=Fa(i,t,e),r=await Cs(n),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(e),additionalData:pt(o)},r,pt(d))),c=new Uint8Array(o.length+l.length);return c.set(o,0),c.set(l,o.length),{data:c,kdf:s}}var Ui=null;async function Ri(){if(Ui!==null)return Ui;try{await Jn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Ui=!0}catch{Ui=!1}return Ui}function Fa(d,a,t){let e=new Uint8Array(Gt.length+1+1+4+4+1+1+a.length+t.length),i=0;return e.set(Gt,i),i+=Gt.length,e[i++]=Yn,e[i++]=d.id,Ea(e,i,d.a),i+=4,Ea(e,i,d.b),i+=4,e[i++]=d.c,e[i++]=a.length,e.set(a,i),i+=a.length,e.set(t,i),i+=t.length,e}async function Vt(d,a){if(!Nt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Gt.length];if(t===1)return Pl(d,a);if(t!==Yn)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Gt.length+1,i={id:d[e++],a:0,b:0,c:0};if(i.a=wa(d,e),e+=4,i.b=wa(d,e),e+=4,i.c=d[e++],i.id===Vn){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===$n&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=d[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=d.slice(e,e+s);e+=s;let o=d.slice(e,e+ii);e+=ii;let r=d.slice(0,e),l=d.slice(e),c=await On(a,n,i),A=await Cs(c),h=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(o),additionalData:pt(r)},A,pt(l));return new Uint8Array(h)}async function Pl(d,a){let t=Gt.length+1,e=d.slice(t,t+16);t+=16;let i=d.slice(t,t+12);t+=12;let s=d.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 Ue(d,a){if(a.length!==Kn)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(ii)),i=Fa({id:va,a:0,b:0,c:0},new Uint8Array(0),t),s=await Cs(a),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:pt(t),additionalData:pt(i)},s,pt(d))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function St(d,a){if(!Nt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Gt.length];if(t!==Yn)throw new Error(`Unsupported encrypted version (${t}).`);let e=Gt.length+1;if(d[e++]!==va)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=d[e++];e+=s;let n=d.slice(e,e+ii);e+=ii;let o=d.slice(0,e),r=d.slice(e),l=await Cs(a),c=await crypto.subtle.decrypt({name:"AES-GCM",iv:pt(n),additionalData:pt(o)},l,pt(r));return new Uint8Array(c)}async function si(d,a,t={}){if(!Nt(a))return a;if(t.secretId){let i=d.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Vt(a,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new vi(d,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Vt(a,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Ut();var Bs={name:"ECDH",namedCurve:"P-256"},Hl="stashpad-vault-dek-wrap",Ul=new TextEncoder;function Wn(d){let a="";for(let t=0;t<d.length;t++)a+=String.fromCharCode(d[t]);return btoa(a)}function Xn(d){let a=atob(d),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}async function ka(){let d=await crypto.subtle.generateKey(Bs,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",d.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",d.privateKey))}}function Sa(d){return crypto.subtle.importKey("spki",d,Bs,!1,[])}function Rl(d){return crypto.subtle.importKey("pkcs8",d,Bs,!1,["deriveBits"])}async function Da(d,a){let t=await crypto.subtle.deriveBits({name:"ECDH",public:a},d,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:Ul.encode(Hl)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function ys(d,a,t){let e=await crypto.subtle.generateKey(Bs,!0,["deriveBits"]),i=await Da(e.privateKey,await Sa(a)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,d)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:Wn(o),iv:Wn(s),ct:Wn(n)}}async function ba(d,a){let t=await Da(await Rl(a),await Sa(Xn(d.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Xn(d.iv)},t,Xn(d.ct)))}var Na=".stashpad/keys.json",Gl=".stashpad",Gi="_keys";function Zn(d){return{v:2,keyId:d,identities:[],slots:[],joinRequests:[]}}var Qs=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(Na);if(a)return a;try{let e=((await this.a.list(Gi)).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(Gl),await this.a.write(Na,t),await this.ensureDir(Gi);for(let e=4;e>=1;e--){let i=`${Gi}/keys-${e}.json`,s=`${Gi}/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(`${Gi}/keys-1.json`,t)}catch{}}};var Re="stashpad-vault-encryption";function Li(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function Ge(d){let a="";for(let t=0;t<d.length;t++)a+=String.fromCharCode(d[t]);return btoa(a)}function Wt(d){let a=atob(d),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}var xa=32,Es=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 Qs(a)}argonProbe(){return Ri()}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(xa)),s=await this.mintIdentity(a,e),n=Zn(W(8));n.identities.push(this.identityRecord(s)),n.slots.push(await ys(i,Wt(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 Vt(Wt(e.wrappedKey),a)}catch{return!1}let n=await this.mintIdentity(a,e.identityLabel??void 0),o=Zn(W(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await ys(s,Wt(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 Vt(Wt(e.identityPrivWrapped),a);try{let n=await ba(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 Vt(Wt(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 zt(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(xa)),r=await zt(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 Vt(Wt(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 A=await zt(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(A.data),kdf:A.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),A=r?this.folderKcIdFor(r):null,h=(r?.passwordSlots??[]).filter(C=>!C.label.startsWith("[deprecated]")),g=A?this.rememberedFolderPassword(A):null;if(g&&h[0])try{await this.secretStore()?.setSecret(`${A}-d-${h[0].id}`,g)}catch{}let u=await zt(e,t),p=(r?.passwordSlots??[]).map(C=>C.label.startsWith("[deprecated]")?C:{...C,label:`[deprecated] ${C.label}`}),I=s??r?.label??`rotated - ${o.split("/").pop()||o}`,f={keyId:c,folderPath:l,label:I,kcId:this.folderKcId(I,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]:f},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||A&&this.isFolderRemembered(A))&&await this.rememberFolder(this.folderKcIdFor(f),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 Vt(Wt(t.identityPrivWrapped),a)).fill(0),!0;if(t.wrappedKey)return(await Vt(Wt(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 Vt(Wt(s.identityPrivWrapped),a)}catch{return!1}let o=await zt(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 ys(this.sessionKey,Wt(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(Li())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(a,t){let e=await ka(),i=await zt(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 qi=null,ws=new Set;function vs(d){if(qi!==d){qi=d;for(let a of ws)a()}}function ce(){return qi}function Ma(d){if(qi===d){qi=null;for(let a of ws)a()}}function Ta(d){return ws.add(d),()=>ws.delete(d)}function Ll(){return N.Platform.isMacOS?"Finder":N.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 to(){let d={};for(let a of ni)d[a.id]={primary:a.defaultPrimary,secondary:a.defaultSecondary??"",preferRight:!1,useBoth:!!a.defaultUseBoth};return d}var ql=!1,Jl=!1,me={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,debugTrace:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,splitMode:"lines",confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,encryption:Li(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],folderEncPrefs:{},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:to()},Pa=JSON.parse(JSON.stringify(me)),_n=new Set;function j(){return Pa}function eo(d){Pa=d;for(let a of _n)a()}function Ha(d){return _n.add(d),()=>_n.delete(d)}function Ss(d){try{let a=d.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 Fs=[{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((d,a)=>{let t=e=>e.replace(/^[^\p{L}\p{N}]+/u,"");return t(d.label).localeCompare(t(a.label))}),jn=null;function Kl(d,a){return jn||(jn=class extends N.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new jn(d,a)}var ks=class extends N.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e;this.pfeSelected=null}display(){let{containerEl:t}=this;t.empty();for(let e of Fs){new N.Setting(t).setName(e.label).setHeading();let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new N.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 Fs.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>Kl(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 N.Notice("Debug trace is empty \u2014 enable it and reproduce the issue first.");return}try{await navigator.clipboard.writeText(i),new N.Notice("Debug trace copied.")}catch{new N.Notice("Couldn't access clipboard.")}})),t.addButton(e=>e.setButtonText("Clear").onClick(()=>{this.plugin.clearDebugTrace(),new N.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 N.Notice("No log yet \u2014 make some changes first.");return}let n=await i.read(s);new We(this.app,n,s).open()})),["log","history","diagnostics"])]}notificationsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(Mn);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=Mn[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 ki(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 N.Notice("No log yet \u2014 make some changes first.");return}let l=await o.read(r);new We(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)}}}}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 At(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 N.Notice("Folder password set \u2014 share it securely."),this.update?.(),null}}).open()}promptChangeFolderPassword(t){new At(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 N.Notice("Folder password changed."),this.update?.(),null}}).open()}promptRotateFolderKey(t){let e=t.split("/").pop()||t;new nt(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 At(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 At(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 N.Notice("Folder unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()}encryptionOrOnboard(){return this.plugin.encryption?.isConfigured?.()?!0:(new N.Notice("That setting needs vault encryption, which isn't set up yet \u2014 let's set it up first.",6e3),new At(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 N.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}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 N.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",A=new N.Setting(t).setName("Password").setDesc(c);o?A.addButton(p=>p.setButtonText("Manage on parent folder").onClick(()=>{this.pfeSelected=n,this.update?.()})):s?r?(A.addButton(p=>p.setButtonText("Lock (forget password)").onClick(()=>{this.plugin.encryption.lockFolder(e),new N.Notice("Folder locked \u2014 you'll re-enter its password next time."),this.update?.()})),A.addButton(p=>p.setButtonText("Change password\u2026").onClick(()=>this.promptChangeFolderPassword(e))),A.addButton(p=>{p.setButtonText("Rotate key\u2026").onClick(()=>this.promptRotateFolderKey(e)),p.buttonEl.addClass("mod-warning")})):A.addButton(p=>p.setButtonText("Unlock\u2026").setCta().onClick(()=>this.promptUnlockFolder(e))):A.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 N.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 I=>{await h({archive:I,...I&&l.archiveEncryptContent===void 0?{archiveEncryptContent:!0}:{}});let f=new Set((this.plugin.settings.archiveFolders??[]).map(m=>m.replace(/\/+$/,"")));I?f.add(e):f.delete(e),this.plugin.settings.archiveFolders=[...f],!I&&(this.plugin.settings.defaultArchiveFolder??"")===e&&(this.plugin.settings.defaultArchiveFolder=void 0),await this.plugin.saveSettings(),this.plugin.refreshFolderPanels(),this.update?.()})),new N.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(I=>h({trashHandling:I||void 0})));let g=(p,I,f,m)=>{new N.Setting(t).setName(p).addToggle(C=>C.setValue(!!l[I]).onChange(async B=>{let Q={};Q[I]=B,B||(Q[f]=!1),await h(Q),m&&await m(B),this.update?.()})),new N.Setting(t).setName(`\u21B3 ${p} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(C=>{C.setValue(!!l[f]),C.setDisabled(!l[I]),C.onChange(B=>{let Q={};Q[f]=B,h(Q)})})};g("Encrypt this folder's notes","encryptContent","encryptFilenames",async p=>{p?await this.plugin.lockFolder(e):await this.plugin.unlockFolder(e);let I=(this.plugin.settings.lockedSubtrees??[]).some(f=>(f.folder||"").replace(/\/+$/,"")===e);await h({encryptContent:I,...I?{}:{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 N.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 I=(this.plugin.settings.folderEncPrefs??{})[p]??{},f=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 N.Setting(t).setName(C).addToggle(B=>B.setValue(m).onChange(async Q=>{Q?await this.plugin.lockFolder(p):await this.plugin.unlockFolder(p);let y=(this.plugin.settings.lockedSubtrees??[]).some(E=>(E.folder||"").replace(/\/+$/,"")===p);await f({encryptContent:y,...y?{}:{encryptFilenames:!1}}),this.update?.()})),new N.Setting(t).setName(`\u21B3 ${C} \u2014 hide filenames`).setClass("stashpad-subsetting").addToggle(B=>{B.setValue(!!I.encryptFilenames),B.setDisabled(!m),B.onChange(Q=>void f({encryptFilenames:Q}))})}}}buildGeneralCategories(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,r,l)=>this.renderDef(s,n,c=>c.addToggle(A=>A.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 ei(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let r=(o||"").trim().replace(/^\/+|\/+$/g,"")||me.folder,l=r.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(A=>(A??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(l)){new N.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.importExport.push(this.renderDef("Dedicated import subfolder (optional)","Optional. A subfolder (relative to each Stashpad folder) where dropped .stash files auto-import. Leave blank to just drop files into the Stashpad folder itself (recommended). Suggested name: _imports.",s=>s.addText(n=>n.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async o=>{this.plugin.settings.importDropFolder=(o||"").trim().replace(/^\/+|\/+$/g,""),await t()})),["import","subfolder"])),i.importExport.push(this.renderDef("Stash export subfolder","Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.",s=>s.addText(n=>n.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async o=>{this.plugin.settings.exportFolder=(o||"").trim().replace(/^\/+|\/+$/g,"")||me.exportFolder,await t()})),["export","stash","subfolder"])),i.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{let{touched:o,fmChecked:r,fmWritten:l,slugsRenamed:c,authors:A,imported:h,attachmentsLinked:g,attachmentsRenamed:u,attachmentsSkipped:p}=await this.plugin.rebootstrapAllFolders(),I=[];I.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),h>0&&I.push(`imported ${h} loose file${h===1?"":"s"}`),g>0&&I.push(`linked attachments on ${g} note${g===1?"":"s"}`),u>0&&I.push(`renamed ${u} attachment${u===1?"":"s"}`),l>0?I.push(`updated frontmatter on ${l} of ${r} notes`):r>0&&I.push(`frontmatter already in sync (${r} notes checked)`),c>0&&I.push(`renamed ${c} note${c===1?"":"s"} to match body`),A>0&&I.push(`rebuilt author registry (${A} author${A===1?"":"s"})`),new N.Notice(`Stashpad: ${I.join("; ")}.`),p>0&&new N.Notice(`Stashpad: ${p} attachment${p===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(o){new N.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.maintenance.push(this.renderDef("Write recovery navigation links","Maintain the redundant parentLink/children frontmatter so you can walk the hierarchy from raw Markdown if the index ever breaks. On a slow / network drive this is a big per-move cost (several round-trips each); turn it off there for snappier moves \u2014 Rebootstrap rebuilds the fields on demand, and your notes' canonical structure (id/parent) is unaffected either way.",s=>s.addToggle(n=>n.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async o=>{this.plugin.settings.writeRecoveryLinks=o,await t()})),["recovery","parentlink","children","frontmatter"])),i.datesTime.push(this.renderDef("Use Templates plugin date/time formats","When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.",s=>{s.addToggle(o=>o.setValue(this.plugin.settings.useTemplatesFormat).onChange(async r=>{this.plugin.settings.useTemplatesFormat=r,await t()}));let n=Ss(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: ${ae(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:$t).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=[...$t],n&&(n.value=$t.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 N.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 N.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 N.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(l),new N.Notice(`Created Stashpad "${l}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(l,2e3),this.update?.()}catch(c){new N.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 N.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 N.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(h=>h.setButtonText("Set up password\u2026").setCta().onClick(()=>{new At(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:p,remember:u})=>{if(!p)return"Enter a password.";try{await t.setup(p,u,o())}catch(g){return g.message}return new N.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}if(l==="outsider"&&!t.isUnlocked()){t.hasSharedPassword()&&new N.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 At(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:p,remember:u})=>await t.unlock(p,u)?(new N.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password (or the keyfile hasn't synced here yet)."}).open()})),new N.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 At(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:p,remember:u})=>{if(!p)return"Choose a password for this device.";try{await t.requestAccess(o(),p,u)}catch(g){return g.message}return new N.Notice("Access requested. An existing member can now approve this device."),this.update?.(),null}}).open()}));return}if(l==="pending"){new N.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 At(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:p,remember:u})=>await t.unlock(p,u)?(new N.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 p=t.myIdentityId();p&&await t.denyJoinRequest(p),new N.Notice("Access request cancelled."),this.update?.()}));return}let c=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",A=t.isRemembered()?" \xB7 remembered on this device":"";if(new N.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${c?` \xB7 ${c}`:""}${A}`),t.isUnlocked()?new N.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 N.Notice("Encryption locked."),this.update?.()})):new N.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(h=>h.setButtonText("Unlock\u2026").setCta().onClick(()=>{new At(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:p,remember:u})=>await t.unlock(p,u)?(new N.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),Ul&&t.keychainAvailable()&&t.isRemembered()&&new N.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 N.Notice("Removed from this device's keychain \u2014 encryption still set up."),this.update?.()})),t.amIMember()&&new N.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 At(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:p,next:u,remember:g})=>await t.changePassword(p,u,g)?(new N.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),t.amIMember()&&new N.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 p=async()=>{let u=await this.plugin.encryptionStateStrict();if(u.live){let I=()=>{new nt(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 f=>{if(!f)return;let C=await this.plugin.purgeAllLockedContent();new N.Notice(`Deleted ${C} locked item${C===1?"":"s"}.`),p()}).open()},m=async()=>{if(await this.plugin.unlockAllInVault(),(await this.plugin.encryptionStateStrict()).live){new N.Notice("Some notes are still locked (decryption was cancelled or failed) \u2014 removal cancelled.",1e4);return}p()};new nt(this.app,"Encrypted notes are still locked",`Some notes or folders are still encrypted (locked) and have no plaintext copy. Before removing encryption: +`)),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 N.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 N.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 N.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(l),new N.Notice(`Created Stashpad "${l}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(l,2e3),this.update?.()}catch(c){new N.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 N.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 N.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(h=>h.setButtonText("Set up password\u2026").setCta().onClick(()=>{new At(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 N.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}if(l==="outsider"&&!t.isUnlocked()){t.hasSharedPassword()&&new N.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 At(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(new N.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password (or the keyfile hasn't synced here yet)."}).open()})),new N.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 At(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 N.Notice("Access requested. An existing member can now approve this device."),this.update?.(),null}}).open()}));return}if(l==="pending"){new N.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 At(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(new N.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 N.Notice("Access request cancelled."),this.update?.()}));return}let c=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",A=t.isRemembered()?" \xB7 remembered on this device":"";if(new N.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${c?` \xB7 ${c}`:""}${A}`),t.isUnlocked()?new N.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 N.Notice("Encryption locked."),this.update?.()})):new N.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(h=>h.setButtonText("Unlock\u2026").setCta().onClick(()=>{new At(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:g,remember:u})=>await t.unlock(g,u)?(new N.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),Jl&&t.keychainAvailable()&&t.isRemembered()&&new N.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 N.Notice("Removed from this device's keychain \u2014 encryption still set up."),this.update?.()})),t.amIMember()&&new N.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 At(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:g,next:u,remember:p})=>await t.changePassword(g,u,p)?(new N.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),t.amIMember()&&new N.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 I=()=>{new nt(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 N.Notice(`Deleted ${C} locked item${C===1?"":"s"}.`),g()}).open()},f=async()=>{if(await this.plugin.unlockAllInVault(),(await this.plugin.encryptionStateStrict()).live){new N.Notice("Some notes are still locked (decryption was cancelled or failed) \u2014 removal cancelled.",1e4);return}g()};new nt(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",f=>{f?m():I()},"Delete locked content").open();return}let g=(I,m)=>{new vi(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.${I} 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 f=await this.plugin.encryptionStateStrict();if(f.live){new N.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}if(f.trash&&!m){new N.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 N.Notice("Encryption removed."),this.update?.()}}).open()};if(u.trash){let I=async()=>{let f=await this.plugin.restoreAllTrash();if((await this.plugin.encryptionStateStrict()).trash){new N.Notice("Some encrypted-trash items couldn't be decrypted \u2014 removal cancelled. Check the trash tab and try again.",1e4);return}g(f>0?` (${f} trash item${f===1?"":"s"} were decrypted back to their folders.)`:"",!0)},m=()=>{new nt(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",f=>{f&&g(" \u26A0\uFE0F The encrypted trash is being permanently discarded.",!0)}).open()};new nt(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?f():I()},"Delete locked content").open();return}let p=(I,f)=>{new Fi(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.${I} 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 N.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}if(m.trash&&!f){new N.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 N.Notice("Encryption removed."),this.update?.()}}).open()};if(u.trash){let I=async()=>{let m=await this.plugin.restoreAllTrash();if((await this.plugin.encryptionStateStrict()).trash){new N.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)},f=()=>{new nt(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 nt(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",f=>{f?I():m()},"Discard trash").open();return}g("",!1)};h.setButtonText("Remove\u2026").onClick(()=>void p()),h.buttonEl.addClass("mod-warning")}),new N.Setting(i).setName("Sharing").setHeading(),t.isUnlocked()?t.hasSharedPassword()?new N.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 At(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:p,remember:u})=>{if(!p)return"Enter a password.";try{await t.setSharedPassword(p,u)}catch(g){return g.message}return new N.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(h=>{h.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new N.Notice("Shared password turned off."),this.update?.()}),h.buttonEl.addClass("mod-warning")}):new N.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 At(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:p,remember:u})=>{if(!p)return"Enter a password.";try{await t.setSharedPassword(p,u)}catch(g){return g.message}return new N.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."),Hl)if(new N.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 N.Setting(i).setName("Synced from the vault keyfile").addButton(p=>p.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 p=t.myIdentityId();for(let g of t.members()){let I=g.id===p,m=new N.Setting(i).setName(`${g.label}${I?" \u2014 this device":""}`).setDesc(I?"You":"Member");I||m.addButton(f=>{f.setButtonText("Remove").onClick(async()=>{await t.removeMember(g.id),new N.Notice(`Removed ${g.label}. (Not full revocation without rotating the key.)`),this.update?.()}),f.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 g of u)new N.Setting(i).setName(g.label).setDesc("Wants access to this vault").addButton(I=>I.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(g.id)}catch(m){new N.Notice(m.message);return}new N.Notice(`Approved ${g.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(I=>I.setButtonText("Deny").onClick(async()=>{await t.denyJoinRequest(g.id),new N.Notice("Request denied."),this.update?.()}))}},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private","collaborator","share","team","member","approve"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{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.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=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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 ds(this.app,this.plugin,this.plugin.settings);if(c.error==="no-dest"){new N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(c.error==="no-home"){new N.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}hs(this.app,c),this.display()}catch(c){console.error("[stashpad] preview failed",c),new N.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 N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Ni(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let h=await Sn(this.app,this.plugin,this.plugin.settings);if(h.error==="no-dest"){new N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(h.error==="dest-not-stashpad"){new N.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 N.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 N.Notice(`Build failed: ${h?.message??h}`,8e3)}}).open()})}).addButton(l=>{l.setButtonText(`Reveal in ${Pl()}`),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 N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(c)){new N.Notice(`Folder "${c}" doesn't exist yet.`,5e3);return}try{let h=this.app.vault.adapter.basePath;if(h){let{shell:p}=window.require?.("electron")??{},u=`${h}/${c}`;p?.openPath?.(u)}else new N.Notice("Reveal in file system not supported on this platform.",4e3)}catch(h){new N.Notice(`Couldn't open folder: ${h?.message??h}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new N.Setting(t).setName("Color aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=le()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new N.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 A=[...c].map(h=>({hex:h,count:r.get(h)??0}));A.sort((h,p)=>p.count-h.count||h.hex.localeCompare(p.hex));for(let h of A)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 N.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 N.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 N.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 N.Notice(`Couldn't create the OKF template: ${c.message}`);return}new N.Notice(`OKF template ready at "${l}" \u2014 set a folder's template to that path.`),this.update?.(),this.openSettingsPage("Templates")})}),new N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new N.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 N.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new N.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(A=>`${A.from} \u2192 ${A.to}`).join(", ");l.setText(`Renamed: ${c}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;if(new N.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"}),A=c.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});A.value=(this.plugin.settings.noteTemplates??{})[o]??"";let h=c.createDiv({cls:"stashpad-note-template-suggest"});h.setCssStyles({display:"none"});let p=[],u=[],g=-1,I=()=>h.style.display!=="none"&&p.length>0,m=w=>{g=w,u.forEach((D,b)=>D.toggleClass("is-active",b===w)),w>=0&&u[w]&&u[w].scrollIntoView({block:"nearest"})},f=()=>{h.setCssStyles({display:"none"}),g=-1},C=async w=>{A.value=w,await E(),f()},B=r.createDiv({cls:"stashpad-note-template-warn"});B.setCssStyles({display:"none"});let Q=()=>this.app.vault.getMarkdownFiles().map(w=>w.path).filter(w=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(w)).sort(),y=()=>{h.empty(),u=[];let w=A.value.trim().toLowerCase().split(/\s+/).filter(Boolean),D=b=>{let H=b.toLowerCase();return w.every(U=>H.includes(U))};if(p=Q().filter(b=>D(b)).slice(0,12),p.length===0){f();return}h.setCssStyles({display:""}),p.forEach((b,H)=>{let U=h.createDiv({cls:"stashpad-note-template-suggest-item",text:b});u.push(U),U.addEventListener("mousemove",()=>m(H)),U.addEventListener("mousedown",async x=>{x.preventDefault(),await C(b)})}),g=g>=0&&g<p.length?g:-1,g>=0&&m(g)},E=async()=>{let w=A.value.trim(),D={...this.plugin.settings.noteTemplates??{}};w?D[o]=w:delete D[o],this.plugin.settings.noteTemplates=D,await this.plugin.saveSettings(),v()},v=()=>{B.empty(),B.setCssStyles({display:"none"});let w=A.value.trim();if(!w)return;let D=this.app.vault.getAbstractFileByPath(w);if(!D||D.extension!=="md"){B.setCssStyles({display:""}),B.setText(`\u26A0 "${w}" is not a markdown file in this vault.`);return}let b=this.app.metadataCache.getFileCache(D)?.frontmatter??{},U=se.filter(x=>{let S=b[x];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.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.`))};A.addEventListener("focus",y),A.addEventListener("input",()=>{g=-1,y()}),A.addEventListener("blur",()=>{setTimeout(f,150)}),A.addEventListener("change",()=>{E()}),A.addEventListener("keydown",w=>{if(w.key==="ArrowDown")w.preventDefault(),I()?m((g+1)%p.length):(y(),p.length&&m(0));else if(w.key==="ArrowUp"){if(!I())return;w.preventDefault(),m((g-1+p.length)%p.length)}else if(w.key==="Enter")I()&&g>=0&&(w.preventDefault(),C(p[g]));else if(w.key==="Escape")I()&&(w.preventDefault(),f());else if(w.key==="Tab"&&!w.shiftKey){if(!I())return;let D=p[g>=0?g:0],b=A.value,H;if(D.toLowerCase().startsWith(b.toLowerCase())){let U=D.indexOf("/",b.length);H=U>=0?D.slice(0,U+1):D}else H=D;H&&H!==b&&(w.preventDefault(),A.value=H,g=-1,y(),p.length===1&&m(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 Te(this.app,i,h,async p=>{if((p??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(p&&p.toLowerCase()===i){n();return}let u=await this.plugin.recolorAllInFolder(e,i,p??null);if(u>0)new N.Notice(`Recolored ${u} note${u===1?"":"s"}.`);else if(s===0){let g=this.plugin.getColorAlias(e,i);g&&(await this.plugin.setColorAlias(e,i,""),p&&await this.plugin.setColorAlias(e,p,g))}n()},async p=>{let u=(this.plugin.settings.customPalette??[]).filter(g=>g.toLowerCase()!==p.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 A=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});c.value||A.setCssStyles({visibility:"hidden"}),A.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(c.value="",A.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 A=r();n.toggleClass("is-right",A),n.setAttribute("aria-checked",String(A)),o.setText(A?"X":"\u2713"),s.setText(A?"Excluded":"Included"),s.toggleClass("is-excluded",A),n.title=A?"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 A=new Set(this.plugin.settings.searchExcludedFolders??[]);A.has(e)?A.delete(e):A.add(e),this.plugin.settings.searchExcludedFolders=[...A].sort(),l(),await this.plugin.saveSettings()};n.onclick=()=>void c(),n.onkeydown=A=>{(A.key===" "||A.key==="Enter")&&(A.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 A=l.createDiv({cls:"stashpad-folder-row"});A.createSpan({cls:"stashpad-folder-row-label",text:c});let h=A.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 g=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),I=g.createEl("input",{type:"text"});I.readOnly=!0,I.placeholder="Click & press a key",I.value=Mi(i()[u]),I.classList.add("stashpad-binding-input");let m=()=>{I.size=Math.max(3,I.value.length||I.placeholder.length)};m();let f=u==="primary"?e.defaultPrimary:e.defaultSecondary??"";I.onclick=()=>{da(I,async y=>{this.plugin.settings.bindings[e.id][u]=y,I.value=Mi(y),m(),await this.plugin.saveSettings(),o(),Q()})};let C=g.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});C.title="Clear this slot",C.onclick=async()=>{this.plugin.settings.bindings[e.id][u]="",I.value="",m(),await this.plugin.saveSettings(),o(),Q()};let B=g.createEl("button",{cls:"stashpad-binding-revert"});(0,N.setIcon)(B,"rotate-ccw");let Q=()=>{let E=i()[u]!==f;B.toggleClass("is-hidden",!E),B.title=f?`Revert to default (${Mi(f)})`:"Revert to default (no binding)"};return B.onclick=async()=>{this.plugin.settings.bindings[e.id][u]=f,I.value=Mi(f),m(),await this.plugin.saveSettings(),o(),Q()},Q(),I};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"}),A=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),h=A.createEl("input",{type:"checkbox"});h.title="Use both bindings simultaneously (overrides the L/R toggle)",A.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(),g=!!(u.primary&&u.secondary);h.checked=!!u.useBoth,h.disabled=!g,A.toggleClass("is-disabled",!g);let I=!!u.useBoth&&g;l.toggleClass("is-disabled",!g||I),l.toggleClass("is-right",u.preferRight),l.setAttribute("aria-checked",String(u.preferRight)),l.setAttribute("aria-disabled",String(!g||I)),c.setText(u.preferRight?"R":"L"),l.title=g?I?'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 p=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 p(),l.onkeydown=u=>{(u.key===" "||u.key==="Enter")&&(u.preventDefault(),p())},o()}};var oi=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=j().inheritObsidianExclusions,t=a?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!qo(i.path)&&!Jo(i.path)&&!(a&&Ko(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 Ta.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()}};at();var Ss=class extends vt.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 ke}getDisplayText(){return"Stashpad detail"}getIcon(){return"panel-right"}async onOpen(){this.render(),this.unsubscribeSelection=this.plugin.onStashpadSelectionChange(()=>{this.displayedId=null,this.scheduleRender()}),this.unsubscribeContent=this.plugin.onStashpadContentChange(()=>this.scheduleRender()),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{!t||t===this.leaf||t.view?.getViewType?.()===J&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("modify",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()})),this.registerEvent(this.app.metadataCache.on("changed",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()}))}async onClose(){this.unsubscribeSelection?.(),this.unsubscribeSelection=null,this.unsubscribeContent?.(),this.unsubscribeContent=null,this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,this.renderTimer!=null&&(window.clearTimeout(this.renderTimer),this.renderTimer=null)}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},60))}resolveDisplayed(){if(this.displayedId){let e=this.plugin.lastActiveStashpadLeaf?.view;if(e?.getViewType?.()===J&&e.tree?.get){let i=e.tree.get(this.displayedId);if(i?.file)return{folder:e.noteFolder,id:this.displayedId,file:i.file}}this.displayedId=null}let t=this.plugin.getActiveStashpadSelection();return t&&(this.displayedId=t.id),t}async render(){let t=this.contentEl,e=!!this.composerInputEl&&document.activeElement===this.composerInputEl,i=this.composerInputEl?.selectionStart??null;this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,t.empty(),t.addClass("stashpad-detail-root");let s=this.resolveDisplayed();if(!s){this.displayedPath=null;let g=t.createDiv({cls:"stashpad-detail-empty"});(0,vt.setIcon)(g.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),g.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 A=c.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,vt.setIcon)(A,"arrow-up-right"),A.title="Open this note in a new Stashpad tab",A.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 g=h.createSpan({cls:"stashpad-detail-meta-color"});g.style.background=o.color,g.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 g=Date.parse(String(o.due)),I=Number.isNaN(g)?String(o.due):oe(g,this.plugin.settings);h.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${I}`})}if(Array.isArray(o.tags))for(let g of o.tags.filter(I=>typeof I=="string"))h.createSpan({cls:"stashpad-detail-meta-tag",text:`#${g.replace(/^#/,"")}`});let p=r.createDiv({cls:"stashpad-detail-body"});try{let g=await this.app.vault.cachedRead(n),I=this.stripFrontmatter(g);await vt.MarkdownRenderer.render(this.app,I,p,n.path,this)}catch(g){p.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${g.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 g=Math.min(i,u.value.length);try{u.setSelectionRange(g,g)}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,vt.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?.()!==J||typeof i.createNoteUnder!="function"){new vt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new vt.Notice(`Couldn't add note: ${s.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,i){let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==J)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let 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,A=i.getChildren(n.id),h=A.length>0,p=`${s}|${n.id}`,u=this.expanded.has(p),g=t.createDiv({cls:"stashpad-detail-child-row"});c&&g.addClass("is-completed"),o>0&&(g.style.paddingLeft=`${o*16}px`),g.draggable=!0,g.dataset.id=n.id,g.addEventListener("dragstart",B=>{B.dataTransfer?.setData("text/plain",n.id),B.dataTransfer&&(B.dataTransfer.effectAllowed="move"),g.addClass("is-dragging")}),g.addEventListener("dragend",()=>g.removeClass("is-dragging")),g.addEventListener("dragover",B=>{B.preventDefault(),B.dataTransfer&&(B.dataTransfer.dropEffect="move");let Q=g.getBoundingClientRect(),y=B.clientY-Q.top<Q.height/2;g.toggleClass("drop-before",y),g.toggleClass("drop-after",!y)}),g.addEventListener("dragleave",()=>{g.removeClass("drop-before"),g.removeClass("drop-after")}),g.addEventListener("drop",B=>{B.preventDefault(),g.removeClass("drop-before"),g.removeClass("drop-after");let Q=B.dataTransfer?.getData("text/plain");if(!Q||Q===n.id)return;let y=g.getBoundingClientRect(),E=B.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([Q],n.id,E?"before":"after")}),g.oncontextmenu=B=>{B.preventDefault();let Q=i.get(n.id);Q&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(B,Q)};let I=g.createSpan({cls:"stashpad-detail-child-toggle"});if(h&&(Ie(I,A.length,u),I.onclick=B=>{B.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Ye(r,"task")||r.task===!0||r.completed!==void 0){let B=g.createSpan({cls:"stashpad-detail-child-checkbox"});(0,vt.setIcon)(B,c?"check-square":"square"),B.title=c?"Mark not done":"Mark done",B.addEventListener("mousedown",Q=>Q.stopPropagation()),B.addEventListener("dblclick",Q=>{Q.preventDefault(),Q.stopPropagation()}),B.onclick=Q=>{Q.preventDefault(),Q.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let f=g.createSpan({cls:"stashpad-detail-child-icon"});(0,vt.setIcon)(f,h?"folder-tree":"file-text"),l&&(f.style.color=l);let C=g.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 A)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)?oe(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==F&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new vt.Notice(`Couldn't open: ${i.message}`)}}};async function Ds(d){let a=d.workspace.getLeavesOfType(ke);if(a.length>0){d.workspace.revealLeaf(a[0]);return}let t=d.workspace.getRightLeaf(!1);if(!t){new vt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:ke,active:!0}),d.workspace.revealLeaf(t)}var k=require("obsidian");at();var Ce=require("obsidian");at();function Gl(d,a){let t=d.vault.getAbstractFileByPath(a);if(!(t instanceof Ce.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof Ce.TFile?n.extension==="md"&&e.push(n):n instanceof Ce.TFolder&&(fi.has(n.name)||i.push(n))}return e}var bs=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(F,{id:F,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(F,{id:F,parent:null,children:[],file:null,created:""});let s=t?Gl(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),A=c?i.get(c):void 0,h=this.synthetic.get(n.path),p=A??h;p&&(this.nodes.set(p.id,{...p,children:[],file:n}),this.byPath.set(n.path,p.id));continue}if(this.synthetic.delete(n.path),r===F){let c=this.nodes.get(F);c.file=n,c.created=o?.created??"",this.byPath.set(n.path,F);continue}let l=o?.parent??null;l===r&&(l=null),this.nodes.set(r,{id:r,parent:l??F,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,r)}for(let n of this.nodes.values()){if(n.id===F)continue;let o=n.parent??F;(this.nodes.get(o)??this.nodes.get(F)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,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 A=r.has(l)?r.get(l):1/0,h=r.has(c)?r.get(c):1/0;return A===h?0:A-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??F,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(F)}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!==F&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(a){return this.byPath.get(a)}snapshot(){let a={};for(let t of this.nodes.values())t.id===F||!t.file||(a[t.id]={parent:t.parent===F?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 Ce.TFile&&t(l.path)&&l.extension==="md"&&(this.applyChange(l),i())},n=l=>{l instanceof Ce.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 Ce.TFile))return;let A=typeof c=="string"?c:null;!t(l.path)&&!t(A)||this.applyRename(l,A??"")&&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===F){let c=this.nodes.get(F),A=t?.created??"",h=!1;return c.file!==a&&(c.file=a,h=!0),c.created!==A&&(c.created=A,h=!0),this.byPath.get(a.path)!==F&&(this.byPath.set(a.path,F),h=!0),h}let s=t?.parent??F,n=t?.created??"";if(!(s===F||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let 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??F),l=!0),r.parent!==s){let c=r.parent??F;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(F);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=F,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(F),this.nodes.delete(t),this.byPath.delete(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??F);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??F);t||(t=this.nodes.get(F)),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 _n=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(` -`)}},Ft=new _n;var Pa=".stashpad-order.json",ai=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}/${Pa}`,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}/${Pa}`,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 qi={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"},to=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],Ll=new Set(to),Ha=".stashpad-sort.json",Ns=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}/${Ha}`,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"&&Ll.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}/${Ha}`,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)}};at();var Be="parentLink",ri="children";var Ts=class Ts{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||!j().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(),Ts.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[Be]=="string"?n[Be]:null,r=n?.[ri],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 Ft.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[Be]=i:delete n[Be],s.length>0?n[ri]=s:delete n[ri]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(a){if(a.id===F)return null;let t=this.getTree();if(!a.parent||a.parent===F){let i=t.getRoot();return i&&i.id!==a.id&&i.file?xs(i.file.path):null}let e=t.get(a.parent);return e?.file?xs(e.file.path):null}computeChildrenLinks(a){return this.getTree().getChildren(a.id).filter(e=>!!e.file).map(e=>xs(e.file.path))}};Ts.PACING_MS=100;var Ms=Ts;async function li(d,a){let t=a.endsWith("/")?a:a+"/",e=new Map,i=new Map;for(let c of d.vault.getMarkdownFiles()){if(c.path!==a&&!c.path.startsWith(t))continue;let A=d.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id:null;if(!h)continue;let p=typeof A?.parent=="string"?A.parent:F;e.set(h,{file:c,id:h,parent:p});let u=i.get(p)??[];u.push(h),i.set(p,u)}let s=c=>xs(c.file.path),n=c=>{if(c.id===F)return null;if(c.parent===F||!c.parent){let h=e.get(F);return h?s(h):null}let A=e.get(c.parent);return A?s(A):null},o=c=>{let A=i.get(c.id)??[],h=[];for(let p of A){let u=e.get(p);u&&h.push(s(u))}return h},r=0,l=0;for(let c of e.values()){r+=1;let A=n(c),h=o(c),p=d.metadataCache.getFileCache(c.file)?.frontmatter,u=p&&typeof p[Be]=="string"?p[Be]:null,g=p?.[ri],I=Array.isArray(g)?g.filter(C=>typeof C=="string"):[],m=(u??null)===(A??null),f=I.length===h.length&&I.every((C,B)=>C===h[B]);if(!(m&&f))try{await d.fileManager.processFrontMatter(c.file,C=>{A?C[Be]=A:delete C[Be],h.length>0?C[ri]=h:delete C[ri]}),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 xs(d){return`[[${d.replace(/\.md$/i,"")}]]`}Ut();je();var Ps=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");at();En();var mt=gt.moment;function eo(d){let a=d.trim().toLowerCase();if(!a)return null;let t=Date.now(),e=g=>mt(g).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 g=parseInt(r[1],10),I=r[2]?parseInt(r[2],10):0,m=r[3];m==="pm"&&g<12&&(g+=12),m==="am"&&g===12&&(g=0),g>=0&&g<24&&I>=0&&I<60&&(s=(g*3600+I*60)*1e3,n=!0,o=a.replace(r[0]," ").replace(/\s+/g," ").trim())}let l=g=>n?g+s:g;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"],A=["sun","mon","tue","wed","thu","fri","sat"],h=c.indexOf(o)>=0?c.indexOf(o):A.indexOf(o);if(h>=0){let g=mt().startOf("day"),m=(g.day()-h+7)%7;return l(g.subtract(m,"days").valueOf())}let p=/^(\d+)\s*([dwmy])$/.exec(o);if(p){let g=parseInt(p[1],10),I={d:"days",w:"weeks",m:"months",y:"years"}[p[2]];return l(mt().subtract(g,I).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 Ua(d){let a={text:[],filters:{}},t=(d||"").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=eo(o);r!=null&&(a.filters.before=r)}else if(n==="after"){let r=eo(o);r!=null&&(a.filters.after=r)}else if(n==="on"){let r=eo(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 Xt=class d 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!==F?this.notes.push({node:r,title:`${" ".repeat(o)}${this.titleFn(r)}`,body:""}):r?.file&&n===F&&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(F))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(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=Ua(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=f=>{if(!s.length)return!0;for(let C of s)if(!f.includes(C))return!1;return!0},o=null,r=null;if(i.filters.in){let f=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,r=new Map;let C=y=>f.every(E=>y.toLowerCase().includes(E)),B=y=>{if(!o.has(y)){o.add(y);for(let E of this.tree.getChildren(y))B(E.id)}};for(let y of this.notes)!y.node||y.cross||C(y.title)&&B(y.node.id);let Q=new Map;for(let y of this.notes){if(!y.cross)continue;let E=Q.get(y.cross.folder)??[];E.push(y),Q.set(y.cross.folder,E)}for(let[y,E]of Q){let v=new Map;for(let b of E){let H=b.cross?.parentId??null;if(!H)continue;let U=v.get(H)??[];U.push(b.cross.id),v.set(H,U)}let w=new Set;r.set(y,w);let D=b=>{if(!w.has(b)){w.add(b);for(let H of v.get(b)??[])D(H)}};for(let b of E)C(b.title)&&D(b.cross.id)}}let l=f=>{let C=i.filters;if(o||r)if(f.cross){let B=r?.get(f.cross.folder);if(!B||!B.has(f.cross.id))return!1}else if(f.node){if(!o||!o.has(f.node.id))return!1}else return!1;if(C.before||C.after||C.on){let B=this.createdMsFor(f);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=f=>n(f.toLowerCase()),A=this.notes.filter(f=>!f.cross),h=this.notes.filter(f=>f.cross),p=(f,C)=>({id:f.cross?`cross:${f.cross.folder}:${f.cross.id}`:f.node.id,label:f.title,node:f.node,kind:"note",bodyPreview:this.previewFromBody(f.body,C),matchLine:C,crossFolder:f.cross?.folder,crossFile:f.cross?.file,crossId:f.cross?.id}),u=f=>{let C=[];for(let B of f)if(l(B))if(this.opts.mode==="search"){if(!e){C.push(p(B,-1));continue}let Q=n(B.title.toLowerCase()),y=B.body.split(/\r?\n/),E=[];for(let w=0;w<y.length;w++)c(y[w])&&E.push(w);let v=E.length>0||n(B.body.toLowerCase());if(!Q&&!v)continue;if(E.length===0)C.push(p(B,-1));else{let w=[],D=-100;for(let H of E)H-D>5&&w.push(H),D=H;let b=5;for(let H of w.slice(0,b))C.push(p(B,H))}}else{if(e&&!n(B.title.toLowerCase())&&!n(B.body.toLowerCase()))continue;C.push(p(B,-1))}return C},g=u(A),I=[...g];if(this.opts.mode==="search"?e?!0:g.length<10:!!e){let f=u(h);this.opts.mode==="search"&&!e&&(I.length=Math.min(I.length,50)),I.push(...f)}if(this.opts.folderResults){let f=this.opts.folderResults(),C={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};f.length>0&&(e?f.some(B=>{let Q=B.split("/").pop()??B;return n(`${B.toLowerCase()} ${Q.toLowerCase()}`)})&&I.push(C):I.unshift(C))}if(this.opts.allowCreate&&e&&!I.some(f=>f.label.trim().toLowerCase()===e)&&I.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let f=B=>B.kind==="note"&&(B.id===F||B.crossId===F)&&n(B.label.toLowerCase()),C=I.filter(f);if(C.length>0){let B=I.filter(Q=>!f(Q));I.splice(0,I.length,...C,...B)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&I.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),I}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?I():f()},"Discard trash").open();return}p("",!1)};h.setButtonText("Remove\u2026").onClick(()=>void g()),h.buttonEl.addClass("mod-warning")}),new N.Setting(i).setName("Sharing").setHeading(),t.isUnlocked()?t.hasSharedPassword()?new N.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 At(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 N.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(h=>{h.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new N.Notice("Shared password turned off."),this.update?.()}),h.buttonEl.addClass("mod-warning")}):new N.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 At(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 N.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."),ql)if(new N.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 N.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 I=p.id===g,f=new N.Setting(i).setName(`${p.label}${I?" \u2014 this device":""}`).setDesc(I?"You":"Member");I||f.addButton(m=>{m.setButtonText("Remove").onClick(async()=>{await t.removeMember(p.id),new N.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 N.Setting(i).setName(p.label).setDesc("Wants access to this vault").addButton(I=>I.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(p.id)}catch(f){new N.Notice(f.message);return}new N.Notice(`Approved ${p.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(I=>I.setButtonText("Deny").onClick(async()=>{await t.denyJoinRequest(p.id),new N.Notice("Request denied."),this.update?.()}))}},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private","collaborator","share","team","member","approve"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{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.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=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 N.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 N.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 N.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(l=>{new ei(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 N.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 N.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 ei(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 N.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=ti(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 N.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 hs(this.app,this.plugin,this.plugin.settings);if(c.error==="no-dest"){new N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(c.error==="no-home"){new N.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}ps(this.app,c),this.display()}catch(c){console.error("[stashpad] preview failed",c),new N.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 N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new xi(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let h=await Nn(this.app,this.plugin,this.plugin.settings);if(h.error==="no-dest"){new N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(h.error==="dest-not-stashpad"){new N.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 N.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 N.Notice(`Build failed: ${h?.message??h}`,8e3)}}).open()})}).addButton(l=>{l.setButtonText(`Reveal in ${Ll()}`),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 N.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(c)){new N.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 N.Notice("Reveal in file system not supported on this platform.",4e3)}catch(h){new N.Notice(`Couldn't open folder: ${h?.message??h}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new N.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 N.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 A=[...c].map(h=>({hex:h,count:r.get(h)??0}));A.sort((h,g)=>g.count-h.count||h.hex.localeCompare(g.hex));for(let h of A)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 N.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 N.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 N.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 N.Notice(`Couldn't create the OKF template: ${c.message}`);return}new N.Notice(`OKF template ready at "${l}" \u2014 set a folder's template to that path.`),this.update?.(),this.openSettingsPage("Templates")})}),new N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.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 N.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new N.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 N.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new N.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(A=>`${A.from} \u2192 ${A.to}`).join(", ");l.setText(`Renamed: ${c}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;if(new N.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"}),A=c.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});A.value=(this.plugin.settings.noteTemplates??{})[o]??"";let h=c.createDiv({cls:"stashpad-note-template-suggest"});h.setCssStyles({display:"none"});let g=[],u=[],p=-1,I=()=>h.style.display!=="none"&&g.length>0,f=w=>{p=w,u.forEach((D,b)=>D.toggleClass("is-active",b===w)),w>=0&&u[w]&&u[w].scrollIntoView({block:"nearest"})},m=()=>{h.setCssStyles({display:"none"}),p=-1},C=async w=>{A.value=w,await E(),m()},B=r.createDiv({cls:"stashpad-note-template-warn"});B.setCssStyles({display:"none"});let Q=()=>this.app.vault.getMarkdownFiles().map(w=>w.path).filter(w=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(w)).sort(),y=()=>{h.empty(),u=[];let w=A.value.trim().toLowerCase().split(/\s+/).filter(Boolean),D=b=>{let H=b.toLowerCase();return w.every(U=>H.includes(U))};if(g=Q().filter(b=>D(b)).slice(0,12),g.length===0){m();return}h.setCssStyles({display:""}),g.forEach((b,H)=>{let U=h.createDiv({cls:"stashpad-note-template-suggest-item",text:b});u.push(U),U.addEventListener("mousemove",()=>f(H)),U.addEventListener("mousedown",async x=>{x.preventDefault(),await C(b)})}),p=p>=0&&p<g.length?p:-1,p>=0&&f(p)},E=async()=>{let w=A.value.trim(),D={...this.plugin.settings.noteTemplates??{}};w?D[o]=w:delete D[o],this.plugin.settings.noteTemplates=D,await this.plugin.saveSettings(),v()},v=()=>{B.empty(),B.setCssStyles({display:"none"});let w=A.value.trim();if(!w)return;let D=this.app.vault.getAbstractFileByPath(w);if(!D||D.extension!=="md"){B.setCssStyles({display:""}),B.setText(`\u26A0 "${w}" is not a markdown file in this vault.`);return}let b=this.app.metadataCache.getFileCache(D)?.frontmatter??{},U=ne.filter(x=>{let S=b[x];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.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.`))};A.addEventListener("focus",y),A.addEventListener("input",()=>{p=-1,y()}),A.addEventListener("blur",()=>{setTimeout(m,150)}),A.addEventListener("change",()=>{E()}),A.addEventListener("keydown",w=>{if(w.key==="ArrowDown")w.preventDefault(),I()?f((p+1)%g.length):(y(),g.length&&f(0));else if(w.key==="ArrowUp"){if(!I())return;w.preventDefault(),f((p-1+g.length)%g.length)}else if(w.key==="Enter")I()&&p>=0&&(w.preventDefault(),C(g[p]));else if(w.key==="Escape")I()&&(w.preventDefault(),m());else if(w.key==="Tab"&&!w.shiftKey){if(!I())return;let D=g[p>=0?p:0],b=A.value,H;if(D.toLowerCase().startsWith(b.toLowerCase())){let U=D.indexOf("/",b.length);H=U>=0?D.slice(0,U+1):D}else H=D;H&&H!==b&&(w.preventDefault(),A.value=H,p=-1,y(),g.length===1&&f(0))}}),v()};for(let n of e)s(n)}renderColorAliasRow(t,e,i,s,n){let o=t.createDiv({cls:"stashpad-color-alias-row"});s===0&&o.addClass("is-unused");let 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 Te(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 N.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 A=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});c.value||A.setCssStyles({visibility:"hidden"}),A.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(c.value="",A.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 A=r();n.toggleClass("is-right",A),n.setAttribute("aria-checked",String(A)),o.setText(A?"X":"\u2713"),s.setText(A?"Excluded":"Included"),s.toggleClass("is-excluded",A),n.title=A?"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 A=new Set(this.plugin.settings.searchExcludedFolders??[]);A.has(e)?A.delete(e):A.add(e),this.plugin.settings.searchExcludedFolders=[...A].sort(),l(),await this.plugin.saveSettings()};n.onclick=()=>void c(),n.onkeydown=A=>{(A.key===" "||A.key==="Enter")&&(A.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 A=l.createDiv({cls:"stashpad-folder-row"});A.createSpan({cls:"stashpad-folder-row-label",text:c});let h=A.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"}),I=p.createEl("input",{type:"text"});I.readOnly=!0,I.placeholder="Click & press a key",I.value=Ti(i()[u]),I.classList.add("stashpad-binding-input");let f=()=>{I.size=Math.max(3,I.value.length||I.placeholder.length)};f();let m=u==="primary"?e.defaultPrimary:e.defaultSecondary??"";I.onclick=()=>{ga(I,async y=>{this.plugin.settings.bindings[e.id][u]=y,I.value=Ti(y),f(),await this.plugin.saveSettings(),o(),Q()})};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]="",I.value="",f(),await this.plugin.saveSettings(),o(),Q()};let B=p.createEl("button",{cls:"stashpad-binding-revert"});(0,N.setIcon)(B,"rotate-ccw");let Q=()=>{let E=i()[u]!==m;B.toggleClass("is-hidden",!E),B.title=m?`Revert to default (${Ti(m)})`:"Revert to default (no binding)"};return B.onclick=async()=>{this.plugin.settings.bindings[e.id][u]=m,I.value=Ti(m),f(),await this.plugin.saveSettings(),o(),Q()},Q(),I};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"}),A=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),h=A.createEl("input",{type:"checkbox"});h.title="Use both bindings simultaneously (overrides the L/R toggle)",A.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,A.toggleClass("is-disabled",!p);let I=!!u.useBoth&&p;l.toggleClass("is-disabled",!p||I),l.toggleClass("is-right",u.preferRight),l.setAttribute("aria-checked",String(u.preferRight)),l.setAttribute("aria-disabled",String(!p||I)),c.setText(u.preferRight?"R":"L"),l.title=p?I?'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 oi=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=j().inheritObsidianExclusions,t=a?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!Oo(i.path)&&!Yo(i.path)&&!(a&&$o(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 Ua.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()}};at();var Ds=class extends vt.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 ke}getDisplayText(){return"Stashpad detail"}getIcon(){return"panel-right"}async onOpen(){this.render(),this.unsubscribeSelection=this.plugin.onStashpadSelectionChange(()=>{this.displayedId=null,this.scheduleRender()}),this.unsubscribeContent=this.plugin.onStashpadContentChange(()=>this.scheduleRender()),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{!t||t===this.leaf||t.view?.getViewType?.()===J&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("modify",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()})),this.registerEvent(this.app.metadataCache.on("changed",t=>{this.displayedPath&&t.path===this.displayedPath&&this.scheduleRender()}))}async onClose(){this.unsubscribeSelection?.(),this.unsubscribeSelection=null,this.unsubscribeContent?.(),this.unsubscribeContent=null,this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,this.renderTimer!=null&&(window.clearTimeout(this.renderTimer),this.renderTimer=null)}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},60))}resolveDisplayed(){if(this.displayedId){let e=this.plugin.lastActiveStashpadLeaf?.view;if(e?.getViewType?.()===J&&e.tree?.get){let i=e.tree.get(this.displayedId);if(i?.file)return{folder:e.noteFolder,id:this.displayedId,file:i.file}}this.displayedId=null}let t=this.plugin.getActiveStashpadSelection();return t&&(this.displayedId=t.id),t}async render(){let t=this.contentEl,e=!!this.composerInputEl&&document.activeElement===this.composerInputEl,i=this.composerInputEl?.selectionStart??null;this.composerAutocomplete?.detach(),this.composerAutocomplete=null,this.composerInputEl=null,t.empty(),t.addClass("stashpad-detail-root");let s=this.resolveDisplayed();if(!s){this.displayedPath=null;let p=t.createDiv({cls:"stashpad-detail-empty"});(0,vt.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 A=c.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,vt.setIcon)(A,"arrow-up-right"),A.title="Open this note in a new Stashpad tab",A.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)),I=Number.isNaN(p)?String(o.due):ae(p,this.plugin.settings);h.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${I}`})}if(Array.isArray(o.tags))for(let p of o.tags.filter(I=>typeof I=="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),I=this.stripFrontmatter(p);await vt.MarkdownRenderer.render(this.app,I,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,vt.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?.()!==J||typeof i.createNoteUnder!="function"){new vt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new vt.Notice(`Couldn't add note: ${s.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,i){let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==J)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let 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,A=i.getChildren(n.id),h=A.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 Q=p.getBoundingClientRect(),y=B.clientY-Q.top<Q.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 Q=B.dataTransfer?.getData("text/plain");if(!Q||Q===n.id)return;let y=p.getBoundingClientRect(),E=B.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([Q],n.id,E?"before":"after")}),p.oncontextmenu=B=>{B.preventDefault();let Q=i.get(n.id);Q&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(B,Q)};let I=p.createSpan({cls:"stashpad-detail-child-toggle"});if(h&&(Ie(I,A.length,u),I.onclick=B=>{B.stopPropagation(),this.expanded.has(g)?this.expanded.delete(g):this.expanded.add(g),this.render()}),$e(r,"task")||r.task===!0||r.completed!==void 0){let B=p.createSpan({cls:"stashpad-detail-child-checkbox"});(0,vt.setIcon)(B,c?"check-square":"square"),B.title=c?"Mark not done":"Mark done",B.addEventListener("mousedown",Q=>Q.stopPropagation()),B.addEventListener("dblclick",Q=>{Q.preventDefault(),Q.stopPropagation()}),B.onclick=Q=>{Q.preventDefault(),Q.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,vt.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 A)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)?ae(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==F&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new vt.Notice(`Couldn't open: ${i.message}`)}}};async function bs(d){let a=d.workspace.getLeavesOfType(ke);if(a.length>0){d.workspace.revealLeaf(a[0]);return}let t=d.workspace.getRightLeaf(!1);if(!t){new vt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:ke,active:!0}),d.workspace.revealLeaf(t)}var k=require("obsidian");at();var Ce=require("obsidian");at();function Ol(d,a){let t=d.vault.getAbstractFileByPath(a);if(!(t instanceof Ce.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof Ce.TFile?n.extension==="md"&&e.push(n):n instanceof Ce.TFolder&&(mi.has(n.name)||i.push(n))}return e}var Ns=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(F,{id:F,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(F,{id:F,parent:null,children:[],file:null,created:""});let s=t?Ol(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),A=c?i.get(c):void 0,h=this.synthetic.get(n.path),g=A??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===F){let c=this.nodes.get(F);c.file=n,c.created=o?.created??"",this.byPath.set(n.path,F);continue}let l=o?.parent??null;l===r&&(l=null),this.nodes.set(r,{id:r,parent:l??F,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,r)}for(let n of this.nodes.values()){if(n.id===F)continue;let o=n.parent??F;(this.nodes.get(o)??this.nodes.get(F)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,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 A=r.has(l)?r.get(l):1/0,h=r.has(c)?r.get(c):1/0;return A===h?0:A-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??F,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(F)}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!==F&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(a){return this.byPath.get(a)}snapshot(){let a={};for(let t of this.nodes.values())t.id===F||!t.file||(a[t.id]={parent:t.parent===F?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 Ce.TFile&&t(l.path)&&l.extension==="md"&&(this.applyChange(l),i())},n=l=>{l instanceof Ce.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 Ce.TFile))return;let A=typeof c=="string"?c:null;!t(l.path)&&!t(A)||this.applyRename(l,A??"")&&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(Ve(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===F){let c=this.nodes.get(F),A=t?.created??"",h=!1;return c.file!==a&&(c.file=a,h=!0),c.created!==A&&(c.created=A,h=!0),this.byPath.get(a.path)!==F&&(this.byPath.set(a.path,F),h=!0),h}let s=t?.parent??F,n=t?.created??"";if(!(s===F||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let 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??F),l=!0),r.parent!==s){let c=r.parent??F;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(F);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=F,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(F),this.nodes.delete(t),this.byPath.delete(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(Ve(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??F);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??F);t||(t=this.nodes.get(F)),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 io=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(` +`)}},Ft=new io;var Ra=".stashpad-order.json",ai=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}/${Ra}`,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}/${Ra}`,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 Ji={manual:"Manual","created-asc":"Created \u2014 oldest first","created-desc":"Created \u2014 newest first","modified-asc":"Modified \u2014 oldest first","modified-desc":"Modified \u2014 newest first","title-az":"Title \u2014 A\u2192Z","title-za":"Title \u2014 Z\u2192A"},so=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],Yl=new Set(so),Ga=".stashpad-sort.json",xs=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}/${Ga}`,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"&&Yl.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}/${Ga}`,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)}};at();var Be="parentLink",ri="children";var Ps=class Ps{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||!j().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(),Ps.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[Be]=="string"?n[Be]:null,r=n?.[ri],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 Ft.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[Be]=i:delete n[Be],s.length>0?n[ri]=s:delete n[ri]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(a){if(a.id===F)return null;let t=this.getTree();if(!a.parent||a.parent===F){let i=t.getRoot();return i&&i.id!==a.id&&i.file?Ms(i.file.path):null}let e=t.get(a.parent);return e?.file?Ms(e.file.path):null}computeChildrenLinks(a){return this.getTree().getChildren(a.id).filter(e=>!!e.file).map(e=>Ms(e.file.path))}};Ps.PACING_MS=100;var Ts=Ps;async function li(d,a){let t=a.endsWith("/")?a:a+"/",e=new Map,i=new Map;for(let c of d.vault.getMarkdownFiles()){if(c.path!==a&&!c.path.startsWith(t))continue;let A=d.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id:null;if(!h)continue;let g=typeof A?.parent=="string"?A.parent:F;e.set(h,{file:c,id:h,parent:g});let u=i.get(g)??[];u.push(h),i.set(g,u)}let s=c=>Ms(c.file.path),n=c=>{if(c.id===F)return null;if(c.parent===F||!c.parent){let h=e.get(F);return h?s(h):null}let A=e.get(c.parent);return A?s(A):null},o=c=>{let A=i.get(c.id)??[],h=[];for(let g of A){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 A=n(c),h=o(c),g=d.metadataCache.getFileCache(c.file)?.frontmatter,u=g&&typeof g[Be]=="string"?g[Be]:null,p=g?.[ri],I=Array.isArray(p)?p.filter(C=>typeof C=="string"):[],f=(u??null)===(A??null),m=I.length===h.length&&I.every((C,B)=>C===h[B]);if(!(f&&m))try{await d.fileManager.processFrontMatter(c.file,C=>{A?C[Be]=A:delete C[Be],h.length>0?C[ri]=h:delete C[ri]}),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 Ms(d){return`[[${d.replace(/\.md$/i,"")}]]`}Ut();_e();var Hs=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");at();Fn();var mt=gt.moment;function no(d){let a=d.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),I=r[2]?parseInt(r[2],10):0,f=r[3];f==="pm"&&p<12&&(p+=12),f==="am"&&p===12&&(p=0),p>=0&&p<24&&I>=0&&I<60&&(s=(p*3600+I*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"],A=["sun","mon","tue","wed","thu","fri","sat"],h=c.indexOf(o)>=0?c.indexOf(o):A.indexOf(o);if(h>=0){let p=mt().startOf("day"),f=(p.day()-h+7)%7;return l(p.subtract(f,"days").valueOf())}let g=/^(\d+)\s*([dwmy])$/.exec(o);if(g){let p=parseInt(g[1],10),I={d:"days",w:"weeks",m:"months",y:"years"}[g[2]];return l(mt().subtract(p,I).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 La(d){let a={text:[],filters:{}},t=(d||"").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=no(o);r!=null&&(a.filters.before=r)}else if(n==="after"){let r=no(o);r!=null&&(a.filters.after=r)}else if(n==="on"){let r=no(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 Xt=class d 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!==F?this.notes.push({node:r,title:`${" ".repeat(o)}${this.titleFn(r)}`,body:""}):r?.file&&n===F&&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(F))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(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=La(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(E=>y.toLowerCase().includes(E)),B=y=>{if(!o.has(y)){o.add(y);for(let E of this.tree.getChildren(y))B(E.id)}};for(let y of this.notes)!y.node||y.cross||C(y.title)&&B(y.node.id);let Q=new Map;for(let y of this.notes){if(!y.cross)continue;let E=Q.get(y.cross.folder)??[];E.push(y),Q.set(y.cross.folder,E)}for(let[y,E]of Q){let v=new Map;for(let b of E){let H=b.cross?.parentId??null;if(!H)continue;let U=v.get(H)??[];U.push(b.cross.id),v.set(H,U)}let w=new Set;r.set(y,w);let D=b=>{if(!w.has(b)){w.add(b);for(let H of v.get(b)??[])D(H)}};for(let b of E)C(b.title)&&D(b.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()),A=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 Q=n(B.title.toLowerCase()),y=B.body.split(/\r?\n/),E=[];for(let w=0;w<y.length;w++)c(y[w])&&E.push(w);let v=E.length>0||n(B.body.toLowerCase());if(!Q&&!v)continue;if(E.length===0)C.push(g(B,-1));else{let w=[],D=-100;for(let H of E)H-D>5&&w.push(H),D=H;let b=5;for(let H of w.slice(0,b))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(A),I=[...p];if(this.opts.mode==="search"?e?!0:p.length<10:!!e){let m=u(h);this.opts.mode==="search"&&!e&&(I.length=Math.min(I.length,50)),I.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 Q=B.split("/").pop()??B;return n(`${B.toLowerCase()} ${Q.toLowerCase()}`)})&&I.push(C):I.unshift(C))}if(this.opts.allowCreate&&e&&!I.some(m=>m.label.trim().toLowerCase()===e)&&I.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let m=B=>B.kind==="note"&&(B.id===F||B.crossId===F)&&n(B.label.toLowerCase()),C=I.filter(m);if(C.length>0){let B=I.filter(Q=>!m(Q));I.splice(0,I.length,...C,...B)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&I.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),I}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(` `);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"}),g=u.createSpan({cls:"stashpad-search-excluded-icon"});(0,gt.setIcon)(g,"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=Ua(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 A=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),h=t.crossFolder??this.opts.localFolder??null;if(h||A){let u=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),I=[h?h.split("/").pop()||h:"",A].filter(m=>m&&m.length>0).join(" \u203A ");I&&u.setText(I)}let p=s?this.createdMsFor(s):null;if(p!=null||l){let u=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let g=u.createDiv({cls:"stashpad-suggest-time"});g.setText(this.formatRelativeTime(p)),g.title=mt(p).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 A=0;for(;(A=n.indexOf(c,A))!==-1;)o.push([A,A+c.length]),A+=c.length}if(!o.length){t.appendText(e);return}o.sort((c,A)=>c[0]-A[0]);let r=[];for(let c of o){let A=r[r.length-1];A&&c[0]<=A[1]?A[1]=Math.max(A[1],c[1]):r.push([c[0],c[1]])}let l=0;for(let[c,A]of r)c>l&&t.appendText(e.slice(l,c)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(c,A)}),l=A;l<e.length&&t.appendText(e.slice(l))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===F)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==F&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==F?this.tree.get(s.parent):void 0;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let l of this.notes){if(!l.cross)continue;let 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===F)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!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 A=t.selectionStart??t.value.length,h=t.selectionEnd??A,p=t.value.slice(0,A),u=t.value.slice(A,h),g=t.value.slice(h);t.value=`${p}[${u}]${g}`;let I=A+1+u.length;t.setSelectionRange(I,I),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(c.key==="]"){let A=t.selectionStart??-1;A>=0&&t.value[A]==="]"&&(c.preventDefault(),t.setSelectionRange(A+1,A+1));return}if(c.key==="Backspace"&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&t.selectionStart===t.selectionEnd){let A=t.selectionStart??-1;if(A>0&&t.value[A-1]==="["&&t.value[A]==="]"){c.preventDefault();let h=t.value.slice(0,A-1),p=t.value.slice(A+1);t.value=`${h}${p}`,t.setSelectionRange(A-1,A-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 A=document.activeElement;return A?.classList?.contains("stashpad-search-filter-chip")?(c.preventDefault(),A.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 A=this.inputEl;return A&&(A.focus(),A.select()),!1}),r.register([],"Tab",c=>{let A=this.modalEl,h=this.inputEl;if(!A)return!0;let p=Array.from(A.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(I=>!I.hasAttribute("disabled")&&I.tabIndex!==-1&&I.offsetParent!==null);if(p.length===0)return!0;let u=document.activeElement,g=u?p.indexOf(u):-1;if(c.shiftKey){if(g<=0)return c.preventDefault(),p[p.length-1].focus(),!1}else if(g===p.length-1)return c.preventDefault(),(h??p[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 A=s.length+o.length;t.setSelectionRange(A,A)}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 I of o){let m=document.createElement("button");m.type="button",m.className="stashpad-when-tab",m.textContent=I.label,this.whenMode===I.id&&m.addClass("is-active"),m.addEventListener("mousedown",f=>f.preventDefault()),m.addEventListener("click",f=>{if(f.preventDefault(),this.whenMode===I.id)return;let C=this.whenMode;C!=="between"&&I.id==="between"?this.whenBetweenEndText="":C==="between"&&I.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=I.id;for(let B in r)r[B].toggleClass("is-active",B===I.id);g()}),r[I.id]=m,n.appendChild(m)}s.appendChild(n);let l=document.createElement("div");l.className="stashpad-when-body",s.appendChild(l);let c=(I,m,f="single")=>{let C=mt().format("YYYY-MM-DD"),B=!m||m===C;if(f==="betweenStart")return"00:00";if(f==="betweenEnd")return"23:59";switch(I){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"}},A=(I,m)=>{I.addEventListener("keydown",f=>{f.key==="Enter"?(f.preventDefault(),f.stopPropagation(),m()):f.key==="Escape"&&(f.preventDefault(),f.stopPropagation(),this.closeWhenBuilder())})},h=(I,m)=>{let f=I.selectionStart??I.value.length,C=I.selectionEnd??I.value.length,Q=`${f>0&&!/\s$/.test(I.value.slice(0,f))?" ":""}${m}`,y=I.value.slice(0,f)+Q+I.value.slice(C);I.value=y;let E=f+Q.length;I.setSelectionRange(E,E),I.focus(),I.dispatchEvent(new Event("input",{bubbles:!0}))},p=(I,m)=>{let C=I.slice(0,m).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return C?C[1]:null},u=(I,m,f,C)=>{let B=l.createDiv({cls:"stashpad-when-input-wrap has-icons"}),Q=B.createDiv({cls:"stashpad-when-icon-slot"}),y=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,gt.setIcon)(y,"calendar-days");let E=Q.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});E.tabIndex=-1;let v=B.createDiv({cls:"stashpad-when-icon-slot"}),w=v.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});w.type="button",w.title="Pick time",(0,gt.setIcon)(w,"clock");let D=B.createDiv({cls:"stashpad-when-icon-slot"}),b=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});b.type="button",b.title="Pick day",(0,gt.setIcon)(b,"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 x=B.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:I}});x.value=m(),x.addEventListener("input",()=>f(x.value));let S=B.createEl("button",{cls:"stashpad-when-clear"});S.type="button",S.textContent="\xD7",S.title="Clear";for(let $ of[y,w,b,U,S])$.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),K=null,O=Z=>{K=Z},it=!1,lt=Z=>{!L.contains(Z.target)&&Z.target!==$&&!$.contains(Z.target)&&tt()},tt=()=>{if(!it){it=!0,L.remove(),document.removeEventListener("mousedown",lt,!0);try{this.app.keymap?.popScope(z)}catch{}T===tt&&(T=null)}};T=tt,z.register([],"Escape",Z=>(Z.preventDefault(),tt(),!1)),z.register([],"Enter",Z=>(Z.preventDefault(),K&&K(),!1));try{V(L,tt,O)}catch(Z){console.error("[stashpad] popover fill threw:",Z),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 K=this.whenMode==="on",O=(st,Qt)=>{if(!K)return`${st}${Qt}`;let ve={d:"days",w:"weeks",m:"months",y:"years"}[Qt];return mt().subtract(st,ve).format("YYYY-MM-DD")},it=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 st of lt){let Qt=it.createEl("button",{cls:"stashpad-when-pop-chip",text:st.label});Qt.type="button",Qt.addEventListener("mousedown",ve=>ve.preventDefault()),Qt.addEventListener("click",ve=>{ve.preventDefault(),h(x,O(st.n,st.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 Z=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 st of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let Qt=yt.createEl("option",{text:st.label});Qt.value=st.v}let ht=tt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ht.type="button";let Dt=()=>{let st=parseInt(Z.value,10);!Number.isFinite(st)||st<1||(h(x,O(st,yt.value)),L())};ht.addEventListener("mousedown",st=>st.preventDefault()),ht.addEventListener("click",st=>{st.preventDefault(),Dt()}),z(Dt),Z.focus(),Z.select()})});let R=($,V,L,z,K)=>{P(V,(O,it,lt)=>{ns(O,{seedH:L,seedM:z,seedPeriod:K,close:it,setOnEnter:lt,onFinalize:tt=>h($,_o(tt))})})};b.addEventListener("click",$=>{$.preventDefault(),P(D,(V,L,z)=>{let K=V.createDiv({cls:"stashpad-when-pop-row"});for(let Z of["Today","Yesterday"]){let yt=K.createEl("button",{cls:"stashpad-when-pop-chip",text:Z});yt.type="button",yt.addEventListener("mousedown",ht=>ht.preventDefault()),yt.addEventListener("click",ht=>{ht.preventDefault(),h(x,Z),L()})}let O=V.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),it=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],tt=(mt().day()+6)%7;for(let Z=0;Z<it.length;Z++){let yt=it[Z],ht=O.createEl("button",{cls:"stashpad-when-pop-chip",text:yt.slice(0,3)});ht.type="button",ht.title=yt,Z===tt&&ht.addClass("is-today"),ht.addEventListener("mousedown",Dt=>Dt.preventDefault()),ht.addEventListener("click",Dt=>{if(Dt.preventDefault(),C==="betweenEnd"){let st=Z,Qt=mt().startOf("day"),ve=(Qt.day()+6)%7,un=(st-ve+7)%7;un===0&&(un=7);let Lr=Qt.clone().add(un,"days").format("YYYY-MM-DD");h(x,Lr)}else h(x,yt);L()})}})});let X=($,V)=>{$.value||($.value=V);let L=$;if(typeof L.showPicker=="function")try{L.showPicker();return}catch{}$.focus(),$.click()};return y.addEventListener("click",$=>{$.preventDefault(),X(E,mt().format("YYYY-MM-DD"))}),E.addEventListener("change",()=>{E.value&&h(x,E.value)}),w.addEventListener("click",$=>{$.preventDefault();let V=x.selectionStart??x.value.length,L=p(x.value,V),z=c(this.whenMode,L,C),[K,O]=z.split(":"),it=parseInt(K,10),lt=parseInt(O,10),tt=it%12;tt===0&&(tt=12);let Z=it>=12?"pm":"am";R(x,v,tt,lt,Z)}),S.addEventListener("click",$=>{$.preventDefault(),x.value="",f(""),x.focus()}),x},g=()=>{if(l.empty(),this.whenMode==="between"){let I=u("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),m=u("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),f=l.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",y=>y.preventDefault());let B=()=>{let y=I.value.trim(),E=m.value.trim();y&&this.appendFilterToInput(t,"after",y),E&&this.appendFilterToInput(t,"before",E),this.closeWhenBuilder()};C.addEventListener("click",y=>{y.preventDefault(),B()});let Q=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});Q.type="button",Q.addEventListener("mousedown",y=>y.preventDefault()),Q.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),A(I,B),A(m,B),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}else{let I=u("date / day / timeframe",()=>this.whenSingleText,Q=>{this.whenSingleText=Q},"single"),m=l.createDiv({cls:"stashpad-when-actions"}),f=m.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});f.type="button",f.addEventListener("mousedown",Q=>Q.preventDefault());let C=()=>{let Q=I.value.trim();Q&&this.appendFilterToInput(t,this.whenMode,Q),this.closeWhenBuilder()};f.addEventListener("click",Q=>{Q.preventDefault(),C()});let B=m.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});B.type="button",B.addEventListener("mousedown",Q=>Q.preventDefault()),B.addEventListener("click",Q=>{Q.preventDefault(),this.closeWhenBuilder()}),A(I,C),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}};g(),e.parentElement?.insertBefore(s,e.nextSibling),this.whenBuilderEl=s}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}selectSuggestion(t,e){if(t&&t.kind==="search-excluded"){this.loadExcludedNotes();return}super.selectSuggestion(t,e)}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}if(t.kind==="folder-open"&&t.id==="__folder_picker__"){let e=this.opts.folderResults?.()??[];if(!e.length)return;let i=this.inputEl?.value??"",s=!1,n=p=>{s=!0;let u=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${u}\u201D in a new tab`,node:null,kind:"folder-open",folder:p})},o=new io(this.app,e,n),r=o.onClose.bind(o),l=this.tree,c=this.titleFn,A=this.opts,h=this.app;o.onClose=()=>{if(r(),!s){let p=new d(h,l,c,A);p.open(),setTimeout(()=>{let u=p.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)}},io=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 Ra=require("obsidian");at();var Hs=class extends Ra.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:ql(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(a){return this.commands.filter(t=>is(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 ql(d){return d.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||d}kt();var so=require("obsidian");function Jl(d,a){return!a||d.metaKey||d.ctrlKey||d.altKey?!1:d.key.toLowerCase()===a.toLowerCase()}function ci(d,a){return a?a.includes("+")?Kl(d,a):Jl(d,a):!1}function G(d,a){if(!a)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=a;return t&&e?s?ci(d,t)||ci(d,e):i?ci(d,e):ci(d,t):ci(d,t)||ci(d,e)}function Ji(d){if(!d)return"";let a=so.Platform.isMacOS;return d.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 Kl(d,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"),A=so.Platform.isMacOS?d.metaKey:d.ctrlKey;return s&&!A||n&&!d.ctrlKey||o&&!d.metaKey||r!==d.altKey||l!==d.shiftKey||!s&&(!n&&d.ctrlKey||!o&&d.metaKey)?!1:d.key.toLowerCase()===e}var Ge=require("obsidian");kt();var xt=class xt{constructor(a){this.host=a;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let a of this.contribTimers.values())clearTimeout(a);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let a=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!a||!t)return null;let e=a.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=a.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:a,id:t}}claimSelectedAsAuthor(){this.claimAuthorship({scope:"selection",contributorMode:!1})}claimFolderAsAuthor(){this.claimAuthorship({scope:"folder",contributorMode:!1})}claimSelectedWithContributor(){this.claimAuthorship({scope:"selection",contributorMode:!0})}claimFolderWithContributor(){this.claimAuthorship({scope:"folder",contributorMode:!0})}fileBackedNotesInFolder(){let a=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==a&&!e.startsWith(a+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(a,t){for(let s=0;s<a.length;s++){let n=this.host.app.vault.getAbstractFileByPath(a[s]);if(n instanceof Ge.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,a[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",a[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(a){let t=this.currentAuthorLink();if(!t){new Ge.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=a.scope==="selection"?this.host.getActionTargets().map(p=>p.file).filter(p=>!!p):this.fileBackedNotesInFolder();if(i.length===0){new Ge.Notice(a.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let u=this.host.app.metadataCache.getFileCache(p)?.frontmatter,g=typeof u?.author=="string"?u.author:"";if(!g.trim()){s.push(p.path);continue}if(g.includes(e)||!a.contributorMode)continue;(Array.isArray(u?.contributors)?u.contributors.filter(m=>typeof m=="string"):[]).some(m=>m.includes(e))||n.push(p.path)}let o=s.length+n.length;if(o===0){new Ge.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(a.scope==="folder"){let p=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&p.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(g=>{new nt(this.host.app,"Claim authorship",`${p.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",g).open()}))return}let r=this.host.noteFolder,l=t.link,c=new Set,A=async()=>{await this.pacedFrontmatter(s,(p,u)=>{typeof p.author=="string"&&p.author.trim()||(p.author=l),Array.isArray(p.contributors)&&p.contributors.some(g=>typeof g=="string"&&g.includes(e))&&(p.contributors=p.contributors.filter(g=>!(typeof g=="string"&&g.includes(e))),c.add(u))}),await this.pacedFrontmatter(n,p=>{let u=Array.isArray(p.contributors)?p.contributors.filter(g=>typeof g=="string"):[];u.some(g=>g.includes(e))||u.push(l),p.contributors=u})};this.ensureAuthorFile(t),await A(),this.host.plugin.getUndoStack(r).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(p,u)=>{if(typeof p.author=="string"&&p.author.includes(e)&&delete p.author,c.has(u)){let g=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];g.some(I=>I.includes(e))||g.push(l),p.contributors=g}}),await this.pacedFrontmatter(n,p=>{Array.isArray(p.contributors)&&(p.contributors=p.contributors.filter(u=>!(typeof u=="string"&&u.includes(e))))}),this.host.debouncedRender()},redo:async()=>{c.clear(),await A(),this.host.debouncedRender()}});let h=[];s.length&&h.push(`authored ${s.length}`),n.length&&h.push(`contributing to ${n.length}`),new Ge.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=xt.EXTERNAL_WRITE_GRACE_MS*20,e=xt.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<xt.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=xt.CONTRIB_DEBOUNCE_MS+(e?xt.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<xt.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(p=>typeof p=="string"):[],c=`-${s.id}`,A=r.includes(c),h=l.some(p=>p.includes(c));!A&&!h&&l.push(s.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};xt.CONTRIB_DEBOUNCE_MS=4e3,xt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,xt.EXTERNAL_WRITE_GRACE_MS=1500,xt.EXTERNAL_QUIESCENCE_MS=5e3;var Us=xt;var Rs=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,A="before";r&&r.classList.contains("stashpad-note")?(c=r.dataset.id,A="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,A="after"),c&&this.host.reorderToTarget(o,c,A)}),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 Ga=require("obsidian");var Gs=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 Ft.record("render.row.cacheHit",0),t;let e=await Ft.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 Ft.timeAsync("render.row.markdown",()=>Ga.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=La(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 A=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),h=t.crossFolder??this.opts.localFolder??null;if(h||A){let u=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),I=[h?h.split("/").pop()||h:"",A].filter(f=>f&&f.length>0).join(" \u203A ");I&&u.setText(I)}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 A=0;for(;(A=n.indexOf(c,A))!==-1;)o.push([A,A+c.length]),A+=c.length}if(!o.length){t.appendText(e);return}o.sort((c,A)=>c[0]-A[0]);let r=[];for(let c of o){let A=r[r.length-1];A&&c[0]<=A[1]?A[1]=Math.max(A[1],c[1]):r.push([c[0],c[1]])}let l=0;for(let[c,A]of r)c>l&&t.appendText(e.slice(l,c)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(c,A)}),l=A;l<e.length&&t.appendText(e.slice(l))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===F)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==F&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==F?this.tree.get(s.parent):void 0;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let l of this.notes){if(!l.cross)continue;let 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===F)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!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 A=t.selectionStart??t.value.length,h=t.selectionEnd??A,g=t.value.slice(0,A),u=t.value.slice(A,h),p=t.value.slice(h);t.value=`${g}[${u}]${p}`;let I=A+1+u.length;t.setSelectionRange(I,I),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(c.key==="]"){let A=t.selectionStart??-1;A>=0&&t.value[A]==="]"&&(c.preventDefault(),t.setSelectionRange(A+1,A+1));return}if(c.key==="Backspace"&&!c.metaKey&&!c.ctrlKey&&!c.altKey&&t.selectionStart===t.selectionEnd){let A=t.selectionStart??-1;if(A>0&&t.value[A-1]==="["&&t.value[A]==="]"){c.preventDefault();let h=t.value.slice(0,A-1),g=t.value.slice(A+1);t.value=`${h}${g}`,t.setSelectionRange(A-1,A-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 A=document.activeElement;return A?.classList?.contains("stashpad-search-filter-chip")?(c.preventDefault(),A.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 A=this.inputEl;return A&&(A.focus(),A.select()),!1}),r.register([],"Tab",c=>{let A=this.modalEl,h=this.inputEl;if(!A)return!0;let g=Array.from(A.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(I=>!I.hasAttribute("disabled")&&I.tabIndex!==-1&&I.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 A=s.length+o.length;t.setSelectionRange(A,A)}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 I of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=I.label,this.whenMode===I.id&&f.addClass("is-active"),f.addEventListener("mousedown",m=>m.preventDefault()),f.addEventListener("click",m=>{if(m.preventDefault(),this.whenMode===I.id)return;let C=this.whenMode;C!=="between"&&I.id==="between"?this.whenBetweenEndText="":C==="between"&&I.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=I.id;for(let B in r)r[B].toggleClass("is-active",B===I.id);p()}),r[I.id]=f,n.appendChild(f)}s.appendChild(n);let l=document.createElement("div");l.className="stashpad-when-body",s.appendChild(l);let c=(I,f,m="single")=>{let C=mt().format("YYYY-MM-DD"),B=!f||f===C;if(m==="betweenStart")return"00:00";if(m==="betweenEnd")return"23:59";switch(I){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"}},A=(I,f)=>{I.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.stopPropagation(),f()):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),this.closeWhenBuilder())})},h=(I,f)=>{let m=I.selectionStart??I.value.length,C=I.selectionEnd??I.value.length,Q=`${m>0&&!/\s$/.test(I.value.slice(0,m))?" ":""}${f}`,y=I.value.slice(0,m)+Q+I.value.slice(C);I.value=y;let E=m+Q.length;I.setSelectionRange(E,E),I.focus(),I.dispatchEvent(new Event("input",{bubbles:!0}))},g=(I,f)=>{let C=I.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return C?C[1]:null},u=(I,f,m,C)=>{let B=l.createDiv({cls:"stashpad-when-input-wrap has-icons"}),Q=B.createDiv({cls:"stashpad-when-icon-slot"}),y=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,gt.setIcon)(y,"calendar-days");let E=Q.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});E.tabIndex=-1;let v=B.createDiv({cls:"stashpad-when-icon-slot"}),w=v.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});w.type="button",w.title="Pick time",(0,gt.setIcon)(w,"clock");let D=B.createDiv({cls:"stashpad-when-icon-slot"}),b=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});b.type="button",b.title="Pick day",(0,gt.setIcon)(b,"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 x=B.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:I}});x.value=f(),x.addEventListener("input",()=>m(x.value));let S=B.createEl("button",{cls:"stashpad-when-clear"});S.type="button",S.textContent="\xD7",S.title="Clear";for(let $ of[y,w,b,U,S])$.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),K=null,O=Z=>{K=Z},it=!1,lt=Z=>{!L.contains(Z.target)&&Z.target!==$&&!$.contains(Z.target)&&tt()},tt=()=>{if(!it){it=!0,L.remove(),document.removeEventListener("mousedown",lt,!0);try{this.app.keymap?.popScope(z)}catch{}T===tt&&(T=null)}};T=tt,z.register([],"Escape",Z=>(Z.preventDefault(),tt(),!1)),z.register([],"Enter",Z=>(Z.preventDefault(),K&&K(),!1));try{V(L,tt,O)}catch(Z){console.error("[stashpad] popover fill threw:",Z),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 K=this.whenMode==="on",O=(st,Qt)=>{if(!K)return`${st}${Qt}`;let ve={d:"days",w:"weeks",m:"months",y:"years"}[Qt];return mt().subtract(st,ve).format("YYYY-MM-DD")},it=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 st of lt){let Qt=it.createEl("button",{cls:"stashpad-when-pop-chip",text:st.label});Qt.type="button",Qt.addEventListener("mousedown",ve=>ve.preventDefault()),Qt.addEventListener("click",ve=>{ve.preventDefault(),h(x,O(st.n,st.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 Z=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 st of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let Qt=yt.createEl("option",{text:st.label});Qt.value=st.v}let ht=tt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ht.type="button";let bt=()=>{let st=parseInt(Z.value,10);!Number.isFinite(st)||st<1||(h(x,O(st,yt.value)),L())};ht.addEventListener("mousedown",st=>st.preventDefault()),ht.addEventListener("click",st=>{st.preventDefault(),bt()}),z(bt),Z.focus(),Z.select()})});let R=($,V,L,z,K)=>{P(V,(O,it,lt)=>{os(O,{seedH:L,seedM:z,seedPeriod:K,close:it,setOnEnter:lt,onFinalize:tt=>h($,ia(tt))})})};b.addEventListener("click",$=>{$.preventDefault(),P(D,(V,L,z)=>{let K=V.createDiv({cls:"stashpad-when-pop-row"});for(let Z of["Today","Yesterday"]){let yt=K.createEl("button",{cls:"stashpad-when-pop-chip",text:Z});yt.type="button",yt.addEventListener("mousedown",ht=>ht.preventDefault()),yt.addEventListener("click",ht=>{ht.preventDefault(),h(x,Z),L()})}let O=V.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),it=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],tt=(mt().day()+6)%7;for(let Z=0;Z<it.length;Z++){let yt=it[Z],ht=O.createEl("button",{cls:"stashpad-when-pop-chip",text:yt.slice(0,3)});ht.type="button",ht.title=yt,Z===tt&&ht.addClass("is-today"),ht.addEventListener("mousedown",bt=>bt.preventDefault()),ht.addEventListener("click",bt=>{if(bt.preventDefault(),C==="betweenEnd"){let st=Z,Qt=mt().startOf("day"),ve=(Qt.day()+6)%7,mn=(st-ve+7)%7;mn===0&&(mn=7);let Yr=Qt.clone().add(mn,"days").format("YYYY-MM-DD");h(x,Yr)}else h(x,yt);L()})}})});let X=($,V)=>{$.value||($.value=V);let L=$;if(typeof L.showPicker=="function")try{L.showPicker();return}catch{}$.focus(),$.click()};return y.addEventListener("click",$=>{$.preventDefault(),X(E,mt().format("YYYY-MM-DD"))}),E.addEventListener("change",()=>{E.value&&h(x,E.value)}),w.addEventListener("click",$=>{$.preventDefault();let V=x.selectionStart??x.value.length,L=g(x.value,V),z=c(this.whenMode,L,C),[K,O]=z.split(":"),it=parseInt(K,10),lt=parseInt(O,10),tt=it%12;tt===0&&(tt=12);let Z=it>=12?"pm":"am";R(x,v,tt,lt,Z)}),S.addEventListener("click",$=>{$.preventDefault(),x.value="",m(""),x.focus()}),x},p=()=>{if(l.empty(),this.whenMode==="between"){let I=u("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=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=I.value.trim(),E=f.value.trim();y&&this.appendFilterToInput(t,"after",y),E&&this.appendFilterToInput(t,"before",E),this.closeWhenBuilder()};C.addEventListener("click",y=>{y.preventDefault(),B()});let Q=m.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});Q.type="button",Q.addEventListener("mousedown",y=>y.preventDefault()),Q.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),A(I,B),A(f,B),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}else{let I=u("date / day / timeframe",()=>this.whenSingleText,Q=>{this.whenSingleText=Q},"single"),f=l.createDiv({cls:"stashpad-when-actions"}),m=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",Q=>Q.preventDefault());let C=()=>{let Q=I.value.trim();Q&&this.appendFilterToInput(t,this.whenMode,Q),this.closeWhenBuilder()};m.addEventListener("click",Q=>{Q.preventDefault(),C()});let B=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});B.type="button",B.addEventListener("mousedown",Q=>Q.preventDefault()),B.addEventListener("click",Q=>{Q.preventDefault(),this.closeWhenBuilder()}),A(I,C),I.focus(),I.setSelectionRange(I.value.length,I.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 oo(this.app,e,n),r=o.onClose.bind(o),l=this.tree,c=this.titleFn,A=this.opts,h=this.app;o.onClose=()=>{if(r(),!s){let g=new d(h,l,c,A);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)}},oo=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 qa=require("obsidian");at();var Us=class extends qa.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:$l(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(a){return this.commands.filter(t=>ss(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 $l(d){return d.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||d}kt();var ao=require("obsidian");function Vl(d,a){return!a||d.metaKey||d.ctrlKey||d.altKey?!1:d.key.toLowerCase()===a.toLowerCase()}function ci(d,a){return a?a.includes("+")?zl(d,a):Vl(d,a):!1}function G(d,a){if(!a)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=a;return t&&e?s?ci(d,t)||ci(d,e):i?ci(d,e):ci(d,t):ci(d,t)||ci(d,e)}function Ki(d){if(!d)return"";let a=ao.Platform.isMacOS;return d.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 zl(d,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"),A=ao.Platform.isMacOS?d.metaKey:d.ctrlKey;return s&&!A||n&&!d.ctrlKey||o&&!d.metaKey||r!==d.altKey||l!==d.shiftKey||!s&&(!n&&d.ctrlKey||!o&&d.metaKey)?!1:d.key.toLowerCase()===e}var Le=require("obsidian");kt();var xt=class xt{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(f=>typeof f=="string"):[]).some(f=>f.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 nt(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,A=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 A(),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(I=>typeof I=="string"):[];p.some(I=>I.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 A(),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=xt.EXTERNAL_WRITE_GRACE_MS*20,e=xt.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<xt.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=xt.CONTRIB_DEBOUNCE_MS+(e?xt.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<xt.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}`,A=r.includes(c),h=l.some(g=>g.includes(c));!A&&!h&&l.push(s.link),o.contributors=l})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};xt.CONTRIB_DEBOUNCE_MS=4e3,xt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,xt.EXTERNAL_WRITE_GRACE_MS=1500,xt.EXTERNAL_QUIESCENCE_MS=5e3;var Rs=xt;var Gs=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,A="before";r&&r.classList.contains("stashpad-note")?(c=r.dataset.id,A="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,A="after"),c&&this.host.reorderToTarget(o,c,A)}),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 Ja=require("obsidian");var Ls=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 Ft.record("render.row.cacheHit",0),t;let e=await Ft.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 Ft.timeAsync("render.row.markdown",()=>Ja.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,` -`).trim(),attachments:t}}};function qa(d,a,t){return d.tree.getChildren(a).slice().sort((i,s)=>Ol(d,i,s,t)).map(i=>i.id)}function Ol(d,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=La(d,a)||a.created||"",s=La(d,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=d.titleForNode(a),s=d.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 La(d,a){if(!a.file)return"";let t=d.app.metadataCache.getFileCache(a.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Ai=require("obsidian");yi();async function no(d){let a=d.getActionTargets();if(!a.length)return;let t=j().prefixTimestampsOnCopy,e=[];for(let i of a){if(!i.file)continue;let s=await d.app.vault.cachedRead(i.file),n=d.stripFrontmatter(s).trim();e.push(t?`${d.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function Oa(d,a,t){return d.tree.getChildren(a).slice().sort((i,s)=>Wl(d,i,s,t)).map(i=>i.id)}function Wl(d,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=Ka(d,a)||a.created||"",s=Ka(d,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=d.titleForNode(a),s=d.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 Ka(d,a){if(!a.file)return"";let t=d.app.metadataCache.getFileCache(a.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Ai=require("obsidian");Qi();async function ro(d){let a=d.getActionTargets();if(!a.length)return;let t=j().prefixTimestampsOnCopy,e=[];for(let i of a){if(!i.file)continue;let s=await d.app.vault.cachedRead(i.file),n=d.stripFrontmatter(s).trim();e.push(t?`${d.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` -`)),d.plugin.notifications.show({message:`Copied ${d.titleList(a)} to clipboard`,kind:"success",category:"system",affectedIds:a.map(i=>i.id),folder:d.noteFolder})}async function Ja(d){let a=d.getActionTargets();if(!a.length||!a[0].file){new Ai.Notice("Nothing to copy from.");return}let t=a[0],e=await d.app.vault.cachedRead(t.file),i=d.stripFrontmatter(e),s=Wo(i);if(s.length===0){d.plugin.notifications.show({message:`No codeblock found in "${d.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:d.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),d.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${d.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:d.noteFolder});return}let n=s.map((r,l)=>({kind:"one",idx:l,label:`${l+1}. ${r.lang||"(no language)"} \u2014 ${r.code.split(` +`)),d.plugin.notifications.show({message:`Copied ${d.titleList(a)} to clipboard`,kind:"success",category:"system",affectedIds:a.map(i=>i.id),folder:d.noteFolder})}async function Ya(d){let a=d.getActionTargets();if(!a.length||!a[0].file){new Ai.Notice("Nothing to copy from.");return}let t=a[0],e=await d.app.vault.cachedRead(t.file),i=d.stripFrontmatter(e),s=jo(i);if(s.length===0){d.plugin.notifications.show({message:`No codeblock found in "${d.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:d.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),d.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${d.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:d.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(A=>{let h=A.label.toLowerCase();return c.every(p=>h.includes(p))})}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(` +`)?"\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(A=>{let h=A.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(` -`):s[r.idx].code;await navigator.clipboard.writeText(l),d.plugin.notifications.show({message:r.kind==="all"?`Copied all ${s.length} codeblocks from "${d.titleForNode(t)}".`:`Copied codeblock${s[r.idx].lang?` (${s[r.idx].lang})`:""} from "${d.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:d.noteFolder})}}(d.app);o.setPlaceholder(`${s.length} codeblocks in "${d.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function Ka(d){let a=d.getActionTargets();if(a.length===0){let n=d.tree.get(d.focusId);n?.file&&(a=[n])}if(a.length===0){new Ai.Notice("Nothing to copy.");return}let t=j().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let r=await d.app.vault.cachedRead(n.file),l=d.stripFrontmatter(r).trim().split(/\r?\n/).join(" "),c=t?`${d.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${c}${l}`)}for(let r of d.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),d.plugin.clearNoteClipboard(),d.plugin.noteClipboard={mode:"copy",folder:d.noteFolder,ids:a.map(n=>n.id),text:s},d.render(),d.plugin.notifications.show({message:`Copied tree of ${d.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:d.noteFolder})}async function Oa(d){let a=d.getActionTargets();if(a.length===0){let i=d.tree.get(d.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 d.tree.getChildren(i.id))e(o,s+1)};for(let i of a)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),d.plugin.notifications.show({message:`Copied outline of ${d.titleList(a)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:a.map(i=>i.id),folder:d.noteFolder})}var Bt=require("obsidian");at();var Ys=require("obsidian");Os();Ut();at();var _t="stash",Ar=1;function lr(d){let t=(d.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var Co=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Qe(d,a){let t=[],e=pc([...a.rootNotes,...a.allDescendants]),i=new Map,s=[];for(let o of e){let r=await d.vault.read(o.file),l=r,c=dr(r);for(let A of c){let h=d.metadataCache.getFirstLinkpathDest(A,o.file.path);if(!h){s.push(`Missing attachment "${A}" in ${o.file.path}`);continue}let p=h.name;i.has(p)||i.set(p,await d.vault.readBinary(h)),l=gc(l,A,p)}l=fc(l,d,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:Ar,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(` -`)}),Vi(t,6)}async function te(d,a,t,e,i={}){let s=await zi(a),n=s["manifest.json"];if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(Ks(n));if(typeof o.stashSchema!="number"||o.stashSchema>Ar)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await cr(d,t);let r=Object.entries(s).filter(([E])=>E.startsWith("notes/")&&E.endsWith(".md")),l=[];for(let[E,v]of r){let w=Ks(v),{fm:D,body:b}=dt(w),H=lr(E.slice(6))||`${D.id||"imported-"+W(4)}.md`;l.push({originalName:H,fm:D,body:b})}let c=new Map,A=0;for(let E of l){let v=E.fm.id;v&&(i.forceNewIds?c.set(v,W(6)):e.has(v)||c.has(v)?(c.set(v,`${v}-${W(4)}-Imported`),A++):c.set(v,v))}let h=new Date().toISOString(),p=[],u=`${t}/_attachments`,g=0,I=Object.entries(s).filter(([E])=>E.startsWith("attachments/")),m=new Map,f=null;if(i.dedupeExisting){f=new Map;for(let E of d.vault.getFiles())f.has(E.name)||f.set(E.name,E.path)}let C=(E,v)=>{if(E.length!==v.length)return!1;for(let w=0;w<E.length;w++)if(E[w]!==v[w])return!1;return!0},B=!1;for(let[E,v]of I){let w=lr(E.slice(12));if(!w)continue;let D=v,b=[],H=f?.get(w);H&&b.push(H);let U=`${u}/${w}`;await d.vault.adapter.exists(U)&&b.push(U);let x=null;for(let T of b)try{if(C(new Uint8Array(await d.vault.adapter.readBinary(T)),D)){x=T;break}}catch{}if(x){m.set(w,x);continue}let S=U;for(let T=1;await d.vault.adapter.exists(S);T++)S=`${u}/${uc(w,T)}`;m.set(w,S),B||(await cr(d,u),B=!0),await d.vault.createBinary(S,D.buffer),g++}let Q=0;for(let E of l){let v=E.fm.id;if(!v){p.push(`Skipped ${E.originalName} \u2014 no id in frontmatter`);continue}let w=c.get(v),D=E.fm.parent??null,b=D;!D||D===F?b=i.reparentRootsTo??D??F:c.has(D)?b=c.get(D):b=e.has(D)?D:i.reparentRootsTo??F;let H=Ic(E.body,m,u),U={...E.fm,id:w,parent:b,import_date:h};Array.isArray(U.attachments)&&(U.attachments=U.attachments.map(P=>{let R=hr(Se(P));return Yt(m.get(R)??`${u}/${R}`)}));let x=Ee(U,H),S=w===v?E.originalName:Cc(E.originalName,v,w),T=`${t}/${S}`;await d.vault.adapter.exists(T)&&(S=`${S.replace(/\.md$/,"")}-${W(4)}.md`,T=`${t}/${S}`),await d.vault.create(T,x),Q++}let y;if(o.colorAliases&&typeof o.colorAliases=="object"){let E={};for(let[v,w]of Object.entries(o.colorAliases)){let D=String(v).trim().toLowerCase(),b=String(w??"").trim();/^#([0-9a-f]{6})$/.test(D)&&b&&(E[D]=b.slice(0,60))}Object.keys(E).length&&(y=E)}return{notesWritten:Q,attachmentsWritten:g,collisionsRenamed:A,warnings:p,colorAliases:y,idRemap:Object.fromEntries(c)}}function pc(d){let a=new Set,t=[];for(let e of d)a.has(e.id)||(a.add(e.id),t.push(e));return t}function dr(d){let a=new Set,t;for(Co.lastIndex=0;(t=Co.exec(d))!==null;)a.add(t[1]);return[...a]}async function $s(d,a){let t=await d.vault.read(a),e=[],i=new Set;for(let s of dr(t)){let n=d.metadataCache.getFirstLinkpathDest(s,a.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function gc(d,a,t){return d.replace(new RegExp(`!\\[\\[${mc(a)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function uc(d,a){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${a}${d.slice(t)}`:`${d}-${a}`}function Ic(d,a,t){return d.replace(Co,(e,i,s)=>{if(i.includes("/"))return e;let n=a.get(i)??`${t}/${i}`;return e.replace(i,n)})}function fc(d,a,t){let e=dt(d);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return d;let i=e.fm.attachments.map(n=>{let o=a.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:hr(n)}),s={...e.fm,attachments:i};return Ee(s,e.body)}function mc(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function hr(d){let a=d.lastIndexOf("/");return a<0?d:d.slice(a+1)}function Cc(d,a,t){return d.includes(a)?d.replace(a,t):d.replace(/\.md$/,`-${t}.md`)}function dt(d){if(!d.startsWith("---"))return{fm:{},body:d};let a=d.indexOf(` ----`,3);if(a<0)return{fm:{},body:d};let t=d.slice(3,a).replace(/^\n/,""),e=d.slice(a+4),i={};try{i=(0,Ys.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` +`):s[r.idx].code;await navigator.clipboard.writeText(l),d.plugin.notifications.show({message:r.kind==="all"?`Copied all ${s.length} codeblocks from "${d.titleForNode(t)}".`:`Copied codeblock${s[r.idx].lang?` (${s[r.idx].lang})`:""} from "${d.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:d.noteFolder})}}(d.app);o.setPlaceholder(`${s.length} codeblocks in "${d.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function $a(d){let a=d.getActionTargets();if(a.length===0){let n=d.tree.get(d.focusId);n?.file&&(a=[n])}if(a.length===0){new Ai.Notice("Nothing to copy.");return}let t=j().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let r=await d.app.vault.cachedRead(n.file),l=d.stripFrontmatter(r).trim().split(/\r?\n/).join(" "),c=t?`${d.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${c}${l}`)}for(let r of d.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),d.plugin.clearNoteClipboard(),d.plugin.noteClipboard={mode:"copy",folder:d.noteFolder,ids:a.map(n=>n.id),text:s},d.render(),d.plugin.notifications.show({message:`Copied tree of ${d.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:d.noteFolder})}async function Va(d){let a=d.getActionTargets();if(a.length===0){let i=d.tree.get(d.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 d.tree.getChildren(i.id))e(o,s+1)};for(let i of a)e(i,0);await navigator.clipboard.writeText(t.join(` +`)),d.plugin.notifications.show({message:`Copied outline of ${d.titleList(a)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:a.map(i=>i.id),folder:d.noteFolder})}var Bt=require("obsidian");at();var $s=require("obsidian");Ys();Ut();at();var _t="stash",pr=1;function dr(d){let t=(d.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var Qo=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Qe(d,a){let t=[],e=mc([...a.rootNotes,...a.allDescendants]),i=new Map,s=[];for(let o of e){let r=await d.vault.read(o.file),l=r,c=gr(r);for(let A of c){let h=d.metadataCache.getFirstLinkpathDest(A,o.file.path);if(!h){s.push(`Missing attachment "${A}" in ${o.file.path}`);continue}let g=h.name;i.has(g)||i.set(g,await d.vault.readBinary(h)),l=Cc(l,A,g)}l=Qc(l,d,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:pr,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(` +`)}),zi(t,6)}async function te(d,a,t,e,i={}){let s=await Wi(a),n=s["manifest.json"];if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(Os(n));if(typeof o.stashSchema!="number"||o.stashSchema>pr)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await hr(d,t);let r=Object.entries(s).filter(([E])=>E.startsWith("notes/")&&E.endsWith(".md")),l=[];for(let[E,v]of r){let w=Os(v),{fm:D,body:b}=dt(w),H=dr(E.slice(6))||`${D.id||"imported-"+W(4)}.md`;l.push({originalName:H,fm:D,body:b})}let c=new Map,A=0;for(let E of l){let v=E.fm.id;v&&(i.forceNewIds?c.set(v,W(6)):e.has(v)||c.has(v)?(c.set(v,`${v}-${W(4)}-Imported`),A++):c.set(v,v))}let h=new Date().toISOString(),g=[],u=`${t}/_attachments`,p=0,I=Object.entries(s).filter(([E])=>E.startsWith("attachments/")),f=new Map,m=null;if(i.dedupeExisting){m=new Map;for(let E of d.vault.getFiles())m.has(E.name)||m.set(E.name,E.path)}let C=(E,v)=>{if(E.length!==v.length)return!1;for(let w=0;w<E.length;w++)if(E[w]!==v[w])return!1;return!0},B=!1;for(let[E,v]of I){let w=dr(E.slice(12));if(!w)continue;let D=v,b=[],H=m?.get(w);H&&b.push(H);let U=`${u}/${w}`;await d.vault.adapter.exists(U)&&b.push(U);let x=null;for(let T of b)try{if(C(new Uint8Array(await d.vault.adapter.readBinary(T)),D)){x=T;break}}catch{}if(x){f.set(w,x);continue}let S=U;for(let T=1;await d.vault.adapter.exists(S);T++)S=`${u}/${Bc(w,T)}`;f.set(w,S),B||(await hr(d,u),B=!0),await d.vault.createBinary(S,D.buffer),p++}let Q=0;for(let E of l){let v=E.fm.id;if(!v){g.push(`Skipped ${E.originalName} \u2014 no id in frontmatter`);continue}let w=c.get(v),D=E.fm.parent??null,b=D;!D||D===F?b=i.reparentRootsTo??D??F:c.has(D)?b=c.get(D):b=e.has(D)?D:i.reparentRootsTo??F;let H=yc(E.body,f,u),U={...E.fm,id:w,parent:b,import_date:h};Array.isArray(U.attachments)&&(U.attachments=U.attachments.map(P=>{let R=ur(Se(P));return Yt(f.get(R)??`${u}/${R}`)}));let x=Ee(U,H),S=w===v?E.originalName:wc(E.originalName,v,w),T=`${t}/${S}`;await d.vault.adapter.exists(T)&&(S=`${S.replace(/\.md$/,"")}-${W(4)}.md`,T=`${t}/${S}`),await d.vault.create(T,x),Q++}let y;if(o.colorAliases&&typeof o.colorAliases=="object"){let E={};for(let[v,w]of Object.entries(o.colorAliases)){let D=String(v).trim().toLowerCase(),b=String(w??"").trim();/^#([0-9a-f]{6})$/.test(D)&&b&&(E[D]=b.slice(0,60))}Object.keys(E).length&&(y=E)}return{notesWritten:Q,attachmentsWritten:p,collisionsRenamed:A,warnings:g,colorAliases:y,idRemap:Object.fromEntries(c)}}function mc(d){let a=new Set,t=[];for(let e of d)a.has(e.id)||(a.add(e.id),t.push(e));return t}function gr(d){let a=new Set,t;for(Qo.lastIndex=0;(t=Qo.exec(d))!==null;)a.add(t[1]);return[...a]}async function Vs(d,a){let t=await d.vault.read(a),e=[],i=new Set;for(let s of gr(t)){let n=d.metadataCache.getFirstLinkpathDest(s,a.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Cc(d,a,t){return d.replace(new RegExp(`!\\[\\[${Ec(a)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function Bc(d,a){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${a}${d.slice(t)}`:`${d}-${a}`}function yc(d,a,t){return d.replace(Qo,(e,i,s)=>{if(i.includes("/"))return e;let n=a.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Qc(d,a,t){let e=dt(d);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return d;let i=e.fm.attachments.map(n=>{let o=a.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:ur(n)}),s={...e.fm,attachments:i};return Ee(s,e.body)}function Ec(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ur(d){let a=d.lastIndexOf("/");return a<0?d:d.slice(a+1)}function wc(d,a,t){return d.includes(a)?d.replace(a,t):d.replace(/\.md$/,`-${t}.md`)}function dt(d){if(!d.startsWith("---"))return{fm:{},body:d};let a=d.indexOf(` +---`,3);if(a<0)return{fm:{},body:d};let t=d.slice(3,a).replace(/^\n/,""),e=d.slice(a+4),i={};try{i=(0,$s.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` `)?e.slice(1):e;return{fm:i,body:s}}function Ee(d,a){return`--- -${(0,Ys.stringifyYaml)(d).trimEnd()} +${(0,$s.stringifyYaml)(d).trimEnd()} --- -${a}`}async function cr(d,a){if(!(!a||await d.vault.adapter.exists(a)))try{await d.vault.createFolder(a)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}os();kt();Os();var de="stashenc",Bc="stashmeta";function he(d){return d.replace(/\.stashenc$/,`.${Bc}`)}async function zs(d,a){try{return JSON.parse(await d.vault.adapter.read(he(a)))}catch{return null}}async function we(d,a,t){let e=a.replace(/\/+$/,""),i=[];for(let c of d.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let A;try{A=dt(await d.vault.read(c)).fm}catch{continue}typeof A.id=="string"&&i.push({id:A.id,file:c,parent:typeof A.parent=="string"?A.parent:null,created:typeof A.created=="string"?A.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 A=n.get(c.parent)??[];A.push(c),n.set(c.parent,A)}let o=[],r=new Set([t]),l=[t];for(;l.length;){let c=[];for(let A of l)for(let h of n.get(A)??[])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 Bo(d){if(!d)return null;let a=d.replace(/\/+$/,"");return!a||a.startsWith("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a)||a.split("/").some(t=>t===".."||t===".")?null:a}async function Wi(d,a,t){await d.vault.adapter.writeBinary(a,t);let e;try{e=new Uint8Array(await d.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 d.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 Vs(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function di(d){return(d.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function pr(d,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 $s(d,r.file))i.set(l.path,l);let s=new Set,n=d.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 d.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 d.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 d.vault.delete(l)}catch(c){console.warn("[Stashpad] couldn't delete exclusive attachment",r,c),o.push(r)}return{unpurged:o}}async function gr(d,a,t,e,i=null,s=!1,n){let o=await we(d,a,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:r,descendants:l,parentId:c}=o,A=[r,...l],h=new Map;for(let y of A)try{let E=await d.vault.adapter.stat(y.file.path);E&&h.set(y.file.path,E.mtime)}catch{}let p=await Qe(d,{rootNotes:[{id:r.id,file:r.file}],allDescendants:l.map(y=>({id:y.id,file:y.file})),sourceFolder:a}),u=await ii(p,e),g=await Nt(u,e);if(g.length!==p.length)throw new Error("Encryption self-check failed (size mismatch).");for(let y=0;y<p.length;y++)if(g[y]!==p[y])throw new Error("Encryption self-check failed (content mismatch).");let I=(n??a).replace(/\/+$/,"");n&&!await d.vault.adapter.exists(I)&&await d.vault.adapter.mkdir(I);let m=di(s?t:Vs(r.file)),f=`${I}/${m}.${de}`;for(let y=1;await d.vault.adapter.exists(f);y++)f=`${I}/${m} (${y}).${de}`;await Wi(d,f,u);let C=A,B={v:1,parentId:c,title:s?"":Vs(r.file),count:C.length,created:r.created,rootId:t,prevSibling:i};try{await d.vault.adapter.write(he(f),JSON.stringify(B))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:Q}=await pr(d,C,h);return{blobPath:f,noteCount:C.length,rootId:t,parentId:c,title:B.title,created:r.created,unpurged:Q}}async function ur(d,a,t,e,i){let s=new Uint8Array(await d.vault.adapter.readBinary(a));if(!bt(s))throw new Error("Not an encrypted bundle.");let n=await Nt(s,t),o=Bo(i)??a.replace(/\/[^/]*$/,""),r=await te(d,n,o,e,{dedupeExisting:!0});await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(he(a))}catch{}return{notesWritten:r.notesWritten,restoredTo:o}}var Tt="_deleted";function yc(d){let a="";for(let t=0;t<d.length;t++)a+=String.fromCharCode(d[t]);return btoa(a)}function Qc(d){let a=atob(d),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}async function yo(d,a,t,e){let i=Bo(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=Bo(new TextDecoder().decode(await Nt(Qc(t.originalFolderEnc),e)))}catch{i=null}if(i)return await d.vault.adapter.exists(i)||await d.vault.adapter.mkdir(i),i;let s=a.replace(/\/[^/]*$/,"");if(s===Tt||s.startsWith(`${Tt}/`))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 Ir(d,a,t,e,i,s=!1){let n=await we(d,a,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:r,parentId:l}=n,c=[o,...r],A=new Map;for(let y of c)try{let E=await d.vault.adapter.stat(y.file.path);E&&A.set(y.file.path,E.mtime)}catch{}let h=await Qe(d,{rootNotes:[{id:o.id,file:o.file}],allDescendants:r.map(y=>({id:y.id,file:y.file})),sourceFolder:a}),p=await ii(h,e),u=await Nt(p,e);if(u.length!==h.length)throw new Error("Encryption self-check failed (size).");for(let y=0;y<h.length;y++)if(u[y]!==h[y])throw new Error("Encryption self-check failed (content).");await d.vault.adapter.exists(Tt)||await d.vault.adapter.mkdir(Tt);let g=a.replace(/\/+$/,""),I=g.split("/").pop()||"vault",m=di(s?t:`${I} ${Vs(o.file)}`),f=`${Tt}/${m}.${de}`;for(let y=1;await d.vault.adapter.exists(f);y++)f=`${Tt}/${m} (${y}).${de}`;await Wi(d,f,p);let C=c,B={v:1,kind:"deleted",originalFolder:s?"":g,...s?{originalFolderEnc:yc(await ii(new TextEncoder().encode(g),e))}:{},parentId:l,title:s?"":Vs(o.file),count:C.length,created:o.created,rootId:t,deletedAt:i};try{await d.vault.adapter.write(he(f),JSON.stringify(B))}catch(y){console.warn("[Stashpad] couldn't write deleted sidecar",y)}let{unpurged:Q}=await pr(d,C,A);return{blobPath:f,noteCount:C.length,rootId:t,originalFolder:g,title:B.title,unpurged:Q}}async function fr(d,a,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(a));if(!bt(i))throw new Error("Not an encrypted bundle.");let s=await Ws(d,a),n=await yo(d,a,s,t),o=await Nt(i,t),r=await te(d,o,n,e,{dedupeExisting:!0});await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(he(a))}catch{}return{notesWritten:r.notesWritten,restoredTo:n}}async function Ws(d,a){try{return JSON.parse(await d.vault.adapter.read(he(a)))}catch{return null}}async function Qo(d,a){await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(he(a))}catch{}}var Pt=".trash";async function Ec(d,a){let t=[],e=[a];for(;e.length;){let i=e.shift(),s;try{s=await d.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function wc(d){let a=d.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 mr(d,a,t,e=!1){if(!await d.vault.adapter.exists(Pt))return null;let i=await Ec(d,Pt);if(i.length===0)return null;let s=[],n=new Map;for(let u of i){let g=u.slice(Pt.length+1);s.push({name:`files/${g}`,data:await d.vault.adapter.readBinary(u)});try{let I=await d.vault.adapter.stat(u);I&&n.set(u,I.mtime)}catch{}}let o=await Vi(s),r=await ii(o,a),l=await Nt(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 d.vault.adapter.exists(Tt)||await d.vault.adapter.mkdir(Tt);let c=di(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),A=`${Tt}/${c}.${de}`;for(let u=1;await d.vault.adapter.exists(A);u++)A=`${Tt}/${c} (${u}).${de}`;await Wi(d,A,r);let h={v:1,kind:"rawtrash",originalFolder:Pt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await d.vault.adapter.write(he(A),JSON.stringify(h))}catch(u){console.warn("[Stashpad] couldn't write backfill sidecar",u)}let p=[];for(let u of i){let g=n.get(u);try{if(g!=null){let I=await d.vault.adapter.stat(u);if(I&&I.mtime!==g){p.push(u);continue}}await d.vault.adapter.remove(u)}catch(I){console.warn("[Stashpad] couldn't delete trash file",u,I),p.push(u)}}return{blobPath:A,fileCount:i.length,unpurged:p}}async function Cr(d,a,t){let e=new Uint8Array(await d.vault.adapter.readBinary(a));if(!bt(e))throw new Error("Not an encrypted bundle.");let i=await Nt(e,t),s=await zi(i),n=0;for(let[o,r]of Object.entries(s)){if(!o.startsWith("files/"))continue;let l=wc(o.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",o);continue}let c=`${Pt}/${l}`.split("/").slice(0,-1).join("/"),A="";for(let p of c.split("/"))A=A?`${A}/${p}`:p,await d.vault.adapter.exists(A)||await d.vault.adapter.mkdir(A);let h=`${Pt}/${l}`;for(let p=1;await d.vault.adapter.exists(h);p++)h=`${Pt}/${l.replace(/(\.[^./]*)?$/,` (${p})$1`)}`;await d.vault.adapter.writeBinary(h,r.buffer),n++}await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(he(a))}catch{}return{filesWritten:n}}async function Br(d,a,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(a));if(!bt(i))throw new Error(`Not an encrypted blob: ${a}`);let s=await Nt(i,t);try{let n=await ii(s,e),o=await Nt(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 Wi(d,`${a}.rot`,n)}finally{s.fill(0)}}async function yr(d,a){let t=`${a}.rot`;if(!await d.vault.adapter.exists(t))return;let e=new Uint8Array(await d.vault.adapter.readBinary(t));await Wi(d,a,e);try{await d.vault.adapter.remove(t)}catch{}}async function Eo(d,a){let t=a.replace(/\/+$/,"");try{let e=await d.vault.adapter.list(t);for(let i of e.files)if(i.endsWith(`.${de}.rot`))try{await d.vault.adapter.remove(i)}catch{}}catch{}}async function Qr(d,a){let t=a.replace(/\/+$/,"");try{return(await d.vault.adapter.list(t)).files.filter(i=>i.endsWith(`.${de}.rot`)).map(i=>i.replace(/\.rot$/,""))}catch{return[]}}async function wo(d){if(!await d.vault.adapter.exists(Tt))return[];try{return(await d.vault.adapter.list(Tt)).files.filter(t=>t.endsWith(`.${de}`))}catch{return[]}}function Er(d){return d.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function wr(d,a){let t=kr(d,a);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Sr(d,t);if(e.length===0){new Bt.Notice("No exportable notes (no files attached).");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-${t.length}notes`;new Xe(d.app,s,e.length,(n,o,r)=>{Fc(d,t,e,n,o,r)},Ui).open()}async function vr(d,a){let t=a.replace(/\/[^/]*$/,"").replace(/\/+$/,""),e=await d.ensureFolderUnlocked(t);if(!e)return;let i;try{let l=new Uint8Array(await d.app.vault.adapter.readBinary(a));i=await Nt(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 zs(d.app,a),n=(d.settings.lockedSubtrees??[]).find(l=>l.blob===a),o=n?.title||s?.title||"locked-note",r=n?.count??s?.count??1;new Xe(d.app,o,r,(l,c,A)=>{vc(d,t,l,i,c,A)},Ui).open()}async function vc(d,a,t,e,i,s=!1){try{let n=e,o="";if(i){let u=await zt(n,i);n=u.data;let g=Yn[u.kdf];o=g.strong?` (encrypted \xB7 ${g.label})`:` (encrypted \xB7 ${g.label} \u2014 Argon2id unavailable here, weaker)`}let r=(0,Bt.moment)().format("YYYYMMDD-HHmmss"),c=(d.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,"").split("/").filter(u=>u&&u!=="."&&u!==".."&&!/[\\:]/.test(u)).join("/")||"_exports",A=`${a}/${c}`;await d.app.vault.adapter.exists(A)||await d.app.vault.adapter.mkdir(A);let h=`${Er(t)}-${r}`,p=`${A}/${h}.${_t}`;if(await d.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i)try{d.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 ${p}`,0)}catch(n){new Bt.Notice(`Export failed: ${n.message}`),console.error(n)}finally{try{e.fill(0)}catch{}}}async function Fr(d,a){let t=kr(d,a);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Sr(d,t);if(e.length===0){new Bt.Notice("No exportable notes.");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-okf`;new Si(d.app,s,e.length,(n,o)=>{(async()=>{try{let r=await d.plugin.exportOkf(d.noteFolder,t.map(l=>l.id),n,o);if(!r.length){new Bt.Notice("Nothing exported.");return}d.plugin.notifications.show({message:`Exported OKF \u2014 ${r.length} file${r.length===1?"":"s"} \u2192 \`${d.noteFolder}/${d.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:r,folder:d.noteFolder,duration:0}),await d.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 Fc(d,a,t,e,i,s=!1){try{let n=await Qe(d.app,{rootNotes:a.filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),allDescendants:t.filter(u=>!a.some(g=>g.id===u.id)).filter(u=>!!u.file).map(u=>({id:u.id,file:u.file})),sourceFolder:d.noteFolder}),o="";if(i){let u=await zt(n,i);n=u.data;let g=Yn[u.kdf];o=g.strong?` (encrypted \xB7 ${g.label})`:` (encrypted \xB7 ${g.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let r=(0,Bt.moment)().format("YYYYMMDD-HHmmss"),l=Er(e),c=(d.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),A=`${d.noteFolder}/${c}`;await d.ensureFolder(A);let h=`${l}-${r}`,p=`${A}/${h}.${_t}`;if(await d.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let u=d.app.secretStorage;try{u?.setSecret(Ve(h),i)}catch(g){console.warn("[Stashpad] couldn't save export passphrase to secret storage",g)}}await d.log.append({type:"stash_export",id:a[0].id,payload:{path:p,noteCount:t.length,rootIds:a.map(u=>u.id)}}),d.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:d.noteFolder,actions:d.actionsForFile(p),duration:0})}catch(n){d.plugin.notifications.show({message:`Stashpad: export failed +${a}`}async function hr(d,a){if(!(!a||await d.vault.adapter.exists(a)))try{await d.vault.createFolder(a)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}as();kt();Ys();var he="stashenc",vc="stashmeta";function ee(d){return d.replace(/\.stashenc$/,`.${vc}`)}async function Ws(d,a){try{return JSON.parse(await d.vault.adapter.read(ee(a)))}catch{return null}}async function we(d,a,t){let e=a.replace(/\/+$/,""),i=[];for(let c of d.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let A;try{A=dt(await d.vault.read(c)).fm}catch{continue}typeof A.id=="string"&&i.push({id:A.id,file:c,parent:typeof A.parent=="string"?A.parent:null,created:typeof A.created=="string"?A.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 A=n.get(c.parent)??[];A.push(c),n.set(c.parent,A)}let o=[],r=new Set([t]),l=[t];for(;l.length;){let c=[];for(let A of l)for(let h of n.get(A)??[])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 Eo(d){if(!d)return null;let a=d.replace(/\/+$/,"");return!a||a.startsWith("/")||a.includes("\\")||/^[a-zA-Z]:/.test(a)||a.split("/").some(t=>t===".."||t===".")?null:a}async function Xi(d,a,t){await d.vault.adapter.writeBinary(a,t);let e;try{e=new Uint8Array(await d.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 d.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(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function di(d){return(d.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function Ir(d,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 Vs(d,r.file))i.set(l.path,l);let s=new Set,n=d.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 d.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 d.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 d.vault.delete(l)}catch(c){console.warn("[Stashpad] couldn't delete exclusive attachment",r,c),o.push(r)}return{unpurged:o}}async function fr(d,a,t,e,i=null,s=!1,n){let o=await we(d,a,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:r,descendants:l,parentId:c}=o,A=[r,...l],h=new Map;for(let y of A)try{let E=await d.vault.adapter.stat(y.file.path);E&&h.set(y.file.path,E.mtime)}catch{}let g=await Qe(d,{rootNotes:[{id:r.id,file:r.file}],allDescendants:l.map(y=>({id:y.id,file:y.file})),sourceFolder:a}),u=await Ue(g,e),p=await St(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 I=(n??a).replace(/\/+$/,"");n&&!await d.vault.adapter.exists(I)&&await d.vault.adapter.mkdir(I);let f=di(s?t:zs(r.file)),m=`${I}/${f}.${he}`;for(let y=1;await d.vault.adapter.exists(m);y++)m=`${I}/${f} (${y}).${he}`;await Xi(d,m,u);let C=A,B={v:1,parentId:c,title:s?"":zs(r.file),count:C.length,created:r.created,rootId:t,prevSibling:i};try{await d.vault.adapter.write(ee(m),JSON.stringify(B))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:Q}=await Ir(d,C,h);return{blobPath:m,noteCount:C.length,rootId:t,parentId:c,title:B.title,created:r.created,unpurged:Q}}async function mr(d,a,t,e,i){let s=new Uint8Array(await d.vault.adapter.readBinary(a));if(!Nt(s))throw new Error("Not an encrypted bundle.");let n=await St(s,t),o=Eo(i)??a.replace(/\/[^/]*$/,""),r=await te(d,n,o,e,{dedupeExisting:!0});await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(ee(a))}catch{}return{notesWritten:r.notesWritten,restoredTo:o}}var Tt="_deleted";function Cr(d){let a="";for(let t=0;t<d.length;t++)a+=String.fromCharCode(d[t]);return btoa(a)}function Br(d){let a=atob(d),t=new Uint8Array(a.length);for(let e=0;e<a.length;e++)t[e]=a.charCodeAt(e);return t}async function wo(d,a,t,e){let i=Eo(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=Eo(new TextDecoder().decode(await St(Br(t.originalFolderEnc),e)))}catch{i=null}if(i)return await d.vault.adapter.exists(i)||await d.vault.adapter.mkdir(i),i;let s=a.replace(/\/[^/]*$/,"");if(s===Tt||s.startsWith(`${Tt}/`))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 yr(d,a,t,e,i,s=!1,n){let o=await we(d,a,t);if(!o)throw new Error("Couldn't find that note to delete.");let{rootNote:r,descendants:l,parentId:c}=o,A=[r,...l],h=new Map;for(let E of A)try{let v=await d.vault.adapter.stat(E.file.path);v&&h.set(E.file.path,v.mtime)}catch{}let g=await Qe(d,{rootNotes:[{id:r.id,file:r.file}],allDescendants:l.map(E=>({id:E.id,file:E.file})),sourceFolder:a}),u=await Ue(g,e),p=await St(u,e);if(p.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let E=0;E<g.length;E++)if(p[E]!==g[E])throw new Error("Encryption self-check failed (content).");await d.vault.adapter.exists(Tt)||await d.vault.adapter.mkdir(Tt);let I=a.replace(/\/+$/,""),f=I.split("/").pop()||"vault",m=di(s?t:`${f} ${zs(r.file)}`),C=`${Tt}/${m}.${he}`;for(let E=1;await d.vault.adapter.exists(C);E++)C=`${Tt}/${m} (${E}).${he}`;await Xi(d,C,u);let B=A,Q={v:1,kind:"deleted",originalFolder:s?"":I,...s?{originalFolderEnc:Cr(await Ue(new TextEncoder().encode(I),e))}:{},parentId:c,title:s?"":zs(r.file),count:B.length,created:r.created,rootId:t,deletedAt:i,...n?{keyId:n}:{}};try{await d.vault.adapter.write(ee(C),JSON.stringify(Q))}catch(E){console.warn("[Stashpad] couldn't write deleted sidecar",E)}let{unpurged:y}=await Ir(d,B,h);return{blobPath:C,noteCount:B.length,rootId:t,originalFolder:I,title:Q.title,unpurged:y}}async function Qr(d,a,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(a));if(!Nt(i))throw new Error("Not an encrypted bundle.");let s=await hi(d,a),n=await wo(d,a,s,t),o=await St(i,t),r=await te(d,o,n,e,{dedupeExisting:!0});await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(ee(a))}catch{}return{notesWritten:r.notesWritten,restoredTo:n}}async function hi(d,a){try{return JSON.parse(await d.vault.adapter.read(ee(a)))}catch{return null}}async function vo(d,a){await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(ee(a))}catch{}}var Pt=".trash";async function Fo(d,a){let t=[],e=[a];for(;e.length;){let i=e.shift(),s;try{s=await d.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function Fc(d){let a=d.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 Er(d,a,t,e=!1){if(!await d.vault.adapter.exists(Pt))return null;let i=await Fo(d,Pt);if(i.length===0)return null;let s=[],n=new Map;for(let u of i){let p=u.slice(Pt.length+1);s.push({name:`files/${p}`,data:await d.vault.adapter.readBinary(u)});try{let I=await d.vault.adapter.stat(u);I&&n.set(u,I.mtime)}catch{}}let o=await zi(s),r=await Ue(o,a),l=await St(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 d.vault.adapter.exists(Tt)||await d.vault.adapter.mkdir(Tt);let c=di(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),A=`${Tt}/${c}.${he}`;for(let u=1;await d.vault.adapter.exists(A);u++)A=`${Tt}/${c} (${u}).${he}`;await Xi(d,A,r);let h={v:1,kind:"rawtrash",originalFolder:Pt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await d.vault.adapter.write(ee(A),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 I=await d.vault.adapter.stat(u);if(I&&I.mtime!==p){g.push(u);continue}}await d.vault.adapter.remove(u)}catch(I){console.warn("[Stashpad] couldn't delete trash file",u,I),g.push(u)}}return{blobPath:A,fileCount:i.length,unpurged:g}}async function wr(d,a,t){let e=new Uint8Array(await d.vault.adapter.readBinary(a));if(!Nt(e))throw new Error("Not an encrypted bundle.");let i=await St(e,t),s=await Wi(i),n=0;for(let[o,r]of Object.entries(s)){if(!o.startsWith("files/"))continue;let l=Fc(o.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",o);continue}let c=`${Pt}/${l}`.split("/").slice(0,-1).join("/"),A="";for(let g of c.split("/"))A=A?`${A}/${g}`:g,await d.vault.adapter.exists(A)||await d.vault.adapter.mkdir(A);let h=`${Pt}/${l}`;for(let g=1;await d.vault.adapter.exists(h);g++)h=`${Pt}/${l.replace(/(\.[^./]*)?$/,` (${g})$1`)}`;await d.vault.adapter.writeBinary(h,r.buffer),n++}await d.vault.adapter.remove(a);try{await d.vault.adapter.remove(ee(a))}catch{}return{filesWritten:n}}async function vr(d,a,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(a));if(!Nt(i))throw new Error(`Not an encrypted blob: ${a}`);let s=await St(i,t);try{let n=await Ue(s,e),o=await St(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 Xi(d,`${a}.rot`,n)}finally{s.fill(0)}}async function Fr(d,a,t,e){let i=await hi(d,a);if(!i?.originalFolderEnc)return;let s=await St(Br(i.originalFolderEnc),t);try{i.originalFolderEnc=Cr(await Ue(s,e))}finally{s.fill(0)}await d.vault.adapter.write(ee(a),JSON.stringify(i))}async function ko(d,a){let t=[];for(let e of await js(d))(await hi(d,e))?.keyId===a&&t.push(e);return t}async function Xs(d,a){let t=`${a}.rot`;if(!await d.vault.adapter.exists(t))return;let e=new Uint8Array(await d.vault.adapter.readBinary(t));await Xi(d,a,e);try{await d.vault.adapter.remove(t)}catch{}}async function Zs(d,a){let t=a.replace(/\/+$/,"");for(let e of await Fo(d,t))if(e.endsWith(`.${he}.rot`))try{await d.vault.adapter.remove(e)}catch{}}async function kr(d,a){let t=a.replace(/\/+$/,"");return(await Fo(d,t)).filter(e=>e.endsWith(`.${he}.rot`)).map(e=>e.replace(/\.rot$/,""))}async function js(d){if(!await d.vault.adapter.exists(Tt))return[];try{return(await d.vault.adapter.list(Tt)).files.filter(t=>t.endsWith(`.${he}`))}catch{return[]}}function Sr(d){return d.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function Dr(d,a){let t=xr(d,a);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Mr(d,t);if(e.length===0){new Bt.Notice("No exportable notes (no files attached).");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-${t.length}notes`;new Ze(d.app,s,e.length,(n,o,r)=>{Sc(d,t,e,n,o,r)},Ri).open()}async function br(d,a){let t=a.replace(/\/[^/]*$/,"").replace(/\/+$/,""),e=await d.ensureFolderUnlocked(t);if(!e)return;let i;try{let l=new Uint8Array(await d.app.vault.adapter.readBinary(a));i=await St(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 Ws(d.app,a),n=(d.settings.lockedSubtrees??[]).find(l=>l.blob===a),o=n?.title||s?.title||"locked-note",r=n?.count??s?.count??1;new Ze(d.app,o,r,(l,c,A)=>{kc(d,t,l,i,c,A)},Ri).open()}async function kc(d,a,t,e,i,s=!1){try{let n=e,o="";if(i){let u=await zt(n,i);n=u.data;let p=zn[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=(d.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,"").split("/").filter(u=>u&&u!=="."&&u!==".."&&!/[\\:]/.test(u)).join("/")||"_exports",A=`${a}/${c}`;await d.app.vault.adapter.exists(A)||await d.app.vault.adapter.mkdir(A);let h=`${Sr(t)}-${r}`,g=`${A}/${h}.${_t}`;if(await d.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i)try{d.app.secretStorage?.setSecret(ze(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 Nr(d,a){let t=xr(d,a);if(t.length===0){new Bt.Notice("Nothing to export.");return}let e=Mr(d,t);if(e.length===0){new Bt.Notice("No exportable notes.");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-okf`;new Di(d.app,s,e.length,(n,o)=>{(async()=>{try{let r=await d.plugin.exportOkf(d.noteFolder,t.map(l=>l.id),n,o);if(!r.length){new Bt.Notice("Nothing exported.");return}d.plugin.notifications.show({message:`Exported OKF \u2014 ${r.length} file${r.length===1?"":"s"} \u2192 \`${d.noteFolder}/${d.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:r,folder:d.noteFolder,duration:0}),await d.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 Sc(d,a,t,e,i,s=!1){try{let n=await Qe(d.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:d.noteFolder}),o="";if(i){let u=await zt(n,i);n=u.data;let p=zn[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=Sr(e),c=(d.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),A=`${d.noteFolder}/${c}`;await d.ensureFolder(A);let h=`${l}-${r}`,g=`${A}/${h}.${_t}`;if(await d.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let u=d.app.secretStorage;try{u?.setSecret(ze(h),i)}catch(p){console.warn("[Stashpad] couldn't save export passphrase to secret storage",p)}}await d.log.append({type:"stash_export",id:a[0].id,payload:{path:g,noteCount:t.length,rootIds:a.map(u=>u.id)}}),d.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:d.noteFolder,actions:d.actionsForFile(g),duration:0})}catch(n){d.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 kr(d,a){if(a?.file)return[a];if(d.selection.size>0)return[...d.selection].map(e=>d.tree.get(e)).filter(e=>!!e?.file);if(d.cursorIdx>=0&&d.currentChildren[d.cursorIdx])return[d.currentChildren[d.cursorIdx]];let t=d.tree.get(d.focusId);return t?.file?[t]:[]}function Sr(d,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 d.tree.getChildren(s.id))i(n)}};for(let s of a)i(s);return e}async function Dr(d){let a=d.app.vault.getFiles().filter(e=>e.extension===_t);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){vo(d,e)}}(d.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function vo(d,a){try{let t=new Uint8Array(await d.app.vault.readBinary(a)),e=await si(d.app,t,{secretId:Ve(a.basename)});if(!e)return;let i=await te(d.app,e,d.noteFolder,kc(d));d.tree.rebuild(d.noteFolder),d.render(),await d.log.append({type:"stash_import",id:F,payload:{from:a.path,into:d.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await d.app.fileManager.trashFile(a)}catch{}d.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)`),d.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:d.noteFolder})}catch(t){d.plugin.notifications.show({message:`Stashpad: import failed +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function xr(d,a){if(a?.file)return[a];if(d.selection.size>0)return[...d.selection].map(e=>d.tree.get(e)).filter(e=>!!e?.file);if(d.cursorIdx>=0&&d.currentChildren[d.cursorIdx])return[d.currentChildren[d.cursorIdx]];let t=d.tree.get(d.focusId);return t?.file?[t]:[]}function Mr(d,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 d.tree.getChildren(s.id))i(n)}};for(let s of a)i(s);return e}async function Tr(d){let a=d.app.vault.getFiles().filter(e=>e.extension===_t);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){So(d,e)}}(d.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function So(d,a){try{let t=new Uint8Array(await d.app.vault.readBinary(a)),e=await si(d.app,t,{secretId:ze(a.basename)});if(!e)return;let i=await te(d.app,e,d.noteFolder,Dc(d));d.tree.rebuild(d.noteFolder),d.render(),await d.log.append({type:"stash_import",id:F,payload:{from:a.path,into:d.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await d.app.fileManager.trashFile(a)}catch{}d.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)`),d.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:d.noteFolder})}catch(t){d.plugin.notifications.show({message:`Stashpad: import failed File: \`${a.name}\` Error: ${t.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[a.path],actions:d.actionsForFile(a.path)}),console.error(t)}}function kc(d){let a=new Set,t=e=>{if(a.add(e),!!d.tree.get(e))for(let s of d.tree.getChildren(e))t(s.id)};return t(F),a}yi();yi();var Dc=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),Xs={nested:"Nested",flat:"Flat",everything:"Everything"},Zs=[{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"}],Xi=class Xi extends k.ItemView{constructor(t,e){super(t);this.focusId=F;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bulkRenderDepth=0;this.bulkSettleTimer=null;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.pendingCursorId=null;this.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.nextDestinationFolder=null;this.nextDestinationLabel=null;this.inListPicker=null;this.pickerEscapeAt=0;this.composerExitAt=0;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.scrollListenerSaveTimer=null;this.suppressScrollSave=!1;this.selectionGuardKey=0;this.pendingRenderPolicy=null;this.stickToListBottom=!1;this.keyboardTransitionUntil=0;this.tapSettleUntil=0;this.aimedTapTargetId=null;this.aimedTapAt=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.activeVersionByGroup=new Map;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||zo(t.target))return;let e=j().bindings;if(G(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(G(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(G(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(G(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(G(t,e.lockSelection)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdLockSelection();return}if(G(t,e.unlockAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUnlockAll();return}if(G(t,e.moveToArchive)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToArchive();return}if(G(t,e.encryptDelete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdEncryptDelete();return}if(G(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(G(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(G(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(G(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(G(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let i=t.target,s=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!s){let l=this.composerInputEl;if(l){t.preventDefault(),t.stopPropagation(),l.focus();let 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,A=l?.scrollTop??0;if(this.render(),l){let h=c?l.scrollHeight:A;l.scrollTop=h,requestAnimationFrame(()=>{l.scrollTop=c?l.scrollHeight:A}),setTimeout(()=>{l.scrollTop=c?l.scrollHeight:A},60),this.revealCursorRow()}return}if(this.inListPicker&&!n){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,-1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}if(G(t,j().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(G(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(G(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(G(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(G(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(G(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(G(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(G(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(G(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(G(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(G(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(G(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(G(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let l=this.composerInputEl;if(l){l.focus();let 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(A=>A.id===l);this.selection.add(l),this.lastSelected=l,c>=0&&(this.cursorIdx=c)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=j().bindings;if(G(t,o.pasteNotes)&&this.plugin.noteClipboard){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdPasteNotes();return}if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(G(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(G(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(G(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(G(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(G(t,o.copyNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyNotes();return}if(G(t,o.cutNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCutNotes();return}if(G(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(G(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(G(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(G(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let l=this.tree.get(this.focusId);l?.file&&this.cmdOpenInEditor(l)}else this.cmdOpenInEditor();return}if(G(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(G(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(G(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(G(t,o.forkNote)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdForkNote();return}if(G(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(G(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(G(t,o.expandAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExpandAll();return}if(G(t,o.collapseAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCollapseAll();return}if(G(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(G(t,o.listPin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleListPin();return}if(G(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(G(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(G(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(G(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let 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 k.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&(this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.authorship.noteModify(t),this.debouncedRender())};this.onFileCreate=t=>{!(t instanceof k.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new bs(this.app),this.log=e.newLog(),this.integrity=new Ps(this.tree,this.log),this.order=new ai(this.app),this.sortStore=new Ns(this.app),this.fmSync=new Ms(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):qa(this,i,n);return this.hoistListPinned(i,o)}),this.debouncedRender=(0,k.debounce)(()=>{this.renderSuppressed()||this.render()},80),this.authorship=new Us(this),this.dnd=new Rs(this),this.bodyRenderer=new Gs(this,this,this.plugin.renderCacheStore)}getViewType(){return J}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==F){let i=this.tree.get(this.focusId);if(i){let s=this.titleForNode(i).trim(),n=s.length>40?s.slice(0,40)+"\u2026":s;if(n)return`${e} \u2014 ${n} \xB7 ${this.focusId}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let i=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;i&&i.textContent!==t&&i.setText(t)}getIcon(){return"list-tree"}async onOpen(){let t=this.contentEl;t.empty(),t.addClass("stashpad-scroll-host"),this.viewRoot=t.createDiv({cls:"stashpad-view"}),this.viewRoot.setAttribute("tabindex","0"),this.viewRoot.addEventListener("focusin",()=>ws(this)),this.viewRoot.addEventListener("click",()=>ws(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())}),ws(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new k.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.inListPicker)return this.inListPicker=null,this.pickerEscapeAt=Date.now(),this.repaintSelectionClasses(),!1;if(Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return!1;if(this.selection.size>1){let l=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,l){let c=this.currentChildren.findIndex(A=>A.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 A of[this.completedState,this.taskTaggedState])A.has(c)&&(A.set(l.path,A.get(c)),A.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("/"),A=(c>=0?l.path.slice(0,c):"").replace(/\/+$/,"");l.path.endsWith(".md")&&A===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=Ma(()=>{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,A]of l)this.lastCursorByFocus.set(c,A);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(!j().autofocusComposerAfterSend)return;let t=()=>{if(!this.viewRoot?.isConnected||Date.now()<this.suppressComposerFocusUntil||Date.now()<this.plugin.suppressComposerAutofocusUntil)return;let e=document.activeElement;e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA")&&e!==this.composerInputEl||(e&&e.tagName==="BUTTON"&&this.viewRoot.contains(e),this.composerInputEl?.focus({preventScroll:!0}))};requestAnimationFrame(t),setTimeout(t,50),setTimeout(t,200)}async onClose(){ba(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.bodyRenderer.dispose(),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();this.authorship.dispose();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=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[A,h]of c)this.lastCursorByFocus.set(A,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 k.Notice(`"${i}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((i||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=i,this.focusId=F,this.lastCursorByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig();try{await this.bootstrapFolder()}catch(s){let n=s?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",s)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let s=this.app.workspace;typeof s.saveLayout=="function"?await s.saveLayout():this.app.workspace.requestSaveLayout()}catch{this.app.workspace.requestSaveLayout()}this.refreshHeaderTitle(),this.render()}}cmdOpenFolderPicker(){this.openFolderPicker()}openFolderPicker(){this.plugin.openFolderPicker()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof k.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,i)=>e.localeCompare(i))}isReservedFolder(t){let e=t.split("/").filter(Boolean).pop()??"";return e?new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed","_authors"].map(s=>(s??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(e):!1}persistFocus(){try{this.app.workspace.requestSaveLayout()}catch{}}cmdUndo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canUndo()){new k.Notice("Nothing to undo.");return}let e=t.peekUndoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.undo().then(()=>this.plugin.notifications.show({message:`Undid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Undo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new k.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Redo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let i=[],s=new Set;for(let l of t)!l.file||s.has(l.file.path)||(s.add(l.file.path),i.push(l.file));let n=await Promise.all(i.map(l=>this.app.vault.read(l))),o=i.map((l,c)=>({path:l.path,content:n[c]})),r=[];if(e){let l=new Set,c=[];for(let h of n)for(let p of this.extractAttachments(this.stripFrontmatter(h))){let u=this.app.metadataCache.getFirstLinkpathDest(p,"");u&&!l.has(u.path)&&(l.add(u.path),c.push(u))}let A=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:A[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,k.moment)();switch(this.timeFilter){case"day":return e.startOf("day").valueOf();case"week":return e.startOf("isoWeek").valueOf();case"month":return e.startOf("month").valueOf();case"year":return e.startOf("year").valueOf()}}let t=Date.now();switch(this.timeFilter){case"day":return t-864e5;case"week":return t-7*864e5;case"month":return t-30*864e5;case"year":return t-365*864e5}return null}allowedByBases(){return null}currentViewMode(){return this.plugin.settings.viewModes?.[this.noteFolder]??"nested"}currentIncludeAttachments(){return!!this.plugin.settings.includeAttachmentsInEverything?.[this.noteFolder]}async setIncludeAttachments(t){let e={...this.plugin.settings.includeAttachmentsInEverything??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.includeAttachmentsInEverything=e,await this.plugin.saveSettings()}currentEncryptionFilter(){return this.plugin.settings.encryptionFilter?.[this.noteFolder]??"all"}async setEncryptionFilter(t){let e={...this.plugin.settings.encryptionFilter??{}};t==="all"?delete e[this.noteFolder]:e[this.noteFolder]=t,this.plugin.settings.encryptionFilter=e,await this.plugin.saveSettings()}currentHideChildless(){return!!this.plugin.settings.hideChildlessNotes?.[this.noteFolder]}async setHideChildless(t){let e={...this.plugin.settings.hideChildlessNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideChildlessNotes=e,await this.plugin.saveSettings()}currentHideCompleted(){return!!this.plugin.settings.hideCompletedNotes?.[this.noteFolder]}async setHideCompleted(t){let e={...this.plugin.settings.hideCompletedNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideCompletedNotes=e,await this.plugin.saveSettings()}currentAttachmentsOnly(){return!!this.plugin.settings.attachmentsOnlyNotes?.[this.noteFolder]}async setAttachmentsOnly(t){let e={...this.plugin.settings.attachmentsOnlyNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.attachmentsOnlyNotes=e,await this.plugin.saveSettings()}nodeHasAttachment(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.attachments;return Array.isArray(e)&&e.length>0}hasAttachmentInSubtree(t){if(this.nodeHasAttachment(t))return!0;for(let e of this.tree.getChildren(t.id))if(this.hasAttachmentInSubtree(e))return!0;return!1}hasIncompleteDescendant(t){for(let e of t.children){let i=this.tree.get(e);if(i&&(!this.isCompleted(i)||this.hasIncompleteDescendant(i)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof k.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof k.TFolder){s.push(o);continue}if(!(o instanceof k.TFile)||o.extension!=="md")continue;let 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=Se(l),A=this.app.metadataCache.getFirstLinkpathDest(c,o.path);A?t.add(A.path):t.add(c)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof k.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),r=[],l=[i];for(;l.length;){let c=l.pop();for(let A of c.children){if(A instanceof k.TFolder){let h=A.name;if(c===i&&o.has(h)||c===i&&h==="_attachments"&&!s)continue;l.push(A);continue}A instanceof k.TFile&&A.extension!=="md"&&(A.name===".stashpad-order.json"||A.name===".stashpad-sort.json"||!s&&n.has(A.path)||r.push(A))}}return r}populateListBody(t,e){if(this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),this.pendingCursorId){let A=this.currentChildren.findIndex(h=>h.id===this.pendingCursorId);A>=0&&(this.cursorIdx=A,this.selection.clear(),this.selection.add(this.pendingCursorId),this.lastSelected=this.pendingCursorId,this.pendingCursorId=null)}e.file&&k.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode(),s=i==="everything"?this.collectFileItems(e.id):[],n=A=>A.created&&Number.isFinite(Date.parse(A.created))?Date.parse(A.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 A=new Set([e.id,...this.currentChildren.map(p=>p.id)]),h=new Set;r=[];for(let p of A)for(let u of this.plugin.lockedSubtreesFor(this.noteFolder,p))h.has(u.blob)||(h.add(u.blob),r.push(u))}let l=r.map(A=>({lk:A,ts:n(A)})).sort((A,h)=>A.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 A=new Map(this.currentChildren.map((I,m)=>[I.id,m])),h=new Map;for(let{lk:I}of l)I.rootId&&h.set(I.rootId,I);let p=this.currentChildren.map(I=>I.id),u=l.map(({lk:I})=>I).filter(I=>I.rootId).sort((I,m)=>n(m)-n(I)),g=!0;for(;u.length&&g;){g=!1;for(let I=0;I<u.length;I++){let m=u[I],f=m.prevSibling??null,C;if(f==null)C=0;else{let B=p.indexOf(f);if(B<0)continue;C=B+1}p.splice(C,0,m.rootId),u.splice(I,1),I--,g=!0}}for(let I of u)p.push(I.rootId);for(let I of p){let m=A.get(I);if(m!==void 0)this.renderNote(t,this.currentChildren[m],m);else{let f=h.get(I);f&&this.renderLockedPlaceholder(t,f)}}for(let I of s.slice().sort((m,f)=>m.stat.ctime-f.stat.ctime))this.renderFileRow(t,I)}else if(s.length===0){let A=0;for(let h=0;h<this.currentChildren.length;h++){let p=Number.isFinite(Date.parse(this.currentChildren[h].created))?Date.parse(this.currentChildren[h].created):0;for(;A<l.length&&l[A].ts<=p;)this.renderLockedPlaceholder(t,l[A].lk),A++;this.renderNote(t,this.currentChildren[h],h)}for(;A<l.length;)this.renderLockedPlaceholder(t,l[A].lk),A++}else{let A=[...this.currentChildren.map((h,p)=>({kind:"note",ts:Number.isFinite(Date.parse(h.created))?Date.parse(h.created):0,idx:p})),...s.map(h=>({kind:"file",ts:h.stat.ctime,file:h})),...l.map(h=>({kind:"lock",ts:h.ts,lk:h.lk}))];A.sort((h,p)=>h.ts-p.ts);for(let h of A)h.kind==="note"?this.renderNote(t,this.currentChildren[h.idx],h.idx):h.kind==="file"?this.renderFileRow(t,h.file):this.renderLockedPlaceholder(t,h.lk)}e.file&&k.Platform.isMobile&&this.installFocusedMiniObserver(t)}renderLockedPlaceholder(t,e){let i=t.createDiv({cls:"stashpad-locked-row"});e.created&&i.createSpan({cls:"stashpad-note-time stashpad-locked-time",text:this.formatTime(e.created)});let s=i.createSpan({cls:"stashpad-locked-icon"});(0,k.setIcon)(s,"lock");let n=(this.plugin.settings.hideLockedTitles??!1)||!e.title;i.createSpan({cls:"stashpad-locked-title",text:n?"Locked note":e.title}),i.createSpan({cls:"stashpad-locked-count",text:e.count>1?`${e.count} notes \xB7 locked`:"locked"});let o=i.createEl("button",{cls:"stashpad-locked-unlock",text:"Unlock"});(0,k.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let r=async c=>{c.preventDefault(),c.stopPropagation();let A=(this.plugin.settings.lockedSubtrees??[]).find(I=>I.blob===e.blob),h=e.rootId??A?.rootId??null,p=e.parentId??A?.parentId??F,u=e.prevSibling??A?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,h){let I=this.order.getOrder(this.noteFolder,p),m=this.sortStore.getMode(this.noteFolder,p)==="manual";if(I.length===0&&m&&(I=this.tree.getChildren(p).map(f=>f.id)),I.length>0){let f=I.filter(B=>B!==h),C=u&&f.includes(u)?f.indexOf(u)+1:0;f.splice(Math.max(0,C),0,h),this.order.setOrder(this.noteFolder,p,f),this.order.flush(this.noteFolder)}this.pendingCursorId=h}this.render()}};o.onclick=r;let l=c=>{c.preventDefault(),c.stopPropagation();let A=new k.Menu;if(A.addItem(h=>h.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void r(c))),!k.Platform.isMobile){let h=k.Platform.isMacOS?"Finder":k.Platform.isWin?"File Explorer":"file manager";A.addItem(p=>p.setTitle(`Show in ${h}`).setIcon("folder-search").onClick(()=>{try{let u=window.require?.("electron")?.shell,g=this.app.vault.adapter?.getFullPath?.(e.blob);g&&u?.showItemInFolder&&u.showItemInFolder(g)}catch(u){console.warn("[Stashpad] showItemInFolder failed",u)}}))}A.addItem(h=>h.setTitle("Export to .stash\u2026").setIcon("package").onClick(()=>{this.plugin.exportLockedSubtree(e.blob)})),A.addItem(h=>h.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let p=e.blob;if(!k.Platform.isMobile)try{p=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(p),new k.Notice("Path copied.")})),A.showAtMouseEvent(c)};if(i.oncontextmenu=l,k.Platform.isMobile){let c=i.createEl("button",{cls:"stashpad-locked-menu"});(0,k.setIcon)(c,"more-vertical"),c.setAttr("aria-label","Locked note menu"),c.onclick=A=>l(A)}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 A=ue(this.app.metadataCache.getFileCache(c.file)?.frontmatter?.author);if(!A||A.id!==l)return!1}if(e&&c.created){let A=Date.parse(c.created);if(!Number.isNaN(A)&&A<e)return!1}if(i){if(!c.file)return!1;if(this.tagFilter===be){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=ft(this.app,n);if(!ui(o))continue;i=!0;let r=Ot(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=>ui(ft(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 Go(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){Ft.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",k.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let l=this.containerEl.closest(".workspace-leaf");l&&(l.classList.toggle("stashpad-is-tiny",this.tinyMode),l.classList.toggle("stashpad-is-compact",this.compactMode));let c=this.containerEl.closest(".workspace-tabs");c&&c.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let A=this.tree.get(this.focusId)??this.tree.getRoot();A.file&&!k.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,A),this.currentChildren=this.filterChildren(this.collectViewItems(A.id));let h=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let g=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(g.id),this.lastSelected=g.id,this.autoSelectNewest=!1,h=!0}else if(this.pendingFocusIds){let g=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let I=-1;for(let m of g){let f=this.currentChildren.findIndex(C=>C.id===m);f>=0&&(this.selection.add(m),I<0&&(I=f))}this.cursorIdx=I,I>=0&&(this.lastSelected=g.find(m=>this.currentChildren.some(f=>f.id===m))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let p=e.createDiv({cls:"stashpad-list"});if(this.listEl=p,this.dnd.attachListDnD(p),this.populateListBody(p,A),this.renderComposer(e),k.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(Ft.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),h&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let g=this.pendingComposerCaret;this.pendingComposerCaret=null;let I=this.composerInputEl;if(I&&I.isConnected){if(I.focus({preventScroll:!0}),g!=null){let m=Math.min(g,I.value.length);try{I.setSelectionRange(m,m)}catch{}}}else requestAnimationFrame(()=>{let m=this.composerInputEl;if(m&&(m.focus({preventScroll:!0}),g!=null)){let f=Math.min(g,m.value.length);try{m.setSelectionRange(f,f)}catch{}}})}let u=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,u&&this.listEl){let g=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,u.kind){case"preserve":g?this.scrollListToBottom():r?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let I=u.scrollTop,m=this.listEl,f=()=>{this.suppressScrollSave=!0;let C=Math.max(0,m.scrollHeight-m.clientHeight);m.scrollTop=Math.min(I,C),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};f(),requestAnimationFrame(f),setTimeout(f,60),setTimeout(f,200),setTimeout(f,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let I=u.id,m=u.align,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let B=f.querySelector(`[data-id="${I}"]`);B&&B.scrollIntoView({block:m,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 g=this.listEl,I=g.scrollTop,m=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){g.scrollTop=g.scrollHeight,I=g.scrollTop;return}let C=Math.max(0,g.scrollHeight-g.clientHeight);g.scrollTop<I&&I<=C?g.scrollTop=I:I=g.scrollTop});m.observe(g),this.listResizeObserver=m,g.addEventListener("wheel",C=>{C.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let f=0;g.addEventListener("touchstart",C=>{f=C.touches[0]?.clientY??0},{passive:!0}),g.addEventListener("touchmove",C=>{let B=C.touches[0]?.clientY??f;B>f&&(this.stickToListBottom=!1),f=B},{passive:!0}),g.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),g.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),i=e.createEl("button",{cls:"stashpad-folder-btn"}),s=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,k.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[a.path],actions:d.actionsForFile(a.path)}),console.error(t)}}function Dc(d){let a=new Set,t=e=>{if(a.add(e),!!d.tree.get(e))for(let s of d.tree.getChildren(e))t(s.id)};return t(F),a}Qi();Qi();var Nc=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),_s={nested:"Nested",flat:"Flat",everything:"Everything"},tn=[{key:"day",calShort:"Today",rollShort:"24h",calLong:"Since midnight today",rollLong:"Last 24 hours"},{key:"week",calShort:"Week",rollShort:"7d",calLong:"Since Monday this week",rollLong:"Last 7 days"},{key:"month",calShort:"Month",rollShort:"30d",calLong:"Since the 1st of this month",rollLong:"Last 30 days"},{key:"year",calShort:"Year",rollShort:"365d",calLong:"Since January 1 this year",rollLong:"Last 365 days"},{key:"all",calShort:"All",rollShort:"ad infinitum",calLong:"All time",rollLong:"All time"}],Zi=class Zi extends k.ItemView{constructor(t,e){super(t);this.focusId=F;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bulkRenderDepth=0;this.bulkSettleTimer=null;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.pendingCursorId=null;this.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.nextDestinationFolder=null;this.nextDestinationLabel=null;this.inListPicker=null;this.pickerEscapeAt=0;this.composerExitAt=0;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.scrollListenerSaveTimer=null;this.suppressScrollSave=!1;this.selectionGuardKey=0;this.pendingRenderPolicy=null;this.stickToListBottom=!1;this.keyboardTransitionUntil=0;this.tapSettleUntil=0;this.aimedTapTargetId=null;this.aimedTapAt=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.activeVersionByGroup=new Map;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||Zo(t.target))return;let e=j().bindings;if(G(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(G(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(G(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(G(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(G(t,e.lockSelection)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdLockSelection();return}if(G(t,e.unlockAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUnlockAll();return}if(G(t,e.moveToArchive)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToArchive();return}if(G(t,e.encryptDelete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdEncryptDelete();return}if(G(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(G(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(G(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(G(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(G(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let i=t.target,s=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!s){let l=this.composerInputEl;if(l){t.preventDefault(),t.stopPropagation(),l.focus();let 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,A=l?.scrollTop??0;if(this.render(),l){let h=c?l.scrollHeight:A;l.scrollTop=h,requestAnimationFrame(()=>{l.scrollTop=c?l.scrollHeight:A}),setTimeout(()=>{l.scrollTop=c?l.scrollHeight:A},60),this.revealCursorRow()}return}if(this.inListPicker&&!n){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,-1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}if(G(t,j().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(G(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(G(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(G(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(G(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(G(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(G(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(G(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(G(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(G(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(G(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(G(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(G(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let l=this.composerInputEl;if(l){l.focus();let 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(A=>A.id===l);this.selection.add(l),this.lastSelected=l,c>=0&&(this.cursorIdx=c)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=j().bindings;if(G(t,o.pasteNotes)&&this.plugin.noteClipboard){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdPasteNotes();return}if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(G(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(G(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(G(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(G(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(G(t,o.copyNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyNotes();return}if(G(t,o.cutNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCutNotes();return}if(G(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(G(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(G(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(G(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let l=this.tree.get(this.focusId);l?.file&&this.cmdOpenInEditor(l)}else this.cmdOpenInEditor();return}if(G(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(G(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(G(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(G(t,o.forkNote)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdForkNote();return}if(G(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(G(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(G(t,o.expandAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExpandAll();return}if(G(t,o.collapseAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCollapseAll();return}if(G(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(G(t,o.listPin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleListPin();return}if(G(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(G(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(G(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(G(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let 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 k.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&(this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.authorship.noteModify(t),this.debouncedRender())};this.onFileCreate=t=>{!(t instanceof k.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Ns(this.app),this.log=e.newLog(),this.integrity=new Hs(this.tree,this.log),this.order=new ai(this.app),this.sortStore=new xs(this.app),this.fmSync=new Ts(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):Oa(this,i,n);return this.hoistListPinned(i,o)}),this.debouncedRender=(0,k.debounce)(()=>{this.renderSuppressed()||this.render()},80),this.authorship=new Rs(this),this.dnd=new Gs(this),this.bodyRenderer=new Ls(this,this,this.plugin.renderCacheStore)}getViewType(){return J}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==F){let i=this.tree.get(this.focusId);if(i){let s=this.titleForNode(i).trim(),n=s.length>40?s.slice(0,40)+"\u2026":s;if(n)return`${e} \u2014 ${n} \xB7 ${this.focusId}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let i=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;i&&i.textContent!==t&&i.setText(t)}getIcon(){return"list-tree"}async onOpen(){let t=this.contentEl;t.empty(),t.addClass("stashpad-scroll-host"),this.viewRoot=t.createDiv({cls:"stashpad-view"}),this.viewRoot.setAttribute("tabindex","0"),this.viewRoot.addEventListener("focusin",()=>vs(this)),this.viewRoot.addEventListener("click",()=>vs(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())}),vs(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new k.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.inListPicker)return this.inListPicker=null,this.pickerEscapeAt=Date.now(),this.repaintSelectionClasses(),!1;if(Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return!1;if(this.selection.size>1){let l=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,l){let c=this.currentChildren.findIndex(A=>A.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 A of[this.completedState,this.taskTaggedState])A.has(c)&&(A.set(l.path,A.get(c)),A.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("/"),A=(c>=0?l.path.slice(0,c):"").replace(/\/+$/,"");l.path.endsWith(".md")&&A===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=Ha(()=>{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,A]of l)this.lastCursorByFocus.set(c,A);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(!j().autofocusComposerAfterSend)return;let t=()=>{if(!this.viewRoot?.isConnected||Date.now()<this.suppressComposerFocusUntil||Date.now()<this.plugin.suppressComposerAutofocusUntil)return;let e=document.activeElement;e&&(e.tagName==="INPUT"||e.tagName==="TEXTAREA")&&e!==this.composerInputEl||(e&&e.tagName==="BUTTON"&&this.viewRoot.contains(e),this.composerInputEl?.focus({preventScroll:!0}))};requestAnimationFrame(t),setTimeout(t,50),setTimeout(t,200)}async onClose(){Ma(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.bodyRenderer.dispose(),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();this.authorship.dispose();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=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[A,h]of c)this.lastCursorByFocus.set(A,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 k.Notice(`"${i}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((i||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=i,this.focusId=F,this.lastCursorByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig();try{await this.bootstrapFolder()}catch(s){let n=s?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",s)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let s=this.app.workspace;typeof s.saveLayout=="function"?await s.saveLayout():this.app.workspace.requestSaveLayout()}catch{this.app.workspace.requestSaveLayout()}this.refreshHeaderTitle(),this.render()}}cmdOpenFolderPicker(){this.openFolderPicker()}openFolderPicker(){this.plugin.openFolderPicker()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof k.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,i)=>e.localeCompare(i))}isReservedFolder(t){let e=t.split("/").filter(Boolean).pop()??"";return e?new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed","_authors"].map(s=>(s??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(e):!1}persistFocus(){try{this.app.workspace.requestSaveLayout()}catch{}}cmdUndo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canUndo()){new k.Notice("Nothing to undo.");return}let e=t.peekUndoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.undo().then(()=>this.plugin.notifications.show({message:`Undid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Undo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new k.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Redo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let i=[],s=new Set;for(let l of t)!l.file||s.has(l.file.path)||(s.add(l.file.path),i.push(l.file));let n=await Promise.all(i.map(l=>this.app.vault.read(l))),o=i.map((l,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 A=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:A[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,k.moment)();switch(this.timeFilter){case"day":return e.startOf("day").valueOf();case"week":return e.startOf("isoWeek").valueOf();case"month":return e.startOf("month").valueOf();case"year":return e.startOf("year").valueOf()}}let t=Date.now();switch(this.timeFilter){case"day":return t-864e5;case"week":return t-7*864e5;case"month":return t-30*864e5;case"year":return t-365*864e5}return null}allowedByBases(){return null}currentViewMode(){return this.plugin.settings.viewModes?.[this.noteFolder]??"nested"}currentIncludeAttachments(){return!!this.plugin.settings.includeAttachmentsInEverything?.[this.noteFolder]}async setIncludeAttachments(t){let e={...this.plugin.settings.includeAttachmentsInEverything??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.includeAttachmentsInEverything=e,await this.plugin.saveSettings()}currentEncryptionFilter(){return this.plugin.settings.encryptionFilter?.[this.noteFolder]??"all"}async setEncryptionFilter(t){let e={...this.plugin.settings.encryptionFilter??{}};t==="all"?delete e[this.noteFolder]:e[this.noteFolder]=t,this.plugin.settings.encryptionFilter=e,await this.plugin.saveSettings()}currentHideChildless(){return!!this.plugin.settings.hideChildlessNotes?.[this.noteFolder]}async setHideChildless(t){let e={...this.plugin.settings.hideChildlessNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideChildlessNotes=e,await this.plugin.saveSettings()}currentHideCompleted(){return!!this.plugin.settings.hideCompletedNotes?.[this.noteFolder]}async setHideCompleted(t){let e={...this.plugin.settings.hideCompletedNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.hideCompletedNotes=e,await this.plugin.saveSettings()}currentAttachmentsOnly(){return!!this.plugin.settings.attachmentsOnlyNotes?.[this.noteFolder]}async setAttachmentsOnly(t){let e={...this.plugin.settings.attachmentsOnlyNotes??{}};t?e[this.noteFolder]=!0:delete e[this.noteFolder],this.plugin.settings.attachmentsOnlyNotes=e,await this.plugin.saveSettings()}nodeHasAttachment(t){if(!t.file)return!1;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.attachments;return Array.isArray(e)&&e.length>0}hasAttachmentInSubtree(t){if(this.nodeHasAttachment(t))return!0;for(let e of this.tree.getChildren(t.id))if(this.hasAttachmentInSubtree(e))return!0;return!1}hasIncompleteDescendant(t){for(let e of t.children){let i=this.tree.get(e);if(i&&(!this.isCompleted(i)||this.hasIncompleteDescendant(i)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof k.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof k.TFolder){s.push(o);continue}if(!(o instanceof k.TFile)||o.extension!=="md")continue;let 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=Se(l),A=this.app.metadataCache.getFirstLinkpathDest(c,o.path);A?t.add(A.path):t.add(c)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof k.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),r=[],l=[i];for(;l.length;){let c=l.pop();for(let A of c.children){if(A instanceof k.TFolder){let h=A.name;if(c===i&&o.has(h)||c===i&&h==="_attachments"&&!s)continue;l.push(A);continue}A instanceof k.TFile&&A.extension!=="md"&&(A.name===".stashpad-order.json"||A.name===".stashpad-sort.json"||!s&&n.has(A.path)||r.push(A))}}return r}populateListBody(t,e){if(this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),this.pendingCursorId){let A=this.currentChildren.findIndex(h=>h.id===this.pendingCursorId);A>=0&&(this.cursorIdx=A,this.selection.clear(),this.selection.add(this.pendingCursorId),this.lastSelected=this.pendingCursorId,this.pendingCursorId=null)}e.file&&k.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode(),s=i==="everything"?this.collectFileItems(e.id):[],n=A=>A.created&&Number.isFinite(Date.parse(A.created))?Date.parse(A.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 A=new Set([e.id,...this.currentChildren.map(g=>g.id)]),h=new Set;r=[];for(let g of A)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(A=>({lk:A,ts:n(A)})).sort((A,h)=>A.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 A=new Map(this.currentChildren.map((I,f)=>[I.id,f])),h=new Map;for(let{lk:I}of l)I.rootId&&h.set(I.rootId,I);let g=this.currentChildren.map(I=>I.id),u=l.map(({lk:I})=>I).filter(I=>I.rootId).sort((I,f)=>n(f)-n(I)),p=!0;for(;u.length&&p;){p=!1;for(let I=0;I<u.length;I++){let f=u[I],m=f.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,f.rootId),u.splice(I,1),I--,p=!0}}for(let I of u)g.push(I.rootId);for(let I of g){let f=A.get(I);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let m=h.get(I);m&&this.renderLockedPlaceholder(t,m)}}for(let I of s.slice().sort((f,m)=>f.stat.ctime-m.stat.ctime))this.renderFileRow(t,I)}else if(s.length===0){let A=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(;A<l.length&&l[A].ts<=g;)this.renderLockedPlaceholder(t,l[A].lk),A++;this.renderNote(t,this.currentChildren[h],h)}for(;A<l.length;)this.renderLockedPlaceholder(t,l[A].lk),A++}else{let A=[...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}))];A.sort((h,g)=>h.ts-g.ts);for(let h of A)h.kind==="note"?this.renderNote(t,this.currentChildren[h.idx],h.idx):h.kind==="file"?this.renderFileRow(t,h.file):this.renderLockedPlaceholder(t,h.lk)}e.file&&k.Platform.isMobile&&this.installFocusedMiniObserver(t)}renderLockedPlaceholder(t,e){let i=t.createDiv({cls:"stashpad-locked-row"});e.created&&i.createSpan({cls:"stashpad-note-time stashpad-locked-time",text:this.formatTime(e.created)});let s=i.createSpan({cls:"stashpad-locked-icon"});(0,k.setIcon)(s,"lock");let n=(this.plugin.settings.hideLockedTitles??!1)||!e.title;i.createSpan({cls:"stashpad-locked-title",text:n?"Locked note":e.title}),i.createSpan({cls:"stashpad-locked-count",text:e.count>1?`${e.count} notes \xB7 locked`:"locked"});let o=i.createEl("button",{cls:"stashpad-locked-unlock",text:"Unlock"});(0,k.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let r=async c=>{c.preventDefault(),c.stopPropagation();let A=(this.plugin.settings.lockedSubtrees??[]).find(I=>I.blob===e.blob),h=e.rootId??A?.rootId??null,g=e.parentId??A?.parentId??F,u=e.prevSibling??A?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,h){let I=this.order.getOrder(this.noteFolder,g),f=this.sortStore.getMode(this.noteFolder,g)==="manual";if(I.length===0&&f&&(I=this.tree.getChildren(g).map(m=>m.id)),I.length>0){let m=I.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 A=new k.Menu;if(A.addItem(h=>h.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void r(c))),!k.Platform.isMobile){let h=k.Platform.isMacOS?"Finder":k.Platform.isWin?"File Explorer":"file manager";A.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)}}))}A.addItem(h=>h.setTitle("Export to .stash\u2026").setIcon("package").onClick(()=>{this.plugin.exportLockedSubtree(e.blob)})),A.addItem(h=>h.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let g=e.blob;if(!k.Platform.isMobile)try{g=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(g),new k.Notice("Path copied.")})),A.showAtMouseEvent(c)};if(i.oncontextmenu=l,k.Platform.isMobile){let c=i.createEl("button",{cls:"stashpad-locked-menu"});(0,k.setIcon)(c,"more-vertical"),c.setAttr("aria-label","Locked note menu"),c.onclick=A=>l(A)}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 A=ue(this.app.metadataCache.getFileCache(c.file)?.frontmatter?.author);if(!A||A.id!==l)return!1}if(e&&c.created){let A=Date.parse(c.created);if(!Number.isNaN(A)&&A<e)return!1}if(i){if(!c.file)return!1;if(this.tagFilter===be){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=ft(this.app,n);if(!Ii(o))continue;i=!0;let r=Ot(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=>Ii(ft(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 Jo(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){Ft.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",k.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let l=this.containerEl.closest(".workspace-leaf");l&&(l.classList.toggle("stashpad-is-tiny",this.tinyMode),l.classList.toggle("stashpad-is-compact",this.compactMode));let c=this.containerEl.closest(".workspace-tabs");c&&c.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let A=this.tree.get(this.focusId)??this.tree.getRoot();A.file&&!k.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,A),this.currentChildren=this.filterChildren(this.collectViewItems(A.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 I=-1;for(let f of p){let m=this.currentChildren.findIndex(C=>C.id===f);m>=0&&(this.selection.add(f),I<0&&(I=m))}this.cursorIdx=I,I>=0&&(this.lastSelected=p.find(f=>this.currentChildren.some(m=>m.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let g=e.createDiv({cls:"stashpad-list"});if(this.listEl=g,this.dnd.attachListDnD(g),this.populateListBody(g,A),this.renderComposer(e),k.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(Ft.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 I=this.composerInputEl;if(I&&I.isConnected){if(I.focus({preventScroll:!0}),p!=null){let f=Math.min(p,I.value.length);try{I.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),p!=null)){let m=Math.min(p,f.value.length);try{f.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 I=u.scrollTop,f=this.listEl,m=()=>{this.suppressScrollSave=!0;let C=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(I,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 I=u.id,f=u.align,m=this.listEl,C=()=>{this.suppressScrollSave=!0;let B=m.querySelector(`[data-id="${I}"]`);B&&B.scrollIntoView({block:f,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,I=p.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){p.scrollTop=p.scrollHeight,I=p.scrollTop;return}let C=Math.max(0,p.scrollHeight-p.clientHeight);p.scrollTop<I&&I<=C?p.scrollTop=I:I=p.scrollTop});f.observe(p),this.listResizeObserver=f,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})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),i=e.createEl("button",{cls:"stashpad-folder-btn"}),s=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,k.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=u=>{u.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});Ht(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=u=>{u.preventDefault(),this.openSearchModal()},k.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let r=e.createDiv({cls:"stashpad-time-filter-btns"}),l=r.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,k.setIcon)(l,this.timeFilterCalendar?"calendar":"history"),l.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&l.addClass("is-active"),l.onclick=u=>{u.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let u of Zs){let g=this.timeFilterCalendar?u.calShort:u.rollShort,I=this.timeFilterCalendar?u.calLong:u.rollLong,m=r.createEl("button",{cls:"stashpad-time-filter-btn",text:g});m.title=I,this.timeFilter===u.key&&m.addClass("is-active"),m.onclick=f=>{f.preventDefault(),this.setTimeFilter(u.key)}}let c=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let u of Zs){let g=this.timeFilterCalendar?u.calLong:u.rollLong,I=c.createEl("option",{text:g});I.value=u.key,this.timeFilter===u.key&&(I.selected=!0)}c.onchange=()=>this.setTimeFilter(c.value);let A=e.createDiv({cls:"stashpad-view-mode-btns"});if(!k.Platform.isMobile){let u=A.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(u,"minimize-2"),u.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",u.onclick=g=>{g.preventDefault(),this.plugin.openTinyWindow()}}let h=A.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,k.setIcon)(h,this.compactMode?"panel-top":"rows-2"),h.title=this.compactMode?"Compact mode is ON \u2014 click to restore full chrome.":"Compact mode \u2014 hide the filter row + focused header; keep breadcrumb + list + composer.",this.compactMode&&h.addClass("is-active"),h.onclick=u=>{u.preventDefault(),this.toggleCompactMode()},k.Platform.isMobile)return;let p=A.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(p,"external-link"),p.title=j().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",p.onclick=u=>{u.preventDefault();let g=j().popoutDuplicates;try{let I=this.app.workspace;if(g){let m=this.leaf.getViewState(),f=I.openPopoutLeaf?.();f?f.setViewState({...m,active:!0}):new k.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else I.moveLeafToPopout?.(this.leaf)}catch(I){new k.Notice(`Stashpad: open-in-new-window failed (${I.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"});Ht(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==F;i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=A=>{A.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ht(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=A=>{A.preventDefault(),this.navigateForward()};let r=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),l=this.mobileSelectMode;Ht(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=A=>{if(A.preventDefault(),this.mobileSelectMode){let h=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),h){let p=this.currentChildren.findIndex(u=>u.id===h);this.selection.add(h),this.lastSelected=h,p>=0&&(this.cursorIdx=p)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let h=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),h&&(this.selection.add(h.id),this.lastSelected=h.id,this.firstSelectedId=h.id),this.render(),new k.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let c=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ht(c,"zap","\u26A1"),c.title="Actions (move, delete, undo, \u2026)",c.onclick=A=>{A.preventDefault(),this.openMobileActionsMenu(c)}}openMobileActionsMenu(t){let e=new k.Menu,i=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],s=this.selection.size<=1;e.addItem(o=>o.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(o=>o.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(o=>o.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addItem(o=>o.setTitle("Reload without saving").setIcon("rotate-ccw").onClick(()=>this.plugin.reloadAppForUpdate())),e.addSeparator(),e.addItem(o=>o.setTitle("Expand all").setIcon("unfold-vertical").onClick(()=>this.cmdExpandAll())),e.addItem(o=>o.setTitle("Collapse all").setIcon("fold-vertical").onClick(()=>this.cmdCollapseAll())),e.addSeparator(),e.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!i).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(o=>o.setTitle("Open in editor").setIcon("pencil").setDisabled(!i).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(o=>o.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!i).onClick(()=>this.cmdMovePicker())),e.addItem(o=>o.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!i).onClick(()=>this.cmdInListPicker())),e.addItem(o=>o.setTitle("Outdent").setIcon("outdent").setDisabled(!i).onClick(()=>void this.cmdOutdent())),e.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").setDisabled(!i).onClick(()=>this.cmdSetColor())),e.addItem(o=>o.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!i).onClick(()=>void this.cmdToggleComplete())),e.addItem(o=>o.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!i).onClick(()=>void this.cmdToggleTask())),e.addItem(o=>o.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!i).onClick(()=>this.cmdSetDue())),e.addItem(o=>o.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!i).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(o=>o.setTitle("Copy").setIcon("copy").setDisabled(!i).onClick(()=>void this.cmdCopy())),e.addItem(o=>o.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!i).onClick(()=>void this.cmdCopyTree())),e.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!i).onClick(()=>void this.cmdClone())),this.plugin.settings.enableSheetVersions&&(e.addItem(o=>o.setTitle("Fork as a version (draft)").setIcon("git-fork").setDisabled(!i||!s).onClick(()=>void this.cmdForkVersion())),e.addItem(o=>o.setTitle("Mark version as final").setIcon("star").setDisabled(!i||!s).onClick(()=>void this.cmdMarkVersionFinal()))),e.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(o=>o.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(o=>o.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!i||!s).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(o=>o.setTitle("Delete").setIcon("trash-2").setDisabled(!i).onClick(()=>void this.cmdDelete())),e.addSeparator(),e.addItem(o=>o.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}openCommandPalette(){this.app.commands?.executeCommandById?.("command-palette:open")}openStashpadCommandPalette(){new Hs(this.app).open()}tagFilterLabel(){return this.tagFilter===be?"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"});Ht(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(Q=>Q.remove());let i=e.body.createDiv({cls:"stashpad-tag-filter-popover"}),s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${Math.max(s.width,200)}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=new k.Scope(this.app.scope),o=()=>{i.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(n)}catch{}},r=Q=>{!i.contains(Q.target)&&Q.target!==t&&!t.contains(Q.target)&&o()},l=i.createDiv({cls:"stashpad-tag-filter-search"}),c=l.createSpan({cls:"stashpad-tag-filter-search-icon"});Ht(c,"search","\u2315");let A=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"}});Ht(h,"x","\xD7"),h.setCssStyles({display:"none"});let p=i.createDiv({cls:"stashpad-tag-filter-list"}),u=this.collectFolderTags(),g=[],I=0,m=Q=>{this.setTagFilter(Q),o()},f=Q=>{if(g.length===0){I=0;return}I=(Q+g.length)%g.length,g.forEach((y,E)=>y.el.toggleClass("is-highlighted",E===I)),g[I].el.scrollIntoView({block:"nearest"})},C=(Q,y,E,v)=>{let w=p.createDiv({cls:"stashpad-tag-filter-row"});v&&w.addClass("is-active"),w.createSpan({cls:"stashpad-tag-filter-row-label",text:Q}),typeof E=="number"&&w.createSpan({cls:"stashpad-tag-filter-row-count",text:String(E)});let D=g.length;g.push({value:y,el:w}),w.onmousedown=b=>{b.preventDefault(),m(y)},w.onmouseenter=()=>f(D)},B=()=>{let Q=A.value;h.setCssStyles({display:Q?"":"none"}),p.empty(),g=[];let y=this.tagFilter?.toLowerCase();if(Q.trim()){let E=Zo(Q,u);if(E.length===0)p.createDiv({cls:"stashpad-tag-filter-empty",text:"No matching tags"});else for(let v of E)C(`#${v.label}`,v.raw,v.count,y===v.raw.toLowerCase())}else{C("All tags",null,void 0,!this.tagFilter),C("Tagged",be,void 0,this.tagFilter===be),C("Untagged",Ne,void 0,this.tagFilter===Ne);for(let E of u)C(`#${E.label}`,E.raw,E.count,y===E.raw.toLowerCase())}f(0)};h.onclick=()=>{A.value="",B(),A.focus()},A.addEventListener("input",B),A.addEventListener("keydown",Q=>{Q.key==="ArrowDown"?(Q.preventDefault(),f(I+1)):Q.key==="ArrowUp"?(Q.preventDefault(),f(I-1)):Q.key==="Enter"&&(Q.preventDefault(),g[I]&&m(g[I].value))}),n.register([],"Escape",Q=>(Q.preventDefault(),o(),!1)),this.app.keymap?.pushScope(n),B(),setTimeout(()=>{e.addEventListener("mousedown",r,!0),A.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 k.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,k.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 (${Xs[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(c.setText(qi[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: ${qi[s]}. Drag-reorder will revert this parent to Manual.`);let A=h=>{o||(h.preventDefault(),this.openSortMenu(r))};r.onclick=A,r.onkeydown=h=>{o||(h.key==="Enter"||h.key===" ")&&A(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 k.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,k.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=A=>{A.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=c,e.onkeydown=A=>{(A.key==="Enter"||A.key===" ")&&c(A)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(p=>p.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.setCssStyles({right:`${Math.max(8,n.innerWidth-s.right)}px`,left:"auto",top:`${s.bottom+4}px`,maxWidth:"min(360px, calc(100vw - 16px))",width:"max-content",minWidth:"260px"});let o=()=>{i.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(h)}catch{}},r=p=>{!i.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&o()},l=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let p=Zs.find(u=>u.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":qi[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:p=>{if(this.currentViewMode()!=="nested"){p.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(p,o)}},{key:"view",title:"View",summary:()=>Xs[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,o)}],c="",A=()=>{i.empty();for(let p of l){let u=i.createDiv({cls:"stashpad-mobile-filters-section"}),g=u.createDiv({cls:"stashpad-mobile-filters-header"}),I=g.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,k.setIcon)(I,c===p.key?"chevron-down":"chevron-right"),g.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),g.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),g.onclick=m=>{m.preventDefault(),m.stopPropagation(),c=c===p.key?"":p.key,A()},c===p.key){let m=u.createDiv({cls:"stashpad-mobile-filters-body"});p.populate(m)}}};A();let h=new k.Scope(this.app.scope);h.register([],"Escape",p=>(p.preventDefault(),o(),!1)),this.app.keymap?.pushScope(h),setTimeout(()=>{e.addEventListener("mousedown",r,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),i=t.createDiv({cls:"stashpad-view-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-view-icon"});(0,k.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(Xs[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"});k.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${s.width}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(r)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateViewMenuBody(i,n);let r=new k.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,E)=>{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:Xs[y]}),v.createDiv({cls:"stashpad-view-popover-desc",text:E}),v.onclick=async D=>{D.preventDefault(),D.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(),E=(v,w,D)=>{let b=t.createDiv({cls:"stashpad-view-popover-row"});v===y&&b.addClass("is-active"),b.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:w}),b.createDiv({cls:"stashpad-view-popover-desc",text:D}),b.onclick=async H=>{H.preventDefault(),H.stopPropagation(),v!==y&&(await this.setEncryptionFilter(v),this.refreshList()),e()}};E("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),E("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),E("unlocked","Encryption: decrypted only","Hide locked \u{1F512} stubs."),t.createDiv({cls:"stashpad-view-popover-divider"})}let n=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),o=n.createEl("input",{type:"checkbox"});o.checked=this.currentHideChildless(),n.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),n.createDiv({cls:"stashpad-view-popover-desc",text:i==="nested"?"Show only notes that have children. Applied at this level.":"Hide top-level notes without children; keep every parent's full subtree so no task is overlooked."}),n.onclick=async 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"}),A=c.createEl("input",{type:"checkbox"});A.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!==A&&(y.preventDefault(),A.checked=!A.checked),await this.setAttachmentsOnly(A.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 p=h.createEl("input",{type:"checkbox"});p.checked=this.currentIncludeAttachments(),p.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!==p&&(y.preventDefault(),p.checked=!p.checked),await this.setIncludeAttachments(p.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let u=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),g=u.createEl("input",{type:"checkbox"});g.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!==g&&(y.preventDefault(),g.checked=!g.checked),this.importedOnly=g.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let I=new Map,m=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==m)continue;let E=ue(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);E&&I.set(E.id,E.name)}let f=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),C=f.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"}),Q=B.createEl("option",{text:"All authors",value:""});this.authorFilter||(Q.selected=!0);for(let[y,E]of[...I.entries()].sort((v,w)=>v[1].localeCompare(w[1]))){let v=B.createEl("option",{text:E,value:y});this.authorFilter===y&&(v.selected=!0)}B.onclick=y=>y.stopPropagation(),B.onchange=()=>{this.authorFilter=B.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},f.createDiv({cls:"stashpad-view-popover-desc",text:I.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 to){let r=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&r.addClass("is-active"),r.createSpan({cls:"stashpad-sort-popover-label",text:qi[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 Zs){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 A=l.createSpan({cls:"stashpad-color-filter-popover-label"});A.setText(n),o&&(A.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=A=>{A.preventDefault(),A.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null),s("Tagged",be),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"});Ht(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==F||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Ht(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===F?r:`${r} / ${this.titleForNode(o).trim()}`,c=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),A=c.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,k.setIcon)(A,"folder"),c.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:l}),c.title=`${this.noteFolder}${this.focusId!==F?` / ${this.titleForNode(o).trim()}`:""} -Click to switch / create folder.`,c.onclick=I=>{I.preventDefault(),this.plugin.openFolderPicker()};let h=e.createDiv({cls:"stashpad-tiny-sticky"}),p=h.createEl("input",{type:"checkbox"});if(p.checked=this.tinyAlwaysOnTop,h.createSpan({text:"Sticky"}),p.onchange=()=>{this.tinyAlwaysOnTop=p.checked,this.applyTinyAlwaysOnTop()},!k.Platform.isMobile){let I=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,k.setIcon)(I,"contrast"),I.title="Window transparency",this.tinyOpacity<1&&I.addClass("is-active"),I.onclick=m=>{m.stopPropagation(),this.toggleTinyOpacityPopover(I)}}let u=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,k.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 g=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,k.setIcon)(g,"maximize-2"),g.title="Exit tiny mode",g.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 A=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=A/100,s.setText(`${A}%`),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=A=>{e.contains(A.target)||A.target===t||t.contains(A.target)||c()},l=A=>{A.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),k.Platform.isMacOS??!1){let i=this.containerEl?.ownerDocument?.defaultView?.require?.("electron")??window.require?.("electron"),n=(i?.remote?.screen??i?.screen)?.getPrimaryDisplay?.().workArea;n?t?.setBounds?.({x:n.x,y:n.y,width:n.width,height:n.height}):t?.maximize?.()}else t?.maximize?.()}catch{}this.render();try{await this.app.workspace.requestSaveLayout?.()}catch{}}enterTinyMode(){this.tinyMode=!0,this.applyTinyWindow(),this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderBreadcrumb(t){let e=t.createDiv({cls:"stashpad-breadcrumb"});this.renderActionsCluster(e);let i=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(k.Platform.isMobile?((0,k.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(F),this.focusId===F){let A=this.tree.getChildren(this.focusId).length;if(A>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${A}`}).title=`${A} direct child${A===1?"":"ren"}`),this.compactMode){let h=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(h,"panel-top"),h.title="Exit compact mode",h.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),r=o.map(A=>{let h=this.titleForNode(A),p=h.length>s?h.slice(0,s-1)+"\u2026":h;return{id:A.id,label:p}}),l=A=>A.reduce((h,p)=>h+p.label.length+3,0);if(l(r)>n&&r.length>2){let A=!1;for(;l(r)>n&&r.length>2;)r.splice(1,1),A||(r.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),A=!0)}for(let A of r)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),A.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:A.label}).title=o.map(h=>this.titleForNode(h)).join(" / ");else{let h=A.id,p=e.createSpan({cls:"stashpad-crumb",text:A.label});p.title=A.label,p.onclick=()=>this.navigateTo(h),p.oncontextmenu=u=>{u.preventDefault(),this.openCrumbMenu(u,h)},k.Platform.isMobile&&this.attachLongPress(p,()=>this.openCrumbMenu(null,h))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",A=>{A.preventDefault(),this.openCrumbMenu(A,F)}),k.Platform.isMobile){let A=e.querySelector(".stashpad-crumb-home");A&&this.attachLongPress(A,()=>this.openCrumbMenu(null,F))}let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let A=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(A,"panel-top"),A.title="Exit compact mode",A.onclick=h=>{h.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",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){let i=this.tree.get(e);if(!i)return;let s=new k.Menu;if(s.addItem(n=>n.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),s.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(i))),i.file&&s.addItem(n=>n.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(i))),t&&(t.clientX>0||t.clientY>0))s.showAtMouseEvent(t);else{let o=(t?.target??null)?.getBoundingClientRect();s.showAtPosition({x:o?.left??8,y:(o?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused-mini"});s.dataset.id=e.id,s.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let o=s.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,k.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=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,k.setIcon)(c,"pencil"),c.title="Edit in new tab",c.onclick=()=>void this.openFileAtEnd(i);let A=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,k.setIcon)(A,"copy"),A.title="Open this Stashpad in a new tab (clone)",A.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(r,e,{clamp:k.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=A=>{A.stopPropagation(),this.navigateTo(r.id)},l<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Is(this.app,t,k.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(` +Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=u=>{u.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});Ht(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=u=>{u.preventDefault(),this.openSearchModal()},k.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let r=e.createDiv({cls:"stashpad-time-filter-btns"}),l=r.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,k.setIcon)(l,this.timeFilterCalendar?"calendar":"history"),l.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&l.addClass("is-active"),l.onclick=u=>{u.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let u of tn){let p=this.timeFilterCalendar?u.calShort:u.rollShort,I=this.timeFilterCalendar?u.calLong:u.rollLong,f=r.createEl("button",{cls:"stashpad-time-filter-btn",text:p});f.title=I,this.timeFilter===u.key&&f.addClass("is-active"),f.onclick=m=>{m.preventDefault(),this.setTimeFilter(u.key)}}let c=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let u of tn){let p=this.timeFilterCalendar?u.calLong:u.rollLong,I=c.createEl("option",{text:p});I.value=u.key,this.timeFilter===u.key&&(I.selected=!0)}c.onchange=()=>this.setTimeFilter(c.value);let A=e.createDiv({cls:"stashpad-view-mode-btns"});if(!k.Platform.isMobile){let u=A.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(u,"minimize-2"),u.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",u.onclick=p=>{p.preventDefault(),this.plugin.openTinyWindow()}}let h=A.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,k.setIcon)(h,this.compactMode?"panel-top":"rows-2"),h.title=this.compactMode?"Compact mode is ON \u2014 click to restore full chrome.":"Compact mode \u2014 hide the filter row + focused header; keep breadcrumb + list + composer.",this.compactMode&&h.addClass("is-active"),h.onclick=u=>{u.preventDefault(),this.toggleCompactMode()},k.Platform.isMobile)return;let g=A.createEl("button",{cls:"stashpad-view-mode-btn"});(0,k.setIcon)(g,"external-link"),g.title=j().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",g.onclick=u=>{u.preventDefault();let p=j().popoutDuplicates;try{let I=this.app.workspace;if(p){let f=this.leaf.getViewState(),m=I.openPopoutLeaf?.();m?m.setViewState({...f,active:!0}):new k.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else I.moveLeafToPopout?.(this.leaf)}catch(I){new k.Notice(`Stashpad: open-in-new-window failed (${I.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"});Ht(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==F;i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=A=>{A.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ht(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=A=>{A.preventDefault(),this.navigateForward()};let r=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),l=this.mobileSelectMode;Ht(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=A=>{if(A.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 k.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let c=e.createEl("button",{cls:"stashpad-mobile-action-btn"});Ht(c,"zap","\u26A1"),c.title="Actions (move, delete, undo, \u2026)",c.onclick=A=>{A.preventDefault(),this.openMobileActionsMenu(c)}}openMobileActionsMenu(t){let e=new k.Menu,i=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],s=this.selection.size<=1;e.addItem(o=>o.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(o=>o.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(o=>o.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addItem(o=>o.setTitle("Reload without saving").setIcon("rotate-ccw").onClick(()=>this.plugin.reloadAppForUpdate())),e.addSeparator(),e.addItem(o=>o.setTitle("Expand all").setIcon("unfold-vertical").onClick(()=>this.cmdExpandAll())),e.addItem(o=>o.setTitle("Collapse all").setIcon("fold-vertical").onClick(()=>this.cmdCollapseAll())),e.addSeparator(),e.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!i).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(o=>o.setTitle("Open in editor").setIcon("pencil").setDisabled(!i).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(o=>o.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!i).onClick(()=>this.cmdMovePicker())),e.addItem(o=>o.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!i).onClick(()=>this.cmdInListPicker())),e.addItem(o=>o.setTitle("Outdent").setIcon("outdent").setDisabled(!i).onClick(()=>void this.cmdOutdent())),e.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").setDisabled(!i).onClick(()=>this.cmdSetColor())),e.addItem(o=>o.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!i).onClick(()=>void this.cmdToggleComplete())),e.addItem(o=>o.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!i).onClick(()=>void this.cmdToggleTask())),e.addItem(o=>o.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!i).onClick(()=>this.cmdSetDue())),e.addItem(o=>o.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!i).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(o=>o.setTitle("Copy").setIcon("copy").setDisabled(!i).onClick(()=>void this.cmdCopy())),e.addItem(o=>o.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!i).onClick(()=>void this.cmdCopyTree())),e.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!i).onClick(()=>void this.cmdClone())),this.plugin.settings.enableSheetVersions&&(e.addItem(o=>o.setTitle("Fork as a version (draft)").setIcon("git-fork").setDisabled(!i||!s).onClick(()=>void this.cmdForkVersion())),e.addItem(o=>o.setTitle("Mark version as final").setIcon("star").setDisabled(!i||!s).onClick(()=>void this.cmdMarkVersionFinal()))),e.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(o=>o.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(o=>o.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!i||!s).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(o=>o.setTitle("Delete").setIcon("trash-2").setDisabled(!i).onClick(()=>void this.cmdDelete())),e.addSeparator(),e.addItem(o=>o.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}openCommandPalette(){this.app.commands?.executeCommandById?.("command-palette:open")}openStashpadCommandPalette(){new Us(this.app).open()}tagFilterLabel(){return this.tagFilter===be?"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"});Ht(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(Q=>Q.remove());let i=e.body.createDiv({cls:"stashpad-tag-filter-popover"}),s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${Math.max(s.width,200)}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=new k.Scope(this.app.scope),o=()=>{i.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(n)}catch{}},r=Q=>{!i.contains(Q.target)&&Q.target!==t&&!t.contains(Q.target)&&o()},l=i.createDiv({cls:"stashpad-tag-filter-search"}),c=l.createSpan({cls:"stashpad-tag-filter-search-icon"});Ht(c,"search","\u2315");let A=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"}});Ht(h,"x","\xD7"),h.setCssStyles({display:"none"});let g=i.createDiv({cls:"stashpad-tag-filter-list"}),u=this.collectFolderTags(),p=[],I=0,f=Q=>{this.setTagFilter(Q),o()},m=Q=>{if(p.length===0){I=0;return}I=(Q+p.length)%p.length,p.forEach((y,E)=>y.el.toggleClass("is-highlighted",E===I)),p[I].el.scrollIntoView({block:"nearest"})},C=(Q,y,E,v)=>{let w=g.createDiv({cls:"stashpad-tag-filter-row"});v&&w.addClass("is-active"),w.createSpan({cls:"stashpad-tag-filter-row-label",text:Q}),typeof E=="number"&&w.createSpan({cls:"stashpad-tag-filter-row-count",text:String(E)});let D=p.length;p.push({value:y,el:w}),w.onmousedown=b=>{b.preventDefault(),f(y)},w.onmouseenter=()=>m(D)},B=()=>{let Q=A.value;h.setCssStyles({display:Q?"":"none"}),g.empty(),p=[];let y=this.tagFilter?.toLowerCase();if(Q.trim()){let E=ta(Q,u);if(E.length===0)g.createDiv({cls:"stashpad-tag-filter-empty",text:"No matching tags"});else for(let v of E)C(`#${v.label}`,v.raw,v.count,y===v.raw.toLowerCase())}else{C("All tags",null,void 0,!this.tagFilter),C("Tagged",be,void 0,this.tagFilter===be),C("Untagged",Ne,void 0,this.tagFilter===Ne);for(let E of u)C(`#${E.label}`,E.raw,E.count,y===E.raw.toLowerCase())}m(0)};h.onclick=()=>{A.value="",B(),A.focus()},A.addEventListener("input",B),A.addEventListener("keydown",Q=>{Q.key==="ArrowDown"?(Q.preventDefault(),m(I+1)):Q.key==="ArrowUp"?(Q.preventDefault(),m(I-1)):Q.key==="Enter"&&(Q.preventDefault(),p[I]&&f(p[I].value))}),n.register([],"Escape",Q=>(Q.preventDefault(),o(),!1)),this.app.keymap?.pushScope(n),B(),setTimeout(()=>{e.addEventListener("mousedown",r,!0),A.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 k.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,k.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 (${_s[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(c.setText(Ji[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: ${Ji[s]}. Drag-reorder will revert this parent to Manual.`);let A=h=>{o||(h.preventDefault(),this.openSortMenu(r))};r.onclick=A,r.onkeydown=h=>{o||(h.key==="Enter"||h.key===" ")&&A(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 k.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,k.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=A=>{A.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=c,e.onkeydown=A=>{(A.key==="Enter"||A.key===" ")&&c(A)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(g=>g.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.setCssStyles({right:`${Math.max(8,n.innerWidth-s.right)}px`,left:"auto",top:`${s.bottom+4}px`,maxWidth:"min(360px, calc(100vw - 16px))",width:"max-content",minWidth:"260px"});let o=()=>{i.remove(),e.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(h)}catch{}},r=g=>{!i.contains(g.target)&&g.target!==t&&!t.contains(g.target)&&o()},l=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:g=>this.populateTagMenuBody(g,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:g=>this.populateColorMenuBody(g,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let g=tn.find(u=>u.key===this.timeFilter);return g?this.timeFilterCalendar?g.calShort:g.rollShort:"All"},populate:g=>this.populateTimeMenuBody(g,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":Ji[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:g=>{if(this.currentViewMode()!=="nested"){g.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(g,o)}},{key:"view",title:"View",summary:()=>_s[this.currentViewMode()],populate:g=>this.populateViewMenuBody(g,o)}],c="",A=()=>{i.empty();for(let g of l){let u=i.createDiv({cls:"stashpad-mobile-filters-section"}),p=u.createDiv({cls:"stashpad-mobile-filters-header"}),I=p.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,k.setIcon)(I,c===g.key?"chevron-down":"chevron-right"),p.createSpan({cls:"stashpad-mobile-filters-title",text:g.title}),p.createSpan({cls:"stashpad-mobile-filters-summary",text:g.summary()}),p.onclick=f=>{f.preventDefault(),f.stopPropagation(),c=c===g.key?"":g.key,A()},c===g.key){let f=u.createDiv({cls:"stashpad-mobile-filters-body"});g.populate(f)}}};A();let h=new k.Scope(this.app.scope);h.register([],"Escape",g=>(g.preventDefault(),o(),!1)),this.app.keymap?.pushScope(h),setTimeout(()=>{e.addEventListener("mousedown",r,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),i=t.createDiv({cls:"stashpad-view-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-view-icon"});(0,k.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(_s[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"});k.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.setCssStyles({left:`${Math.max(8,s.left)}px`,top:`${s.bottom+4}px`,minWidth:`${s.width}px`,maxWidth:"min(320px, calc(100vw - 16px))",width:"max-content"});let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(r)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&n()};this.populateViewMenuBody(i,n);let r=new k.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,E)=>{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:_s[y]}),v.createDiv({cls:"stashpad-view-popover-desc",text:E}),v.onclick=async D=>{D.preventDefault(),D.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(),E=(v,w,D)=>{let b=t.createDiv({cls:"stashpad-view-popover-row"});v===y&&b.addClass("is-active"),b.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:w}),b.createDiv({cls:"stashpad-view-popover-desc",text:D}),b.onclick=async H=>{H.preventDefault(),H.stopPropagation(),v!==y&&(await this.setEncryptionFilter(v),this.refreshList()),e()}};E("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),E("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),E("unlocked","Encryption: decrypted only","Hide locked \u{1F512} stubs."),t.createDiv({cls:"stashpad-view-popover-divider"})}let n=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),o=n.createEl("input",{type:"checkbox"});o.checked=this.currentHideChildless(),n.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),n.createDiv({cls:"stashpad-view-popover-desc",text:i==="nested"?"Show only notes that have children. Applied at this level.":"Hide top-level notes without children; keep every parent's full subtree so no task is overlooked."}),n.onclick=async 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"}),A=c.createEl("input",{type:"checkbox"});A.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!==A&&(y.preventDefault(),A.checked=!A.checked),await this.setAttachmentsOnly(A.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 I=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let E=ue(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);E&&I.set(E.id,E.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"}),Q=B.createEl("option",{text:"All authors",value:""});this.authorFilter||(Q.selected=!0);for(let[y,E]of[...I.entries()].sort((v,w)=>v[1].localeCompare(w[1]))){let v=B.createEl("option",{text:E,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:I.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 so){let r=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&r.addClass("is-active"),r.createSpan({cls:"stashpad-sort-popover-label",text:Ji[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 tn){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 A=l.createSpan({cls:"stashpad-color-filter-popover-label"});A.setText(n),o&&(A.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=A=>{A.preventDefault(),A.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null),s("Tagged",be),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"});Ht(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==F||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==F?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});Ht(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===F?r:`${r} / ${this.titleForNode(o).trim()}`,c=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),A=c.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,k.setIcon)(A,"folder"),c.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:l}),c.title=`${this.noteFolder}${this.focusId!==F?` / ${this.titleForNode(o).trim()}`:""} +Click to switch / create folder.`,c.onclick=I=>{I.preventDefault(),this.plugin.openFolderPicker()};let h=e.createDiv({cls:"stashpad-tiny-sticky"}),g=h.createEl("input",{type:"checkbox"});if(g.checked=this.tinyAlwaysOnTop,h.createSpan({text:"Sticky"}),g.onchange=()=>{this.tinyAlwaysOnTop=g.checked,this.applyTinyAlwaysOnTop()},!k.Platform.isMobile){let I=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,k.setIcon)(I,"contrast"),I.title="Window transparency",this.tinyOpacity<1&&I.addClass("is-active"),I.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(I)}}let u=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,k.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,k.setIcon)(p,"maximize-2"),p.title="Exit tiny mode",p.onclick=()=>{this.exitTinyMode()}}toggleTinyOpacityPopover(t){if(this.tinyOpacityPopover){this.tinyOpacityPopover.remove(),this.tinyOpacityPopover=null;return}let e=document.createElement("div");e.className="stashpad-tiny-opacity-popover",e.createSpan({cls:"stashpad-tiny-opacity-label",text:"Transparency"});let i=e.createEl("input",{type:"range"});i.min="30",i.max="100",i.step="1",i.value=String(Math.round(this.tinyOpacity*100));let s=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${i.value}%`});i.addEventListener("input",()=>{let A=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=A/100,s.setText(`${A}%`),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=A=>{e.contains(A.target)||A.target===t||t.contains(A.target)||c()},l=A=>{A.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),k.Platform.isMacOS??!1){let i=this.containerEl?.ownerDocument?.defaultView?.require?.("electron")??window.require?.("electron"),n=(i?.remote?.screen??i?.screen)?.getPrimaryDisplay?.().workArea;n?t?.setBounds?.({x:n.x,y:n.y,width:n.width,height:n.height}):t?.maximize?.()}else t?.maximize?.()}catch{}this.render();try{await this.app.workspace.requestSaveLayout?.()}catch{}}enterTinyMode(){this.tinyMode=!0,this.applyTinyWindow(),this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderBreadcrumb(t){let e=t.createDiv({cls:"stashpad-breadcrumb"});this.renderActionsCluster(e);let i=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(k.Platform.isMobile?((0,k.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(F),this.focusId===F){let A=this.tree.getChildren(this.focusId).length;if(A>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${A}`}).title=`${A} direct child${A===1?"":"ren"}`),this.compactMode){let h=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(h,"panel-top"),h.title="Exit compact mode",h.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),r=o.map(A=>{let h=this.titleForNode(A),g=h.length>s?h.slice(0,s-1)+"\u2026":h;return{id:A.id,label:g}}),l=A=>A.reduce((h,g)=>h+g.label.length+3,0);if(l(r)>n&&r.length>2){let A=!1;for(;l(r)>n&&r.length>2;)r.splice(1,1),A||(r.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),A=!0)}for(let A of r)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),A.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:A.label}).title=o.map(h=>this.titleForNode(h)).join(" / ");else{let h=A.id,g=e.createSpan({cls:"stashpad-crumb",text:A.label});g.title=A.label,g.onclick=()=>this.navigateTo(h),g.oncontextmenu=u=>{u.preventDefault(),this.openCrumbMenu(u,h)},k.Platform.isMobile&&this.attachLongPress(g,()=>this.openCrumbMenu(null,h))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",A=>{A.preventDefault(),this.openCrumbMenu(A,F)}),k.Platform.isMobile){let A=e.querySelector(".stashpad-crumb-home");A&&this.attachLongPress(A,()=>this.openCrumbMenu(null,F))}let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let A=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,k.setIcon)(A,"panel-top"),A.title="Exit compact mode",A.onclick=h=>{h.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",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){let i=this.tree.get(e);if(!i)return;let s=new k.Menu;if(s.addItem(n=>n.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),s.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(i))),i.file&&s.addItem(n=>n.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(i))),t&&(t.clientX>0||t.clientY>0))s.showAtMouseEvent(t);else{let o=(t?.target??null)?.getBoundingClientRect();s.showAtPosition({x:o?.left??8,y:(o?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused-mini"});s.dataset.id=e.id,s.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let o=s.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,k.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=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,k.setIcon)(c,"pencil"),c.title="Edit in new tab",c.onclick=()=>void this.openFileAtEnd(i);let A=l.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,k.setIcon)(A,"copy"),A.title="Open this Stashpad in a new tab (clone)",A.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(r,e,{clamp:k.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=A=>{A.stopPropagation(),this.navigateTo(r.id)},l<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return fs(this.app,t,k.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(` `)+` \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.plugin.settings.autoExpandCursorRow&&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 A=this.currentViewMode()==="nested";c.draggable=A,A&&this.dnd.attachRowDnD(c,e,i),c.addEventListener("click",E=>this.handleRowClick(E,i,e)),c.addEventListener("dblclick",E=>{if(!this.plugin.settings.doubleClickToFocus)return;let v=this.shouldAbsorbDismissTap();if(v&&this.aimedTapTargetId&&Date.now()-this.aimedTapAt<=Xi.AIMED_TAP_WINDOW_MS){let D=this.aimedTapTargetId;this.aimedTapTargetId=null,this.traceTap("dblclick",E,i,!1),E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(D);return}if(this.traceTap("dblclick",E,i,v),v){E.preventDefault();return}E.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let h=this.isTask(e)||this.compactMode;h&&(c.addClass("is-task"),k.Platform.isMobile||this.addTaskCheckbox(c,e));let p=c.createDiv({cls:"stashpad-note-meta"}),u=p.createDiv({cls:"stashpad-note-meta-top"});u.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let g=this.colorForNode(e),I=u.createDiv({cls:"stashpad-note-grip"});g&&I.addClass("has-color"),(0,k.setIcon)(I,"grip-vertical"),I.title=g?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",I.draggable=A,A||(I.title=g?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),g&&I.style.setProperty("--stashpad-note-color",g);let m=h&&k.Platform.isMobile,f=this.isListPinned(e.id);if(n>0||m||f){let E=p.createDiv({cls:"stashpad-note-meta-bottom"});if(f){let v=E.createSpan({cls:"stashpad-note-listpin"});(0,k.setIcon)(v,"pin"),v.setAttr("aria-label","Pinned to top of list")}if(m&&this.addTaskCheckbox(E,e),n>0){let v=E.createSpan({cls:"stashpad-note-enter"});g&&(v.style.color=g),(0,k.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)}}}if(g)c.addClass("has-color"),c.style.setProperty("--stashpad-note-color",g);else{let E=this.inheritedColorForNode(e);E&&E.depth>0&&(c.addClass("has-inherited-color"),c.style.setProperty("--stashpad-inherited-color",E.hex),c.style.setProperty("--stashpad-inherited-depth",String(E.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"}),Q=c.createDiv({cls:"stashpad-note-actions"}),y;if(k.Platform.isMobile){let E=Q.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,k.setIcon)(E,"ellipsis-vertical"),E.title="Actions",E.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},y=E}else{let E=Q.createEl("button",{cls:"stashpad-pencil"});(0,k.setIcon)(E,"pencil"),E.title="Edit in new tab",E.onclick=w=>{w.stopPropagation(),this.openFileAtEnd(s)};let v=Q.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,k.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)},y=E}this.renderNoteBody(B,e,{clamp:!0,toggleHost:Q,toggleAnchor:y}),this.renderVersionTabs(C,e),c.oncontextmenu=E=>{E.preventDefault(),this.openNoteMenu(E,e)}}renderVersionTabs(t,e){if(!this.plugin.settings.enableSheetVersions||!ui(ft(this.app,e)))return;let i=Ot(ft(this.app,e)),s=e.parent??this.focusId,n=this.tree.getChildren(s),o=mn(this.app,n.filter(c=>{let A=ft(this.app,c);return ui(A)&&Ot(A)===i}));if(o.length<2)return;let r=t.createDiv({cls:"stashpad-version-tabs"});for(let c of o){let A=c.id===e.id,h=ft(this.app,c),p=Ii(h),u=Ho(h),g=r.createDiv({cls:"stashpad-version-tab"+(A?" is-active":"")+(p?" is-final":"")+(u?" is-original":"")});p&&g.createSpan({cls:"stashpad-version-star",text:"\u2605"}),g.createSpan({cls:"stashpad-version-tab-label",text:Lo(this.app,c,this.titleForNode(c).trim()||"Untitled")});let I=this.titleForNode(c).trim();g.title=u?`${I} (original)`:`${I} (forked)`,A||(g.onclick=m=>{m.stopPropagation(),this.setActiveVersion(i,c.id)})}let l=r.createEl("button",{cls:"stashpad-version-add",text:"+"});l.title="New version",l.onclick=c=>{c.stopPropagation(),this.cmdForkVersion(e,!0)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,k.setIcon)(i,s?"check-square":"square"),i.title=s?"Mark not done":"Mark done",i.addEventListener("mousedown",n=>n.stopPropagation()),i.addEventListener("dblclick",n=>{n.preventDefault(),n.stopPropagation()}),i.onclick=n=>{n.preventDefault(),n.stopPropagation(),this.toggleCompletedForNode(e)}}renderNoteBody(t,e,i={clamp:!0}){if(!e.file)return;if(this.bodyRenderer.hasFreshRenderCache(e.file)||!this.bodyRenderer.isArmed()){this.renderNoteBodyNow(t,e,i);return}t.empty();let s=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});s.textContent=this.titleForNode(e),this.bodyRenderer.defer(t,()=>this.renderNoteBodyNow(t,e,i))}renderNoteBodyNow(t,e,i={clamp:!0}){if(!e.file)return;let s=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.bodyRenderer.getOrComputeRender(s).then(o=>{if(t.__stashpadRenderToken!==n)return;let{text:r,attachments:l,html:c}=o;t.empty();let A=t.createDiv({cls:"stashpad-note-text"}),h=this.isNoteExpanded(e.id);if(i.clamp&&!h&&A.addClass("is-clamped"),this.compactMode||this.tinyMode?(A.addClass("is-plain"),A.textContent=r):A.append((0,k.sanitizeHTMLToDom)(c)),l.length>0&&this.renderAttachmentRail(t,l),this.renderAuthorshipFooter(t,e),!i.clamp)return;let p=this.lastListWidth;if(o.ovW===p&&o.ovV!==void 0&&!h){o.ovV?this.attachExpandToggle(i,t,e,h):A.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let u=A.scrollHeight>A.clientHeight+4;if(o.ovW=p,o.ovV=u,!u&&!h){A.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=o.createEl("button",{cls:"stashpad-expand-toggle"});r.title=s?"Show less":"Show more",n||k.Platform.isMobile?((0,k.setIcon)(r,s?"chevron-up":"chevron-down"),r.addClass("is-icon"),n&&r.addClass("is-inline")):r.setText(s?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(r,t.toggleAnchor),r.onclick=l=>{l.stopPropagation(),this.setNoteExpanded(i.id,!this.isNoteExpanded(i.id)),e.empty(),this.renderNoteBody(e,i,t)}}renderAttachmentRail(t,e){let i=t.createDiv({cls:"stashpad-rail"});for(let s of e){let n=this.app.metadataCache.getFirstLinkpathDest(s,""),o=(s.split(".").pop()??"").toLowerCase(),r=i.createDiv({cls:"stashpad-att"});if(r.title=s,n&&Dc.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)}}}renderComposer(t){let e=j(),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,k.debounce)(x=>{this.saveDraft(x)},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 k.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))},A=()=>{if(l){try{this.app.keymap?.popScope(l)}catch{}l=null}};if(r.addEventListener("focus",c),r.addEventListener("blur",A),document.activeElement===r&&c(),k.Platform.isMobile){let x=()=>{this.keyboardTransitionUntil=Date.now()+600};r.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),x()}),r.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),x(),this.tapSettleUntil=Date.now()+300,k.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=r,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new oi(this.app,r),this.composerAutocomplete.attach();let h=async x=>{let S="";for(let T of x){let P=await this.importAttachment(T);if(!P)continue;let R=r.value+S,X=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),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.plugin.settings.autoExpandCursorRow&&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 A=this.currentViewMode()==="nested";c.draggable=A,A&&this.dnd.attachRowDnD(c,e,i),c.addEventListener("click",E=>this.handleRowClick(E,i,e)),c.addEventListener("dblclick",E=>{if(!this.plugin.settings.doubleClickToFocus)return;let v=this.shouldAbsorbDismissTap();if(v&&this.aimedTapTargetId&&Date.now()-this.aimedTapAt<=Zi.AIMED_TAP_WINDOW_MS){let D=this.aimedTapTargetId;this.aimedTapTargetId=null,this.traceTap("dblclick",E,i,!1),E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(D);return}if(this.traceTap("dblclick",E,i,v),v){E.preventDefault();return}E.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let h=this.isTask(e)||this.compactMode;h&&(c.addClass("is-task"),k.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),I=u.createDiv({cls:"stashpad-note-grip"});p&&I.addClass("has-color"),(0,k.setIcon)(I,"grip-vertical"),I.title=p?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",I.draggable=A,A||(I.title=p?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),p&&I.style.setProperty("--stashpad-note-color",p);let f=h&&k.Platform.isMobile,m=this.isListPinned(e.id);if(n>0||f||m){let E=g.createDiv({cls:"stashpad-note-meta-bottom"});if(m){let v=E.createSpan({cls:"stashpad-note-listpin"});(0,k.setIcon)(v,"pin"),v.setAttr("aria-label","Pinned to top of list")}if(f&&this.addTaskCheckbox(E,e),n>0){let v=E.createSpan({cls:"stashpad-note-enter"});p&&(v.style.color=p),(0,k.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)}}}if(p)c.addClass("has-color"),c.style.setProperty("--stashpad-note-color",p);else{let E=this.inheritedColorForNode(e);E&&E.depth>0&&(c.addClass("has-inherited-color"),c.style.setProperty("--stashpad-inherited-color",E.hex),c.style.setProperty("--stashpad-inherited-depth",String(E.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"}),Q=c.createDiv({cls:"stashpad-note-actions"}),y;if(k.Platform.isMobile){let E=Q.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,k.setIcon)(E,"ellipsis-vertical"),E.title="Actions",E.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},y=E}else{let E=Q.createEl("button",{cls:"stashpad-pencil"});(0,k.setIcon)(E,"pencil"),E.title="Edit in new tab",E.onclick=w=>{w.stopPropagation(),this.openFileAtEnd(s)};let v=Q.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,k.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=w=>{w.stopPropagation(),this.navigateTo(e.id)},y=E}this.renderNoteBody(B,e,{clamp:!0,toggleHost:Q,toggleAnchor:y}),this.renderVersionTabs(C,e),c.oncontextmenu=E=>{E.preventDefault(),this.openNoteMenu(E,e)}}renderVersionTabs(t,e){if(!this.plugin.settings.enableSheetVersions||!Ii(ft(this.app,e)))return;let i=Ot(ft(this.app,e)),s=e.parent??this.focusId,n=this.tree.getChildren(s),o=yn(this.app,n.filter(c=>{let A=ft(this.app,c);return Ii(A)&&Ot(A)===i}));if(o.length<2)return;let r=t.createDiv({cls:"stashpad-version-tabs"});for(let c of o){let A=c.id===e.id,h=ft(this.app,c),g=fi(h),u=Go(h),p=r.createDiv({cls:"stashpad-version-tab"+(A?" 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:Ko(this.app,c,this.titleForNode(c).trim()||"Untitled")});let I=this.titleForNode(c).trim();p.title=u?`${I} (original)`:`${I} (forked)`,A||(p.onclick=f=>{f.stopPropagation(),this.setActiveVersion(i,c.id)})}let l=r.createEl("button",{cls:"stashpad-version-add",text:"+"});l.title="New version",l.onclick=c=>{c.stopPropagation(),this.cmdForkVersion(e,!0)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,k.setIcon)(i,s?"check-square":"square"),i.title=s?"Mark not done":"Mark done",i.addEventListener("mousedown",n=>n.stopPropagation()),i.addEventListener("dblclick",n=>{n.preventDefault(),n.stopPropagation()}),i.onclick=n=>{n.preventDefault(),n.stopPropagation(),this.toggleCompletedForNode(e)}}renderNoteBody(t,e,i={clamp:!0}){if(!e.file)return;if(this.bodyRenderer.hasFreshRenderCache(e.file)||!this.bodyRenderer.isArmed()){this.renderNoteBodyNow(t,e,i);return}t.empty();let s=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});s.textContent=this.titleForNode(e),this.bodyRenderer.defer(t,()=>this.renderNoteBodyNow(t,e,i))}renderNoteBodyNow(t,e,i={clamp:!0}){if(!e.file)return;let s=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.bodyRenderer.getOrComputeRender(s).then(o=>{if(t.__stashpadRenderToken!==n)return;let{text:r,attachments:l,html:c}=o;t.empty();let A=t.createDiv({cls:"stashpad-note-text"}),h=this.isNoteExpanded(e.id);if(i.clamp&&!h&&A.addClass("is-clamped"),this.compactMode||this.tinyMode?(A.addClass("is-plain"),A.textContent=r):A.append((0,k.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):A.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let u=A.scrollHeight>A.clientHeight+4;if(o.ovW=g,o.ovV=u,!u&&!h){A.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=o.createEl("button",{cls:"stashpad-expand-toggle"});r.title=s?"Show less":"Show more",n||k.Platform.isMobile?((0,k.setIcon)(r,s?"chevron-up":"chevron-down"),r.addClass("is-icon"),n&&r.addClass("is-inline")):r.setText(s?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(r,t.toggleAnchor),r.onclick=l=>{l.stopPropagation(),this.setNoteExpanded(i.id,!this.isNoteExpanded(i.id)),e.empty(),this.renderNoteBody(e,i,t)}}renderAttachmentRail(t,e){let i=t.createDiv({cls:"stashpad-rail"});for(let s of e){let n=this.app.metadataCache.getFirstLinkpathDest(s,""),o=(s.split(".").pop()??"").toLowerCase(),r=i.createDiv({cls:"stashpad-att"});if(r.title=s,n&&Nc.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)}}}renderComposer(t){let e=j(),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,k.debounce)(x=>{this.saveDraft(x)},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 k.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))},A=()=>{if(l){try{this.app.keymap?.popScope(l)}catch{}l=null}};if(r.addEventListener("focus",c),r.addEventListener("blur",A),document.activeElement===r&&c(),k.Platform.isMobile){let x=()=>{this.keyboardTransitionUntil=Date.now()+600};r.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),x()}),r.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),x(),this.tapSettleUntil=Date.now()+300,k.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=r,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new oi(this.app,r),this.composerAutocomplete.attach();let h=async x=>{let S="";for(let T of x){let P=await this.importAttachment(T);if(!P)continue;let R=r.value+S,X=R&&!R.endsWith(` `)?` `:"";S+=`${X}${P} -`}S&&(r.value=r.value+S,this.composerDraft=r.value,this.saveDraft(r.value),r.focus(),r.setSelectionRange(r.value.length,r.value.length))};r.addEventListener("dragover",x=>{if(!(!x.dataTransfer||!Array.from(x.dataTransfer.types).includes("Files"))){x.preventDefault(),x.stopPropagation();try{x.dataTransfer.dropEffect="copy"}catch{}}}),r.addEventListener("drop",x=>{let S=Array.from(x.dataTransfer?.files??[]);S.length!==0&&(x.preventDefault(),x.stopPropagation(),h(S))}),r.addEventListener("paste",x=>{let S=this.plugin.noteClipboard;if(S?.mode==="cut"&&S.text&&x.clipboardData?.getData("text/plain")===S.text){if(this.focusedInsideCut(S.ids)){x.preventDefault(),new k.Notice("Can't paste a cut note into the note you're cutting.");return}x.preventDefault(),this.completeCutIntoComposer();return}let T=[],P=x.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 X=R.getAsFile();X&&T.push(X)}}T.length!==0&&(x.preventDefault(),x.stopPropagation(),h(T))}});let p=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});p.setCssStyles({display:"none"});let u=n.createDiv({cls:"stashpad-composer-btn-rail"}),g=u.createDiv({cls:"stashpad-composer-btn-group"}),I=g.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(I,"list-end");let m=mi[j().splitMode].toLowerCase();I.title=s?`Split: ON \u2014 ${m} (Mod+/ to toggle, right-click to change)`:`Split into notes (Mod+/) \u2014 right-click to choose: ${m}`,s&&I.addClass("is-active"),I.onmousedown=x=>x.preventDefault(),I.onclick=x=>{x.preventDefault(),this.toggleSplit()},I.oncontextmenu=x=>{x.preventDefault();let S=new k.Menu,T=j().splitMode;["lines","paragraphs","headings"].forEach(P=>{S.addItem(R=>R.setTitle(mi[P]).setChecked(P===T).onClick(async()=>{this.plugin.settings.splitMode=P,await this.plugin.saveSettings(),this.render()}))}),S.showAtMouseEvent(x)};let f=g.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(f,"map-pin"),this.nextDestination&&f.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),f.title="Set destination (Mod+D)",this.nextDestination&&f.addClass("is-active"),f.onmousedown=x=>x.preventDefault(),f.onclick=x=>{x.preventDefault();let S=document.activeElement===r;this.openDestinationPicker(S)};let C=g.createEl("button",{cls:"stashpad-composer-btn"});(0,k.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=x=>x.preventDefault(),C.onclick=x=>{x.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let B=x=>{let S=r.value&&!r.value.endsWith(` +`}S&&(r.value=r.value+S,this.composerDraft=r.value,this.saveDraft(r.value),r.focus(),r.setSelectionRange(r.value.length,r.value.length))};r.addEventListener("dragover",x=>{if(!(!x.dataTransfer||!Array.from(x.dataTransfer.types).includes("Files"))){x.preventDefault(),x.stopPropagation();try{x.dataTransfer.dropEffect="copy"}catch{}}}),r.addEventListener("drop",x=>{let S=Array.from(x.dataTransfer?.files??[]);S.length!==0&&(x.preventDefault(),x.stopPropagation(),h(S))}),r.addEventListener("paste",x=>{let S=this.plugin.noteClipboard;if(S?.mode==="cut"&&S.text&&x.clipboardData?.getData("text/plain")===S.text){if(this.focusedInsideCut(S.ids)){x.preventDefault(),new k.Notice("Can't paste a cut note into the note you're cutting.");return}x.preventDefault(),this.completeCutIntoComposer();return}let T=[],P=x.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 X=R.getAsFile();X&&T.push(X)}}T.length!==0&&(x.preventDefault(),x.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"}),p=u.createDiv({cls:"stashpad-composer-btn-group"}),I=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(I,"list-end");let f=Ci[j().splitMode].toLowerCase();I.title=s?`Split: ON \u2014 ${f} (Mod+/ to toggle, right-click to change)`:`Split into notes (Mod+/) \u2014 right-click to choose: ${f}`,s&&I.addClass("is-active"),I.onmousedown=x=>x.preventDefault(),I.onclick=x=>{x.preventDefault(),this.toggleSplit()},I.oncontextmenu=x=>{x.preventDefault();let S=new k.Menu,T=j().splitMode;["lines","paragraphs","headings"].forEach(P=>{S.addItem(R=>R.setTitle(Ci[P]).setChecked(P===T).onClick(async()=>{this.plugin.settings.splitMode=P,await this.plugin.saveSettings(),this.render()}))}),S.showAtMouseEvent(x)};let m=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.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=x=>x.preventDefault(),m.onclick=x=>{x.preventDefault();let S=document.activeElement===r;this.openDestinationPicker(S)};let C=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.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=x=>x.preventDefault(),C.onclick=x=>{x.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let B=x=>{let S=r.value&&!r.value.endsWith(` `)?` `:"";r.value+=`${S}${x} -`,this.composerDraft=r.value},Q=g.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(Q,"paperclip"),Q.title="Attach files",Q.onmousedown=x=>x.preventDefault(),Q.onclick=x=>{x.preventDefault();let S=document.activeElement===r;if(p.click(),S){let T=()=>{r.focus()};setTimeout(T,100),setTimeout(T,500)}},p.addEventListener("change",async()=>{let x=Array.from(p.files??[]);p.value="";for(let S of x){let T=await this.importAttachment(S);T&&B(T)}r.focus()});let y=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,k.setIcon)(y,"chevron-left"),y.title="Show more composer options",u.insertBefore(y,g);let E=x=>{u.toggleClass("is-expanded",x),y.title=x?"Hide options":"Show more composer options",(0,k.setIcon)(y,x?"chevron-right":"chevron-left")};y.onmousedown=x=>x.preventDefault(),y.onclick=x=>{x.preventDefault(),E(!u.hasClass("is-expanded"))},E(!1);let v=()=>n.clientWidth<700,w=()=>{let x=v();n.toggleClass("is-narrow",x),E(!x)};w(),requestAnimationFrame(w);let D=new ResizeObserver(w);D.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=D;let b=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});b.title="Send (Enter)",(0,k.setIcon)(b,"arrow-up");let H=async()=>{let x=r.value.trim();if(!x)return;r.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(x)}catch{}let S=this.modeSplit??j().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 X=R?{targetFolder:P}:void 0,$=T??this.focusId;if(S){let V=Ci(x,j().splitMode);V.length===1?await this.createNoteUnder(V[0],$,X):V.length>1&&await this.createNotesBatch(V,$,X,x,R?P:this.noteFolder)}else await this.createNoteUnder(x,$,X);j().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,R&&this.composerInputEl?.focus())};b.onclick=()=>void H(),r.addEventListener("keydown",x=>{let S=this.modeEnterSubmits;if(x.key==="Escape"){x.preventDefault(),x.stopPropagation(),r.blur(),this.viewRoot.focus({preventScroll:!0});return}if(x.key==="ArrowUp"&&r.selectionStart===0&&r.selectionEnd===0){if(x.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}x.key==="Enter"&&!x.isComposing&&(S?!x.shiftKey:x.shiftKey)&&(x.preventDefault(),x.stopPropagation(),x.stopImmediatePropagation(),H())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return k.Platform.isMobile?e?"New notes (split on newlines)":"New note":`Type a note. ${t?"Enter":"Shift+Enter"} = send, ${t?"Shift+Enter":"Enter"} = newline${e?" (each line \u2192 a note)":""}\u2026`}composerHelperText(t,e){let i=t?"Enter":"Shift+Enter",s=t?"Shift+Enter":"Enter",n=j().bindings,o=h=>{let p=n[h];return p.primary&&p.secondary?p.preferRight?p.secondary:p.primary:p.primary||p.secondary},r=Ji(o("toggleSplit")),l=Ji(o("pickDestination")),c=Ji(o("search")),A=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${r} split: ${e?"ON":"off"} \xB7 ${l} destination \xB7 ${c} search${A}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===F)return"Home";let t=this.tree.get(this.nextDestination);return t?this.titleForNode(t).trim():"?"}renderMobileNav(t){let e=t.createDiv({cls:"stashpad-mobile-nav"});e.createEl("button",{text:"Home"}).onclick=()=>this.navigateTo(F),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let 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>Xi.AIMED_TAP_WINDOW_MS)&&(this.aimedTapTargetId=i.id,this.aimedTapAt=Date.now()),t.stopPropagation();return}this.aimedTapTargetId=null;let n=t.target,o=n?.closest?.(".tag");if(o){t.preventDefault(),t.stopPropagation();let A=(o.getAttribute("href")||o.textContent||"").replace(/^#/,"").trim();if(A){let h=this.app.internalPlugins?.plugins?.["global-search"],p=h?.instance?.openGlobalSearch?.bind(h.instance);p&&p(`tag:#${A}`)}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 A=i.file?.path||"";this.app.workspace.openLinkText(c,A,!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(A=>A.id===this.lastSelected);if(l&&(this.firstSelectedId=this.lastSelected),c!==-1){let[A,h]=c<e?[c,e]:[e,c];for(let p=A;p<=h;p++)this.selection.add(this.currentChildren[p].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],A=c?this.currentChildren.findIndex(h=>h.id===c):-1;A>=0&&(this.cursorIdx=A)}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(k.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 k.Platform.isMobile&&Date.now()<this.tapSettleUntil}traceTap(t,e,i,s){if(!this.plugin.settings.debugTrace||!this.listEl)return;let n=this.listEl,o=window.visualViewport,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(!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)),s.classList.toggle("is-cursor-expanded",t&&r),s.classList.toggle("is-pick-target",n===e)})}revealRowAt(t){if(!this.listEl)return;let e=this.listEl.querySelector(`.stashpad-note[data-idx="${t}"]`);if(!e)return;let i=e.getBoundingClientRect(),s=this.listEl.getBoundingClientRect();(i.top<s.top||i.bottom>s.bottom)&&e.scrollIntoView({block:"nearest",behavior:"auto"})}getActionTargets(){if(this.selection.size>0)return[...this.selection].map(e=>this.tree.get(e)).filter(e=>!!e&&!!e.file);let t=this.currentChildren[this.cursorIdx];return t?[t]:[]}async cmdLockSelection(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 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 k.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let r=this.order.getOrder(this.noteFolder,o.parent??F),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 k.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 k.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 Fo(this.app,i,o).open()}async archiveSources(t,e){let i=this.noteFolder,s=e.replace(/\/+$/,"");if(!((this.plugin.settings.folderEncPrefs??{})[s]?.archiveEncryptContent??!0)){new k.Notice(`\u201C${s.split("/").pop()}\u201D is a plaintext archive (encryption off). Moving notes into a plaintext archive from the command isn't wired yet \u2014 drag them in, or turn on \u201CEncrypt archived notes\u201D for that folder.`,9e3);return}if(!this.plugin.encryption?.isConfigured?.()){new k.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 p=h.parent;for(;p;){if(o.has(p))return!1;p=this.tree.get(p)?.parent??null}return!0});if(r.length===0)return;let l=r.map(h=>h.id),c=[];for(let h of r){let p=this.order.getOrder(i,h.parent??F),u=p.indexOf(h.id),g=u>0?p[u-1]:null,I=await this.plugin.lockNoteSubtree(i,h.id,g,{silent:!0,blobFolder:e});I&&c.push(I.blobPath)}if(c.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let A=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${c.length} note${c.length===1?"":"s"} \u2192 \u201C${A}\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(p){console.warn("[Stashpad] archive undo failed",h,p)}c=[],this.tree.rebuild(i),this.render()},redo:async()=>{c=[];for(let h of l){let p=await this.plugin.lockNoteSubtree(i,h,null,{silent:!0,blobFolder:e});p&&c.push(p.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new k.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 nt(this.app,`Encrypt & delete ${s} note${s===1?"":"s"}?`,[`The selected note${s===1?"":"s"} (and any children) will be encrypted and moved to Stashpad's encrypted trash.`,"","\u2022 The readable copy is permanently removed from the folder.",`\u2022 You can restore ${s===1?"it":"them"} later from the encrypted trash \u2014 you'll need your encryption password.`,`\u2022 If you lose your password, ${s===1?"it's":"they're"} gone for good.`].join(` -`),"Encrypt & delete",async n=>{n&&await this.secureDeleteSources(i)}).open()}async secureDeleteSources(t){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 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 k.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 k.Notice("No locked notes to unlock here.");return}if(!await this.plugin.ensureEncryptionUnlocked())return;let s=0;for(let n of t)try{await this.plugin.unlockBundleAt(n,{silent:!0})&&s++}catch(o){console.warn("[Stashpad] batch unlock skipped",n,o)}s>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Unlocked ${s} stash${s===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}toggleSplit(){let t=this.modeSplit??j().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Xt(this.app,this.tree,i=>this.titleForNode(i),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async i=>{if(e=!0,i.crossFolder){let s=i.crossId??i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===F?"Home":(i.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${n} \u25B8 ${o}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=i.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async i=>{e=!0;let s=await this.createNoteUnder(i,this.focusId);s&&(this.nextDestination=s,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,onClose:()=>{t&&!e&&this.composerInputEl?.focus()}}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===F&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:F,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=s=>{if(s===t)return!0;let n=new Set,o=this.tree.get(s);for(;o&&o.id!==F&&!n.has(o.id);){if(n.add(o.id),o.parent===t||o.id===t)return!0;if(!o.parent)return!1;o=this.tree.get(o.parent)}return t===F},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Xt(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 Xt(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 Xt(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,A=c.getLeaf("tab");await A.setViewState({type:J,active:!0,state:{focusId:o,folderOverride:r===l?null:r}}),c.revealLeaf(A);let h=A.view;if(h&&typeof h.createNoteUnder=="function"){let p=await h.createNoteUnder(s,o);p&&typeof h.navigateTo=="function"&&h.navigateTo(p)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.crossId??i.id.replace(/^cross:/,"");s?this.openNoteInNewTab(i.crossFolder,n):this.switchToFolderAndFocus(i.crossFolder,n);return}i.node&&(s?this.openNoteInNewTab(this.noteFolder,i.node.id):this.navigateTo(i.node.id))},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(i=>i!==this.noteFolder),showFilterChips:!0,localFolder:this.noteFolder});this.openSearchInstance=t;let e=t.onClose.bind(t);t.onClose=()=>{e(),this.openSearchInstance===t&&(this.openSearchInstance=null)},t.open()}excludedSearchFolders(){let t=new Set(this.plugin.searchableFolders(this.noteFolder));return this.plugin.discoverStashpadFolders().filter(e=>e!==this.noteFolder&&!t.has(e))}collectExcludedFolderNotes(){let t=this.excludedSearchFolders();if(!t.length)return[];let e=this.collectCrossFolderNotes(t),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!t.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===F&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:F,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let 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 A=this.app.metadataCache.getFileCache(c)?.frontmatter;typeof A?.id=="string"&&l.set(A.id,c)}for(let c of r){let A=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id:"";if(!h||h===F)continue;let p=c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),u,g=A?.parent??null;if(g&&g!==F){let I=l.get(g);I&&(u=I.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:c,folder:o,id:h,title:p,body:"",parentBlurb:u,parentId:g??null})}}return e}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===F){i.push(s.id);continue}let o=n.parent??F;await this.changeParent(s,o),e.push(s)}if(e.length===0){new k.Notice(i.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),i.length&&this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:e,suffix:i.length?`(${i.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e.map(s=>s.id),folder:this.noteFolder}),this.plugin.settings.autoNavOnMoveOut&&e.length>0){let s=e[0].parent;s!=null&&e.every(o=>o.parent===s)&&s!==this.focusId&&this.navigateTo(s)}}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(n=>this.colorForNode(n)??"")),i=e.size===1&&Array.from(e)[0]||null,s=this.plugin.settings.customPalette??[];new Te(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,p=>{n?p.color=n:delete p.color})}catch(p){new k.Notice(`Couldn't set color for ${h.id}: ${p.message}`)}}if(o.addToPalette&&typeof n=="string"){let h=[...this.plugin.settings.customPalette??[]],p=n.toLowerCase();h.some(u=>u.toLowerCase()===p)||(h.push(n),this.plugin.settings.customPalette=h,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:F,payload:{color:n}}))}this.render();let l=this.noteFolder,c=n,A=async h=>{for(let p of h){let u=this.app.vault.getAbstractFileByPath(p.path);if(u)try{await this.app.fileManager.processFrontMatter(u,g=>{p.col?g.color=p.col:delete g.color})}catch{}}this.tree.rebuild(l),this.render()};this.plugin.getUndoStack(l).push({label:r.length===1?"Color change":`Color change (${r.length})`,undo:()=>A(r.map(h=>({path:h.path,col:h.was}))),redo:()=>A(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:F,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Xt(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let o=e.crossId??e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,o),this.selection.clear(),this.render();return}let i=e.id,s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&i!==this.focusId&&this.navigateTo(i)},onCreate:async e=>{let i=await this.createNoteUnder(e,this.focusId);if(!i)return;let s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&this.navigateTo(i)},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,showFilterChips:!0}).open()}async moveAcrossFolders(t,e,i){if(!t.length)return;let s=(e||"").replace(/\/+$/,"");if(!s){new k.Notice("Target folder is empty");return}let n=[],o=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(p.path);let r=(p,u)=>{if(!p.file)return;let g=p.file,I=`${s}/${g.name}`;if(o.has(I)){let m=g.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),f=m?m[1]:g.basename,C=m?m[2]:"";for(let B=1;B<1e3;B++){let Q=`${f}-${B}${C}.md`,y=`${s}/${Q}`;if(!o.has(y)){I=y;break}}}o.add(I),n.push({id:p.id,file:g,oldPath:g.path,newPath:I,oldParent:p.parent,isRoot:u});for(let m of this.tree.getChildren(p.id))r(m,!1)};for(let p of t)r(p,!0);if(!n.length)return;await this.ensureFolder(s);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,u=>{u.parent=i}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?i:p.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(u){new k.Notice(`Move failed for ${p.id}: ${u.message}`)}if(j().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{li(this.app,p),li(this.app,s)},350)}let l=this.titleList(t);this.tree.rebuild(this.noteFolder);let c=i===F?"Open home":"Open parent",A=Math.max(0,n.length-t.length),h=t.length===1?`Moved ${l}${A>0?` and its ${A} nested note${A===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${l}${A>0?` (${A} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:h,kind:"success",category:"move",duration:0,affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:c,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let u=this.app.vault.getAbstractFileByPath(p.newPath);if(u)try{await this.app.fileManager.renameFile(u,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(u,g=>{g.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let u=this.app.vault.getAbstractFileByPath(p.oldPath);if(u)try{await this.app.fileManager.renameFile(u,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(u,g=>{g.parent=i})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}nextPickableIdx(t,e){for(let i=t+e;i>=0&&i<this.currentChildren.length;i+=e){let s=this.currentChildren[i];if(s&&!this.selection.has(s.id))return i}return t}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;if(this.currentChildren[t]&&this.selection.has(this.currentChildren[t].id)){let n=this.nextPickableIdx(t,-1);t=n!==t?n:this.nextPickableIdx(t,1)}this.inListPicker={activeIdx:t};let e=j().bindings.move,i=Ji(e.primary||e.secondary||"M");new k.Notice(`Arrows to pick parent, Enter confirms, ${i} for the full picker, Esc cancels.`);let s=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let n=this.listEl;n.scrollTop=s,requestAnimationFrame(()=>{n.scrollTop=s}),setTimeout(()=>{n.scrollTop=s},60)}}async commitInListPicker(){if(!this.inListPicker)return;let t=this.currentChildren[this.inListPicker.activeIdx];if(this.inListPicker=null,!t){this.render();return}let e=this.getActionTargets().filter(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 k.Notice("Select 2+ notes to merge.");return}t.sort((I,m)=>(I.created||"").localeCompare(m.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 I of t){if(!I.file)continue;let m=await this.app.vault.cachedRead(I.file);r.push(this.stripFrontmatter(m).trim())}let l=r.map(I=>I.trim()).filter(Boolean).join(` +`,this.composerDraft=r.value},Q=p.createEl("button",{cls:"stashpad-composer-btn"});(0,k.setIcon)(Q,"paperclip"),Q.title="Attach files",Q.onmousedown=x=>x.preventDefault(),Q.onclick=x=>{x.preventDefault();let S=document.activeElement===r;if(g.click(),S){let T=()=>{r.focus()};setTimeout(T,100),setTimeout(T,500)}},g.addEventListener("change",async()=>{let x=Array.from(g.files??[]);g.value="";for(let S of x){let T=await this.importAttachment(S);T&&B(T)}r.focus()});let y=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,k.setIcon)(y,"chevron-left"),y.title="Show more composer options",u.insertBefore(y,p);let E=x=>{u.toggleClass("is-expanded",x),y.title=x?"Hide options":"Show more composer options",(0,k.setIcon)(y,x?"chevron-right":"chevron-left")};y.onmousedown=x=>x.preventDefault(),y.onclick=x=>{x.preventDefault(),E(!u.hasClass("is-expanded"))},E(!1);let v=()=>n.clientWidth<700,w=()=>{let x=v();n.toggleClass("is-narrow",x),E(!x)};w(),requestAnimationFrame(w);let D=new ResizeObserver(w);D.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=D;let b=u.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});b.title="Send (Enter)",(0,k.setIcon)(b,"arrow-up");let H=async()=>{let x=r.value.trim();if(!x)return;r.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(x)}catch{}let S=this.modeSplit??j().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 X=R?{targetFolder:P}:void 0,$=T??this.focusId;if(S){let V=Bi(x,j().splitMode);V.length===1?await this.createNoteUnder(V[0],$,X):V.length>1&&await this.createNotesBatch(V,$,X,x,R?P:this.noteFolder)}else await this.createNoteUnder(x,$,X);j().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,R&&this.composerInputEl?.focus())};b.onclick=()=>void H(),r.addEventListener("keydown",x=>{let S=this.modeEnterSubmits;if(x.key==="Escape"){x.preventDefault(),x.stopPropagation(),r.blur(),this.viewRoot.focus({preventScroll:!0});return}if(x.key==="ArrowUp"&&r.selectionStart===0&&r.selectionEnd===0){if(x.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}x.key==="Enter"&&!x.isComposing&&(S?!x.shiftKey:x.shiftKey)&&(x.preventDefault(),x.stopPropagation(),x.stopImmediatePropagation(),H())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return k.Platform.isMobile?e?"New notes (split on newlines)":"New note":`Type a note. ${t?"Enter":"Shift+Enter"} = send, ${t?"Shift+Enter":"Enter"} = newline${e?" (each line \u2192 a note)":""}\u2026`}composerHelperText(t,e){let i=t?"Enter":"Shift+Enter",s=t?"Shift+Enter":"Enter",n=j().bindings,o=h=>{let g=n[h];return g.primary&&g.secondary?g.preferRight?g.secondary:g.primary:g.primary||g.secondary},r=Ki(o("toggleSplit")),l=Ki(o("pickDestination")),c=Ki(o("search")),A=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${r} split: ${e?"ON":"off"} \xB7 ${l} destination \xB7 ${c} search${A}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===F)return"Home";let t=this.tree.get(this.nextDestination);return t?this.titleForNode(t).trim():"?"}renderMobileNav(t){let e=t.createDiv({cls:"stashpad-mobile-nav"});e.createEl("button",{text:"Home"}).onclick=()=>this.navigateTo(F),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let 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>Zi.AIMED_TAP_WINDOW_MS)&&(this.aimedTapTargetId=i.id,this.aimedTapAt=Date.now()),t.stopPropagation();return}this.aimedTapTargetId=null;let n=t.target,o=n?.closest?.(".tag");if(o){t.preventDefault(),t.stopPropagation();let A=(o.getAttribute("href")||o.textContent||"").replace(/^#/,"").trim();if(A){let h=this.app.internalPlugins?.plugins?.["global-search"],g=h?.instance?.openGlobalSearch?.bind(h.instance);g&&g(`tag:#${A}`)}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 A=i.file?.path||"";this.app.workspace.openLinkText(c,A,!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(A=>A.id===this.lastSelected);if(l&&(this.firstSelectedId=this.lastSelected),c!==-1){let[A,h]=c<e?[c,e]:[e,c];for(let g=A;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],A=c?this.currentChildren.findIndex(h=>h.id===c):-1;A>=0&&(this.cursorIdx=A)}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(k.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 k.Platform.isMobile&&Date.now()<this.tapSettleUntil}traceTap(t,e,i,s){if(!this.plugin.settings.debugTrace||!this.listEl)return;let n=this.listEl,o=window.visualViewport,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(!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)),s.classList.toggle("is-cursor-expanded",t&&r),s.classList.toggle("is-pick-target",n===e)})}revealRowAt(t){if(!this.listEl)return;let e=this.listEl.querySelector(`.stashpad-note[data-idx="${t}"]`);if(!e)return;let i=e.getBoundingClientRect(),s=this.listEl.getBoundingClientRect();(i.top<s.top||i.bottom>s.bottom)&&e.scrollIntoView({block:"nearest",behavior:"auto"})}getActionTargets(){if(this.selection.size>0)return[...this.selection].map(e=>this.tree.get(e)).filter(e=>!!e&&!!e.file);let t=this.currentChildren[this.cursorIdx];return t?[t]:[]}async cmdLockSelection(){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 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 k.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let r=this.order.getOrder(this.noteFolder,o.parent??F),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 k.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 k.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 Do(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,I=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))I(B)}};for(let C of g)I(C);let f=[];for(let C of u){let B=C.path,Q=C.name,y=Q.lastIndexOf("."),E=y>0?Q.slice(0,y):Q,v=y>0?Q.slice(y):"",w=`${s}/${Q}`;for(let D=1;await this.app.vault.adapter.exists(w);D++)w=`${s}/${E}-${D}${v}`;try{await this.app.fileManager.renameFile(C,w),f.push({from:B,to:w})}catch(D){console.warn("[Stashpad] plaintext archive move failed",B,D)}}this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let m=s.split("/").pop()||s;this.plugin.notifications.show({message:`Moved ${f.length} note${f.length===1?"":"s"} \u2192 plaintext archive \u201C${m}\u201D (de-indexed, not encrypted). Undo to bring ${f.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 f){let B=this.app.vault.getAbstractFileByPath(C.to);if(B instanceof k.TFile)try{await this.app.fileManager.renameFile(B,C.from)}catch(Q){console.warn("[Stashpad] plaintext archive undo failed",C.to,Q)}}this.tree.rebuild(i),this.render()}});return}if(!this.plugin.encryption?.isConfigured?.()){new k.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??F),u=g.indexOf(h.id),p=u>0?g[u-1]:null,I=await this.plugin.lockNoteSubtree(i,h.id,p,{silent:!0,blobFolder:e});I&&c.push(I.blobPath)}if(c.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let A=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${c.length} note${c.length===1?"":"s"} \u2192 \u201C${A}\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 k.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 nt(this.app,`Encrypt & delete ${s} note${s===1?"":"s"}?`,[`The selected note${s===1?"":"s"} (and any children) will be encrypted and moved to Stashpad's encrypted trash.`,"","\u2022 The readable copy is permanently removed from the folder.",`\u2022 You can restore ${s===1?"it":"them"} later from the encrypted trash \u2014 you'll need your encryption password.`,`\u2022 If you lose your password, ${s===1?"it's":"they're"} gone for good.`].join(` +`),"Encrypt & delete",async n=>{n&&await this.secureDeleteSources(i)}).open()}async secureDeleteSources(t){if(!this.plugin.encryption?.isConfigured?.()){new k.Notice("Set up encryption first (Settings \u2192 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 k.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 k.Notice("No locked notes to unlock here.");return}if(!await this.plugin.ensureEncryptionUnlocked())return;let s=0;for(let n of t)try{await this.plugin.unlockBundleAt(n,{silent:!0})&&s++}catch(o){console.warn("[Stashpad] batch unlock skipped",n,o)}s>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Unlocked ${s} stash${s===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}toggleSplit(){let t=this.modeSplit??j().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new Xt(this.app,this.tree,i=>this.titleForNode(i),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async i=>{if(e=!0,i.crossFolder){let s=i.crossId??i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===F?"Home":(i.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${n} \u25B8 ${o}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=i.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async i=>{e=!0;let s=await this.createNoteUnder(i,this.focusId);s&&(this.nextDestination=s,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,onClose:()=>{t&&!e&&this.composerInputEl?.focus()}}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===F&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:F,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=s=>{if(s===t)return!0;let n=new Set,o=this.tree.get(s);for(;o&&o.id!==F&&!n.has(o.id);){if(n.add(o.id),o.parent===t||o.id===t)return!0;if(!o.parent)return!1;o=this.tree.get(o.parent)}return t===F},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new Xt(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 Xt(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 Xt(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,A=c.getLeaf("tab");await A.setViewState({type:J,active:!0,state:{focusId:o,folderOverride:r===l?null:r}}),c.revealLeaf(A);let h=A.view;if(h&&typeof h.createNoteUnder=="function"){let g=await h.createNoteUnder(s,o);g&&typeof h.navigateTo=="function"&&h.navigateTo(g)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.crossId??i.id.replace(/^cross:/,"");s?this.openNoteInNewTab(i.crossFolder,n):this.switchToFolderAndFocus(i.crossFolder,n);return}i.node&&(s?this.openNoteInNewTab(this.noteFolder,i.node.id):this.navigateTo(i.node.id))},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(i=>i!==this.noteFolder),showFilterChips:!0,localFolder:this.noteFolder});this.openSearchInstance=t;let e=t.onClose.bind(t);t.onClose=()=>{e(),this.openSearchInstance===t&&(this.openSearchInstance=null)},t.open()}excludedSearchFolders(){let t=new Set(this.plugin.searchableFolders(this.noteFolder));return this.plugin.discoverStashpadFolders().filter(e=>e!==this.noteFolder&&!t.has(e))}collectExcludedFolderNotes(){let t=this.excludedSearchFolders();if(!t.length)return[];let e=this.collectCrossFolderNotes(t),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!t.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===F&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:F,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let 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 A=this.app.metadataCache.getFileCache(c)?.frontmatter;typeof A?.id=="string"&&l.set(A.id,c)}for(let c of r){let A=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id:"";if(!h||h===F)continue;let g=c.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),u,p=A?.parent??null;if(p&&p!==F){let I=l.get(p);I&&(u=I.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===F){i.push(s.id);continue}let o=n.parent??F;await this.changeParent(s,o),e.push(s)}if(e.length===0){new k.Notice(i.length?"Already at the top level.":"Nothing to outdent.");return}if(this.render(),i.length&&this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Outdented",nodes:e,suffix:i.length?`(${i.length} already at root)`:void 0}),kind:"success",category:"move",affectedIds:e.map(s=>s.id),folder:this.noteFolder}),this.plugin.settings.autoNavOnMoveOut&&e.length>0){let s=e[0].parent;s!=null&&e.every(o=>o.parent===s)&&s!==this.focusId&&this.navigateTo(s)}}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(n=>this.colorForNode(n)??"")),i=e.size===1&&Array.from(e)[0]||null,s=this.plugin.settings.customPalette??[];new Te(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 k.Notice(`Couldn't set color for ${h.id}: ${g.message}`)}}if(o.addToPalette&&typeof n=="string"){let h=[...this.plugin.settings.customPalette??[]],g=n.toLowerCase();h.some(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:F,payload:{color:n}}))}this.render();let l=this.noteFolder,c=n,A=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:()=>A(r.map(h=>({path:h.path,col:h.was}))),redo:()=>A(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:F,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Xt(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let o=e.crossId??e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,o),this.selection.clear(),this.render();return}let i=e.id,s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&i!==this.focusId&&this.navigateTo(i)},onCreate:async e=>{let i=await this.createNoteUnder(e,this.focusId);if(!i)return;let s=new Map(t.map(o=>[o.id,this.tree.getChildren(o.id).length])),n=[];for(let o of t)await this.changeParent(o,i,{silentSuccess:!0})&&n.push(o);this.notifyBatchMove(n,i,s),this.selection.clear(),this.render(),this.plugin.settings.autoNavOnMoveOut&&this.navigateTo(i)},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,showFilterChips:!0}).open()}async moveAcrossFolders(t,e,i){if(!t.length)return;let s=(e||"").replace(/\/+$/,"");if(!s){new k.Notice("Target folder is empty");return}let n=[],o=new Set;for(let g of this.app.vault.getMarkdownFiles())(g.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(g.path);let r=(g,u)=>{if(!g.file)return;let p=g.file,I=`${s}/${p.name}`;if(o.has(I)){let f=p.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),m=f?f[1]:p.basename,C=f?f[2]:"";for(let B=1;B<1e3;B++){let Q=`${m}-${B}${C}.md`,y=`${s}/${Q}`;if(!o.has(y)){I=y;break}}}o.add(I),n.push({id:g.id,file:p,oldPath:p.path,newPath:I,oldParent:g.parent,isRoot:u});for(let f of this.tree.getChildren(g.id))r(f,!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 k.Notice(`Move failed for ${g.id}: ${u.message}`)}if(j().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===F?"Open home":"Open parent",A=Math.max(0,n.length-t.length),h=t.length===1?`Moved ${l}${A>0?` and its ${A} nested note${A===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${l}${A>0?` (${A} 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=j().bindings.move,i=Ki(e.primary||e.secondary||"M");new k.Notice(`Arrows to pick parent, Enter confirms, ${i} for the full picker, Esc cancels.`);let s=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let n=this.listEl;n.scrollTop=s,requestAnimationFrame(()=>{n.scrollTop=s}),setTimeout(()=>{n.scrollTop=s},60)}}async commitInListPicker(){if(!this.inListPicker)return;let t=this.currentChildren[this.inListPicker.activeIdx];if(this.inListPicker=null,!t){this.render();return}let e=this.getActionTargets().filter(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 k.Notice("Select 2+ notes to merge.");return}t.sort((I,f)=>(I.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],r=[];for(let I of t){if(!I.file)continue;let f=await this.app.vault.cachedRead(I.file);r.push(this.stripFrontmatter(f).trim())}let l=r.map(I=>I.trim()).filter(Boolean).join(` `),c=await this.app.vault.read(e.file),A=c.startsWith("---")?c.indexOf(` ----`,3)+4:0,p=`${c.slice(0,A)} +---`,3)+4:0,g=`${c.slice(0,A)} ${l} -`;await this.app.vault.modify(e.file,p);for(let I=1;I<t.length;I++){let m=t[I];if(m.file){for(let f of this.tree.getChildren(m.id))f.file&&o.push({childId:f.id,childPath:f.file.path,oldParent:f.parent}),await this.changeParent(f,e.id,{record:!1});await this.app.fileManager.trashFile(m.file),await this.log.append({type:"delete",id:m.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(I=>I.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let I=e.id,m=this.selectionGuardKey,f=()=>{if(this.selectionGuardKey!==m||this.selection.has(I))return;let C=this.currentChildren.findIndex(B=>B.id===I);C<0||(this.selection.add(I),this.cursorIdx=C,this.render({kind:"follow-cursor"}))};setTimeout(f,120),setTimeout(f,400)}let g=this.noteFolder;this.plugin.getUndoStack(g).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(m=>m.id));let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,s);for(let m of o){let f=this.app.vault.getAbstractFileByPath(m.childPath);f&&await this.app.fileManager.processFrontMatter(f,C=>{C.parent=m.oldParent})}this.pendingFocusIds=t.map(m=>m.id),this.tree.rebuild(g),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,p);for(let m of o){let f=this.app.vault.getAbstractFileByPath(m.childPath);f&&await this.app.fileManager.processFrontMatter(f,C=>{C.parent=e.id})}this.tree.rebuild(g),this.render()}})}cmdCopy(){return no(this)}cmdCopyCodeBlock(){return Ja(this)}cmdCopyTree(){return Ka(this)}cmdCopyOutline(){return Oa(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.isNoteExpanded(i.id));for(let i of t)this.setNoteExpanded(i.id,e);this.render()}isNoteExpanded(t){let e=this.expandedNotes.has(t);return this.plugin.settings.expandBodiesByDefault?!e:e}setNoteExpanded(t,e){let i=this.plugin.settings.expandBodiesByDefault;e===i?this.expandedNotes.delete(t):this.expandedNotes.add(t)}cmdExpandAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!0);this.render()}cmdCollapseAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!1);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new k.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let s=this.tree.getChildren(t.id).slice(),n=t.file,o=await this.app.vault.read(n),r=this.stripFrontmatter(o),l=this.app.metadataCache.getFileCache(n)?.frontmatter??{},c=W(),A=Et(r,this.activeStopwords()),h=wt(A,c),p=`${this.noteFolder}/${h}`,u=new Date().toISOString(),g=this.extractAttachments(r),I=["---",`id: ${c}`,`parent: ${e}`,`created: ${u}`];if(g.length>0){I.push("attachments:");for(let f of g)I.push(` - "${f.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",r),await this.ensureFolder(this.noteFolder),await this.app.vault.create(p,I.join(` -`)),i.push(p);let m=this.app.vault.getAbstractFileByPath(p);if(m){try{await this.app.fileManager.processFrontMatter(m,f=>{for(let[C,B]of Object.entries(l))se.includes(C)||ts.includes(C)||(f[C]=B)})}catch(f){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",f)}try{this.tree.insertSynthetic({id:c,parent:e,children:[],file:m,created:u})}catch{}this.fmSync.scheduleParentChange(c,null,e)}for(let f of s)await this.cloneSubtree(f,c,i);return c}async cmdClone(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let l of t){if(!l.file)continue;let c=l.parent??this.focusId,A=await this.cloneSubtree(l,c,i);A&&s.push(A)}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:fe(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 k.Notice("Nothing to fork.");return}let e=t.parent??F,i=e===F?null:this.tree.get(e),s=i?this.titleForNode(i):"Home";new Xt(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",allowCreate:!0,placeholder:`Fork "${this.titleForNode(t)}" under\u2026 (default: ${s})`,onPick:n=>{if(n.crossFolder){new k.Notice("Fork stays in this folder for now.");return}this.forkNoteUnder(t,n.id)},onCreate:n=>{(async()=>{let o=await this.createNoteUnder(n,this.focusId);o&&await this.forkNoteUnder(t,o)})()}}).open()}async forkNoteUnder(t,e){if(!t.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(t,e,s);if(!n)return;let o=s[0]?this.app.vault.getAbstractFileByPath(s[0]):null;if(o)try{await this.app.fileManager.processFrontMatter(o,A=>{A[Je]=`[[${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(A=>this.app.vault.getAbstractFileByPath(A)).filter(A=>!!A&&A.extension==="md").map(A=>({id:fe(A.basename)??A.basename,parent:null,children:[],file:A,created:new Date().toISOString()})),l=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(i).push({label:"Fork note",undo:async()=>{for(let A of[...s].reverse()){let h=this.app.vault.getAbstractFileByPath(A);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=Ot(this.app.metadataCache.getFileCache(t)?.frontmatter);if(e)return e;let i=Ro();return await this.app.fileManager.processFrontMatter(t,s=>{s[Le]=i,typeof s[Jt]!="number"&&(s[Jt]=0),s[qe]=!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&&Ot(n)===t.gid&&i(s),t.originName&&(s.basename===t.originName||Uo(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[Kt]=i:delete s[Kt]})}}async cmdForkVersion(t,e=!1){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings(),new k.Notice("Sheet versions enabled."));let i=t??this.getActionTargets()[0];if(!i?.file){new k.Notice("Select a note to version.");return}let s=this.noteFolder,n={...this.app.metadataCache.getFileCache(i.file)?.frontmatter??{}},o=await this.ensureSheetGroup(i.file),r=i.parent??this.focusId,l=typeof n[Jt]=="number"?n[Jt]:0;for(let g of this.tree.getChildren(r)){if(g.id===i.id)continue;let I=ft(this.app,g);if(Ot(I)!==o)continue;let m=I?.[Jt];typeof m=="number"&&m>l&&(l=m)}let c=l+1,A=[],h;if(e){let g=W(),I=wt(Et("",this.activeStopwords()),g),m=`${s}/${I}`,f=new Date().toISOString();await this.ensureFolder(s),await this.app.vault.create(m,["---",`id: ${g}`,`parent: ${r}`,`created: ${f}`,"attachments: []","---",""].join(` -`));let C=this.app.vault.getAbstractFileByPath(m);if(!C){new k.Notice("Sheets: could not create version.");return}await this.app.fileManager.processFrontMatter(C,B=>{for(let[Q,y]of Object.entries(n))se.includes(Q)||ts.includes(Q)||(B[Q]=y);B[Le]=o,B[Jt]=c,delete B[Fe],delete B[qe],B[Je]=`[[${i.file.basename}]]`});try{this.tree.insertSynthetic({id:g,parent:r,children:[],file:C,created:f})}catch{}this.fmSync.scheduleParentChange(g,null,r),A.push(m),h=g}else{let g=await this.cloneSubtree(i,r,A);if(!g||!A.length){new k.Notice("Sheets: could not create version.");return}h=g;let I=this.app.vault.getAbstractFileByPath(A[0]);I&&await this.app.fileManager.processFrontMatter(I,m=>{m[Le]=o,m[Jt]=c,delete m[Fe],delete m[qe],m[Je]=`[[${i.file.basename}]]`})}this.tree.rebuild(s),this.activeVersionByGroup.set(o,h),this.plugin.saveActiveVersion(s,o,h),this.render();let p=this.app.vault.getAbstractFileByPath(A[0]);await this.syncForkSiblings(this.forkFamilyFiles({gid:o,include:[i.file,p]})),this.plugin.getUndoStack(s).push({label:e?"New version":"Fork version",undo:async()=>{for(let g of[...A].reverse()){let I=this.app.vault.getAbstractFileByPath(g);if(I)try{await this.app.fileManager.trashFile(I)}catch{}}this.activeVersionByGroup.delete(o),this.tree.rebuild(s),this.render()},redo:async()=>{}});let u=A.length;new k.Notice(e?"New version added":`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=Ot(ft(this.app,e));if(!i){new k.Notice("Not a versioned note.");return}let s=!Ii(ft(this.app,e)),n=e.parent??this.focusId,o=this.tree.getChildren(n).filter(r=>Ot(ft(this.app,r))===i);for(let r of o){if(!r.file)continue;let l=Ii(ft(this.app,r)),c=s&&r.id===e.id;l!==c&&await this.app.fileManager.processFrontMatter(r.file,A=>{c?A[Fe]=!0:delete A[Fe]})}this.render()}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to copy.");return}await no(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 I=1;I<t.length;I++){let f=t[I];if(f.file){for(let m of this.tree.getChildren(f.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(f.file),await this.log.append({type:"delete",id:f.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let 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(I=>I.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let I=e.id,f=this.selectionGuardKey,m=()=>{if(this.selectionGuardKey!==f||this.selection.has(I))return;let C=this.currentChildren.findIndex(B=>B.id===I);C<0||(this.selection.add(I),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(f=>f.id));let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,s);for(let f of o){let m=this.app.vault.getAbstractFileByPath(f.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=f.oldParent})}this.pendingFocusIds=t.map(f=>f.id),this.tree.rebuild(p),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,g);for(let f of o){let m=this.app.vault.getAbstractFileByPath(f.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=e.id})}this.tree.rebuild(p),this.render()}})}cmdCopy(){return ro(this)}cmdCopyCodeBlock(){return Ya(this)}cmdCopyTree(){return $a(this)}cmdCopyOutline(){return Va(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.isNoteExpanded(i.id));for(let i of t)this.setNoteExpanded(i.id,e);this.render()}isNoteExpanded(t){let e=this.expandedNotes.has(t);return this.plugin.settings.expandBodiesByDefault?!e:e}setNoteExpanded(t,e){let i=this.plugin.settings.expandBodiesByDefault;e===i?this.expandedNotes.delete(t):this.expandedNotes.add(t)}cmdExpandAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!0);this.render()}cmdCollapseAll(){for(let t of this.currentChildren)this.setNoteExpanded(t.id,!1);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new k.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let s=this.tree.getChildren(t.id).slice(),n=t.file,o=await this.app.vault.read(n),r=this.stripFrontmatter(o),l=this.app.metadataCache.getFileCache(n)?.frontmatter??{},c=W(),A=Et(r,this.activeStopwords()),h=wt(A,c),g=`${this.noteFolder}/${h}`,u=new Date().toISOString(),p=this.extractAttachments(r),I=["---",`id: ${c}`,`parent: ${e}`,`created: ${u}`];if(p.length>0){I.push("attachments:");for(let m of p)I.push(` - "${m.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",r),await this.ensureFolder(this.noteFolder),await this.app.vault.create(g,I.join(` +`)),i.push(g);let f=this.app.vault.getAbstractFileByPath(g);if(f){try{await this.app.fileManager.processFrontMatter(f,m=>{for(let[C,B]of Object.entries(l))ne.includes(C)||es.includes(C)||(m[C]=B)})}catch(m){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",m)}try{this.tree.insertSynthetic({id:c,parent:e,children:[],file:f,created:u})}catch{}this.fmSync.scheduleParentChange(c,null,e)}for(let m of s)await this.cloneSubtree(m,c,i);return c}async cmdClone(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let l of t){if(!l.file)continue;let c=l.parent??this.focusId,A=await this.cloneSubtree(l,c,i);A&&s.push(A)}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:fe(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 k.Notice("Nothing to fork.");return}let e=t.parent??F,i=e===F?null:this.tree.get(e),s=i?this.titleForNode(i):"Home";new Xt(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",allowCreate:!0,placeholder:`Fork "${this.titleForNode(t)}" under\u2026 (default: ${s})`,onPick:n=>{if(n.crossFolder){new k.Notice("Fork stays in this folder for now.");return}this.forkNoteUnder(t,n.id)},onCreate:n=>{(async()=>{let o=await this.createNoteUnder(n,this.focusId);o&&await this.forkNoteUnder(t,o)})()}}).open()}async forkNoteUnder(t,e){if(!t.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(t,e,s);if(!n)return;let o=s[0]?this.app.vault.getAbstractFileByPath(s[0]):null;if(o)try{await this.app.fileManager.processFrontMatter(o,A=>{A[Ke]=`[[${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(A=>this.app.vault.getAbstractFileByPath(A)).filter(A=>!!A&&A.extension==="md").map(A=>({id:fe(A.basename)??A.basename,parent:null,children:[],file:A,created:new Date().toISOString()})),l=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(i).push({label:"Fork note",undo:async()=>{for(let A of[...s].reverse()){let h=this.app.vault.getAbstractFileByPath(A);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=Ot(this.app.metadataCache.getFileCache(t)?.frontmatter);if(e)return e;let i=qo();return await this.app.fileManager.processFrontMatter(t,s=>{s[qe]=i,typeof s[Jt]!="number"&&(s[Jt]=0),s[Je]=!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&&Ot(n)===t.gid&&i(s),t.originName&&(s.basename===t.originName||Lo(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[Kt]=i:delete s[Kt]})}}async cmdForkVersion(t,e=!1){this.plugin.settings.enableSheetVersions||(this.plugin.settings.enableSheetVersions=!0,await this.plugin.saveSettings(),new k.Notice("Sheet versions enabled."));let i=t??this.getActionTargets()[0];if(!i?.file){new k.Notice("Select a note to version.");return}let s=this.noteFolder,n={...this.app.metadataCache.getFileCache(i.file)?.frontmatter??{}},o=await this.ensureSheetGroup(i.file),r=i.parent??this.focusId,l=typeof n[Jt]=="number"?n[Jt]:0;for(let p of this.tree.getChildren(r)){if(p.id===i.id)continue;let I=ft(this.app,p);if(Ot(I)!==o)continue;let f=I?.[Jt];typeof f=="number"&&f>l&&(l=f)}let c=l+1,A=[],h;if(e){let p=W(),I=wt(Et("",this.activeStopwords()),p),f=`${s}/${I}`,m=new Date().toISOString();await this.ensureFolder(s),await this.app.vault.create(f,["---",`id: ${p}`,`parent: ${r}`,`created: ${m}`,"attachments: []","---",""].join(` +`));let C=this.app.vault.getAbstractFileByPath(f);if(!C){new k.Notice("Sheets: could not create version.");return}await this.app.fileManager.processFrontMatter(C,B=>{for(let[Q,y]of Object.entries(n))ne.includes(Q)||es.includes(Q)||(B[Q]=y);B[qe]=o,B[Jt]=c,delete B[Fe],delete B[Je],B[Ke]=`[[${i.file.basename}]]`});try{this.tree.insertSynthetic({id:p,parent:r,children:[],file:C,created:m})}catch{}this.fmSync.scheduleParentChange(p,null,r),A.push(f),h=p}else{let p=await this.cloneSubtree(i,r,A);if(!p||!A.length){new k.Notice("Sheets: could not create version.");return}h=p;let I=this.app.vault.getAbstractFileByPath(A[0]);I&&await this.app.fileManager.processFrontMatter(I,f=>{f[qe]=o,f[Jt]=c,delete f[Fe],delete f[Je],f[Ke]=`[[${i.file.basename}]]`})}this.tree.rebuild(s),this.activeVersionByGroup.set(o,h),this.plugin.saveActiveVersion(s,o,h),this.render();let g=this.app.vault.getAbstractFileByPath(A[0]);await this.syncForkSiblings(this.forkFamilyFiles({gid:o,include:[i.file,g]})),this.plugin.getUndoStack(s).push({label:e?"New version":"Fork version",undo:async()=>{for(let p of[...A].reverse()){let I=this.app.vault.getAbstractFileByPath(p);if(I)try{await this.app.fileManager.trashFile(I)}catch{}}this.activeVersionByGroup.delete(o),this.tree.rebuild(s),this.render()},redo:async()=>{}});let u=A.length;new k.Notice(e?"New version added":`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=Ot(ft(this.app,e));if(!i){new k.Notice("Not a versioned note.");return}let s=!fi(ft(this.app,e)),n=e.parent??this.focusId,o=this.tree.getChildren(n).filter(r=>Ot(ft(this.app,r))===i);for(let r of o){if(!r.file)continue;let l=fi(ft(this.app,r)),c=s&&r.id===e.id;l!==c&&await this.app.fileManager.processFrontMatter(r.file,A=>{c?A[Fe]=!0:delete A[Fe]})}this.render()}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to copy.");return}await ro(this),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"copy",folder:this.noteFolder,ids:t.map(e=>e.id)},this.render()}isCutPending(t){let e=this.plugin.noteClipboard;return!!e&&e.mode==="cut"&&e.folder===this.noteFolder&&e.ids.includes(t)}isCopyPending(t){let e=this.plugin.noteClipboard;return!!e&&e.mode==="copy"&&e.folder===this.noteFolder&&e.ids.includes(t)}insertIntoComposer(t){let e=this.composerInputEl;if(!e){this.composerDraft=this.composerDraft?`${this.composerDraft} ${t}`:t;return}let i=e.selectionStart??e.value.length,s=e.selectionEnd??e.value.length;e.value=e.value.slice(0,i)+t+e.value.slice(s);let n=i+t.length;try{e.setSelectionRange(n,n)}catch{}this.composerDraft=e.value}focusedInsideCut(t){let e=new Set(t),i=this.focusId,s=0;for(;i&&i!==F&&s++<1e3;){if(e.has(i))return!0;i=this.tree.get(i)?.parent??null}return!1}async cmdCutNotes(){let t=this.getActionTargets();if(!t.length){new k.Notice("Nothing to cut.");return}let e=[];for(let s of t)s.file&&e.push(this.stripFrontmatter(await this.app.vault.cachedRead(s.file)).trim());let i=e.join(` -`);await navigator.clipboard.writeText(i),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"cut",folder:this.noteFolder,ids:t.map(s=>s.id),text:i},this.render(),this.plugin.noteClipboardNotice=this.plugin.notifications.show({message:`Cut ${this.titleList(t)} \u2014 paste in the LIST to move it there as a note; paste in a note's COMPOSER to drop its text in and delete the original (undoable). Esc cancels. Nothing happens until you paste.`,kind:"info",category:"system",affectedIds:t.map(s=>s.id),folder:this.noteFolder,duration:0})}async cmdPasteNotes(){let t=this.plugin.noteClipboard;if(!t){new k.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){let p=(this.currentChildren[this.cursorIdx]??null)?.parent??this.focusId??F,u=t.mode,g=t.folder,I=await this.plugin.crossFolderPaste(g,t.ids,this.noteFolder,p,u);if(!I||!I.rootIds.length)return;u==="cut"&&this.plugin.clearNoteClipboard();let m=this.noteFolder;this.tree.rebuild(m),this.pendingFocusIds=I.rootIds.slice(),this.render(),u==="cut"&&this.plugin.refreshOpenViewsForFolder(g);let f=g.split("/").pop(),C=I.rootIds.length,B=()=>{this.tree.rebuild(m),this.render(),this.plugin.refreshOpenViewsForFolder(g)};this.plugin.getUndoStack(m).push({label:`${u==="cut"?"Move":"Paste"} ${C} note${C===1?"":"s"} from ${f}`,undo:async()=>{await I.undo(),B()},redo:async()=>{await I.redo(),B()}});let Q=u==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${Q} ${C} note${C===1?"":"s"} (${I.noteCount} total) from "${f}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:u==="cut"?"move":"clone",affectedIds:I.rootIds,folder:m,duration:0});return}let e=t.ids.map(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new k.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??F;if(t.mode==="cut"){let h=new Set(t.ids);for(let u=s;u&&u!==F;u=this.tree.get(u)?.parent??null)if(h.has(u)){new k.Notice("Can't paste cut notes under themselves.");return}let p=i&&!h.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(u=>u.id),s,p,"after");return}let n=this.noteFolder,o=[],r=[];for(let h of e){let p=await this.cloneSubtree(h,s,o);p&&r.push(p)}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:fe(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 p=this.app.vault.getAbstractFileByPath(h);if(p)try{await this.app.fileManager.trashFile(p)}catch{}}this.tree.rebuild(n),this.render()},redo:async()=>{await this.restoreSnapshots(c,r)}});let A=r.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:A,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 p=t.folder,u=t.ids.slice();this.plugin.clearNoteClipboard();let g=await this.plugin.orderedSubtreeNodes(p,u),I=j().prefixTimestampsOnCopy,m=[];for(let{file:y,created:E,depth:v}of g)try{let w=this.stripFrontmatter(await this.app.vault.cachedRead(y)).trim().split(/\r?\n/).join(" "),D=I?`${this.formatTimeInline(E)} `:"";m.push(`${" ".repeat(v)}- ${D}${w}`)}catch{}this.insertIntoComposer(m.length?m.join(` -`):t.text??"");let f=await this.plugin.subtreeFilePaths(p,u),C=await this.plugin.snapshotPaths(f),B=await this.plugin.trashSubtrees(p,u);this.plugin.refreshOpenViewsForFolder(p);let Q=B.filter(y=>y.extension==="md").length;this.plugin.getUndoStack(p).push({label:`Cut ${u.length} note${u.length===1?"":"s"} into composer (from ${p.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(C),this.plugin.refreshOpenViewsForFolder(p)},redo:async()=>{await this.plugin.trashSubtrees(p,u),this.plugin.refreshOpenViewsForFolder(p)}}),this.plugin.notifications.show({message:`Pasted the text of ${u.length} cut note${u.length===1?"":"s"} from "${p.split("/").pop()}" into the composer and removed the original${Q===1?"":"s"} (${Q} note${Q===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:u,folder:p,duration:0});return}this.plugin.clearNoteClipboard();let e=t.ids.map(p=>this.tree.get(p)).filter(p=>!!p&&!!p.file);if(!e.length)return;let i=[],s=new Set,n=(p,u)=>{if(!s.has(p.id)){s.add(p.id),i.push({node:p,depth:u});for(let g of this.tree.getChildren(p.id))n(g,u+1)}};for(let p of e)n(p,0);let o=this.noteFolder,r=j().prefixTimestampsOnCopy,l=[];for(let{node:p,depth:u}of i)if(p.file)try{let g=this.stripFrontmatter(await this.app.vault.cachedRead(p.file)).trim().split(/\r?\n/).join(" "),I=r?`${this.formatTimeInline(p.created)} `:"";l.push(`${" ".repeat(u)}- ${I}${g}`)}catch{}this.insertIntoComposer(l.join(` -`));let c=i.map(p=>p.node),A=await this.snapshotNotes(c,!1);for(let p of[...c].reverse())if(p.file)try{await this.app.fileManager.trashFile(p.file)}catch(u){console.warn("[Stashpad] cut-paste delete failed",p.file.path,u)}this.selection.clear(),this.tree.rebuild(o),this.render();let h=e.map(p=>p.id);this.plugin.getUndoStack(o).push({label:`Cut ${e.length} note${e.length===1?"":"s"} into composer`,undo:async()=>{await this.restoreSnapshots(A,h)},redo:async()=>{for(let p of[...A.notes]){let u=this.app.vault.getAbstractFileByPath(p.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 Xt(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Insert which note as a template?",allowCreate:!1,onPick:async t=>{if(t.crossFolder){new k.Notice("Cross-Stashpad templates aren't supported yet \u2014 pick a note from this Stashpad.");return}let e=this.tree.get(t.id);if(!e?.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(e,this.focusId,s);if(!n)return;this.tree.rebuild(i),this.pendingFocusIds=[n],this.render();let o=s.map(l=>this.app.vault.getAbstractFileByPath(l)).filter(l=>!!l&&l.extension==="md").map(l=>({id:fe(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!==be&&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!==F&&this.navigateUp();return}this.navForwardSnapshots.push(this.captureNavSnapshot()),this.applyNavSnapshot(t)}navigateForward(){let t=this.navForwardSnapshots.pop();t&&(this.navBackStack.push(this.captureNavSnapshot()),this.applyNavSnapshot(t))}async applyNavSnapshot(t){if(this.tagFilter=null,this.colorFilter=null,t.folder!==this.noteFolder){await this.setFolderOverride(t.folder,{skipHistory:!0}),t.focusId!==this.focusId&&this.tree.get(t.focusId)&&(this.focusId=t.focusId,this.render({kind:"preserve"}));return}if(!this.tree.get(t.focusId))return;this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t.focusId,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus();let e=this.lastCursorByFocus.get(t.focusId),i;e&&this.tree.get(e)?(this.pendingFocusIds=[e],i={kind:"scroll-to-id",id:e,align:"start"}):i={kind:"preserve"},this.render(i),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateUp(){this.selectionGuardKey++,this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null){if(this.navBackStack.length>0){this.navigateBack();return}return this.navigateTo(F)}let e=this.focusId;if(this.recordNavState(),this.listEl){let o=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;o&&this.plugin.saveLastCursor(this.noteFolder,e,o)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let i=this.filterChildren(this.tree.getChildren(this.focusId)),s=i.findIndex(n=>n.id===e);this.selection.clear(),s>=0?(this.cursorIdx=s,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=i.length-1,i.length>0&&(this.selection.add(i[i.length-1].id),this.lastSelected=i[i.length-1].id)),s>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),s<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),i=new k.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(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=[F],e=this.tree.getRoot(),i=s=>{for(let n of this.tree.getChildren(s))t.push(n.id),i(n.id)};for(let s of e.children)i(s);for(let s of t)this.fmSync.wouldWrite(s)&&this.fmSync.schedule(s)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata +`);await navigator.clipboard.writeText(i),this.plugin.clearNoteClipboard(),this.plugin.noteClipboard={mode:"cut",folder:this.noteFolder,ids:t.map(s=>s.id),text:i},this.render(),this.plugin.noteClipboardNotice=this.plugin.notifications.show({message:`Cut ${this.titleList(t)} \u2014 paste in the LIST to move it there as a note; paste in a note's COMPOSER to drop its text in and delete the original (undoable). Esc cancels. Nothing happens until you paste.`,kind:"info",category:"system",affectedIds:t.map(s=>s.id),folder:this.noteFolder,duration:0})}async cmdPasteNotes(){let t=this.plugin.noteClipboard;if(!t){new k.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){let g=(this.currentChildren[this.cursorIdx]??null)?.parent??this.focusId??F,u=t.mode,p=t.folder,I=await this.plugin.crossFolderPaste(p,t.ids,this.noteFolder,g,u);if(!I||!I.rootIds.length)return;u==="cut"&&this.plugin.clearNoteClipboard();let f=this.noteFolder;this.tree.rebuild(f),this.pendingFocusIds=I.rootIds.slice(),this.render(),u==="cut"&&this.plugin.refreshOpenViewsForFolder(p);let m=p.split("/").pop(),C=I.rootIds.length,B=()=>{this.tree.rebuild(f),this.render(),this.plugin.refreshOpenViewsForFolder(p)};this.plugin.getUndoStack(f).push({label:`${u==="cut"?"Move":"Paste"} ${C} note${C===1?"":"s"} from ${m}`,undo:async()=>{await I.undo(),B()},redo:async()=>{await I.redo(),B()}});let Q=u==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${Q} ${C} note${C===1?"":"s"} (${I.noteCount} total) from "${m}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:u==="cut"?"move":"clone",affectedIds:I.rootIds,folder:f,duration:0});return}let e=t.ids.map(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new k.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??F;if(t.mode==="cut"){let h=new Set(t.ids);for(let u=s;u&&u!==F;u=this.tree.get(u)?.parent??null)if(h.has(u)){new k.Notice("Can't paste cut notes under themselves.");return}let g=i&&!h.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(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:fe(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 A=r.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:A,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),I=j().prefixTimestampsOnCopy,f=[];for(let{file:y,created:E,depth:v}of p)try{let w=this.stripFrontmatter(await this.app.vault.cachedRead(y)).trim().split(/\r?\n/).join(" "),D=I?`${this.formatTimeInline(E)} `:"";f.push(`${" ".repeat(v)}- ${D}${w}`)}catch{}this.insertIntoComposer(f.length?f.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 Q=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${Q===1?"":"s"} (${Q} note${Q===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=j().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(" "),I=r?`${this.formatTimeInline(g.created)} `:"";l.push(`${" ".repeat(u)}- ${I}${p}`)}catch{}this.insertIntoComposer(l.join(` +`));let c=i.map(g=>g.node),A=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(A,h)},redo:async()=>{for(let g of[...A.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 Xt(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Insert which note as a template?",allowCreate:!1,onPick:async t=>{if(t.crossFolder){new k.Notice("Cross-Stashpad templates aren't supported yet \u2014 pick a note from this Stashpad.");return}let e=this.tree.get(t.id);if(!e?.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(e,this.focusId,s);if(!n)return;this.tree.rebuild(i),this.pendingFocusIds=[n],this.render();let o=s.map(l=>this.app.vault.getAbstractFileByPath(l)).filter(l=>!!l&&l.extension==="md").map(l=>({id:fe(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!==be&&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!==F&&this.navigateUp();return}this.navForwardSnapshots.push(this.captureNavSnapshot()),this.applyNavSnapshot(t)}navigateForward(){let t=this.navForwardSnapshots.pop();t&&(this.navBackStack.push(this.captureNavSnapshot()),this.applyNavSnapshot(t))}async applyNavSnapshot(t){if(this.tagFilter=null,this.colorFilter=null,t.folder!==this.noteFolder){await this.setFolderOverride(t.folder,{skipHistory:!0}),t.focusId!==this.focusId&&this.tree.get(t.focusId)&&(this.focusId=t.focusId,this.render({kind:"preserve"}));return}if(!this.tree.get(t.focusId))return;this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t.focusId,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus();let e=this.lastCursorByFocus.get(t.focusId),i;e&&this.tree.get(e)?(this.pendingFocusIds=[e],i={kind:"scroll-to-id",id:e,align:"start"}):i={kind:"preserve"},this.render(i),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateUp(){this.selectionGuardKey++,this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null){if(this.navBackStack.length>0){this.navigateBack();return}return this.navigateTo(F)}let e=this.focusId;if(this.recordNavState(),this.listEl){let o=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;o&&this.plugin.saveLastCursor(this.noteFolder,e,o)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let i=this.filterChildren(this.tree.getChildren(this.focusId)),s=i.findIndex(n=>n.id===e);this.selection.clear(),s>=0?(this.cursorIdx=s,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=i.length-1,i.length>0&&(this.selection.add(i[i.length-1].id),this.lastSelected=i[i.length-1].id)),s>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),s<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),i=new k.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(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=[F],e=this.tree.getRoot(),i=s=>{for(let n of this.tree.getChildren(s))t.push(n.id),i(n.id)};for(let s of e.children)i(s);for(let s of t)this.fmSync.wouldWrite(s)&&this.fmSync.schedule(s)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata File: \`${t}\` Error: ${e.message}`,kind:"error",category:"system",duration:0,affectedPaths:[t],folder:this.noteFolder})}))}async ensureHomeNote(){let t=this.noteFolder,e=`${t}/${this.buildHomeFilename(t)}`,i=this.app.vault.getMarkdownFiles().filter(o=>o.path.startsWith(t+"/"));for(let o of i){if(this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==F)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let c=this.app.vault.getAbstractFileByPath(e);if(c instanceof k.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: ${F}`,"parent: null",`created: ${s}`,"attachments: []","---","","# Home","","This is your Stashpad home note. Edit me freely \u2014 everything else nests below.",""].join(` -`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===F)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,r=>{r.parent=F}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:F,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:J,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let l=!1;return e.iterateAllLeaves(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:J,active:!0,state:{focusId:e,folderOverride:i===s?null:i}}),n.setActiveLeaf(o,{focus:!0}),n.revealLeaf(o)}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let i=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",s=this.app.workspace,n=this.leaf,o=s.getLeaf("tab");await o.setViewState({type:J,active:!0,state:{focusId:F,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let r=s.on("active-leaf-change",()=>{if((()=>{let A=!1;return s.iterateAllLeaves(h=>{h===o&&(A=!0)}),A})())return;s.offref(r),(()=>{let A=!1;return s.iterateAllLeaves(h=>{h===n&&(A=!0)}),A})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new k.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.openFile(t,{active:!0}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let A=!1;return e.iterateAllLeaves(h=>{h===s&&(A=!0)}),A})())return;e.offref(n),(()=>{let A=!1;return e.iterateAllLeaves(h=>{h===i&&(A=!0)}),A})()&&(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 k.Notice("Nothing to pin.");return}let e=t.some(n=>!this.plugin.isPinned({folder:this.noteFolder,id:n.id})),i=0,s=0;for(let n of t){let o={folder:this.noteFolder,id:n.id};e?this.plugin.isPinned(o)||(await this.plugin.pinNote(o),i++):this.plugin.isPinned(o)&&(await this.plugin.unpinNote(o),s++)}i>0?new k.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new k.Notice(`Unpinned ${s} note${s===1?"":"s"} from sidebar.`)}isListPinned(t){let e=this.tree.get(t);if(!e?.file)return!1;let i=this.listPinnedState.get(e.file.path);return i?i.pinned:this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinned===!0}listPinnedAt(t){let e=this.tree.get(t);if(!e?.file)return 0;let i=this.listPinnedState.get(e.file.path);if(i)return i.at;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinnedAt,n=typeof s=="string"?Date.parse(s):NaN;return Number.isNaN(n)?0:n}hoistListPinned(t,e){let i=this.tree.getChildren(t).map(l=>l.id);if(!i.some(l=>this.isListPinned(l)))return e;let s=new Set(e),n=[...e,...i.filter(l=>!s.has(l))],o=n.filter(l=>this.isListPinned(l)).sort((l,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 k.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,A=>{e?(A.listPinned=!0,A.listPinnedAt||(A.listPinnedAt=s)):(delete A.listPinned,delete A.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,A=typeof r.listPinnedAt=="string"&&Date.parse(r.listPinnedAt)||0;this.listPinnedState.set(r.path,{pinned:c,at:A})}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 k.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,A=>{l.was?A.completed=!0:delete A.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 k.Notice("Nothing to schedule.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=i&&(typeof i.due=="string"||typeof i.due=="number")?String(i.due):null,n=this.plugin.collectKnownAuthors(),o=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 A=this.app.metadataCache.getFileCache(c.file)?.frontmatter,h=this.isTaskTagged(c);s.push({id:c.id,path:c.file.path,due:A?.due,task:A?.task,assignedTo:A?.assignedTo,assignedBy:A?.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 p=e!==null||r.length>0;this.taskTaggedState.set(c.file.path,p||h),n.push(c.id)}if(this.render(),n.length>0){let c=n.map(A=>this.tree.get(A)).filter(A=>!!A);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${oe(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 A=this.app.vault.getAbstractFileByPath(c.path);A&&(await this.app.fileManager.processFrontMatter(A,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 k.Notice("Nothing to assign.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=i&&(typeof i.due=="string"||typeof i.due=="number")?String(i.due):null,n=this.plugin.collectKnownAuthors(),o=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 k.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 A=!1;await this.app.fileManager.processFrontMatter(r.file,h=>{e?(Bn(h,"task"),h.completed===void 0&&(h.completed=!1),A=h.completed===!0,delete h.task):(yn(h,"task"),delete h.completed,delete h.task,A=!1)}),this.completedState.set(r.file.path,A),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,A=>{e?(Bn(A,"task"),A.completed===void 0&&(A.completed=!1),c=A.completed===!0,delete A.task):(yn(A,"task"),delete A.completed,delete A.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!==F&&!s.has(e.id);){s.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:i};e=e.parent?this.tree.get(e.parent):void 0,i+=1}return null}isDescendant(t,e){let i=this.tree.get(t),s=new Set;for(;i&&i.parent&&!s.has(i.id);){if(i.parent===e)return!0;s.add(i.id),i=this.tree.get(i.parent)}return!1}async moveAcrossThenReorder(t,e,i,s){let n=[],o=new Set;for(let v of t){let w=this.tree.get(v);w?.file&&(n.push({id:v,path:w.file.path,oldParent:w.parent}),o.add(w.parent??F))}o.add(e);let 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 w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.fmSync.scheduleParentChange(v.id,v.oldParent,e),await this.log.append({type:"parent_change",id:v.id,payload:{from:v.oldParent,to:e,reason:"drag"}}),this.order.removeChild(l,v.id))}this.tree.rebuild(l);let A=this.tree.getChildren(e).map(v=>v.id),h=new Set(t),p=A.filter(v=>!h.has(v)),u=p.indexOf(i);u<0&&(u=p.length),s==="after"&&(u+=1);let g=[...p.slice(0,u),...t.filter(v=>!!this.tree.get(v)),...p.slice(u)];this.order.setOrder(l,e,g),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 I=this.focusId===e,m=I?t[0]:e,f=I?t.slice():[e];I?this.pendingFocusIds=f:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=f),this.tree.rebuild(l),this.render({kind:"follow-cursor"});let C=this.selectionGuardKey,B=()=>{if(this.selectionGuardKey!==C||this.selection.has(m))return;let v=this.currentChildren.findIndex(w=>w.id===m);v<0||(this.selection.add(m),this.cursorIdx=v,this.render({kind:"follow-cursor"}))};setTimeout(B,120),setTimeout(B,400);let Q=t.map(v=>this.tree.get(v)).filter(v=>!!v),y=this.tree.get(e),E=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:Q,destination:`\u2192 "${E}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:r,folder:l,actions:e===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(l).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{v.oldParent===null||v.oldParent===void 0?D.parent=F:D.parent=v.oldParent}),await this.log.append({type:"parent_change",id:v.id,payload:{from:e,to:v.oldParent,reason:"drag-undo"}}))}for(let[v,w]of Object.entries(c))if(w.length===0){let D=this.order.cache.get(l)??{};delete D[v],this.order.cache.set(l,D)}else this.order.setOrder(l,v,w);await this.order.save(l),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(l),this.render()},redo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.order.removeChild(l,v.id))}this.order.setOrder(l,e,g),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??F;if(n.some(C=>(C.parent??F)!==o)){let C=j(),B=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(Q=>Q.id),o,"","after"):await this.moveAcrossThenReorder(n.map(Q=>Q.id),o,e,i)};if(C.confirmCrossParentDrag){let Q=this.titleForNode(s),y=n.length,E=i==="into"?"Nest":"Move",v=i==="into"?"as children of":"under";new nt(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${E} ${y} note${y===1?"":"s"} ${v} "${Q}"? Their parent will change.`,E,w=>{w&&B()}).open()}else await B();return}let l=o,c=n.map(C=>C.id),A=this.tree.getChildren(l).map(C=>C.id),h=new Set(c),p=A.filter(C=>!h.has(C)),u=p.indexOf(e);if(u<0)return;i==="after"&&(u+=1);let g=[...p.slice(0,u),...c,...p.slice(u)];if(Qn(g,A))return;let I=this.noteFolder,m=this.order.getOrder(I,l).slice();this.order.setOrder(I,l,g),await this.order.save(I),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(I),this.render();let f=c.map(C=>this.tree.get(C)).filter(C=>!!C);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:f}),kind:"success",category:"reorder",affectedIds:c,folder:I}),this.plugin.getUndoStack(I).push({label:`Reorder (drag, ${c.length})`,undo:async()=>{if(m.length===0){let C=this.order.cache.get(I)??{};delete C[l],this.order.cache.set(I,C)}else this.order.setOrder(I,l,m);await this.order.save(I),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(I),this.render()},redo:async()=>{this.order.setOrder(I,l,g),await this.order.save(I),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(I),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 k.Notice("Reorder requires a single-parent selection.");return}e=h}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new k.Notice("Nothing to reorder.");return}let i=e[0].parent??F,s=this.tree.getChildren(i).map(h=>h.id);if(s.length===0)return;let n=new Set(e.map(h=>h.id)),o=s.filter(h=>n.has(h));if(o.length===0)return;let r=Xo(s,o,t);if(Qn(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 A=o.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:A,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 k.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 k.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),A=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(A[C])));let Q=this.app.metadataCache.getFileCache(B.file)?.frontmatter;if(Array.isArray(Q?.attachments))for(let y of Q.attachments)typeof y=="string"&&y.trim()&&h.push(Se(y))}let p=[...new Set(h)],u=o.length-t.length,g=async C=>{let B=await this.snapshotNotes(o,C),Q=0;if(C)for(let P of p){let R=this.app.metadataCache.getFirstLinkpathDest(P,"");if(R)try{await this.app.fileManager.trashFile(R),await this.log.append({type:"attachment_remove",id:F,payload:{path:R.path}}),this.plugin.notifications.show({message:`Deleted attachment "${R.name}"`,kind:"warning",category:"attachment",affectedPaths:[R.path],folder:this.noteFolder}),Q+=1}catch{}}let y=new Set;for(let P of o)P.parent&&y.add(P.parent);let E=this.authorship.collectAuthorIds(o),v=new Set(t.map(P=>P.id)),w=this.currentChildren.map((P,R)=>v.has(P.id)?R:-1).filter(P=>P>=0),D=w.length>0?w[0]:-1,b=null;if(D>=0){for(let P=D+1;P<this.currentChildren.length;P++)if(!v.has(this.currentChildren[P].id)){b=this.currentChildren[P].id;break}if(!b){for(let P=D-1;P>=0;P--)if(!v.has(this.currentChildren[P].id)){b=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?p:[]}})}this.selection.clear(),this.cursorIdx=-1,b&&(this.pendingFocusIds=[b]),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=Q>0?` with ${Q} attachment${Q===1?"":"s"}`:"",U=this.noteFolder,x=t.map(P=>P.id),S=!1,T=async()=>{S||(S=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(B,x.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:E,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,S=!1,await this.trashNotesAndAttachments(B)}}),this.focusView()},I=j(),m=I.confirmBulkDelete,f=p.length>0&&I.confirmAttachmentDelete;if(!m&&!f){await g(!1);return}new We(this.app,`${t.length} selected note${t.length===1?"":"s"}`,u,p.length,f,g).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new k.Notice("Pick a note to split.");return}let i=e.file,s=await this.app.vault.read(i),n=this.stripFrontmatter(s).replace(/\s+$/,""),o=n.split(/\r?\n/);if(n.trim().length<2){new k.Notice("Note is too short to split.");return}let r=s,l=i.path,c=async(h,p,u)=>{if(!h.trim()||!p.trim()){new k.Notice("Split would leave one part empty.");return}try{let g=s.startsWith("---")?s.slice(0,s.indexOf(` ----`,3)+4):"",I=g+(g?` +`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===F)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,r=>{r.parent=F}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:F,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:J,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let l=!1;return e.iterateAllLeaves(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:J,active:!0,state:{focusId:e,folderOverride:i===s?null:i}}),n.setActiveLeaf(o,{focus:!0}),n.revealLeaf(o)}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let i=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",s=this.app.workspace,n=this.leaf,o=s.getLeaf("tab");await o.setViewState({type:J,active:!0,state:{focusId:F,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let r=s.on("active-leaf-change",()=>{if((()=>{let A=!1;return s.iterateAllLeaves(h=>{h===o&&(A=!0)}),A})())return;s.offref(r),(()=>{let A=!1;return s.iterateAllLeaves(h=>{h===n&&(A=!0)}),A})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new k.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.openFile(t,{active:!0}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let A=!1;return e.iterateAllLeaves(h=>{h===s&&(A=!0)}),A})())return;e.offref(n),(()=>{let A=!1;return e.iterateAllLeaves(h=>{h===i&&(A=!0)}),A})()&&(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 k.Notice("Nothing to pin.");return}let e=t.some(n=>!this.plugin.isPinned({folder:this.noteFolder,id:n.id})),i=0,s=0;for(let n of t){let o={folder:this.noteFolder,id:n.id};e?this.plugin.isPinned(o)||(await this.plugin.pinNote(o),i++):this.plugin.isPinned(o)&&(await this.plugin.unpinNote(o),s++)}i>0?new k.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new k.Notice(`Unpinned ${s} note${s===1?"":"s"} from sidebar.`)}isListPinned(t){let e=this.tree.get(t);if(!e?.file)return!1;let i=this.listPinnedState.get(e.file.path);return i?i.pinned:this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinned===!0}listPinnedAt(t){let e=this.tree.get(t);if(!e?.file)return 0;let i=this.listPinnedState.get(e.file.path);if(i)return i.at;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter?.listPinnedAt,n=typeof s=="string"?Date.parse(s):NaN;return Number.isNaN(n)?0:n}hoistListPinned(t,e){let i=this.tree.getChildren(t).map(l=>l.id);if(!i.some(l=>this.isListPinned(l)))return e;let s=new Set(e),n=[...e,...i.filter(l=>!s.has(l))],o=n.filter(l=>this.isListPinned(l)).sort((l,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 k.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,A=>{e?(A.listPinned=!0,A.listPinnedAt||(A.listPinnedAt=s)):(delete A.listPinned,delete A.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,A=typeof r.listPinnedAt=="string"&&Date.parse(r.listPinnedAt)||0;this.listPinnedState.set(r.path,{pinned:c,at:A})}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 k.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,A=>{l.was?A.completed=!0:delete A.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?$e(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 k.Notice("Nothing to schedule.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=i&&(typeof i.due=="string"||typeof i.due=="number")?String(i.due):null,n=this.plugin.collectKnownAuthors(),o=De(i??{});new je(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 A=this.app.metadataCache.getFileCache(c.file)?.frontmatter,h=this.isTaskTagged(c);s.push({id:c.id,path:c.file.path,due:A?.due,task:A?.task,assignedTo:A?.assignedTo,assignedBy:A?.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(A=>this.tree.get(A)).filter(A=>!!A);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 A=this.app.vault.getAbstractFileByPath(c.path);A&&(await this.app.fileManager.processFrontMatter(A,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 k.Notice("Nothing to assign.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=i&&(typeof i.due=="string"||typeof i.due=="number")?String(i.due):null,n=this.plugin.collectKnownAuthors(),o=De(i??{});new je(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 k.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 A=!1;await this.app.fileManager.processFrontMatter(r.file,h=>{e?(En(h,"task"),h.completed===void 0&&(h.completed=!1),A=h.completed===!0,delete h.task):(wn(h,"task"),delete h.completed,delete h.task,A=!1)}),this.completedState.set(r.file.path,A),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,A=>{e?(En(A,"task"),A.completed===void 0&&(A.completed=!1),c=A.completed===!0,delete A.task):(wn(A,"task"),delete A.completed,delete A.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!==F&&!s.has(e.id);){s.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:i};e=e.parent?this.tree.get(e.parent):void 0,i+=1}return null}isDescendant(t,e){let i=this.tree.get(t),s=new Set;for(;i&&i.parent&&!s.has(i.id);){if(i.parent===e)return!0;s.add(i.id),i=this.tree.get(i.parent)}return!1}async moveAcrossThenReorder(t,e,i,s){let n=[],o=new Set;for(let v of t){let w=this.tree.get(v);w?.file&&(n.push({id:v,path:w.file.path,oldParent:w.parent}),o.add(w.parent??F))}o.add(e);let 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 w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.fmSync.scheduleParentChange(v.id,v.oldParent,e),await this.log.append({type:"parent_change",id:v.id,payload:{from:v.oldParent,to:e,reason:"drag"}}),this.order.removeChild(l,v.id))}this.tree.rebuild(l);let A=this.tree.getChildren(e).map(v=>v.id),h=new Set(t),g=A.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 I=this.focusId===e,f=I?t[0]:e,m=I?t.slice():[e];I?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(f))return;let v=this.currentChildren.findIndex(w=>w.id===f);v<0||(this.selection.add(f),this.cursorIdx=v,this.render({kind:"follow-cursor"}))};setTimeout(B,120),setTimeout(B,400);let Q=t.map(v=>this.tree.get(v)).filter(v=>!!v),y=this.tree.get(e),E=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:Q,destination:`\u2192 "${E}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:r,folder:l,actions:e===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(l).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{v.oldParent===null||v.oldParent===void 0?D.parent=F:D.parent=v.oldParent}),await this.log.append({type:"parent_change",id:v.id,payload:{from:e,to:v.oldParent,reason:"drag-undo"}}))}for(let[v,w]of Object.entries(c))if(w.length===0){let D=this.order.cache.get(l)??{};delete D[v],this.order.cache.set(l,D)}else this.order.setOrder(l,v,w);await this.order.save(l),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(l),this.render()},redo:async()=>{for(let v of n){let w=this.app.vault.getAbstractFileByPath(v.path);w&&(await this.app.fileManager.processFrontMatter(w,D=>{D.parent=e}),this.order.removeChild(l,v.id))}this.order.setOrder(l,e,p),await this.order.save(l),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(l),this.render()}})}async reorderToTarget(t,e,i){let s=this.tree.get(e);if(!s)return;let n=t.map(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??F;if(n.some(C=>(C.parent??F)!==o)){let C=j(),B=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(Q=>Q.id),o,"","after"):await this.moveAcrossThenReorder(n.map(Q=>Q.id),o,e,i)};if(C.confirmCrossParentDrag){let Q=this.titleForNode(s),y=n.length,E=i==="into"?"Nest":"Move",v=i==="into"?"as children of":"under";new nt(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${E} ${y} note${y===1?"":"s"} ${v} "${Q}"? Their parent will change.`,E,w=>{w&&B()}).open()}else await B();return}let l=o,c=n.map(C=>C.id),A=this.tree.getChildren(l).map(C=>C.id),h=new Set(c),g=A.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(vn(p,A))return;let I=this.noteFolder,f=this.order.getOrder(I,l).slice();this.order.setOrder(I,l,p),await this.order.save(I),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(I),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:I}),this.plugin.getUndoStack(I).push({label:`Reorder (drag, ${c.length})`,undo:async()=>{if(f.length===0){let C=this.order.cache.get(I)??{};delete C[l],this.order.cache.set(I,C)}else this.order.setOrder(I,l,f);await this.order.save(I),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(I),this.render()},redo:async()=>{this.order.setOrder(I,l,p),await this.order.save(I),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(I),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 k.Notice("Reorder requires a single-parent selection.");return}e=h}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new k.Notice("Nothing to reorder.");return}let i=e[0].parent??F,s=this.tree.getChildren(i).map(h=>h.id);if(s.length===0)return;let n=new Set(e.map(h=>h.id)),o=s.filter(h=>n.has(h));if(o.length===0)return;let r=_o(s,o,t);if(vn(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 A=o.map(h=>this.tree.get(h)).filter(h=>!!h);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:A,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 k.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 k.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),A=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(A[C])));let Q=this.app.metadataCache.getFileCache(B.file)?.frontmatter;if(Array.isArray(Q?.attachments))for(let y of Q.attachments)typeof y=="string"&&y.trim()&&h.push(Se(y))}let g=[...new Set(h)],u=o.length-t.length,p=async C=>{let B=await this.snapshotNotes(o,C),Q=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:F,payload:{path:R.path}}),this.plugin.notifications.show({message:`Deleted attachment "${R.name}"`,kind:"warning",category:"attachment",affectedPaths:[R.path],folder:this.noteFolder}),Q+=1}catch{}}let y=new Set;for(let P of o)P.parent&&y.add(P.parent);let E=this.authorship.collectAuthorIds(o),v=new Set(t.map(P=>P.id)),w=this.currentChildren.map((P,R)=>v.has(P.id)?R:-1).filter(P=>P>=0),D=w.length>0?w[0]:-1,b=null;if(D>=0){for(let P=D+1;P<this.currentChildren.length;P++)if(!v.has(this.currentChildren[P].id)){b=this.currentChildren[P].id;break}if(!b){for(let P=D-1;P>=0;P--)if(!v.has(this.currentChildren[P].id)){b=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,b&&(this.pendingFocusIds=[b]),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=Q>0?` with ${Q} attachment${Q===1?"":"s"}`:"",U=this.noteFolder,x=t.map(P=>P.id),S=!1,T=async()=>{S||(S=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(B,x.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:E,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,S=!1,await this.trashNotesAndAttachments(B)}}),this.focusView()},I=j(),f=I.confirmBulkDelete,m=g.length>0&&I.confirmAttachmentDelete;if(!f&&!m){await p(!1);return}new Xe(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 k.Notice("Pick a note to split.");return}let i=e.file,s=await this.app.vault.read(i),n=this.stripFrontmatter(s).replace(/\s+$/,""),o=n.split(/\r?\n/);if(n.trim().length<2){new k.Notice("Note is too short to split.");return}let r=s,l=i.path,c=async(h,g,u)=>{if(!h.trim()||!g.trim()){new k.Notice("Split would leave one part empty.");return}try{let p=s.startsWith("---")?s.slice(0,s.indexOf(` +---`,3)+4):"",I=p+(p?` `:"")+h+` -`;await this.app.vault.modify(i,I);let m=e.parent??F,f=Date.parse(e.created||""),C=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),B=await this.createNoteUnder(p,m,{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 Q=B?this.tree.get(B):void 0,y=Q?.file?.path,E=y?await this.app.vault.read(Q.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(y){let D=this.app.vault.getAbstractFileByPath(y);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}let w=this.app.vault.getAbstractFileByPath(l);w&&await this.app.vault.modify(w,r),this.tree.rebuild(v),this.render()},redo:async()=>{let w=this.app.vault.getAbstractFileByPath(l);w&&await this.app.vault.modify(w,I),y&&E&&!await this.app.vault.adapter.exists(y)&&await this.app.vault.create(y,E),this.tree.rebuild(v),this.render()}})}catch(g){new k.Notice(`Stashpad: split failed (${g.message})`),console.error(g)}},A=async h=>{if(!(h.length<2))try{let p=s.startsWith("---")?s.slice(0,s.indexOf(` ----`,3)+4):"",u=h[0].replace(/\s+$/,"");if(!u.trim()){new k.Notice("Split would leave the first part empty.");return}let g=p+(p?` +`;await this.app.vault.modify(i,I);let f=e.parent??F,m=Date.parse(e.created||""),C=Number.isFinite(m)?new Date(m+1).toISOString():new Date().toISOString(),B=await this.createNoteUnder(g,f,{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 Q=B?this.tree.get(B):void 0,y=Q?.file?.path,E=y?await this.app.vault.read(Q.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(y){let D=this.app.vault.getAbstractFileByPath(y);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}let w=this.app.vault.getAbstractFileByPath(l);w&&await this.app.vault.modify(w,r),this.tree.rebuild(v),this.render()},redo:async()=>{let w=this.app.vault.getAbstractFileByPath(l);w&&await this.app.vault.modify(w,I),y&&E&&!await this.app.vault.adapter.exists(y)&&await this.app.vault.create(y,E),this.tree.rebuild(v),this.render()}})}catch(p){new k.Notice(`Stashpad: split failed (${p.message})`),console.error(p)}},A=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 k.Notice("Split would leave the first part empty.");return}let p=g+(g?` `:"")+u+` -`;await this.app.vault.modify(i,g);let I=e.parent??F,m=Date.parse(e.created||""),f=Number.isFinite(m)?m:Date.now(),C=[];this.beginBulkRender();try{for(let y=1;y<h.length;y++)await this.createNoteUnder(h[y],I,{record:!1,createdOverride:new Date(f+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(),Q=this.noteFolder;this.plugin.getUndoStack(Q).push({label:`Split note into ${h.length}`,undo:async()=>{for(let{path:E}of B){let v=this.app.vault.getAbstractFileByPath(E);if(v)try{await this.app.fileManager.trashFile(v)}catch{}}let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,r),this.tree.rebuild(Q),this.render()},redo:async()=>{let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,g);for(let{path:E,content:v}of B)await this.app.vault.adapter.exists(E)||await this.app.vault.create(E,v);this.tree.rebuild(Q),this.render()}})}catch(p){new k.Notice(`Stashpad: split failed (${p.message})`),console.error(p)}};new Ei(this.app,n,async h=>{let p=o.slice(0,h).join(` +`;await this.app.vault.modify(i,p);let I=e.parent??F,f=Date.parse(e.created||""),m=Number.isFinite(f)?f:Date.now(),C=[];this.beginBulkRender();try{for(let y=1;y<h.length;y++)await this.createNoteUnder(h[y],I,{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(),Q=this.noteFolder;this.plugin.getUndoStack(Q).push({label:`Split note into ${h.length}`,undo:async()=>{for(let{path:E}of B){let v=this.app.vault.getAbstractFileByPath(E);if(v)try{await this.app.fileManager.trashFile(v)}catch{}}let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,r),this.tree.rebuild(Q),this.render()},redo:async()=>{let y=this.app.vault.getAbstractFileByPath(l);y&&await this.app.vault.modify(y,p);for(let{path:E,content:v}of B)await this.app.vault.adapter.exists(E)||await this.app.vault.create(E,v);this.tree.rebuild(Q),this.render()}})}catch(g){new k.Notice(`Stashpad: split failed (${g.message})`),console.error(g)}};new wi(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(p,u,{mode:"line",splitAtLine:h})},async h=>{let p=n.slice(0,h).replace(/\s+$/,""),u=n.slice(h).replace(/^\s+|\s+$/g,"");await c(p,u,{mode:"cursor",splitAtChar:h})},async h=>{await A(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 wr(this,t)}cmdExportOkf(t){return Fr(this,t)}cmdImportStash(){return Dr(this)}processStashFile(t){return vo(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 m=(this.plugin.settings.noteTemplates??{})[s];if(m){let f=this.app.vault.getAbstractFileByPath(m);if(f&&f.extension==="md")try{let C=await this.app.vault.cachedRead(f),B=this.stripFrontmatter(C);r=this.app.metadataCache.getFileCache(f)?.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 A(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 Dr(this,t)}cmdExportOkf(t){return Nr(this,t)}cmdImportStash(){return Tr(this)}processStashFile(t){return So(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 f=(this.plugin.settings.noteTemplates??{})[s];if(f){let m=this.app.vault.getAbstractFileByPath(f);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} -${B}`):t=B}catch(C){console.warn("[Stashpad] template read failed",C)}}}let l=Et(t,this.activeStopwords()),c=wt(l,o),A=`${s}/${c}`,h=e??this.focusId,p=i.createdOverride??new Date().toISOString(),u=this.extractAttachments(t),g=this.authorship.currentAuthorLink();g&&this.authorship.ensureAuthorFile(g);let I=["---",`id: ${o}`,`parent: ${h}`,`created: ${p}`,`modified: ${p}`];if(g&&I.push(`author: "${g.link.replace(/"/g,'\\"')}"`),u.length>0){I.push("attachments:");for(let m of u)I.push(` - "${m.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",t);try{let m=I.join(` -`);this.plugin.importService.suppress(A,6e4),await Ft.timeAsync("write.createNote.file",()=>this.app.vault.create(A,m)),i.collectInto?.push({path:A,content:m});try{let f=this.app.vault.getAbstractFileByPath(A);if(f&&f.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:h,children:[],file:f,created:p}),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(Q=>Q.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(f,C=>{for(let[B,Q]of Object.entries(r))se.includes(B)||ts.includes(B)||C[B]===void 0&&(C[B]=Q)})}catch(C){console.warn("[Stashpad] template fm overlay failed",C)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:A,parent:h}}),i.record!==!1&&!i.deferUndo){let f=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let C=this.app.vault.getAbstractFileByPath(A);if(C)try{await this.app.fileManager.trashFile(C)}catch{}if(this.composerDraft=f,this.saveDraft(f),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=f;let B=f.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(A)||await this.app.vault.create(A,m),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(f),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(m){return new k.Notice(`Stashpad: failed to create note (${m.message})`),null}}async createNotesBatch(t,e,i,s,n){let o=t.length,r=[],l=!!i?.targetFolder&&i.targetFolder!==this.noteFolder,c=8,A=null;if(o>=c){let h=new k.Notice("",0),p=h.messageEl;p.empty(),p.createDiv({cls:"stashpad-split-progress-title",text:`Splitting into ${o} notes\u2026`});let g=p.createDiv({cls:"stashpad-split-progress-bar"}).createDiv({cls:"stashpad-split-progress-fill"}),I=p.createDiv({cls:"stashpad-split-progress-label",text:`0 / ${o}`});A={notice:h,fill:g,label:I}}this.beginBulkRender();try{for(let h=0;h<o;h++)if(await this.createNoteUnder(t[h],e,{...i??{},deferRender:!0,deferUndo:!0,collectInto:r}),A){let p=h+1;A.label.setText(`${p} / ${o}`),A.fill.setCssStyles({width:`${Math.round(p/o*100)}%`}),p%5===0&&await new Promise(u=>window.setTimeout(u,0))}}finally{A?.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:p}of h){let u=this.app.vault.getAbstractFileByPath(p);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 p=s.length;this.composerInputEl.setSelectionRange(p,p),this.composerInputEl.focus()}l||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let{path:p,content:u}of h)await this.app.vault.adapter.exists(p)||await this.app.vault.create(p,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 k.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${As(s,n)}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:F,payload:{path:o,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[o],folder:this.noteFolder}),`![[${o}]]`}catch(e){return new k.Notice(`Stashpad: attachment failed (${e.message})`),null}}claimSelectedAsAuthor(){this.authorship.claimSelectedAsAuthor()}claimFolderAsAuthor(){this.authorship.claimFolderAsAuthor()}claimSelectedWithContributor(){this.authorship.claimSelectedWithContributor()}claimFolderWithContributor(){this.authorship.claimFolderWithContributor()}renderAuthorshipFooter(t,e){if(!e.file)return;let i=this.plugin.settings;if(!i.showAuthor&&!i.showContributors&&!i.showLastEdit)return;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof s.author=="string"?s.author:"",o=Array.isArray(s.contributors)?s.contributors.filter(g=>typeof g=="string"&&g.trim()!==""):[],r=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",l=i.showAuthor&&!!n,c=i.showContributors&&o.length>0,A=i.showLastEdit&&!!r;if(!l&&!c&&!A)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),p=(g,I)=>{let m=I.replace(/^\[\[/,"").replace(/\]\]$/,""),f=m.indexOf("|"),C=f>=0?m.slice(0,f):m,B=f>=0?m.slice(f+1):m.split("/").pop()??m,Q=g.createEl("a",{cls:"internal-link",text:B});Q.setAttribute("data-href",C),Q.setAttribute("href",C)},u=[];l&&u.push(g=>{g.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(g,n)}),c&&u.push(g=>{g.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((I,m)=>{m>0&&g.createSpan({text:", "}),p(g,I)})}),A&&u.push(g=>{g.createSpan({cls:"stashpad-authorship-label",text:"edited "}),g.createSpan({text:this.formatTimeInline(r)})}),u.forEach((g,I)=>{I>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let m=h.createSpan({cls:"stashpad-authorship-piece"});g(m)}),h.addEventListener("click",g=>this.handleRenderedClick(g,e))}activeStopwords(){return this.plugin.settings.slugStopWords??$t}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,k.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=fe(t.basename);if(!e||e===F)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Et(s,this.activeStopwords()),o=wt(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,k.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(e),s=this.extractAttachments(i),n=this.app.metadataCache.getFileCache(t)?.frontmatter,r=(Array.isArray(n?.attachments)?n.attachments:[]).filter(A=>typeof A=="string").map(A=>Se(A));if(r.length===s.length&&r.every((A,h)=>A===s[h]))return;let c=s.map(A=>Yt(A));await this.app.fileManager.processFrontMatter(t,A=>{A.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,k.moment)(t);if(!e.isValid())return"";if(j().useTemplatesFormat){let s=ks(this.app);if(s)return`${e.format(s.dateFormat)} +${B}`):t=B}catch(C){console.warn("[Stashpad] template read failed",C)}}}let l=Et(t,this.activeStopwords()),c=wt(l,o),A=`${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 I=["---",`id: ${o}`,`parent: ${h}`,`created: ${g}`,`modified: ${g}`];if(p&&I.push(`author: "${p.link.replace(/"/g,'\\"')}"`),u.length>0){I.push("attachments:");for(let f of u)I.push(` - "${f.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",t);try{let f=I.join(` +`);this.plugin.importService.suppress(A,6e4),await Ft.timeAsync("write.createNote.file",()=>this.app.vault.create(A,f)),i.collectInto?.push({path:A,content:f});try{let m=this.app.vault.getAbstractFileByPath(A);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(Q=>Q.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,Q]of Object.entries(r))ne.includes(B)||es.includes(B)||C[B]===void 0&&(C[B]=Q)})}catch(C){console.warn("[Stashpad] template fm overlay failed",C)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:A,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(A);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(A)||await this.app.vault.create(A,f),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(m),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(f){return new k.Notice(`Stashpad: failed to create note (${f.message})`),null}}async createNotesBatch(t,e,i,s,n){let o=t.length,r=[],l=!!i?.targetFolder&&i.targetFolder!==this.noteFolder,c=8,A=null;if(o>=c){let h=new k.Notice("",0),g=h.messageEl;g.empty(),g.createDiv({cls:"stashpad-split-progress-title",text:`Splitting into ${o} notes\u2026`});let p=g.createDiv({cls:"stashpad-split-progress-bar"}).createDiv({cls:"stashpad-split-progress-fill"}),I=g.createDiv({cls:"stashpad-split-progress-label",text:`0 / ${o}`});A={notice:h,fill:p,label:I}}this.beginBulkRender();try{for(let h=0;h<o;h++)if(await this.createNoteUnder(t[h],e,{...i??{},deferRender:!0,deferUndo:!0,collectInto:r}),A){let g=h+1;A.label.setText(`${g} / ${o}`),A.fill.setCssStyles({width:`${Math.round(g/o*100)}%`}),g%5===0&&await new Promise(u=>window.setTimeout(u,0))}}finally{A?.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 k.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${ds(s,n)}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:F,payload:{path:o,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[o],folder:this.noteFolder}),`![[${o}]]`}catch(e){return new k.Notice(`Stashpad: attachment failed (${e.message})`),null}}claimSelectedAsAuthor(){this.authorship.claimSelectedAsAuthor()}claimFolderAsAuthor(){this.authorship.claimFolderAsAuthor()}claimSelectedWithContributor(){this.authorship.claimSelectedWithContributor()}claimFolderWithContributor(){this.authorship.claimFolderWithContributor()}renderAuthorshipFooter(t,e){if(!e.file)return;let i=this.plugin.settings;if(!i.showAuthor&&!i.showContributors&&!i.showLastEdit)return;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof s.author=="string"?s.author:"",o=Array.isArray(s.contributors)?s.contributors.filter(p=>typeof p=="string"&&p.trim()!==""):[],r=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",l=i.showAuthor&&!!n,c=i.showContributors&&o.length>0,A=i.showLastEdit&&!!r;if(!l&&!c&&!A)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),g=(p,I)=>{let f=I.replace(/^\[\[/,"").replace(/\]\]$/,""),m=f.indexOf("|"),C=m>=0?f.slice(0,m):f,B=m>=0?f.slice(m+1):f.split("/").pop()??f,Q=p.createEl("a",{cls:"internal-link",text:B});Q.setAttribute("data-href",C),Q.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((I,f)=>{f>0&&p.createSpan({text:", "}),g(p,I)})}),A&&u.push(p=>{p.createSpan({cls:"stashpad-authorship-label",text:"edited "}),p.createSpan({text:this.formatTimeInline(r)})}),u.forEach((p,I)=>{I>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=h.createSpan({cls:"stashpad-authorship-piece"});p(f)}),h.addEventListener("click",p=>this.handleRenderedClick(p,e))}activeStopwords(){return this.plugin.settings.slugStopWords??$t}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,k.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=fe(t.basename);if(!e||e===F)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Et(s,this.activeStopwords()),o=wt(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,k.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(e),s=this.extractAttachments(i),n=this.app.metadataCache.getFileCache(t)?.frontmatter,r=(Array.isArray(n?.attachments)?n.attachments:[]).filter(A=>typeof A=="string").map(A=>Se(A));if(r.length===s.length&&r.every((A,h)=>A===s[h]))return;let c=s.map(A=>Yt(A));await this.app.fileManager.processFrontMatter(t,A=>{A.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,k.moment)(t);if(!e.isValid())return"";if(j().useTemplatesFormat){let s=Ss(this.app);if(s)return`${e.format(s.dateFormat)} ${e.format(s.timeFormat)}`}return`${e.format("YYYY.MM.DD")} -${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,k.moment)(t);if(!e.isValid())return"";if(j().useTemplatesFormat){let s=ks(this.app);if(s){let n=/:ss/.test(s.timeFormat)?s.timeFormat:s.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(s.dateFormat)} ${e.format(n)}`}}return`${e.format("YYYY.MM.DD")} ${e.format("HH:mm:ss A")}`}scrollListToBottom(){let t=this.listEl;if(!t)return;if(this.stickToListBottom=!0,t.scrollTop=t.scrollHeight,k.Platform.isMobile){let 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 k.Menu;s.addItem(A=>A.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(A=>A.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(A=>A.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(A=>A.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(A=>A.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),s.addItem(A=>A.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(A=>A.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(A=>A.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),this.plugin.settings.okfEnabled&&s.addItem(A=>A.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(A=>A.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let h=this.order.getOrder(this.noteFolder,e.parent??F),p=h.indexOf(e.id),u=p>0?h[p-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,u)&&this.render()})),s.addSeparator(),s.addItem(A=>A.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(A=>A.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,F),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==F&&this.navigateTo(F)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(A=>A.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(A=>A.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(A=>A.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let l=()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id)},c=A=>{let h=this.isTask(e);if(h){let p=this.isCompleted(e);A.addItem(u=>u.setTitle(p?"Mark incomplete":"Mark complete").setIcon(p?"circle":"check-circle").onClick(()=>{l(),this.cmdToggleComplete()}))}else A.addItem(p=>p.setTitle("Turn into task").setIcon("check-square").onClick(()=>{l(),this.cmdToggleTask()}));A.addItem(p=>p.setTitle("Assign / schedule\u2026").setIcon("user-plus").onClick(()=>{l(),this.cmdAssign()})),h&&A.addItem(p=>p.setTitle("Remove from tasks").setIcon("square").onClick(()=>{l(),this.cmdToggleTask()}))};s.addItem(A=>{A.setTitle("Task").setIcon("check-square");let h=typeof A.setSubmenu=="function"?A.setSubmenu():null;h&&typeof h.addItem=="function"?c(h):A.onClick(()=>this.openCommandPalette())}),s.addSeparator(),s.addItem(A=>A.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(A=>A.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=g=>{for(let I of this.tree.getChildren(g.id))i(I),e.push(I)};i(t);let s=[...e,t],n=s.filter(g=>!!g.file),o=await Promise.all(n.map(g=>this.app.vault.cachedRead(g.file))),r=[];for(let g=0;g<n.length;g++){let I=n[g];r.push(...this.extractAttachments(this.stripFrontmatter(o[g])));let m=this.app.metadataCache.getFileCache(I.file)?.frontmatter;if(Array.isArray(m?.attachments))for(let f of m.attachments)typeof f=="string"&&f.trim()&&r.push(Se(f))}let l=[...new Set(r)],c=this.authorship.collectAuthorIds(s),A=async g=>{let I=await this.snapshotNotes(s,g),m=0;if(g)for(let b of l){let H=this.app.metadataCache.getFirstLinkpathDest(b,"");if(H)try{await this.app.fileManager.trashFile(H),await this.log.append({type:"attachment_remove",id:F,payload:{path:H.path}}),this.plugin.notifications.show({message:`Deleted attachment "${H.name}"`,kind:"warning",category:"attachment",affectedPaths:[H.path],folder:this.noteFolder}),m+=1}catch{}}let f=new Set;for(let b of s)b.parent&&f.add(b.parent);let C=this.currentChildren.findIndex(b=>b.id===t.id),B=null;if(C>=0){for(let b=C+1;b<this.currentChildren.length;b++)if(this.currentChildren[b].id!==t.id){B=this.currentChildren[b].id;break}if(!B){for(let b=C-1;b>=0;b--)if(this.currentChildren[b].id!==t.id){B=this.currentChildren[b].id;break}}}for(let b of s)if(b.file){try{await this.app.fileManager.trashFile(b.file)}catch{}await this.log.append({type:"delete",id:b.id,payload:{path:b.file.path,attachmentsRemoved:g?l:[]}})}this.selection.clear(),this.cursorIdx=-1,B&&(this.pendingFocusIds=[B]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let b of f)s.some(H=>H.id===b)||this.fmSync.scheduleParentOfDeleted(b);let Q=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,E=t.id,v=m>0?` with ${m} attachment${m===1?"":"s"}`:"",w=!1,D=async()=>{w||(w=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(I,[E]))};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 D()}]}),this.plugin.getUndoStack(Q).push({label:y,undo:async()=>{await D()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,w=!1,await this.trashNotesAndAttachments(I)}})},h=j(),p=e.length>0&&h.confirmBulkDelete,u=l.length>0&&h.confirmAttachmentDelete;if(!p&&!u){await A(!1),this.focusView();return}new We(this.app,this.titleForNode(t),e.length,l.length,u,async g=>{await A(g),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new k.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===F){new k.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new k.Notice("Couldn't find the parent note.");return}let i=e.parent??F,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(l=>l.id!==t.id).length,r=[`"${n}" becomes a child of "${s}".`];o>0&&r.push(`${o} sibling${o===1?"":"s"} move with it.`),new nt(this.app,"Swap notes?",r.join(` +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,k.moment)(t);if(!e.isValid())return"";if(j().useTemplatesFormat){let s=Ss(this.app);if(s){let n=/:ss/.test(s.timeFormat)?s.timeFormat:s.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(s.dateFormat)} ${e.format(n)}`}}return`${e.format("YYYY.MM.DD")} ${e.format("HH:mm:ss A")}`}scrollListToBottom(){let t=this.listEl;if(!t)return;if(this.stickToListBottom=!0,t.scrollTop=t.scrollHeight,k.Platform.isMobile){let 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 k.Menu;s.addItem(A=>A.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(A=>A.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(A=>A.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(A=>A.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(A=>A.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),s.addItem(A=>A.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(A=>A.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(A=>A.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),this.plugin.settings.okfEnabled&&s.addItem(A=>A.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(A=>A.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let h=this.order.getOrder(this.noteFolder,e.parent??F),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(A=>A.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(A=>A.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,F),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==F&&this.navigateTo(F)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(A=>A.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(A=>A.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(A=>A.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let l=()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id)},c=A=>{let h=this.isTask(e);if(h){let g=this.isCompleted(e);A.addItem(u=>u.setTitle(g?"Mark incomplete":"Mark complete").setIcon(g?"circle":"check-circle").onClick(()=>{l(),this.cmdToggleComplete()}))}else A.addItem(g=>g.setTitle("Turn into task").setIcon("check-square").onClick(()=>{l(),this.cmdToggleTask()}));A.addItem(g=>g.setTitle("Assign / schedule\u2026").setIcon("user-plus").onClick(()=>{l(),this.cmdAssign()})),h&&A.addItem(g=>g.setTitle("Remove from tasks").setIcon("square").onClick(()=>{l(),this.cmdToggleTask()}))};s.addItem(A=>{A.setTitle("Task").setIcon("check-square");let h=typeof A.setSubmenu=="function"?A.setSubmenu():null;h&&typeof h.addItem=="function"?c(h):A.onClick(()=>this.openCommandPalette())}),s.addSeparator(),s.addItem(A=>A.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(A=>A.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 I of this.tree.getChildren(p.id))i(I),e.push(I)};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 I=n[p];r.push(...this.extractAttachments(this.stripFrontmatter(o[p])));let f=this.app.metadataCache.getFileCache(I.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let m of f.attachments)typeof m=="string"&&m.trim()&&r.push(Se(m))}let l=[...new Set(r)],c=this.authorship.collectAuthorIds(s),A=async p=>{let I=await this.snapshotNotes(s,p),f=0;if(p)for(let b of l){let H=this.app.metadataCache.getFirstLinkpathDest(b,"");if(H)try{await this.app.fileManager.trashFile(H),await this.log.append({type:"attachment_remove",id:F,payload:{path:H.path}}),this.plugin.notifications.show({message:`Deleted attachment "${H.name}"`,kind:"warning",category:"attachment",affectedPaths:[H.path],folder:this.noteFolder}),f+=1}catch{}}let m=new Set;for(let b of s)b.parent&&m.add(b.parent);let C=this.currentChildren.findIndex(b=>b.id===t.id),B=null;if(C>=0){for(let b=C+1;b<this.currentChildren.length;b++)if(this.currentChildren[b].id!==t.id){B=this.currentChildren[b].id;break}if(!B){for(let b=C-1;b>=0;b--)if(this.currentChildren[b].id!==t.id){B=this.currentChildren[b].id;break}}}for(let b of s)if(b.file){try{await this.app.fileManager.trashFile(b.file)}catch{}await this.log.append({type:"delete",id:b.id,payload:{path:b.file.path,attachmentsRemoved:p?l:[]}})}this.selection.clear(),this.cursorIdx=-1,B&&(this.pendingFocusIds=[B]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let b of m)s.some(H=>H.id===b)||this.fmSync.scheduleParentOfDeleted(b);let Q=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,E=t.id,v=f>0?` with ${f} attachment${f===1?"":"s"}`:"",w=!1,D=async()=>{w||(w=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(I,[E]))};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 D()}]}),this.plugin.getUndoStack(Q).push({label:y,undo:async()=>{await D()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,w=!1,await this.trashNotesAndAttachments(I)}})},h=j(),g=e.length>0&&h.confirmBulkDelete,u=l.length>0&&h.confirmAttachmentDelete;if(!g&&!u){await A(!1),this.focusView();return}new Xe(this.app,this.titleForNode(t),e.length,l.length,u,async p=>{await A(p),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new k.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===F){new k.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new k.Notice("Couldn't find the parent note.");return}let i=e.parent??F,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(l=>l.id!==t.id).length,r=[`"${n}" becomes a child of "${s}".`];o>0&&r.push(`${o} sibling${o===1?"":"s"} move with it.`),new nt(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 nt(this.app,"Confirm Note Swap",r.join(` -`),"Swap",async l=>{if(!l)return;let c=t.parent??F;await this.swapParentChild(t,i,c)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new k.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(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(),A=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,g=>{g.parent=e.id}),this.fmSync.scheduleParentChange(u.id,t.id,e.id);if(l.length>0){let u=l.includes(t.id)?l.map(g=>g===t.id?e.id:g):[...l.filter(g=>g!==e.id),e.id];this.order.setOrder(s,i,u)}let h=o.map(u=>u.id),p=[t.id,...c.filter(u=>u!==t.id&&!h.includes(u)),...h];this.order.setOrder(s,e.id,p),this.order.setOrder(s,t.id,[]),await this.order.save(s),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:i,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let 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),g=this.tree.get(e.id);u?.file&&await this.app.fileManager.processFrontMatter(u.file,I=>{n==null||n===F?(delete I.parent,I.parent=F):I.parent=n}),g?.file&&await this.app.fileManager.processFrontMatter(g.file,I=>{I.parent=t.id});for(let I of r){let m=this.app.vault.getAbstractFileByPath(I.path);m&&await this.app.fileManager.processFrontMatter(m,f=>{I.was==null?f.parent=F:f.parent=I.was})}this.order.setOrder(s,i,l),this.order.setOrder(s,e.id,c),this.order.setOrder(s,t.id,A),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=l=>l??F;if(o(n)===o(e)){if(!i.quiet){let l=this.titleForNode(t),c=e===F?"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!==F&&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===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let l=this.noteFolder,c=s.path,A=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,p=>{p.parent=n}),this.pendingFocusIds=[A],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 p=this.selectionGuardKey,u=()=>{if(this.selectionGuardKey!==p||this.selection.has(A))return;let g=this.currentChildren.findIndex(I=>I.id===A);g<0||(this.selection.add(A),this.cursorIdx=g,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,p=>{p.parent=e}),this.pendingFocusIds=[A],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 p=this.selectionGuardKey,u=()=>{if(this.selectionGuardKey!==p||this.selection.has(A))return;let g=this.currentChildren.findIndex(I=>I.id===A);g<0||(this.selection.add(A),this.cursorIdx=g,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===F?"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,A)=>c+o(A),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===F?void 0:0,affectedIds:t.map(l=>l.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===F?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};Xi.AIMED_TAP_WINDOW_MS=600;var js=Xi,Fo=class extends k.SuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onPick=i;this.setPlaceholder("Move to which archive folder?")}getSuggestions(t){let e=t.toLowerCase();return this.folders.filter(i=>i.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.split("/").pop()||t}),e.createEl("small",{text:t,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t)}},_s=class extends k.SuggestModal{constructor(t,e,i){super(t);this.entries=e;this.onPick=i;this.setPlaceholder("Restore which deleted note?")}getSuggestions(t){let e=t.toLowerCase();return this.entries.filter(i=>`${i.label} ${i.folder}`.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.label}),e.createEl("small",{text:`from ${t.folder}`,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t.blob)}};var ee=require("obsidian");at();kt();var bc=ee.moment,tn=class extends ee.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 Ke}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,ee.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,ee.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(A=>A.blob));for(let A of[...this.selected])r.has(A)||this.selected.delete(A);if(this.selected.size>0){let A=e.createDiv({cls:"stashpad-trash-selbar"});A.createSpan({cls:"stashpad-trash-selcount",text:`${this.selected.size} selected`});let h=A.createEl("button",{cls:"stashpad-trash-restore",text:"Restore selected"});h.onclick=async()=>{h.disabled=!0;for(let g of[...this.selected])await this.plugin.restoreDeletedAt(g,{silent:!0});this.clearSelection(),await this.render()};let p=A.createEl("button",{cls:"stashpad-trash-delete mod-warning",text:"Delete selected"});p.onclick=()=>this.confirmPurge([...this.selected]);let u=A.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Clear"});u.onclick=()=>{this.clearSelection(),this.render()}}let l=new Map;for(let A of n){let h=A.meta?.title?A.meta.originalFolder||"(unknown folder)":" hidden";(l.get(h)??l.set(h,[]).get(h)).push(A)}let c=[...l.keys()].sort((A,h)=>A===" hidden"?1:h===" hidden"?-1:A.localeCompare(h));this.order=[];for(let A of c){let h=A===" hidden",p=e.createDiv({cls:"stashpad-trash-group"}),u=p.createDiv({cls:"stashpad-trash-group-head"});(0,ee.setIcon)(u.createSpan({cls:"stashpad-trash-group-icon"}),h?"lock":"folder"),u.createSpan({text:h?"Hidden (title obscured)":A.split("/").pop()||A}),u.createSpan({cls:"stashpad-trash-group-count",text:String(l.get(A).length)});for(let g of l.get(A)){let I=this.order.length;this.order.push(g.blob);let m=p.createDiv({cls:"stashpad-trash-row"});this.selected.has(g.blob)&&m.addClass("is-selected"),m.addEventListener("click",E=>{E.target.closest("button")||this.onRowClick(I,g.blob,E)});let f=m.createDiv({cls:"stashpad-trash-row-main"});f.createSpan({cls:"stashpad-trash-title",text:h?"Locked note":g.meta?.title||"Locked note"});let C=g.meta?.deletedAt?`deleted ${bc(g.meta.deletedAt).fromNow()}`:"deleted",B=g.meta&&g.meta.count>1?` \xB7 ${g.meta.count} ${g.meta.kind==="rawtrash"?"files":"notes"}`:"";f.createSpan({cls:"stashpad-trash-sub",text:C+B});let Q=m.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,ee.setIcon)(Q.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),Q.onclick=async()=>{Q.disabled=!0,await this.plugin.restoreDeletedAt(g.blob)?await this.render():Q.disabled=!1};let y=m.createEl("button",{cls:"stashpad-trash-delete",attr:{"aria-label":"Delete permanently"}});(0,ee.setIcon)(y,"trash-2"),y.onclick=()=>this.confirmPurge([g.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 nt(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 br(d){let{workspace:a}=d.app,t=a.getLeavesOfType(Ke);if(t.length>0){a.revealLeaf(t[0]);return}let e=a.getLeaf("tab");await e.setViewState({type:Ke,active:!0}),a.revealLeaf(e)}var ie=require("obsidian");at();var Nr=ie.moment,en=class extends ie.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,ie.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,ie.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 A=o.createDiv({cls:"stashpad-trash-row"}),h=A.createDiv({cls:"stashpad-trash-row-main"});h.createSpan({cls:"stashpad-trash-title",text:c.title||"Locked note"});let p=c.created?`locked ${Nr(c.created).fromNow()}`:"locked",u=c.count>1?` \xB7 ${c.count} notes`:"";h.createSpan({cls:"stashpad-trash-sub",text:p+u});let g=A.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Export"});g.setAttr("aria-label","Export to .stash (encrypted with a password you choose)"),g.onclick=()=>void this.plugin.exportLockedSubtree(c.blob);let I=A.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,ie.setIcon)(I,"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"}),A=c.createDiv({cls:"stashpad-trash-group-head"});(0,ie.setIcon)(A.createSpan({cls:"stashpad-trash-group-icon"}),"archive"),A.createSpan({text:r.split("/").pop()||r}),A.createSpan({cls:"stashpad-trash-group-count",text:String(l.length)});let h=A.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 p of l){let u=c.createDiv({cls:"stashpad-trash-row"}),g=u.createDiv({cls:"stashpad-trash-row-main"});g.createSpan({cls:"stashpad-trash-title",text:p.title||"Locked note"});let I=p.created?`archived ${Nr(p.created).fromNow()}`:"archived",m=p.count>1?` \xB7 ${p.count} notes`:"";g.createSpan({cls:"stashpad-trash-sub",text:I+m});let f=u.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Export"});f.setAttr("aria-label","Export to .stash (encrypted with a password you choose)"),f.onclick=()=>void this.plugin.exportLockedSubtree(p.blob);let C=u.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,ie.setIcon)(C,"lock")}}}async onClose(){this.contentEl.empty()}};async function ko(d,a){let{workspace:t}=d.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)}at();var Y=require("obsidian");at();kt();var sn=class d 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 A=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-newfolder"});if((0,Y.setIcon)(A,"folder-plus"),A.setAttr("aria-label","New Stashpad folder (folder switcher)"),A.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=p=>{p.button===0&&(p.preventDefault(),p.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 A=n.get(l.folder);A||(A=[],n.set(l.folder,A)),A.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 A of n.get(l)??[])this.renderPinNote(t,A.folder,A.id,A.file,A.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((A,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,A=>{A.pinnedAt=c})}catch(A){console.warn("[Stashpad] pin reorder failed",A)}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),A=c.length>0,h=`${e}|${i}`,p=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",f=>{f.dataTransfer?.setData("text/plain",String(n)),f.dataTransfer&&(f.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",f=>{f.preventDefault(),f.dataTransfer&&(f.dataTransfer.dropEffect="move");let C=u.getBoundingClientRect(),B=f.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",f=>{f.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let C=parseInt(f.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===n)return;let B=u.getBoundingClientRect(),Q=f.clientY-B.top<B.height/2;this.reorderPin(C,Q?n:n+1)});let g=u.createSpan({cls:"stashpad-pinned-toggle"});A&&(Ie(g,c.length,p),g.onclick=f=>{f.stopPropagation(),this.pinExpanded.has(h)?this.pinExpanded.delete(h):this.pinExpanded.add(h),this.render()});let I=u.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(I,A?"folder-tree":"file-text"),r&&(I.style.color=r);let m=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(m.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},u.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),u.oncontextmenu=f=>{f.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(f)},A&&p){let f=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(f,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,A=this.childrenOf(e,r),h=A.length>0,p=`${e}|${r}`,u=this.pinExpanded.has(p),g=t.createDiv({cls:"stashpad-pinned-subrow"});c&&g.addClass("is-completed"),g.style.paddingLeft=`${s*16}px`;let I=g.createSpan({cls:"stashpad-pinned-toggle"});h&&(Ie(I,A.length,u),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let m=g.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(m,"file-text"),l&&(m.style.color=l);let f=g.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});f.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===F&&(r==null||r===F)){if(o.id===F)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(J)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=d.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=d.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(d.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==F||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],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(d.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 f=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,Y.setIcon)(f,"pin"),f.setAttr("aria-label","Pinned")}let l=this.folderHomePinnedNotes(e),c=d.clean(e),A=this.folderPinExpanded.has(c);if(l.length>0){let f=o.createSpan({cls:"stashpad-folderpanel-pinreveal"});Ie(f,l.length,A),f.setAttr("aria-label",A?"Hide pinned notes":`${l.length} pinned note${l.length===1?"":"s"}`),f.addEventListener("mousedown",C=>{C.stopPropagation(),C.preventDefault()}),f.onclick=C=>{C.stopPropagation(),this.folderPinExpanded.has(c)?this.folderPinExpanded.delete(c):this.folderPinExpanded.add(c),this.render()}}let h=this.plugin.isArchiveFolder(e),p=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,Y.setIcon)(p,h?"archive":"folder"),h&&p.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let u=this.folderHomeColor(e);u&&(p.style.color=u);let g=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:g});let m=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});if((0,Y.setIcon)(m,"plus-square"),m.setAttr("aria-label","Open in new tab"),m.onmousedown=f=>{f.button===0&&(f.preventDefault(),f.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",f=>{f.button===0&&(f.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=f=>{f.preventDefault(),this.openFolderMenu(f,e)},l.length>0&&A){let f=t.createDiv({cls:"stashpad-folderpanel-pinlist"});for(let C of l){let B=f.createDiv({cls:"stashpad-folderpanel-pinrow"}),Q=this.app.metadataCache.getFileCache(C)?.frontmatter??{},y=B.createSpan({cls:"stashpad-folderpanel-pinrow-icon"});(0,Y.setIcon)(y,"arrow-up-to-line"),typeof Q.color=="string"&&(y.style.color=Q.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,F).filter(e=>this.app.metadataCache.getFileCache(e)?.frontmatter?.listPinned===!0)}renderHiddenSection(t,e){let i=t.createDiv({cls:"stashpad-folderpanel-hidden"}),s=i.createDiv({cls:"stashpad-folderpanel-hidden-header"}),n=s.createSpan({cls:"stashpad-folderpanel-hidden-caret"});(0,Y.setIcon)(n,"chevron-right"),s.createSpan({cls:"stashpad-folderpanel-hidden-title",text:`Hidden (${e.length})`});let o=i.createDiv({cls:"stashpad-folderpanel-hidden-body"});o.setCssStyles({display:"none"}),s.onclick=()=>{let 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 A=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,Y.setIcon)(A,"eye"),A.setAttr("aria-label","Unhide"),A.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 nt(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 So(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 nt(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()}},So=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 nn(d){let a=d.workspace.getLeavesOfType(ge);if(a.length>0){d.workspace.revealLeaf(a[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new Y.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ge,active:!0}),d.workspace.revealLeaf(t)}kt();je();at();var Do="OKF Template.md",Nc=`--- +`),"Swap",async l=>{if(!l)return;let c=t.parent??F;await this.swapParentChild(t,i,c)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new k.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(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(),A=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,I=>{n==null||n===F?(delete I.parent,I.parent=F):I.parent=n}),p?.file&&await this.app.fileManager.processFrontMatter(p.file,I=>{I.parent=t.id});for(let I of r){let f=this.app.vault.getAbstractFileByPath(I.path);f&&await this.app.fileManager.processFrontMatter(f,m=>{I.was==null?m.parent=F:m.parent=I.was})}this.order.setOrder(s,i,l),this.order.setOrder(s,e.id,c),this.order.setOrder(s,t.id,A),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=l=>l??F;if(o(n)===o(e)){if(!i.quiet){let l=this.titleForNode(t),c=e===F?"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!==F&&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===F?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let l=this.noteFolder,c=s.path,A=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=[A],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(A))return;let p=this.currentChildren.findIndex(I=>I.id===A);p<0||(this.selection.add(A),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=[A],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(A))return;let p=this.currentChildren.findIndex(I=>I.id===A);p<0||(this.selection.add(A),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===F?"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,A)=>c+o(A),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===F?void 0:0,affectedIds:t.map(l=>l.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===F?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}};Zi.AIMED_TAP_WINDOW_MS=600;var en=Zi,Do=class extends k.SuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onPick=i;this.setPlaceholder("Move to which archive folder?")}getSuggestions(t){let e=t.toLowerCase();return this.folders.filter(i=>i.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.split("/").pop()||t}),e.createEl("small",{text:t,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t)}},sn=class extends k.SuggestModal{constructor(t,e,i){super(t);this.entries=e;this.onPick=i;this.setPlaceholder("Restore which deleted note?")}getSuggestions(t){let e=t.toLowerCase();return this.entries.filter(i=>`${i.label} ${i.folder}`.toLowerCase().includes(e))}renderSuggestion(t,e){e.createDiv({text:t.label}),e.createEl("small",{text:`from ${t.folder}`,cls:"stashpad-suggest-path"})}onChooseSuggestion(t){this.onPick(t.blob)}};var ie=require("obsidian");at();kt();var xc=ie.moment,nn=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 Oe}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(A=>A.blob));for(let A of[...this.selected])r.has(A)||this.selected.delete(A);if(this.selected.size>0){let A=e.createDiv({cls:"stashpad-trash-selbar"});A.createSpan({cls:"stashpad-trash-selcount",text:`${this.selected.size} selected`});let h=A.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=A.createEl("button",{cls:"stashpad-trash-delete mod-warning",text:"Delete selected"});g.onclick=()=>this.confirmPurge([...this.selected]);let u=A.createEl("button",{cls:"stashpad-trash-iconbtn",text:"Clear"});u.onclick=()=>{this.clearSelection(),this.render()}}let l=new Map;for(let A of n){let h=A.meta?.title?A.meta.originalFolder||"(unknown folder)":" hidden";(l.get(h)??l.set(h,[]).get(h)).push(A)}let c=[...l.keys()].sort((A,h)=>A===" hidden"?1:h===" hidden"?-1:A.localeCompare(h));this.order=[];for(let A of c){let h=A===" 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)":A.split("/").pop()||A}),u.createSpan({cls:"stashpad-trash-group-count",text:String(l.get(A).length)});for(let p of l.get(A)){let I=this.order.length;this.order.push(p.blob);let f=g.createDiv({cls:"stashpad-trash-row"});this.selected.has(p.blob)&&f.addClass("is-selected"),f.addEventListener("click",E=>{E.target.closest("button")||this.onRowClick(I,p.blob,E)});let m=f.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 ${xc(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 Q=f.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,ie.setIcon)(Q.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),Q.onclick=async()=>{Q.disabled=!0,await this.plugin.restoreDeletedAt(p.blob)?await this.render():Q.disabled=!1};let y=f.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 nt(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 Pr(d){let{workspace:a}=d.app,t=a.getLeavesOfType(Oe);if(t.length>0){a.revealLeaf(t[0]);return}let e=a.getLeaf("tab");await e.setViewState({type:Oe,active:!0}),a.revealLeaf(e)}var se=require("obsidian");at();var Hr=se.moment,on=class extends se.ItemView{constructor(t,e){super(t);this.plugin=e;this.mode="encrypted";this.renderPending=!1}getViewType(){return Ye}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 A=o.createDiv({cls:"stashpad-trash-row"}),h=A.createDiv({cls:"stashpad-trash-row-main"});h.createSpan({cls:"stashpad-trash-title",text:c.title||"Locked note"});let g=c.created?`locked ${Hr(c.created).fromNow()}`:"locked",u=c.count>1?` \xB7 ${c.count} notes`:"";h.createSpan({cls:"stashpad-trash-sub",text:g+u});let p=A.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 I=A.createSpan({cls:"stashpad-aggregate-lockbadge"});(0,se.setIcon)(I,"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"}),A=c.createDiv({cls:"stashpad-trash-group-head"});(0,se.setIcon)(A.createSpan({cls:"stashpad-trash-group-icon"}),"archive"),A.createSpan({text:r.split("/").pop()||r}),A.createSpan({cls:"stashpad-trash-group-count",text:String(l.length)});let h=A.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 I=g.created?`archived ${Hr(g.created).fromNow()}`:"archived",f=g.count>1?` \xB7 ${g.count} notes`:"";p.createSpan({cls:"stashpad-trash-sub",text:I+f});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 bo(d,a){let{workspace:t}=d.app,e=t.getLeavesOfType(Ye).find(s=>s.view?.getState?.().mode===a);if(e){t.revealLeaf(e);return}let i=t.getLeaf("tab");await i.setViewState({type:Ye,active:!0,state:{mode:a}}),t.revealLeaf(i)}at();var Y=require("obsidian");at();kt();var an=class d 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 A=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-newfolder"});if((0,Y.setIcon)(A,"folder-plus"),A.setAttr("aria-label","New Stashpad folder (folder switcher)"),A.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 A=n.get(l.folder);A||(A=[],n.set(l.folder,A)),A.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 A of n.get(l)??[])this.renderPinNote(t,A.folder,A.id,A.file,A.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((A,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,A=>{A.pinnedAt=c})}catch(A){console.warn("[Stashpad] pin reorder failed",A)}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),A=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(),Q=m.clientY-B.top<B.height/2;this.reorderPin(C,Q?n:n+1)});let p=u.createSpan({cls:"stashpad-pinned-toggle"});A&&(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 I=u.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(I,A?"folder-tree":"file-text"),r&&(I.style.color=r);let f=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.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)},A&&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,A=this.childrenOf(e,r),h=A.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 I=p.createSpan({cls:"stashpad-pinned-toggle"});h&&(Ie(I,A.length,u),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let f=p.createSpan({cls:"stashpad-pinned-icon"});(0,Y.setIcon)(f,"file-text"),l&&(f.style.color=l);let 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===F&&(r==null||r===F)){if(o.id===F)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(J)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=d.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=d.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(d.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==F||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],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(d.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=d.clean(e),A=this.folderPinExpanded.has(c);if(l.length>0){let m=o.createSpan({cls:"stashpad-folderpanel-pinreveal"});Ie(m,l.length,A),m.setAttr("aria-label",A?"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,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 f=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});if((0,Y.setIcon)(f,"plus-square"),f.setAttr("aria-label","Open in new tab"),f.onmousedown=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&&A){let m=t.createDiv({cls:"stashpad-folderpanel-pinlist"});for(let C of l){let B=m.createDiv({cls:"stashpad-folderpanel-pinrow"}),Q=this.app.metadataCache.getFileCache(C)?.frontmatter??{},y=B.createSpan({cls:"stashpad-folderpanel-pinrow-icon"});(0,Y.setIcon)(y,"arrow-up-to-line"),typeof Q.color=="string"&&(y.style.color=Q.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,F).filter(e=>this.app.metadataCache.getFileCache(e)?.frontmatter?.listPinned===!0)}renderHiddenSection(t,e){let i=t.createDiv({cls:"stashpad-folderpanel-hidden"}),s=i.createDiv({cls:"stashpad-folderpanel-hidden-header"}),n=s.createSpan({cls:"stashpad-folderpanel-hidden-caret"});(0,Y.setIcon)(n,"chevron-right"),s.createSpan({cls:"stashpad-folderpanel-hidden-title",text:`Hidden (${e.length})`});let o=i.createDiv({cls:"stashpad-folderpanel-hidden-body"});o.setCssStyles({display:"none"}),s.onclick=()=>{let 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 A=l.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,Y.setIcon)(A,"eye"),A.setAttr("aria-label","Unhide"),A.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 nt(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 No(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 nt(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()}},No=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 rn(d){let a=d.workspace.getLeavesOfType(ge);if(a.length>0){d.workspace.revealLeaf(a[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new Y.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ge,active:!0}),d.workspace.revealLeaf(t)}kt();_e();at();var xo="OKF Template.md",Mc=`--- okfType: concept --- {{body}} -`,bo=["> 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 Zi(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function xr(d){return`[${Zi(d)}](${encodeURI(d.name)})`}async function Mr(d,a=Do){try{await d.vault.adapter.exists(a)||await d.vault.create(a,Nc)}catch{}return a}function Tr(d,a){if(!a)return[];let t=a.replace(/^\/+/,"");return Object.entries(d??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function No(d,a){let t=a.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of d.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let r;try{r=dt(await d.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:F;e.set(l,{file:o,id:l,parent:c,modified:typeof r.modified=="string"?r.modified:"",created:typeof r.created=="string"?r.created:""});let A=i.get(c)??[];A.push(l),i.set(c,A)}let s=0,n=0;for(let o of e.values()){if(o.id===F)continue;s+=1;let r=o.parent&&o.parent!==F&&e.get(o.parent)?xr(e.get(o.parent).file):null,l=(i.get(o.id)??[]).map(c=>e.get(c)).filter(c=>!!c).map(c=>xr(c.file));try{let c=!1;await d.fileManager.processFrontMatter(o.file,A=>{r?A.okfParent!==r&&(A.okfParent=r,c=!0):A.okfParent!==void 0&&(delete A.okfParent,c=!0);let h=Array.isArray(A.okfChildren)?A.okfChildren:[],p=h.length===l.length&&h.every((u,g)=>u===l[g]);if(l.length?p||(A.okfChildren=l,c=!0):A.okfChildren!==void 0&&(delete A.okfChildren,c=!0),A.okfType===void 0&&(A.okfType="concept",c=!0),A.okfTitle===void 0&&(A.okfTitle=Zi(o.file),c=!0),A.okfTimestamp===void 0){let u=o.modified||o.created;u&&(A.okfTimestamp=u,c=!0)}}),c&&(n+=1,await new Promise(A=>setTimeout(A,50)))}catch(c){console.warn("[Stashpad] OKF rebuild failed",o.file.path,c)}}try{await d.vault.adapter.write(`${t}/index.md`,await xo(d,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function xo(d,a,t){let e=a.replace(/\/+$/,""),i=new Map,s=new Map;for(let A of d.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e||A.name==="index.md")continue;let h;try{h=dt(await d.vault.read(A)).fm}catch{continue}let p=typeof h.id=="string"?h.id:null;!p||p===F||t&&!t.has(p)||i.set(p,{id:p,file:A,parent:typeof h.parent=="string"?h.parent:F,title:typeof h.okfTitle=="string"&&h.okfTitle?h.okfTitle:Zi(A),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 A of i.values()){let h=s.get(A.parent)??[];h.push(A),s.set(A.parent,h)}for(let A of s.values())A.sort((h,p)=>h.position-p.position||h.created.localeCompare(p.created));let n=[],o=(A,h,p)=>{if(!p.has(A.id)){p.add(A.id),n.push(`${" ".repeat(h)}- [${A.title}](${encodeURI(A.file.name)}) \u2014 ${A.type}`);for(let u of s.get(A.id)??[])o(u,h+1,p)}},r=new Set,l=[...i.values()].filter(A=>A.parent===F||!i.has(A.parent)).sort((A,h)=>A.position-h.position||A.created.localeCompare(h.created));for(let A of l)o(A,0,r);let c=e.split("/").pop()||e;return["---","type: index",`title: ${c} (OKF index)`,"---","",`# ${c}`,"",bo,"","## Concepts",n.length?n.join(` +`,Mo=["> 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 ji(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function Ur(d){return`[${ji(d)}](${encodeURI(d.name)})`}async function Rr(d,a=xo){try{await d.vault.adapter.exists(a)||await d.vault.create(a,Mc)}catch{}return a}function Gr(d,a){if(!a)return[];let t=a.replace(/^\/+/,"");return Object.entries(d??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function To(d,a){let t=a.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of d.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let r;try{r=dt(await d.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:F;e.set(l,{file:o,id:l,parent:c,modified:typeof r.modified=="string"?r.modified:"",created:typeof r.created=="string"?r.created:""});let A=i.get(c)??[];A.push(l),i.set(c,A)}let s=0,n=0;for(let o of e.values()){if(o.id===F)continue;s+=1;let r=o.parent&&o.parent!==F&&e.get(o.parent)?Ur(e.get(o.parent).file):null,l=(i.get(o.id)??[]).map(c=>e.get(c)).filter(c=>!!c).map(c=>Ur(c.file));try{let c=!1;await d.fileManager.processFrontMatter(o.file,A=>{r?A.okfParent!==r&&(A.okfParent=r,c=!0):A.okfParent!==void 0&&(delete A.okfParent,c=!0);let h=Array.isArray(A.okfChildren)?A.okfChildren:[],g=h.length===l.length&&h.every((u,p)=>u===l[p]);if(l.length?g||(A.okfChildren=l,c=!0):A.okfChildren!==void 0&&(delete A.okfChildren,c=!0),A.okfType===void 0&&(A.okfType="concept",c=!0),A.okfTitle===void 0&&(A.okfTitle=ji(o.file),c=!0),A.okfTimestamp===void 0){let u=o.modified||o.created;u&&(A.okfTimestamp=u,c=!0)}}),c&&(n+=1,await new Promise(A=>setTimeout(A,50)))}catch(c){console.warn("[Stashpad] OKF rebuild failed",o.file.path,c)}}try{await d.vault.adapter.write(`${t}/index.md`,await Po(d,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function Po(d,a,t){let e=a.replace(/\/+$/,""),i=new Map,s=new Map;for(let A of d.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e||A.name==="index.md")continue;let h;try{h=dt(await d.vault.read(A)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===F||t&&!t.has(g)||i.set(g,{id:g,file:A,parent:typeof h.parent=="string"?h.parent:F,title:typeof h.okfTitle=="string"&&h.okfTitle?h.okfTitle:ji(A),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 A of i.values()){let h=s.get(A.parent)??[];h.push(A),s.set(A.parent,h)}for(let A of s.values())A.sort((h,g)=>h.position-g.position||h.created.localeCompare(g.created));let n=[],o=(A,h,g)=>{if(!g.has(A.id)){g.add(A.id),n.push(`${" ".repeat(h)}- [${A.title}](${encodeURI(A.file.name)}) \u2014 ${A.type}`);for(let u of s.get(A.id)??[])o(u,h+1,g)}},r=new Set,l=[...i.values()].filter(A=>A.parent===F||!i.has(A.parent)).sort((A,h)=>A.position-h.position||A.created.localeCompare(h.created));for(let A of l)o(A,0,r);let c=e.split("/").pop()||e;return["---","type: index",`title: ${c} (OKF index)`,"---","",`# ${c}`,"",Mo,"","## Concepts",n.length?n.join(` `):"_No concepts yet._",""].join(` -`)}var xc=new TextEncoder,on=d=>xc.encode(d);function ji(d){if(typeof d=="number"||typeof d=="boolean")return String(d);let a=String(d??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(a)?JSON.stringify(a):a}function Mc(d,a){let{fm:t}=dt(d),e=[];e.push(`type: ${ji(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${ji(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:Zi(a))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${ji(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let r of i)e.push(` - ${ji(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: ${ji(s)}`);let n=e.join(` +`)}var Tc=new TextEncoder,ln=d=>Tc.encode(d);function _i(d){if(typeof d=="number"||typeof d=="boolean")return String(d);let a=String(d??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(a)?JSON.stringify(a):a}function Pc(d,a){let{fm:t}=dt(d),e=[];e.push(`type: ${_i(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${_i(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:ji(a))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${_i(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let r of i)e.push(` - ${_i(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: ${_i(s)}`);let n=e.join(` `),o=d.match(/^---\r?\n/);return o?d.slice(0,o[0].length)+n+` `+d.slice(o[0].length):`--- ${n} --- -${d}`}async function Pr(d,a,t,e){let i=[],s=new Map;for(let n of a){let o=await d.vault.read(n);i.push({name:n.name,data:on(Mc(o,n))});for(let r of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let l=r.slice(3,-2).split("|")[0].split("#")[0].trim(),c=d.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 d.vault.readBinary(o))});return i.push({name:"index.md",data:on(await xo(d,t,e))}),i.push({name:"_okf.md",data:on(`# About this bundle +${d}`}async function Lr(d,a,t,e){let i=[],s=new Map;for(let n of a){let o=await d.vault.read(n);i.push({name:n.name,data:ln(Pc(o,n))});for(let r of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let l=r.slice(3,-2).split("|")[0].split("#")[0].trim(),c=d.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 d.vault.readBinary(o))});return i.push({name:"index.md",data:ln(await Po(d,t,e))}),i.push({name:"_okf.md",data:ln(`# About this bundle -${bo.replace(/^> /gm,"")} -`)}),i}async function Hr(d){let{zipFiles:a}=await Promise.resolve().then(()=>(Os(),rr));return a(d.map(t=>({name:t.name,data:t.data})))}function hi(d,a){return d.toString(8).padStart(a-1,"0")+"\0"}function Tc(d,a){let t=new Uint8Array(512),e=(s,n,o)=>{let r=on(s);t.set(r.subarray(0,o),n)};e(d.slice(0,100),0,100),e(hi(420,8),100,8),e(hi(0,8),108,8),e(hi(0,8),116,8),e(hi(a,12),124,12),e(hi(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(hi(i,8),148,8),t}function Pc(d){let a=[],t=0;for(let s of d){let n=Tc(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 Hc(d){let a=new CompressionStream("gzip"),t=new Response(d).body.pipeThrough(a);return new Uint8Array(await new Response(t).arrayBuffer())}async function Ur(d){return Hc(Pc(d))}var an=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))}};at();var rn=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 ln=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");at();Ut();je();os();kt();var cn=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),Rr="_archive",Gr=new Set([_t,"edtz","stashenc","stashmeta"]),pi=class pi{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)&&(cn.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(),pi.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)||Gr.has(a.extension))return!1;let t=a.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return cn.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,p)=>h+p.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(g=>`\u2022 ${g.name}`).join(` -`),p=c.length>5?` +${Mo.replace(/^> /gm,"")} +`)}),i}async function qr(d){let{zipFiles:a}=await Promise.resolve().then(()=>(Ys(),Ar));return a(d.map(t=>({name:t.name,data:t.data})))}function pi(d,a){return d.toString(8).padStart(a-1,"0")+"\0"}function Hc(d,a){let t=new Uint8Array(512),e=(s,n,o)=>{let r=ln(s);t.set(r.subarray(0,o),n)};e(d.slice(0,100),0,100),e(pi(420,8),100,8),e(pi(0,8),108,8),e(pi(0,8),116,8),e(pi(a,12),124,12),e(pi(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(pi(i,8),148,8),t}function Uc(d){let a=[],t=0;for(let s of d){let n=Hc(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 Rc(d){let a=new CompressionStream("gzip"),t=new Response(d).body.pipeThrough(a);return new Uint8Array(await new Response(t).arrayBuffer())}async function Jr(d){return Rc(Uc(d))}var cn=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))}};at();var An=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 dn=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");at();Ut();_e();as();kt();var hn=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),Kr="_archive",Or=new Set([_t,"edtz","stashenc","stashmeta"]),gi=class gi{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)&&(hn.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(),gi.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)||Or.has(a.extension))return!1;let t=a.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return hn.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(` +`),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}${p} +${h}${g} -Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(u==="skip"){let g=new Set(c.map(I=>I.path));if(r=e.filter(I=>!g.has(I.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 g of c){let I=this.plugin.importLog.findDuplicate(g.name,g.stat?.size??null);for(let m of I?.notePaths??[]){let f=this.app.vault.getAbstractFileByPath(m);if(f instanceof et.TFile)try{l.push({path:m,content:await this.app.vault.read(f)}),await this.app.fileManager.trashFile(f)}catch(C){console.warn("[Stashpad] replace: couldn't remove prior note",m,C)}}}}if(o=r.length+n,o>=pi.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 A=[];for(let h of r)try{let p=h.stat?.size??null,u=h.extension==="md"?await this.importMarkdown(h):await this.importOtherFile(h);u&&(A.push(u),this.plugin.importLog.append({ts:new Date().toISOString(),folder:u.folder,kind:u.kind,originalName:h.name,size:p,sourcePath:h.path,notePaths:u.kind==="folder"?u.notePaths:[u.notePath]}))}catch(p){console.warn("[Stashpad] import failed",h.path,p)}for(let{folder:h}of s)try{let p=await this.importFolder(h);p&&p.kind==="folder"&&(A.push(p),this.plugin.importLog.append({ts:new Date().toISOString(),folder:p.folder,kind:"folder",originalName:p.originalName,size:null,sourcePath:h.path,notePaths:p.notePaths}))}catch(p){console.warn("[Stashpad] folder import failed",h.path,p)}(A.length>0||l.length>0)&&this.announce(A,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}/${Rr}`;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,p]of Object.entries(i))se.includes(h)||(r[h]=p);r.id=W(),r.parent=F;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=Et(s)||a.basename,A=await this.uniquePath(t,wt(c,r.id));return await this.createNote(A,Ee(r,s)),{kind:"md",folder:t,archivePath:o,notePath:A,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:F,created:new Date().toISOString(),attachments:[Yt(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(I=>I.path));if(r=e.filter(I=>!p.has(I.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 I=this.plugin.importLog.findDuplicate(p.name,p.stat?.size??null);for(let f of I?.notePaths??[]){let m=this.app.vault.getAbstractFileByPath(f);if(m instanceof et.TFile)try{l.push({path:f,content:await this.app.vault.read(m)}),await this.app.fileManager.trashFile(m)}catch(C){console.warn("[Stashpad] replace: couldn't remove prior note",f,C)}}}}if(o=r.length+n,o>=gi.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 A=[];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&&(A.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"&&(A.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)}(A.length>0||l.length>0)&&this.announce(A,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}/${Kr}`;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))ne.includes(h)||(r[h]=g);r.id=W(),r.parent=F;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=Et(s)||a.basename,A=await this.uniquePath(t,wt(c,r.id));return await this.createNote(A,Ee(r,s)),{kind:"md",folder:t,archivePath:o,notePath:A,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:F,created:new Date().toISOString(),attachments:[Yt(i)],imported:!0},r=`${s} ![[${i}]] -`,l=Et(s)||s,c=await this.uniquePath(t,wt(l,n));return await this.createNote(c,Ee(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}/${Rr}`;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 A of this.app.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let h=this.app.metadataCache.getFileCache(A)?.frontmatter?.id;typeof h=="string"&&h&&o.add(h)}let r=[],l=[],c=await this.createFolderNote(t,e,F,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=Et(t)||t,l=await this.uniquePath(a,wt(r,n));return await this.createNote(l,Ee(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(cn.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),A={};for(let[m,f]of Object.entries(l))se.includes(m)||(A[m]=f);let h=typeof l.id=="string"&&l.id?l.id:null,p=h&&!s.has(h)?h:W();s.add(p),A.id=p,A.parent=e;let u=this.preservedTimes(l,o);A.created=u.created,u.modified&&(A.modified=u.modified),A.attachments=Array.isArray(l.attachments)?l.attachments:[];let g=Et(c)||o.basename,I=await this.uniquePath(t,wt(g,A.id));await this.createNote(I,Ee(A,c)),i.push(I)}else{if(Gr.has(o.extension))continue;{let r=W(),l={id:r,parent:e,created:new Date().toISOString(),attachments:[Yt(o.path)]},c=`${o.basename} +`,l=Et(s)||s,c=await this.uniquePath(t,wt(l,n));return await this.createNote(c,Ee(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}/${Kr}`;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 A of this.app.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let h=this.app.metadataCache.getFileCache(A)?.frontmatter?.id;typeof h=="string"&&h&&o.add(h)}let r=[],l=[],c=await this.createFolderNote(t,e,F,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=Et(t)||t,l=await this.uniquePath(a,wt(r,n));return await this.createNote(l,Ee(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(hn.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),A={};for(let[f,m]of Object.entries(l))ne.includes(f)||(A[f]=m);let h=typeof l.id=="string"&&l.id?l.id:null,g=h&&!s.has(h)?h:W();s.add(g),A.id=g,A.parent=e;let u=this.preservedTimes(l,o);A.created=u.created,u.modified&&(A.modified=u.modified),A.attachments=Array.isArray(l.attachments)?l.attachments:[];let p=Et(c)||o.basename,I=await this.uniquePath(t,wt(p,A.id));await this.createNote(I,Ee(A,c)),i.push(I)}else{if(Or.has(o.extension))continue;{let r=W(),l={id:r,parent:e,created:new Date().toISOString(),attachments:[Yt(o.path)]},c=`${o.basename} ![[${o.path}]] -`,A=Et(o.basename)||o.basename,h=await this.uniquePath(t,wt(A,r));await this.createNote(h,Ee(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&&!cn.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&&bt(n))return this.pendingEncryptedStashes.add(a.path),!1;let o=await si(this.app,n,{...s,secretId:Ve(a.basename)});if(!o)return!1;let r=await te(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:F,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===_t);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 nt(this.app,a,t,e,i).open()})}dupChoice(a){return new Promise(t=>{new ki(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}};pi.DEBOUNCE_MS=900,pi.BATCH_CONFIRM_AT=8;var An=pi;var dn=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 pn=class pn{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()},pn.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}};pn.SAVE_DEBOUNCE_MS=8e3;var hn=pn;var Mo="stashpad:unghost-after-reload",_i=class _i extends M.Plugin{constructor(){super(...arguments);this.settings={...me};this.debugBuffer=[];this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.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>_i.DEBUG_BUFFER_MAX&&this.debugBuffer.splice(0,this.debugBuffer.length-_i.DEBUG_BUFFER_MAX)}getDebugTrace(){return this.debugBuffer.join(` -`)}clearDebugTrace(){this.debugBuffer=[]}get notifications(){return this._notifications||(this._notifications=new us(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new ln(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new An(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new dn(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 hn(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 an(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(/^.*\//,""),A=this.pluginPrivatePath(c);if(!await t.exists(A))try{let h=await t.read(l);await t.write(A,h),console.debug("[Stashpad] migrated",l,"\u2192",A)}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,A=>{(typeof A.id!="string"||!A.id)&&(A.id=F),"parent"in A||(A.parent=null),(typeof A.created!="string"||!A.created)&&(A.created=new Date().toISOString())});return}let r=new Date().toISOString(),l=["---",`id: ${F}`,"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 A=this.app.metadataCache.getFileCache(l)?.frontmatter;if((typeof A?.color=="string"?A.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(l,p=>{i?p.color=i:delete p.color}),o++}catch(p){console.warn(`Stashpad: recolor failed for ${l.path}`,p)}}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))}}discoverStashpadFolders(){let t=new Set;for(let i of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(i)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let n=i.parent?.path?.replace(/\/+$/,"")??"";n&&t.add(n)}let e=[...t].sort();return this.knownStashpadFolders=new Set(e),e}closeStashpadTabsFor(t){let e=0;for(let i of this.app.workspace.getLeavesOfType(J)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(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 A=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id.trim():"";if(!h)continue;let p=A&&"parent"in A?A.parent??null:null;s[h]={parent:p,path:c.path}}let o=await i.readState(),r=c=>c===t||c.startsWith(t+"/");if(!e.silent){for(let[c,A]of Object.entries(s)){let h=o[c];h?h.parent!==A.parent?await i.append({type:"parent_change",id:c,payload:{from:h.parent,to:A.parent}}):h.path!==A.path&&await i.append({type:"rename",id:c,payload:{from:h.path,to:A.path}}):await i.append({type:"create",id:c,payload:{path:A.path,parent:A.parent}})}for(let[c,A]of Object.entries(o))!s[c]&&r(A.path)&&await i.append({type:"missing",id:c,payload:{lastPath:A.path}})}let l={};for(let[c,A]of Object.entries(o))r(A.path)||(l[c]=A);for(let[c,A]of Object.entries(s))l[c]=A;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 rn,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),Ft.enabled=!!this.settings.enablePerfProfiling,this.encryption=new Qs(this.app,()=>({...Gi(),...this.settings.encryption??{}}),async g=>{this.settings.encryption=g,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.app.workspace.onLayoutReady(()=>{this.resumeRotations()}),this.settingTab=new Fs(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),this.registerEvent(this.app.vault.on("delete",g=>this.renderCacheStore.evict(g.path))),this.registerEvent(this.app.vault.on("rename",(g,I)=>this.renderCacheStore.evict(I)));let t=(0,M.debounce)(()=>void this.flushForkSiblingPrune(),250,!0);this.registerEvent(this.app.vault.on("delete",g=>{g instanceof M.TFile&&g.extension==="md"&&(this.pendingForkDeletes.add(g.basename),t())})),this.registerEvent(this.app.vault.on("create",g=>this.onOkfFileEvent(g.path))),this.registerEvent(this.app.vault.on("delete",g=>this.onOkfFileEvent(g.path))),this.registerEvent(this.app.vault.on("rename",(g,I)=>{this.onOkfFileEvent(g.path),this.onOkfFileEvent(I)})),await this.authorRegistry.load();{let g=(this.settings.authorId??"").trim();g&&this.authorRegistry.record({id:g,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.registerEvent(this.app.vault.on("create",g=>{g.path.endsWith(".stashenc")&&this.pendingEncBlobs.delete(g.path)})),this.registerEvent(this.app.vault.on("delete",g=>{g.path.endsWith(".stashenc")&&this.pendingEncBlobs.delete(g.path)})),this.app.workspace.onLayoutReady(()=>{this.reconcileLockedRegistry(),window.setTimeout(()=>void this.checkDueReminders(),6e3),this.registerInterval(window.setInterval(()=>void this.checkDueReminders(),5*60*1e3)),window.setTimeout(()=>{this.seedLocalAuthorStubsEverywhere()},4e3),window.setTimeout(()=>this.syncObsidianExcludedArchives(),4500),window.setTimeout(()=>this.importService.setArmed(!0),2500),window.setTimeout(()=>void this.runAutoImportSweep(),5e3),this.registerInterval(window.setInterval(()=>void this.runAutoImportSweep(),5*60*1e3)),window.setTimeout(()=>void this.migratePinnedNotesToFrontmatter(),3e3),window.setTimeout(()=>void this.unghostStashpadTabsIfFlagged(),1200)}),this.registerView(J,g=>new js(g,this)),this.registerView(ke,g=>new Ss(g,this)),this.registerView(pe,g=>new ls(g,this)),this.registerView(Ke,g=>new tn(g,this)),this.registerView(Oe,g=>new en(g,this)),this.registerView(ge,g=>new sn(g,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",g=>{g&&g.view.getViewType()===J&&(this.lastActiveStashpadLeaf=g,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(ke).length===0&&setTimeout(()=>{Ds(this.app)},0),this.notifyStashpadSelectionChanged())}));let e=()=>{let g=le(),I=!!g&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===g,m=!!I&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",m),document.body.classList.toggle("stashpad-active",!!I)};this.register(Na(e)),this.registerEvent(this.app.workspace.on("active-leaf-change",e));let i=g=>{try{let I=Array.from(document.querySelectorAll("style")).filter(m=>(m.textContent??"").includes(".stashpad-"));for(let m of I){let f=m.id||"",C=f?`style[data-stashpad-source="${f}"]`:null;if(C&&g.head.querySelector(C))continue;let B=g.createElement("style");f?B.setAttribute("data-stashpad-source",f):B.setAttribute("data-stashpad-source","anon"),B.textContent=m.textContent??"",g.head.appendChild(B)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",g=>{let I=g?.doc??g?.win?.document??null;I&&i(I)})),this.registerEvent(this.app.workspace.on("file-menu",(g,I)=>{if(!(I instanceof M.TFolder))return;let m=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(m)&&g.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(m))})})),setTimeout(()=>{try{let g=this.app.workspace;typeof g.iterateAllLeaves=="function"&&g.iterateAllLeaves(I=>{let m=I?.view?.containerEl?.ownerDocument;m&&m!==document&&i(m)})}catch{}},200),e(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let s=window.visualViewport,n=()=>{let g=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=g&&g.isConnected?g.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${I}px`);let m=0;s&&(m=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${m}px`),document.body.classList.toggle("stashpad-keyboard-open",m>100)};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",g=>{g.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{cs(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{nn(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{Ds(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=g=>{let I=le();I&&typeof I[g]=="function"&&I[g]()};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 ko(this,"encrypted")}),this.addCommand({id:"stashpad-open-all-archived",name:"Open \u201CAll archived\u201D (every archive folder)",callback:()=>void ko(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 g=Ft.report();console.log(g);try{await navigator.clipboard.writeText(g)}catch{}new M.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{Ft.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:g}=await Promise.resolve().then(()=>(kt(),Di));new g(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:g=>{let I=this.importService.defaultDestination();return g?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:g=>{let I=this.importService.defaultDestination();return g?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:g=>{let I=this.importService.defaultDestination();return g?!!I:(I&&this.runFolderFrontmatterBackfill(I),!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 cs(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void nn(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void Ds(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:g=>{let I=this.app.workspace.getActiveFile(),m=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return g||m&&I&&this.revealNoteInStashpad(I),m}});let l=Object.keys(bi);for(let g of l){let I=bi[g];this.addCommand({id:`stashpad-open-panels-${g}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await cs(this.app),this.app.workspace.getLeavesOfType(pe)[0]?.view?.setActivePanel?.(g)}})}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:g=>{let I=le(),m=I&&I.noteFolder;return m?(g||(new M.Notice(`Running integrity check on "${m}"\u2026`),this.runIntegrityCheckOnFolder(m).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 g=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${g.total} author(s) \u2014 ${g.fromStubs} from stubs, ${g.fromNotes} from note links.`,kind:"success",category:"system"})}catch(g){new M.Notice(`Author registry rebuild failed: ${g.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 g=await this.restoreMissingAuthorStubs();this.notifications.show({message:g.created>0?`Restored ${g.created} author stub(s) across ${g.folders} folder(s).`:`No missing author stubs \u2014 all present across ${g.folders} folder(s).`,kind:"success",category:"system"})}catch(g){new M.Notice(`Restore author stubs failed: ${g.message}`)}}}),this.addCommand({id:"stashpad-sync-authors",name:"Sync authors across all folders (multiplayer)",callback:()=>void this.syncAuthorsAcrossFolders()}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new M.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:g,fmChecked:I,fmWritten:m,slugsRenamed:f,authors:C,imported:B,attachmentsLinked:Q,attachmentsRenamed:y,attachmentsSkipped:E}=await this.rebootstrapAllFolders(),v=[];v.push(`rebootstrapped ${g.length} folder${g.length===1?"":"s"}`),B>0&&v.push(`imported ${B} loose file${B===1?"":"s"}`),Q>0&&v.push(`linked attachments on ${Q} note${Q===1?"":"s"}`),y>0&&v.push(`renamed ${y} attachment${y===1?"":"s"}`),m>0&&v.push(`updated ${m} note${m===1?"":"s"}' metadata`),f>0&&v.push(`renamed ${f} note${f===1?"":"s"}`),C>0&&v.push(`${C} author${C===1?"":"s"} in registry`),v.push(`(checked ${I} total)`),new M.Notice(`Stashpad: ${v.join(" \xB7 ")}`),E>0&&new M.Notice(`Stashpad: ${E} attachment${E===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(g){new M.Notice(`Stashpad: rebootstrap failed (${g.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:g=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(g||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(kt(),Di)).then(({NotificationHistoryModal:g,LogModal:I})=>{new g(this.app,this.notifications,async()=>{let m=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await m.exists(f)){new M.Notice("No log yet \u2014 make some changes first.");return}let C=await m.read(f);new I(this.app,C,f).open()},this.settings.authorId||null,m=>this.lookupNoteAuthorIds(m)).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 g of c){let I=`stashpad-toggle-${String(g.key).replace(/[A-Z]/g,m=>`-${m.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${g.label}`,callback:async()=>{let m=!this.settings[g.key];this.settings[g.key]=m,await this.saveSettings(),new M.Notice(`${g.label}: ${m?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let g=this.app.setting;!g?.open||!g?.openTabById||(g.open(),g.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let g=this.app.setting;!g?.open||!g?.openTabById||(g.open(),g.openTabById(this.manifest.id),setTimeout(()=>{g?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let g of vs)this.addCommand({id:`stashpad-open-settings-${g.id}`,name:`Open Stashpad settings: ${g.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let A=()=>{let g=this.app.setting;!g?.open||!g?.openTabById||(g.open(),g.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:g}=await Promise.resolve().then(()=>(xi(),ps)),I=await g(this.app,this,this.settings);if(I.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}if(I.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:m}=await Promise.resolve().then(()=>(xi(),ps));m(this.app,I)}catch(g){console.error("[stashpad] preview failed",g),new M.Notice(`Preview failed: ${g?.message??g}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:g,scanForJdNotes:I,JdBuildConfirmModal:m}=await Promise.resolve().then(()=>(xi(),ps));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}let C=I(this.app,this,this.settings);new m(this.app,this,this.settings,C.indexed.length,async()=>{try{let Q=await g(this.app,this,this.settings);if(Q.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}if(Q.error==="dest-not-stashpad"){new M.Notice(`"${Q.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),A();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new M.Notice(`Index built: ${Q.created} created, ${Q.updated} updated, ${Q.skipped} skipped \u2192 ${Q.destFolder}`,6e3)}catch(Q){console.error("[stashpad] build failed",Q),new M.Notice(`Build failed: ${Q?.message??Q}`,8e3)}}).open()}catch(g){console.error("[stashpad] build failed",g),new M.Notice(`Build failed: ${g?.message??g}`,8e3)}}});let h=g=>{if(g.extension!==_t)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),m=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=g.parent?.path||"",C=f.split("/").pop()??"";if(I&&C===I){if(m&&f.endsWith(`/${m}`))return;let B=f.slice(0,f.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(g,B);return}this.settings.autoImport&&this.importService.isArmed()&&($e(g.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(g,f))};this.registerEvent(this.app.vault.on("create",g=>{g instanceof M.TFile&&h(g)})),this.registerEvent(this.app.vault.on("rename",g=>{g instanceof M.TFile&&h(g)}));let p=g=>{if(g.extension!=="md")return;let I=g.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(g)},800)},u=g=>{if(g.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let m=g.parent?.path?.replace(/\/+$/,"")??"";if((m.split("/").pop()??"")!==I)return;let C=m.slice(0,m.length-I.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(g,C)},200)};this.registerEvent(this.app.vault.on("create",g=>{g instanceof M.TFile&&(p(g),u(g))})),this.registerEvent(this.app.vault.on("rename",g=>{g instanceof M.TFile&&(p(g),u(g))})),this.registerEvent(this.app.vault.on("delete",g=>{if(!(g instanceof M.TFolder))return;let I=g.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(g,I)=>{g instanceof M.TFile&&this.maybeReHomeOnCrossFolderMove(g,I)})),this.registerEvent(this.app.vault.on("rename",(g,I)=>{g instanceof M.TFile&&this.maybeArchiveOnMoveIn(g,I)})),this.registerEvent(this.app.vault.on("create",g=>{g instanceof M.TFile?this.importService.enqueue(g):g instanceof M.TFolder&&this.importService.enqueueFolder(g)})),this.registerEvent(this.app.vault.on("rename",g=>{g instanceof M.TFile?this.importService.enqueue(g):g instanceof M.TFolder&&this.importService.enqueueFolder(g)})),this.registerEvent(this.app.vault.on("rename",(g,I)=>{g instanceof M.TFile&&this.maybeAdoptAuthorRename(g,I)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(Mo,"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(Mo)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Mo)}catch{}for(let e of this.app.workspace.getLeavesOfType(J))try{let i=e;i.isDeferred&&typeof i.loadIfDeferred=="function"&&await i.loadIfDeferred()}catch(i){console.warn("[Stashpad] un-ghost leaf failed",i)}}}isSemverGreater(t,e){let i=t.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0),n=Math.max(i.length,s.length);for(let o=0;o<n;o++){let 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 A=this.app.vault.getAbstractFileByPath(l);A&&(c=A)}catch(A){console.warn("[Stashpad] author file rename failed",A);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 A=this.app.vault.getAbstractFileByPath(c);A instanceof M.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(A)},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:A}=await Promise.resolve().then(()=>(Ut(),as)),h,p=!1,u=!1;if(await this.app.fileManager.processFrontMatter(t,m=>{if(r&&(typeof m.id=="string"&&m.id.trim()||(h=A(),m.id=h)),l){let f=m.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(m.parent=F,p=!0)}c&&(typeof m.created=="string"&&m.created.trim()||(m.created=new Date(t.stat.ctime).toISOString(),u=!0))}),!h&&!p&&!u)return;let g=this.newLog(),I=h||i;I&&await g.append({type:"parent_change",id:I,payload:{from:null,to:F,reason:"orphan_auto_fix",path:t.path,addedId:!!h,addedParent:p,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===F||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!==F&&(r.parent=F)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:F,reason:"rehome_cross_folder_move",path:t.path}}),new M.Notice(`Re-homed ${t.basename} \u2192 Home (its parent isn't in this folder)`)}catch(i){console.warn("[Stashpad] re-home on cross-folder move failed",i)}}async autoImportStash(t,e){try{let i=new Uint8Array(await this.app.vault.readBinary(t));if(bt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await si(this.app,i);if(!s)return;let n=le(),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 A=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof A=="string"&&o.add(A)}let r=await te(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:F,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 +`,A=Et(o.basename)||o.basename,h=await this.uniquePath(t,wt(A,r));await this.createNote(h,Ee(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&&!hn.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&&Nt(n))return this.pendingEncryptedStashes.add(a.path),!1;let o=await si(this.app,n,{...s,secretId:ze(a.basename)});if(!o)return!1;let r=await te(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:F,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===_t);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 nt(this.app,a,t,e,i).open()})}dupChoice(a){return new Promise(t=>{new Si(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}};gi.DEBOUNCE_MS=900,gi.BATCH_CONFIRM_AT=8;var pn=gi;var gn=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 In=class In{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()},In.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}};In.SAVE_DEBOUNCE_MS=8e3;var un=In;var Ho="stashpad:unghost-after-reload",ts=class ts extends M.Plugin{constructor(){super(...arguments);this.settings={...me};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>ts.DEBUG_BUFFER_MAX&&this.debugBuffer.splice(0,this.debugBuffer.length-ts.DEBUG_BUFFER_MAX)}getDebugTrace(){return this.debugBuffer.join(` +`)}clearDebugTrace(){this.debugBuffer=[]}get notifications(){return this._notifications||(this._notifications=new Is(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new dn(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new pn(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new gn(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 un(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 cn(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(/^.*\//,""),A=this.pluginPrivatePath(c);if(!await t.exists(A))try{let h=await t.read(l);await t.write(A,h),console.debug("[Stashpad] migrated",l,"\u2192",A)}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,A=>{(typeof A.id!="string"||!A.id)&&(A.id=F),"parent"in A||(A.parent=null),(typeof A.created!="string"||!A.created)&&(A.created=new Date().toISOString())});return}let r=new Date().toISOString(),l=["---",`id: ${F}`,"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 A=this.app.metadataCache.getFileCache(l)?.frontmatter;if((typeof A?.color=="string"?A.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(J)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(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 A=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id.trim():"";if(!h)continue;let g=A&&"parent"in A?A.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,A]of Object.entries(s)){let h=o[c];h?h.parent!==A.parent?await i.append({type:"parent_change",id:c,payload:{from:h.parent,to:A.parent}}):h.path!==A.path&&await i.append({type:"rename",id:c,payload:{from:h.path,to:A.path}}):await i.append({type:"create",id:c,payload:{path:A.path,parent:A.parent}})}for(let[c,A]of Object.entries(o))!s[c]&&r(A.path)&&await i.append({type:"missing",id:c,payload:{lastPath:A.path}})}let l={};for(let[c,A]of Object.entries(o))r(A.path)||(l[c]=A);for(let[c,A]of Object.entries(s))l[c]=A;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 An,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),Ft.enabled=!!this.settings.enablePerfProfiling,this.encryption=new Es(this.app,()=>({...Li(),...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 ks(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,I)=>this.renderCacheStore.evict(I)));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,I)=>{this.onOkfFileEvent(p.path),this.onOkfFileEvent(I)})),await this.authorRegistry.load();{let p=(this.settings.authorId??"").trim();p&&this.authorRegistry.record({id:p,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.registerEvent(this.app.vault.on("create",p=>{p.path.endsWith(".stashenc")&&this.pendingEncBlobs.delete(p.path)})),this.registerEvent(this.app.vault.on("delete",p=>{p.path.endsWith(".stashenc")&&this.pendingEncBlobs.delete(p.path)})),this.app.workspace.onLayoutReady(()=>{this.reconcileLockedRegistry(),window.setTimeout(()=>void this.checkDueReminders(),6e3),this.registerInterval(window.setInterval(()=>void this.checkDueReminders(),5*60*1e3)),window.setTimeout(()=>{this.seedLocalAuthorStubsEverywhere()},4e3),window.setTimeout(()=>this.syncObsidianExcludedArchives(),4500),window.setTimeout(()=>this.importService.setArmed(!0),2500),window.setTimeout(()=>void this.runAutoImportSweep(),5e3),this.registerInterval(window.setInterval(()=>void this.runAutoImportSweep(),5*60*1e3)),window.setTimeout(()=>void this.migratePinnedNotesToFrontmatter(),3e3),window.setTimeout(()=>void this.unghostStashpadTabsIfFlagged(),1200)}),this.registerView(J,p=>new en(p,this)),this.registerView(ke,p=>new Ds(p,this)),this.registerView(pe,p=>new cs(p,this)),this.registerView(Oe,p=>new nn(p,this)),this.registerView(Ye,p=>new on(p,this)),this.registerView(ge,p=>new an(p,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",p=>{p&&p.view.getViewType()===J&&(this.lastActiveStashpadLeaf=p,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(ke).length===0&&setTimeout(()=>{bs(this.app)},0),this.notifyStashpadSelectionChanged())}));let e=()=>{let p=ce(),I=!!p&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===p,f=!!I&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",f),document.body.classList.toggle("stashpad-active",!!I)};this.register(Ta(e)),this.registerEvent(this.app.workspace.on("active-leaf-change",e));let i=p=>{try{let I=Array.from(document.querySelectorAll("style")).filter(f=>(f.textContent??"").includes(".stashpad-"));for(let f of I){let m=f.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=f.textContent??"",p.head.appendChild(B)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",p=>{let I=p?.doc??p?.win?.document??null;I&&i(I)})),this.registerEvent(this.app.workspace.on("file-menu",(p,I)=>{if(!(I instanceof M.TFolder))return;let f=I.path.replace(/\/+$/,"");p.addItem(m=>m.setTitle("\u{1F512} Encrypt with Stashpad").setIcon("lock").onClick(()=>void this.encryptFolderFromExplorer(f))),this.discoverStashpadFolders().includes(f)&&p.addItem(m=>{m.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(f))})})),setTimeout(()=>{try{let p=this.app.workspace;typeof p.iterateAllLeaves=="function"&&p.iterateAllLeaves(I=>{let f=I?.view?.containerEl?.ownerDocument;f&&f!==document&&i(f)})}catch{}},200),e(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let s=window.visualViewport,n=()=>{let p=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=p&&p.isConnected?p.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${I}px`);let f=0;s&&(f=Math.max(0,window.innerHeight-s.height-s.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${f}px`),document.body.classList.toggle("stashpad-keyboard-open",f>100)};n(),s&&(s.addEventListener("resize",n),s.addEventListener("scroll",n),this.register(()=>{s.removeEventListener("resize",n),s.removeEventListener("scroll",n)})),window.addEventListener("resize",n),this.register(()=>window.removeEventListener("resize",n)),requestAnimationFrame(n),setTimeout(n,250),setTimeout(n,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",p=>{p.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{As(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{rn(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{bs(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 I=ce();I&&typeof I[p]=="function"&&I[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 bo(this,"encrypted")}),this.addCommand({id:"stashpad-open-all-archived",name:"Open \u201CAll archived\u201D (every archive folder)",callback:()=>void bo(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=Ft.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:()=>{Ft.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(),bi));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 I=this.importService.defaultDestination();return p?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:p=>{let I=this.importService.defaultDestination();return p?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:p=>{let I=this.importService.defaultDestination();return p?!!I:(I&&this.runFolderFrontmatterBackfill(I),!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 As(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void rn(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void bs(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:p=>{let I=this.app.workspace.getActiveFile(),f=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return p||f&&I&&this.revealNoteInStashpad(I),f}});let l=Object.keys(Ni);for(let p of l){let I=Ni[p];this.addCommand({id:`stashpad-open-panels-${p}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await As(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 I=ce(),f=I&&I.noteFolder;return f?(p||(new M.Notice(`Running integrity check on "${f}"\u2026`),this.runIntegrityCheckOnFolder(f).then(()=>{new M.Notice("Integrity check complete \u2014 see Stashpad log.")})),!0):!1}}),this.addCommand({id:"stashpad-fix-orphans",name:"Set missing parents to Home (orphan fix)",callback:()=>void this.fixOrphanParents()}),this.addCommand({id:"stashpad-rebuild-author-registry",name:"Rebuild author registry (scan authors + note frontmatter)",callback:async()=>{new M.Notice("Stashpad: rebuilding author registry\u2026");try{let p=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${p.total} author(s) \u2014 ${p.fromStubs} from stubs, ${p.fromNotes} from note links.`,kind:"success",category:"system"})}catch(p){new M.Notice(`Author registry rebuild failed: ${p.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new M.Notice("Stashpad: restoring author stubs\u2026");try{let p=await this.restoreMissingAuthorStubs();this.notifications.show({message:p.created>0?`Restored ${p.created} author stub(s) across ${p.folders} folder(s).`:`No missing author stubs \u2014 all present across ${p.folders} folder(s).`,kind:"success",category:"system"})}catch(p){new M.Notice(`Restore author stubs failed: ${p.message}`)}}}),this.addCommand({id:"stashpad-sync-authors",name:"Sync authors across all folders (multiplayer)",callback:()=>void this.syncAuthorsAcrossFolders()}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new M.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:p,fmChecked:I,fmWritten:f,slugsRenamed:m,authors:C,imported:B,attachmentsLinked:Q,attachmentsRenamed:y,attachmentsSkipped:E}=await this.rebootstrapAllFolders(),v=[];v.push(`rebootstrapped ${p.length} folder${p.length===1?"":"s"}`),B>0&&v.push(`imported ${B} loose file${B===1?"":"s"}`),Q>0&&v.push(`linked attachments on ${Q} note${Q===1?"":"s"}`),y>0&&v.push(`renamed ${y} attachment${y===1?"":"s"}`),f>0&&v.push(`updated ${f} note${f===1?"":"s"}' metadata`),m>0&&v.push(`renamed ${m} note${m===1?"":"s"}`),C>0&&v.push(`${C} author${C===1?"":"s"} in registry`),v.push(`(checked ${I} total)`),new M.Notice(`Stashpad: ${v.join(" \xB7 ")}`),E>0&&new M.Notice(`Stashpad: ${E} attachment${E===1?"":"s"} need renaming, but skipped to protect links. Enable Settings \u2192 Files & Links \u2192 \u201CAutomatically update internal links\u201D in Obsidian, then rebootstrap again.`,12e3)}catch(p){new M.Notice(`Stashpad: rebootstrap failed (${p.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:p=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(p||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(kt(),bi)).then(({NotificationHistoryModal:p,LogModal:I})=>{new p(this.app,this.notifications,async()=>{let f=this.app.vault.adapter,m=this.pluginPrivatePath("log.jsonl");if(!await f.exists(m)){new M.Notice("No log yet \u2014 make some changes first.");return}let C=await f.read(m);new I(this.app,C,m).open()},this.settings.authorId||null,f=>this.lookupNoteAuthorIds(f)).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 I=`stashpad-toggle-${String(p.key).replace(/[A-Z]/g,f=>`-${f.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${p.label}`,callback:async()=>{let f=!this.settings[p.key];this.settings[p.key]=f,await this.saveSettings(),new M.Notice(`${p.label}: ${f?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let p=this.app.setting;!p?.open||!p?.openTabById||(p.open(),p.openTabById(this.manifest.id),setTimeout(()=>{p?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let p of Fs)this.addCommand({id:`stashpad-open-settings-${p.id}`,name:`Open Stashpad settings: ${p.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let A=()=>{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(()=>(Mi(),gs)),I=await p(this.app,this,this.settings);if(I.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}if(I.error==="no-home"){new M.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:f}=await Promise.resolve().then(()=>(Mi(),gs));f(this.app,I)}catch(p){console.error("[stashpad] preview failed",p),new M.Notice(`Preview failed: ${p?.message??p}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:p,scanForJdNotes:I,JdBuildConfirmModal:f}=await Promise.resolve().then(()=>(Mi(),gs));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}let C=I(this.app,this,this.settings);new f(this.app,this,this.settings,C.indexed.length,async()=>{try{let Q=await p(this.app,this,this.settings);if(Q.error==="no-dest"){new M.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}if(Q.error==="dest-not-stashpad"){new M.Notice(`"${Q.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),A();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new M.Notice(`Index built: ${Q.created} created, ${Q.updated} updated, ${Q.skipped} skipped \u2192 ${Q.destFolder}`,6e3)}catch(Q){console.error("[stashpad] build failed",Q),new M.Notice(`Build failed: ${Q?.message??Q}`,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!==_t)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),f=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),m=p.parent?.path||"",C=m.split("/").pop()??"";if(I&&C===I){if(f&&m.endsWith(`/${f}`))return;let B=m.slice(0,m.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(p,B);return}this.settings.autoImport&&this.importService.isArmed()&&(Ve(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 I=p.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(p)},800)},u=p=>{if(p.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let f=p.parent?.path?.replace(/\/+$/,"")??"";if((f.split("/").pop()??"")!==I)return;let C=f.slice(0,f.length-I.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 I=p.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(p,I)=>{p instanceof M.TFile&&this.maybeReHomeOnCrossFolderMove(p,I)})),this.registerEvent(this.app.vault.on("rename",(p,I)=>{p instanceof M.TFile&&this.maybeArchiveOnMoveIn(p,I)})),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,I)=>{p instanceof M.TFile&&this.maybeAdoptAuthorRename(p,I)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(Ho,"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(Ho)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Ho)}catch{}for(let e of this.app.workspace.getLeavesOfType(J))try{let i=e;i.isDeferred&&typeof i.loadIfDeferred=="function"&&await i.loadIfDeferred()}catch(i){console.warn("[Stashpad] un-ghost leaf failed",i)}}}isSemverGreater(t,e){let i=t.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0),n=Math.max(i.length,s.length);for(let o=0;o<n;o++){let 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 A=this.app.vault.getAbstractFileByPath(l);A&&(c=A)}catch(A){console.warn("[Stashpad] author file rename failed",A);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 A=this.app.vault.getAbstractFileByPath(c);A instanceof M.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(A)},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:A}=await Promise.resolve().then(()=>(Ut(),rs)),h,g=!1,u=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(r&&(typeof f.id=="string"&&f.id.trim()||(h=A(),f.id=h)),l){let m=f.parent;(typeof m=="string"?m.trim()!=="":m!=null)||(f.parent=F,g=!0)}c&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),u=!0))}),!h&&!g&&!u)return;let p=this.newLog(),I=h||i;I&&await p.append({type:"parent_change",id:I,payload:{from:null,to:F,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===F||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!==F&&(r.parent=F)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:F,reason:"rehome_cross_folder_move",path:t.path}}),new M.Notice(`Re-homed ${t.basename} \u2192 Home (its parent isn't in this folder)`)}catch(i){console.warn("[Stashpad] re-home on cross-folder move failed",i)}}async autoImportStash(t,e){try{let i=new Uint8Array(await this.app.vault.readBinary(t));if(Nt(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 A=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof A=="string"&&o.add(A)}let r=await te(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:F,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 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:Is(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 rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1;for(let t of this.app.workspace.getLeavesOfType(J))t.view?.forceReconcileRender?.()},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let f of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(f)?.frontmatter?.id!==t)continue;let B=f.parent?.path;B&&e.add(B)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async f=>{if(f&&!await this.app.vault.adapter.exists(f))try{await this.app.vault.createFolder(f)}catch(C){let B=C?.message??"";if(!/already exists/i.test(B))throw C}},r=0,l=0,c=0,A=0,h=0,p=0,u=!!this.app.vault.getConfig?.("alwaysUpdateLinks"),g=new Set(this.okfActiveFolders());for(let f of e)try{if(i&&await o(`${f}/${i}`),s&&await o(`${f}/${s}`),this.settings.autoImport)try{let Q=await this.importService.importLooseInto(f);A+=Q.files+Q.folders+Q.stashes}catch(Q){console.warn("Stashpad: loose sweep failed",f,Q)}let C=await li(this.app,f);r+=C.checked,l+=C.written,c+=await this.rebootstrapFolderSlugs(f);let B=await this.rebootstrapFolderAttachments(f,u);if(h+=B.renamed,p+=B.skipped,g.has(f.replace(/\/+$/,"")))try{await No(this.app,f)}catch(Q){console.warn("Stashpad: OKF rebuild during rebootstrap failed",f,Q)}n.push(f)}catch(C){console.warn(`Stashpad: rebootstrap skipped ${f}`,C)}let I=0;try{I=(await this.rebuildAuthorRegistry()).total}catch(f){console.warn("Stashpad: rebootstrap author-registry rebuild failed",f)}let m=0;try{m=await this.convertAttachmentsToLinks()}catch(f){console.warn("Stashpad: attachment-link conversion failed",f)}return{touched:n,fmChecked:r,fmWritten:l,slugsRenamed:c,authors:I,imported:A,attachmentsLinked:m,attachmentsRenamed:h,attachmentsSkipped:p}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??$t,n=0,o=this.app.vault.getMarkdownFiles().filter(r=>(r.parent?.path?.replace(/\/+$/,"")??"")===i);for(let r of o){let l=fe(r.basename);if(!(!l||l===e||this.app.metadataCache.getFileCache(r)?.frontmatter?.id!==l))try{let A=await this.app.vault.cachedRead(r),h=A.startsWith("---")?A.slice(A.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):A,p=Et(h,s),u=wt(p,l);if(r.name===u)continue;let g=r.parent?`${r.parent.path}/${u}`:u;if(this.app.vault.getAbstractFileByPath(g))continue;await this.app.fileManager.renameFile(r,g),n+=1}catch(A){console.warn(`Stashpad: slug rebootstrap skipped ${r.path}`,A)}}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=na(l.name);if(!c)continue;let A=As(c.rest,c.stamp);if(l.name===A)continue;if(!e){r+=1;continue}let h=`${i}/${A}`;if(!this.app.vault.getAbstractFileByPath(h))try{await this.app.fileManager.renameFile(l,h),o+=1,await new Promise(p=>setTimeout(p,30))}catch(p){console.warn(`Stashpad: attachment rebootstrap skipped ${l.path}`,p)}}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?.()!==J)return null;let i=e.noteFolder??"";if(!i)return null;let s=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=s[e.cursorIdx]),!n&&e.selection?.size>0){let o=e.firstSelectedId??[...e.selection][0];n=s.find(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(J)){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()}}openFolderPicker(){let t=g=>{let m=g.getViewState().state?.folderOverride;return typeof m=="string"&&m.trim()?m.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(J),i=this.discoverStashpadFolders(),s=le(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let g of this.app.vault.getAllLoadedFiles())if(g.children){let I=g.path;I&&I!=="/"&&!I.startsWith(".")&&o.add(I)}let r=g=>{let I=g.split("/").filter(Boolean).pop()??"";return I?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(f=>(f??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(I):!1},l=new Set,c=[],A=[],h=new Set;for(let g of e){let I=t(g);if(h.has(I))continue;h.add(I),l.add(I);let m=I.split("/").pop()||I;c.push({kind:"reveal",folder:I,label:`Reveal "${m}" tab`,leaf:g,icon:this.isArchiveFolder(I)?"archive":"layout-grid"}),A.push({kind:"open-anyway",folder:I,label:`Open "${m}" in another new tab`,icon:"layout-template"})}for(let g of i.filter(I=>!l.has(I))){let I=g.split("/").pop()||g;c.push({kind:"open",folder:g,label:`Open "${I}" in new tab`,icon:this.isArchiveFolder(g)?"archive":"layout-template"})}let p=this,u=new class extends M.SuggestModal{getSuggestions(g){let I=g.trim().toLowerCase(),m=I?I.split(/\s+/).filter(Boolean):[],f=y=>{if(!m.length)return!0;let E=y.toLowerCase();for(let v of m)if(!E.includes(v))return!1;return!0},C=I?c.filter(y=>{let E="folder"in y?y.folder:"";return f(y.label)||f(E)}):c.slice();if(I&&s&&n)for(let y of i){if(y.toLowerCase()===n.toLowerCase())continue;let E=y.split("/").pop()??y,v=`${y} ${E}`;f(v)&&C.push({kind:"switch-current",folder:y,label:`Switch this tab to "${E}"`,icon:"folder-input"})}let B=g.trim().replace(/^\/+|\/+$/g,"");if(B&&!r(B)){let y=Array.from(o).find(v=>v.toLowerCase()===B.toLowerCase()),E=i.some(v=>v.toLowerCase()===B.toLowerCase());if(y&&!E)C.push({kind:"convert",folder:y,label:`Convert \u201C${Bi(y)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!y){let v=Bi(B);C.push({kind:"create",folder:B,label:`+ Create new Stashpad \u201C${v}\u201D`,icon:"folder-plus"})}}let Q=A.filter(y=>f(y.label)||f("folder"in y?y.folder:""));return C.push(...Q),p.encryption?.isConfigured?.()&&f("trash deleted encrypted")&&C.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),C}renderSuggestion(g,I){I.addClass("stashpad-suggest-item"),I.addClass("stashpad-ribbon-suggest-item"),g.kind==="create"&&I.addClass("stashpad-suggest-create");let m=I.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,M.setIcon)(m,g.icon);let f=I.createDiv({cls:"stashpad-ribbon-suggest-body"});f.createDiv({cls:"stashpad-suggest-title",text:g.label}),"folder"in g&&g.folder&&g.label!==g.folder&&f.createDiv({cls:"stashpad-suggest-preview",text:g.folder})}async onChooseSuggestion(g){if(g.kind==="trash"){p.openEncryptedTrash();return}if(g.kind==="reveal"){p.app.workspace.revealLeaf(g.leaf);return}if(g.kind==="open"||g.kind==="open-anyway"){await p.activateViewForFolder(g.folder);return}if(g.kind==="switch-current"){let I=s;I&&typeof I.setFolderOverride=="function"&&(await I.setFolderOverride(g.folder),p.app.workspace.revealLeaf(I.leaf));return}if(g.kind==="create"){try{let I=Bi(g.folder);await p.app.vault.adapter.exists(I)||await p.app.vault.createFolder(I),await p.activateViewForFolder(I)}catch(I){new M.Notice(`Stashpad: couldn't create folder (${I.message})`)}return}if(g.kind==="convert"){let{ConfirmModal:I}=await Promise.resolve().then(()=>(kt(),Di)),m=g.folder,f=[`\u201C${m}\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 I(p.app,"Convert into a Stashpad?",f.join(` -`),"Convert & import",async C=>{if(C)try{await p.activateViewForFolder(m),await p.runImportLooseFiles(m)}catch(B){new M.Notice(`Stashpad: couldn't convert folder (${B.message})`)}}).open();return}}}(this.app);u.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"),u.open()}async openTinyWindow(){let t=le(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new M.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:J,active:!0,state:{folderOverride:e,focusId:i,tinyMode:!0,tinyAlwaysOnTop:!1,compactMode:s}});try{this.app.workspace.revealLeaf(n)}catch{}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let s=e.getLeavesOfType(J);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:J,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(J),i=this.lastActiveStashpadLeaf&&e.includes(this.lastActiveStashpadLeaf)?this.lastActiveStashpadLeaf:e[0]??null;if(!i){await this.activateView({reveal:!0});return}t.revealLeaf(i),t.setActiveLeaf(i,{focus:!0})}async focusFolderPanel(){await nn(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 zs(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??F)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??F,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let r=o.parent?.path?.replace(/\/+$/,"")??"";r!==i||r==="_deleted"||r.startsWith("_deleted/")||e===F&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:F,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new At(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 At(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 wo(this.app)).length>0}catch{}if(!e)try{e=(await this.app.vault.adapter.list(Pt)).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,A=await gr(this.app,t,e,o,i,c,s.blobFolder);this.pendingEncBlobs.add(A.blobPath);let h=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(p=>p.blob!==A.blobPath),{folder:h,blob:A.blobPath,parentId:A.parentId,title:A.title,count:A.noteCount,created:A.created,rootId:A.rootId,prevSibling:i}],await this.saveSettings(),A.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Locked, but ${A.unpurged.length} file${A.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:fs(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 rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1;for(let t of this.app.workspace.getLeavesOfType(J))t.view?.forceReconcileRender?.()},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let m of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(m)?.frontmatter?.id!==t)continue;let B=m.parent?.path;B&&e.add(B)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async m=>{if(m&&!await this.app.vault.adapter.exists(m))try{await this.app.vault.createFolder(m)}catch(C){let B=C?.message??"";if(!/already exists/i.test(B))throw C}},r=0,l=0,c=0,A=0,h=0,g=0,u=!!this.app.vault.getConfig?.("alwaysUpdateLinks"),p=new Set(this.okfActiveFolders());for(let m of e)try{if(i&&await o(`${m}/${i}`),s&&await o(`${m}/${s}`),this.settings.autoImport)try{let Q=await this.importService.importLooseInto(m);A+=Q.files+Q.folders+Q.stashes}catch(Q){console.warn("Stashpad: loose sweep failed",m,Q)}let C=await li(this.app,m);r+=C.checked,l+=C.written,c+=await this.rebootstrapFolderSlugs(m);let B=await this.rebootstrapFolderAttachments(m,u);if(h+=B.renamed,g+=B.skipped,p.has(m.replace(/\/+$/,"")))try{await To(this.app,m)}catch(Q){console.warn("Stashpad: OKF rebuild during rebootstrap failed",m,Q)}n.push(m)}catch(C){console.warn(`Stashpad: rebootstrap skipped ${m}`,C)}let I=0;try{I=(await this.rebuildAuthorRegistry()).total}catch(m){console.warn("Stashpad: rebootstrap author-registry rebuild failed",m)}let f=0;try{f=await this.convertAttachmentsToLinks()}catch(m){console.warn("Stashpad: attachment-link conversion failed",m)}return{touched:n,fmChecked:r,fmWritten:l,slugsRenamed:c,authors:I,imported:A,attachmentsLinked:f,attachmentsRenamed:h,attachmentsSkipped:g}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??$t,n=0,o=this.app.vault.getMarkdownFiles().filter(r=>(r.parent?.path?.replace(/\/+$/,"")??"")===i);for(let r of o){let l=fe(r.basename);if(!(!l||l===e||this.app.metadataCache.getFileCache(r)?.frontmatter?.id!==l))try{let A=await this.app.vault.cachedRead(r),h=A.startsWith("---")?A.slice(A.indexOf(` +---`,3)+4).replace(/^\r?\n/,""):A,g=Et(h,s),u=wt(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(A){console.warn(`Stashpad: slug rebootstrap skipped ${r.path}`,A)}}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=ra(l.name);if(!c)continue;let A=ds(c.rest,c.stamp);if(l.name===A)continue;if(!e){r+=1;continue}let h=`${i}/${A}`;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?.()!==J)return null;let i=e.noteFolder??"";if(!i)return null;let s=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=s[e.cursorIdx]),!n&&e.selection?.size>0){let o=e.firstSelectedId??[...e.selection][0];n=s.find(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(J)){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()}}openFolderPicker(){let t=p=>{let f=p.getViewState().state?.folderOverride;return typeof f=="string"&&f.trim()?f.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(J),i=this.discoverStashpadFolders(),s=ce(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let p of this.app.vault.getAllLoadedFiles())if(p.children){let I=p.path;I&&I!=="/"&&!I.startsWith(".")&&o.add(I)}let r=p=>{let I=p.split("/").filter(Boolean).pop()??"";return I?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(m=>(m??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(I):!1},l=new Set,c=[],A=[],h=new Set;for(let p of e){let I=t(p);if(h.has(I))continue;h.add(I),l.add(I);let f=I.split("/").pop()||I;c.push({kind:"reveal",folder:I,label:`Reveal "${f}" tab`,leaf:p,icon:this.isArchiveFolder(I)?"archive":"layout-grid"}),A.push({kind:"open-anyway",folder:I,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let p of i.filter(I=>!l.has(I))){let I=p.split("/").pop()||p;c.push({kind:"open",folder:p,label:`Open "${I}" in new tab`,icon:this.isArchiveFolder(p)?"archive":"layout-template"})}let g=this,u=new class extends M.SuggestModal{getSuggestions(p){let I=p.trim().toLowerCase(),f=I?I.split(/\s+/).filter(Boolean):[],m=y=>{if(!f.length)return!0;let E=y.toLowerCase();for(let v of f)if(!E.includes(v))return!1;return!0},C=I?c.filter(y=>{let E="folder"in y?y.folder:"";return m(y.label)||m(E)}):c.slice();if(I&&s&&n)for(let y of i){if(y.toLowerCase()===n.toLowerCase())continue;let E=y.split("/").pop()??y,v=`${y} ${E}`;m(v)&&C.push({kind:"switch-current",folder:y,label:`Switch this tab to "${E}"`,icon:"folder-input"})}let B=p.trim().replace(/^\/+|\/+$/g,"");if(B&&!r(B)){let y=Array.from(o).find(v=>v.toLowerCase()===B.toLowerCase()),E=i.some(v=>v.toLowerCase()===B.toLowerCase());if(y&&!E)C.push({kind:"convert",folder:y,label:`Convert \u201C${yi(y)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!y){let v=yi(B);C.push({kind:"create",folder:B,label:`+ Create new Stashpad \u201C${v}\u201D`,icon:"folder-plus"})}}let Q=A.filter(y=>m(y.label)||m("folder"in y?y.folder:""));return C.push(...Q),g.encryption?.isConfigured?.()&&m("trash deleted encrypted")&&C.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),C}renderSuggestion(p,I){I.addClass("stashpad-suggest-item"),I.addClass("stashpad-ribbon-suggest-item"),p.kind==="create"&&I.addClass("stashpad-suggest-create");let f=I.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,M.setIcon)(f,p.icon);let m=I.createDiv({cls:"stashpad-ribbon-suggest-body"});m.createDiv({cls:"stashpad-suggest-title",text:p.label}),"folder"in p&&p.folder&&p.label!==p.folder&&m.createDiv({cls:"stashpad-suggest-preview",text:p.folder})}async onChooseSuggestion(p){if(p.kind==="trash"){g.openEncryptedTrash();return}if(p.kind==="reveal"){g.app.workspace.revealLeaf(p.leaf);return}if(p.kind==="open"||p.kind==="open-anyway"){await g.activateViewForFolder(p.folder);return}if(p.kind==="switch-current"){let I=s;I&&typeof I.setFolderOverride=="function"&&(await I.setFolderOverride(p.folder),g.app.workspace.revealLeaf(I.leaf));return}if(p.kind==="create"){try{let I=yi(p.folder);await g.app.vault.adapter.exists(I)||await g.app.vault.createFolder(I),await g.activateViewForFolder(I)}catch(I){new M.Notice(`Stashpad: couldn't create folder (${I.message})`)}return}if(p.kind==="convert"){let{ConfirmModal:I}=await Promise.resolve().then(()=>(kt(),bi)),f=p.folder,m=[`\u201C${f}\u201D already exists as a regular vault folder.`,"Converting adds a Home note + _imports / _exports subfolders, and imports the existing loose files and subfolders inside it as notes.","(Files already structured as notes, and reserved subfolders, are left alone.)"];new I(g.app,"Convert into a Stashpad?",m.join(` +`),"Convert & import",async C=>{if(C)try{await g.activateViewForFolder(f),await g.runImportLooseFiles(f)}catch(B){new M.Notice(`Stashpad: couldn't convert folder (${B.message})`)}}).open();return}}}(this.app);u.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"),u.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:J,active:!0,state:{folderOverride:e,focusId:i,tinyMode:!0,tinyAlwaysOnTop:!1,compactMode:s}});try{this.app.workspace.revealLeaf(n)}catch{}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let s=e.getLeavesOfType(J);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:J,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(J),i=this.lastActiveStashpadLeaf&&e.includes(this.lastActiveStashpadLeaf)?this.lastActiveStashpadLeaf:e[0]??null;if(!i){await this.activateView({reveal:!0});return}t.revealLeaf(i),t.setActiveLeaf(i,{focus:!0})}async focusFolderPanel(){await rn(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 Ws(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??F)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??F,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let r=o.parent?.path?.replace(/\/+$/,"")??"";r!==i||r==="_deleted"||r.startsWith("_deleted/")||e===F&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:F,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new At(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 At(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 js(this.app)).length>0}catch{}if(!e)try{e=(await this.app.vault.adapter.list(Pt)).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,A=await fr(this.app,t,e,o,i,c,s.blobFolder);this.pendingEncBlobs.add(A.blobPath);let h=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(g=>g.blob!==A.blobPath),{folder:h,blob:A.blobPath,parentId:A.parentId,title:A.title,count:A.noteCount,created:A.created,rootId:A.rootId,prevSibling:i}],await this.saveSettings(),A.unpurged.length>0?new M.Notice(`\u26A0\uFE0F Locked, but ${A.unpurged.length} file${A.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): ${A.unpurged.join(` -`)}`,0):s.silent||this.notifications.show({message:`Locked ${A.title?`\u201C${A.title}\u201D`:"a note"} (${A.noteCount} note${A.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),A}catch(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 ur(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 A of this.app.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let h;try{h=dt(await this.app.vault.read(A)).fm}catch{continue}let p=h.id;typeof p!="string"||p===F||(typeof h.parent=="string"?h.parent:F)!==F||i.push(p)}let s=new Set((this.settings.lockedSubtrees??[]).map(A=>A.rootId).filter(A=>!!A)),n=i.filter(A=>!s.has(A));if(n.length===0)return new M.Notice("Nothing to lock in this folder."),0;let r=(await new ai(this.app).load(e))[F]??[],l=n.length>3?new M.Notice("",0):null,c=0;for(let A=0;A<n.length;A++){let h=n[A];l?.setMessage(`\u{1F512} Encrypting ${A+1}/${n.length}\u2026`);let p=r.indexOf(h),u=p>0?r[p-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(A=>A.extension==="stashenc"&&(A.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(A=>A.path);if(t.length===0)return new M.Notice("No locked notes anywhere in the vault."),0;let e=t.length>3?new M.Notice("",0):null,i=new Map,s=!1,n=async A=>{if(i.has(A))return i.get(A);let h=null;return this.encryption.hasFolderKey(A)?(this.encryption.isFolderUnlocked(A)||await this.encryption.tryAutoUnlockFolder(A))&&(h=this.encryption.getFolderKey(A)):(s||(s=!0,await this.ensureEncryptionUnlocked()),h=this.encryption.getSessionKey()),i.set(A,h),h},o=0,r=[],l=new Set;for(let A=0;A<t.length;A++){e?.setMessage(`\u{1F513} Decrypting ${A+1}/${t.length}\u2026`);let h=t[A].replace(/\/[^/]*$/,"").replace(/\/+$/,""),p=await n(h);if(!p){l.add(h||"(vault root)");continue}try{let u=await this.unlockBundleCore(t[A],p);o+=u.notesWritten,r.push(t[A])}catch(u){console.warn("[Stashpad] vault unlock skipped",t[A],u)}}if(r.length>0){let A=new Set(r);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(h=>!A.has(h.blob)),await this.saveSettings()}e?.hide();for(let A of i.values())try{A?.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(A=>A.split("/").pop()||A).join(", ")}. Open each to unlock it, then run this again.`,0),o}exportLockedSubtree(t){return vr(this,t)}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 Qr(this.app,t))try{await yr(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.rotationLockPath(s);if(await this.app.vault.adapter.exists(o))return new M.Notice("A rotation is already in progress for this folder (or one was interrupted \u2014 reload to recover)."),-1;let r=this.app.vault.getFiles().filter(h=>h.extension==="stashenc"&&(h.parent?.path?.replace(/\/+$/,"")??"")===s).map(h=>h.path),l=crypto.getRandomValues(new Uint8Array(32)),c=[...crypto.getRandomValues(new Uint8Array(8))].map(h=>h.toString(16).padStart(2,"0")).join(""),A=r.length>0?new M.Notice("",0):null;try{await this.app.vault.adapter.write(o,JSON.stringify({folder:s,phase:"encrypting",at:new Date().toISOString()}));for(let h=0;h<r.length;h++)A?.setMessage(`\u{1F504} Re-encrypting ${h+1}/${r.length}\u2026`),await Br(this.app,r[h],n,l);await this.app.vault.adapter.write(o,JSON.stringify({folder:s,phase:"committing",rotId:c,at:new Date().toISOString()})),await this.encryption.commitFolderRotation(s,e,l,c,void 0,i),A?.setMessage("\u{1F504} Finalizing\u2026"),await this.commitRotTemps(s);try{await this.app.vault.adapter.remove(o)}catch{}return A?.hide(),new M.Notice(`\u{1F511} Rotated the key for \u201C${s.split("/").pop()}\u201D \u2014 ${r.length} item${r.length===1?"":"s"} re-encrypted. The OLD password no longer unlocks it; share the new one with anyone who should keep access.`,0),r.length}catch(h){A?.hide();try{await Eo(this.app,s)}catch{}try{await this.app.vault.adapter.remove(o)}catch{}return console.warn("[Stashpad] rotation failed",h),new M.Notice(`Rotation failed: ${h.message}. Nothing was changed (originals intact).`,0),-1}finally{l.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}if(!!i.rotId&&this.encryption.folderKeyEntry(s)?.rotId===i.rotId)await this.commitRotTemps(s),new M.Notice(`Finished an interrupted key rotation for \u201C${s.split("/").pop()}\u201D.`,0);else try{await Eo(this.app,s)}catch{}try{await this.app.vault.adapter.remove(e)}catch{}}}}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),o=(((this.settings.folderEncPrefs??{})[t.replace(/\/+$/,"")]??{}).trashEncryptFilenames??!1)||(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),r=await Ir(this.app,t,e,i,s,o);return this.pendingEncBlobs.add(r.blobPath),r.unpurged.length>0&&new M.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${r.unpurged.length} file${r.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): -${r.unpurged.join(` -`)}`,0),r.blobPath}catch(s){return console.warn("[Stashpad] encrypt-delete failed",s),new M.Notice(`Couldn't encrypt-delete: ${s.message}`,0),null}}async restoreDeletedAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=await Ws(this.app,t);if(s?.kind==="rawtrash")try{let n=await Cr(this.app,t,i);return this.pendingEncBlobs.delete(t),e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Pt}/).`,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 yo(this.app,t,s,i),o=new Set;for(let l of this.app.vault.getMarkdownFiles())if((l.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let c=dt(await this.app.vault.read(l)).fm.id;typeof c=="string"&&o.add(c)}catch{}let r=await fr(this.app,t,i,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 Qo(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 Qo(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 wo(this.app),e=[];for(let i of t)e.push({blob:i,meta:await Ws(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 mr(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):s.silent||this.notifications.show({message:`Locked ${A.title?`\u201C${A.title}\u201D`:"a note"} (${A.noteCount} note${A.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),A}catch(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 mr(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 A of this.app.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let h;try{h=dt(await this.app.vault.read(A)).fm}catch{continue}let g=h.id;typeof g!="string"||g===F||(typeof h.parent=="string"?h.parent:F)!==F||i.push(g)}let s=new Set((this.settings.lockedSubtrees??[]).map(A=>A.rootId).filter(A=>!!A)),n=i.filter(A=>!s.has(A));if(n.length===0)return new M.Notice("Nothing to lock in this folder."),0;let r=(await new ai(this.app).load(e))[F]??[],l=n.length>3?new M.Notice("",0):null,c=0;for(let A=0;A<n.length;A++){let h=n[A];l?.setMessage(`\u{1F512} Encrypting ${A+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(A=>A.extension==="stashenc"&&(A.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(A=>A.path);if(t.length===0)return new M.Notice("No locked notes anywhere in the vault."),0;let e=t.length>3?new M.Notice("",0):null,i=new Map,s=!1,n=async A=>{if(i.has(A))return i.get(A);let h=null;return this.encryption.hasFolderKey(A)?(this.encryption.isFolderUnlocked(A)||await this.encryption.tryAutoUnlockFolder(A))&&(h=this.encryption.getFolderKey(A)):(s||(s=!0,await this.ensureEncryptionUnlocked()),h=this.encryption.getSessionKey()),i.set(A,h),h},o=0,r=[],l=new Set;for(let A=0;A<t.length;A++){e?.setMessage(`\u{1F513} Decrypting ${A+1}/${t.length}\u2026`);let h=t[A].replace(/\/[^/]*$/,"").replace(/\/+$/,""),g=await n(h);if(!g){l.add(h||"(vault root)");continue}try{let u=await this.unlockBundleCore(t[A],g);o+=u.notesWritten,r.push(t[A])}catch(u){console.warn("[Stashpad] vault unlock skipped",t[A],u)}}if(r.length>0){let A=new Set(r);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(h=>!A.has(h.blob)),await this.saveSettings()}e?.hide();for(let A of i.values())try{A?.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(A=>A.split("/").pop()||A).join(", ")}. Open each to unlock it, then run this again.`,0),o}exportLockedSubtree(t){return br(this,t)}async encryptFolderFromExplorer(t){if(this.encryption.hasOwnFolderKey(t)){await this.ensureFolderUnlocked(t)&&await this.lockFolder(t);return}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,i=new Date,s=c=>String(c).padStart(2,"0"),n=`${i.getFullYear()}${s(i.getMonth()+1)}${s(i.getDate())}-${s(i.getHours())}${s(i.getMinutes())}`,o=(this.settings.authorName||"").trim(),r=o?o.split(/\s+/).map(c=>c[0]).join(""):(this.settings.authorId||"anon").slice(0,4),l=`${n} - ${e} - ${r}`;new At(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:c,remember:A})=>{if(!c)return"Enter a password.";try{await this.encryption.setupFolderKey(t,c,l,A)}catch(g){return g.message}let h=await this.lockFolder(t);return new M.Notice(h>0?`Encrypted ${h} note${h===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()}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 kr(this.app,t))try{await Xs(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=f=>f===o||f.startsWith(o+"/"),c=this.app.vault.getFiles().filter(f=>f.extension==="stashenc"&&l(f.parent?.path?.replace(/\/+$/,"")??"")).map(f=>f.path),A=this.encryption.folderKeyEntry(o)?.keyId,h=A?await ko(this.app,A):[],g=[...c,...h],u=crypto.getRandomValues(new Uint8Array(32)),p=[...crypto.getRandomValues(new Uint8Array(8))].map(f=>f.toString(16).padStart(2,"0")).join(""),I=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 f=0;f<g.length;f++)I?.setMessage(`\u{1F504} Re-encrypting ${f+1}/${g.length}\u2026`),await vr(this.app,g[f],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),I?.setMessage("\u{1F504} Finalizing\u2026"),await this.commitRotTemps(o);for(let f of h){await Xs(this.app,f);try{await Fr(this.app,f,n,u)}catch(m){console.warn("[Stashpad] trash sidecar rewrap failed",f,m)}}try{await this.app.vault.adapter.remove(r)}catch{}return I?.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(f){I?.hide();try{await Zs(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",f),new M.Notice(`Rotation failed: ${f.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 ko(this.app,n.keyId))try{await Xs(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 Zs(this.app,s)}catch{}try{await Zs(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 yr(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): +${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 hi(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 wr(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 (${Pt}/).`,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 wo(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 Qr(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 vo(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 vo(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 js(this.app),e=[];for(let i of t)e.push({blob:i,meta:await hi(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 Er(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 ${Pt}/.`,kind:"success",category:"system",folder:""}),!0):(new M.Notice(`Obsidian's vault trash (${Pt}/) 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}br(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 _s(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 Mr(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||Do}okfActiveFolders(){return this.settings.okfEnabled?Tr(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}async rebuildOkfSuppressed(t){this.okfRebuildingFolders.add(t);try{return await No(this.app,t)}finally{window.setTimeout(()=>{this.okfRebuildingFolders.delete(t);for(let e of this.app.workspace.getLeavesOfType(J)){let i=e.view;i?.noteFolder===t&&i.forceReconcileRender?.()}},600)}}onOkfFileEvent(t){if(!this.settings.okfEnabled||!t.toLowerCase().endsWith(".md"))return;let e=t.lastIndexOf("/"),i=(e>=0?t.slice(0,e):"").replace(/\/+$/,"");(e>=0?t.slice(e+1):t)!=="index.md"&&(/(^|\/)(_imports|_exports|_attachments|_deleted|\.stashpad)(\/|$)/.test(t)||this.okfActiveFolders().includes(i)&&this.scheduleOkfRebuild(i))}scheduleOkfRebuild(t){let e=this.okfRebuildTimers.get(t);e!=null&&window.clearTimeout(e),this.okfRebuildTimers.set(t,window.setTimeout(()=>{this.okfRebuildTimers.delete(t),this.okfActiveFolders().includes(t)&&this.rebuildOkfSuppressed(t).catch(i=>console.warn("[Stashpad] OKF auto-rebuild failed",t,i))},2500))}async rebuildAllOkf(){let t=this.okfActiveFolders(),e=0,i=0;for(let s of t){let n=await this.rebuildOkfSuppressed(s);e+=n.checked,i+=n.written}return{folders:t.length,checked:e,written:i}}async exportOkf(t,e,i,s){let n=t.replace(/\/+$/,""),o=[],r=[],l=[],c=new Set;for(let m of e){let f=await we(this.app,n,m);if(f){o.push({id:f.rootNote.id,file:f.rootNote.file}),l.push(f.rootNote.file),c.add(f.rootNote.id);for(let C of f.descendants)r.push({id:C.id,file:C.file}),l.push(C.file),c.add(C.id)}}if(!l.length)return[];let A=(i||"okf-export").replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim().slice(0,80)||"okf-export",h=new Date().toISOString().replace(/\D/g,"").slice(0,14),p=(this.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),u=`${n}/${p}`;for(let m of[n,u])try{await this.app.vault.adapter.exists(m)||await this.app.vault.adapter.mkdir(m)}catch{}let g=[],I=async(m,f)=>{let C=`${u}/${m}`;await this.app.vault.createBinary(C,f.buffer.slice(f.byteOffset,f.byteOffset+f.byteLength)),g.push(C)};if(s.zip||s.targz){let m=await Pr(this.app,l,n,c);s.zip&&await I(`${A}-${h}.okf.zip`,await Hr(m)),s.targz&&await I(`${A}-${h}.okf.tar.gz`,await Ur(m))}if(s.stash){let m=await Qe(this.app,{rootNotes:o,allDescendants:r,sourceFolder:n});await I(`${A}-${h}.${_t}`,m)}return g}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=[],A=[];for(let w of e){let D=await we(this.app,t,w);if(D){c.push(D.rootNote.id),r.push({id:D.rootNote.id,file:D.rootNote.file}),A.push(D.rootNote.file);for(let b of D.descendants)l.push({id:b.id,file:b.file}),A.push(b.file)}}if(!r.length)return null;let h=r.length+l.length,p=[],u=[];n==="cut"&&(p=await this.exclusiveAttachmentsOf(A),u=await this.snapshotPaths([...A.map(w=>w.path),...p.map(w=>w.path)]));let g=await Qe(this.app,{rootNotes:r,allDescendants:l,sourceFolder:t}),I=await this.idsInFolder(o),m=new Set(this.filesUnder(o)),f=await te(this.app,g,o,I,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),C=this.filesUnder(o).filter(w=>!m.has(w)),B=await this.snapshotPaths(C),Q=c.map(w=>f.idRemap[w]).filter(w=>!!w);if(n==="cut"){for(let w of A)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source note",w.path,D)}for(let w of p)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",w.path,D)}}let y=async()=>{for(let w of[...C].reverse()){let D=this.app.vault.getAbstractFileByPath(w);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}};return{rootIds:Q,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 w of u){let D=this.app.vault.getAbstractFileByPath(w.path);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}}:async()=>{await this.restoreSnapshot(B)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let r=await we(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 $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 we(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 we(this.app,t,o);if(!r)continue;let l=new Map;for(let A of r.descendants){if(!A.parent)continue;let h=l.get(A.parent)??[];h.push({id:A.id,file:A.file,created:A.created}),l.set(A.parent,h)}for(let A of l.values())A.sort((h,p)=>n(h.file)-n(p.file)||h.created.localeCompare(p.created));let c=(A,h)=>{if(!s.has(A.id)){s.add(A.id),i.push({file:A.file,created:A.created,depth:h});for(let p of l.get(A.id)??[])c(p,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(J)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,"");if(!((this.settings.folderEncPrefs??{})[i]?.archiveEncryptContent??!0))return;let s=[];for(let c of e){let A=this.app.vault.getAbstractFileByPath(c);if(!(A instanceof M.TFile)||(A.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let h;try{h=dt(await this.app.vault.read(A)).fm}catch{continue}let p=typeof h.id=="string"?h.id:null;!p||p===F||s.push({id:p,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:J,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(i),i}navigateLeafTo(t,e,i){let s=t?.view;if(s?.navigateTo&&(!s.tree||s.tree.get(i))){s.navigateTo(i);return}this.navigateWhenReady(e,i)}async openFolderInStashpad(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=await this.findStashpadLeafForFolder(e);if(i){this.app.workspace.revealLeaf(i),this.app.workspace.setActiveLeaf(i,{focus:!0});return}await this.activateViewForFolder(e)}async findStashpadLeafForFolder(t){let e=t.replace(/\/+$/,""),i=this.app.workspace.getLeavesOfType(J),s=i.find(o=>!o.isDeferred&&(o.view?.noteFolder??"").replace(/\/+$/,"")===e);if(s)return s;let n=i.find(o=>o.isDeferred&&(o.getViewState()?.state?.folderOverride??"").replace(/\/+$/,"")===e);if(n){try{await n.loadIfDeferred?.()}catch{}return n}return null}isStashpadNoteFile(t){let e=t.parent?.path?.replace(/\/+$/,"")??"";if(!this.discoverStashpadFolders().includes(e))return!1;let i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;return typeof i=="string"&&i.length>0}async revealNoteInStashpad(t){let e=t.parent?.path?.replace(/\/+$/,"")??"",i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;if(!e||typeof i!="string"||!i){new M.Notice("That note isn't a Stashpad note.");return}await this.revealNoteByRef(e,i)}async revealNoteByRef(t,e){let i=t.replace(/\/+$/,""),s=await this.findStashpadLeafForFolder(i);if(s){this.app.workspace.revealLeaf(s),this.app.workspace.setActiveLeaf(s,{focus:!0}),this.navigateLeafTo(s,i,e);return}let n=await this.activateViewForFolder(i);this.navigateLeafTo(n,i,e)}async closeDuplicateStashpadTabs(){let t=this.app.workspace.getLeavesOfType(J),e=this.app.workspace.activeLeaf;for(let g of t)try{await g.loadIfDeferred?.()}catch{}let i=g=>g.getViewState()?.state??{},s=g=>{let I=i(g);return(g.isDeferred?I.folderOverride??"":g.view?.noteFolder??I.folderOverride??"").replace(/\/+$/,"")},n=g=>{let I=i(g);return(g.isDeferred?I.focusId:g.view?.focusId??I.focusId)||F},o=g=>{let I=g.view;return!!I&&I.getViewType?.()===J&&typeof I.navigateTo=="function"&&typeof I.noteFolder=="string"},r=new Map;for(let g of this.app.vault.getMarkdownFiles()){let I=(g.parent?.path??"").replace(/\/+$/,""),m=this.app.metadataCache.getFileCache(g)?.frontmatter?.id;typeof m=="string"&&m&&(r.get(I)??r.set(I,new Set).get(I)).add(m)}let l=0,c=[];for(let g of t){let I=s(g),m=n(g);if(I&&m&&m!==F){let f=!g.isDeferred&&!!g.view?.tree?.get?.(m),C=r.get(I)?.has(m)??!1;if(!f&&!C){g.detach(),l++;continue}}c.push(g)}let A=new Map;for(let g of c){let I=s(g);if(!I)continue;let m=I+" "+n(g);(A.get(m)??A.set(m,[]).get(m)).push(g)}let h=0;for(let g of A.values()){if(g.length<=1)continue;g.sort((m,f)=>{let C=B=>B===e?2:B.isDeferred?0:1;return C(f)-C(m)});let I=null;for(let m of g){try{await m.loadIfDeferred?.()}catch{}if(o(m)){I=m;break}}I||(I=g[0]);for(let m of g)m!==I&&(m.detach(),h++)}let p=this.app.workspace.getLeavesOfType(J).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 ${p} Stashpad tab${p===1?"":"s"} remaining`}),new M.Notice(u,7e3),h+l}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(J).find(o=>(o.view?.noteFolder??"").replace(/\/+$/,"")===s)?.view??this.lastActiveStashpadLeaf?.view;if(n&&typeof n.navigateTo=="function"&&(!n.tree||typeof n.tree.get!="function"||!!n.tree.get(e))){n.navigateTo(e);return}i>0?window.setTimeout(()=>this.navigateWhenReady(t,e,i-1),90):n&&typeof n.navigateTo=="function"&&n.navigateTo(e)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,i=this.discoverStashpadFolders(),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let r=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(g=>typeof g=="string"):[],c=r.includes(e),A=l.some(g=>g.includes(e));if(!c&&!A)continue;let h=n.parent?.path??"",p=i.find(g=>h===g||h.startsWith(g+"/"));if(!p)continue;s.has(p)||s.set(p,{authored:0,contributed:0});let u=s.get(p);c&&u.authored++,A&&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 ue(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),A=typeof r.due=="number"?r.due:Date.parse(c);if(!Number.isFinite(A)||A>t)continue;let h=De(r);if(h.length>0&&!(i&&h.some(u=>u.id===i)))continue;let p=`${l}@${c}`;e.has(p)||s.push({id:l,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:A,key:p})}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 (${oe(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 A=e.get(c.id);!A.name&&c.name&&(A.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(I=>typeof I=="string")??"":typeof c?.aliases=="string"?c.aliases:"")||(typeof c?.name=="string"?c.name:"")||l.name).trim(),p=typeof c?.role=="string"?c.role:void 0,u=typeof c?.department=="string"?c.department:void 0,g=e.get(l.id);g||s++,e.set(l.id,{id:l.id,name:h||g?.name,role:p??g?.role,department:u??g?.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),A=`${o}/${c}-${l.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(A))continue;await this.app.vault.create(A,this.buildAuthorStub(l,l.firstSeen??new Date().toISOString())),s++}catch(h){console.warn("[Stashpad] restore author stub failed",A,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),A=typeof l=="string"&&l.trim().length>0;if(!(!c&&!A||!(A?!e(l):l.some(p=>typeof p=="string"&&p.trim()&&!e(p)))))try{await this.app.fileManager.processFrontMatter(n,p=>{Array.isArray(p.attachments)?p.attachments=p.attachments.map(u=>typeof u=="string"&&u.trim()?Yt(u):u):typeof p.attachments=="string"&&p.attachments.trim()&&(p.attachments=[Yt(p.attachments)])}),t++}catch(p){console.warn("[Stashpad] attachment-link conversion failed",n.path,p)}}}return t}syncObsidianExcludedArchives(){try{let t=this.app.vault;if(typeof t.getConfig!="function"||typeof t.setConfig!="function")return;let e=Array.isArray(t.getConfig("userIgnoreFilters"))?t.getConfig("userIgnoreFilters"):[],i=new Set(e),s=!1;for(let n of this.discoverStashpadFolders()){let o=`${n.replace(/\/+$/,"")}/_archive/`;i.has(o)||(i.add(o),s=!0)}s&&t.setConfig("userIgnoreFilters",[...i])}catch(t){console.warn("[Stashpad] couldn't update Obsidian excluded files",t)}}openImportPicker(){let t=this.discoverStashpadFolders();if(t.length===0){new 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 To(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}\` +`)}`,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 ${Pt}/.`,kind:"success",category:"system",folder:""}),!0):(new M.Notice(`Obsidian's vault trash (${Pt}/) 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}Pr(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 sn(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 Rr(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||xo}okfActiveFolders(){return this.settings.okfEnabled?Gr(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}async rebuildOkfSuppressed(t){this.okfRebuildingFolders.add(t);try{return await To(this.app,t)}finally{window.setTimeout(()=>{this.okfRebuildingFolders.delete(t);for(let e of this.app.workspace.getLeavesOfType(J)){let i=e.view;i?.noteFolder===t&&i.forceReconcileRender?.()}},600)}}onOkfFileEvent(t){if(!this.settings.okfEnabled||!t.toLowerCase().endsWith(".md"))return;let e=t.lastIndexOf("/"),i=(e>=0?t.slice(0,e):"").replace(/\/+$/,"");(e>=0?t.slice(e+1):t)!=="index.md"&&(/(^|\/)(_imports|_exports|_attachments|_deleted|\.stashpad)(\/|$)/.test(t)||this.okfActiveFolders().includes(i)&&this.scheduleOkfRebuild(i))}scheduleOkfRebuild(t){let e=this.okfRebuildTimers.get(t);e!=null&&window.clearTimeout(e),this.okfRebuildTimers.set(t,window.setTimeout(()=>{this.okfRebuildTimers.delete(t),this.okfActiveFolders().includes(t)&&this.rebuildOkfSuppressed(t).catch(i=>console.warn("[Stashpad] OKF auto-rebuild failed",t,i))},2500))}async rebuildAllOkf(){let t=this.okfActiveFolders(),e=0,i=0;for(let s of t){let n=await this.rebuildOkfSuppressed(s);e+=n.checked,i+=n.written}return{folders:t.length,checked:e,written:i}}async exportOkf(t,e,i,s){let n=t.replace(/\/+$/,""),o=[],r=[],l=[],c=new Set;for(let f of e){let m=await we(this.app,n,f);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 A=(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 f of[n,u])try{await this.app.vault.adapter.exists(f)||await this.app.vault.adapter.mkdir(f)}catch{}let p=[],I=async(f,m)=>{let C=`${u}/${f}`;await this.app.vault.createBinary(C,m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)),p.push(C)};if(s.zip||s.targz){let f=await Lr(this.app,l,n,c);s.zip&&await I(`${A}-${h}.okf.zip`,await qr(f)),s.targz&&await I(`${A}-${h}.okf.tar.gz`,await Jr(f))}if(s.stash){let f=await Qe(this.app,{rootNotes:o,allDescendants:r,sourceFolder:n});await I(`${A}-${h}.${_t}`,f)}return p}async idsInFolder(t){let e=t.replace(/\/+$/,""),i=new Set;for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===e)try{let n=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=[],A=[];for(let w of e){let D=await we(this.app,t,w);if(D){c.push(D.rootNote.id),r.push({id:D.rootNote.id,file:D.rootNote.file}),A.push(D.rootNote.file);for(let b of D.descendants)l.push({id:b.id,file:b.file}),A.push(b.file)}}if(!r.length)return null;let h=r.length+l.length,g=[],u=[];n==="cut"&&(g=await this.exclusiveAttachmentsOf(A),u=await this.snapshotPaths([...A.map(w=>w.path),...g.map(w=>w.path)]));let p=await Qe(this.app,{rootNotes:r,allDescendants:l,sourceFolder:t}),I=await this.idsInFolder(o),f=new Set(this.filesUnder(o)),m=await te(this.app,p,o,I,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),C=this.filesUnder(o).filter(w=>!f.has(w)),B=await this.snapshotPaths(C),Q=c.map(w=>m.idRemap[w]).filter(w=>!!w);if(n==="cut"){for(let w of A)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source note",w.path,D)}for(let w of g)try{await this.app.fileManager.trashFile(w)}catch(D){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",w.path,D)}}let y=async()=>{for(let w of[...C].reverse()){let D=this.app.vault.getAbstractFileByPath(w);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}};return{rootIds:Q,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 w of u){let D=this.app.vault.getAbstractFileByPath(w.path);if(D)try{await this.app.fileManager.trashFile(D)}catch{}}}:async()=>{await this.restoreSnapshot(B)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let r=await we(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 Vs(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 we(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 we(this.app,t,o);if(!r)continue;let l=new Map;for(let A of r.descendants){if(!A.parent)continue;let h=l.get(A.parent)??[];h.push({id:A.id,file:A.file,created:A.created}),l.set(A.parent,h)}for(let A of l.values())A.sort((h,g)=>n(h.file)-n(g.file)||h.created.localeCompare(g.created));let c=(A,h)=>{if(!s.has(A.id)){s.add(A.id),i.push({file:A.file,created:A.created,depth:h});for(let g of l.get(A.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(J)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,"");if(!((this.settings.folderEncPrefs??{})[i]?.archiveEncryptContent??!0))return;let s=[];for(let c of e){let A=this.app.vault.getAbstractFileByPath(c);if(!(A instanceof M.TFile)||(A.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let h;try{h=dt(await this.app.vault.read(A)).fm}catch{continue}let g=typeof h.id=="string"?h.id:null;!g||g===F||s.push({id:g,parent:typeof h.parent=="string"?h.parent:null})}if(s.length===0)return;let n=new Set(s.map(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:J,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(i),i}navigateLeafTo(t,e,i){let s=t?.view;if(s?.navigateTo&&(!s.tree||s.tree.get(i))){s.navigateTo(i);return}this.navigateWhenReady(e,i)}async openFolderInStashpad(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let i=await this.findStashpadLeafForFolder(e);if(i){this.app.workspace.revealLeaf(i),this.app.workspace.setActiveLeaf(i,{focus:!0});return}await this.activateViewForFolder(e)}async findStashpadLeafForFolder(t){let e=t.replace(/\/+$/,""),i=this.app.workspace.getLeavesOfType(J),s=i.find(o=>!o.isDeferred&&(o.view?.noteFolder??"").replace(/\/+$/,"")===e);if(s)return s;let n=i.find(o=>o.isDeferred&&(o.getViewState()?.state?.folderOverride??"").replace(/\/+$/,"")===e);if(n){try{await n.loadIfDeferred?.()}catch{}return n}return null}isStashpadNoteFile(t){let e=t.parent?.path?.replace(/\/+$/,"")??"";if(!this.discoverStashpadFolders().includes(e))return!1;let i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;return typeof i=="string"&&i.length>0}async revealNoteInStashpad(t){let e=t.parent?.path?.replace(/\/+$/,"")??"",i=this.app.metadataCache.getFileCache(t)?.frontmatter?.id;if(!e||typeof i!="string"||!i){new M.Notice("That note isn't a Stashpad note.");return}await this.revealNoteByRef(e,i)}async revealNoteByRef(t,e){let i=t.replace(/\/+$/,""),s=await this.findStashpadLeafForFolder(i);if(s){this.app.workspace.revealLeaf(s),this.app.workspace.setActiveLeaf(s,{focus:!0}),this.navigateLeafTo(s,i,e);return}let n=await this.activateViewForFolder(i);this.navigateLeafTo(n,i,e)}async closeDuplicateStashpadTabs(){let t=this.app.workspace.getLeavesOfType(J),e=this.app.workspace.activeLeaf;for(let p of t)try{await p.loadIfDeferred?.()}catch{}let i=p=>p.getViewState()?.state??{},s=p=>{let I=i(p);return(p.isDeferred?I.folderOverride??"":p.view?.noteFolder??I.folderOverride??"").replace(/\/+$/,"")},n=p=>{let I=i(p);return(p.isDeferred?I.focusId:p.view?.focusId??I.focusId)||F},o=p=>{let I=p.view;return!!I&&I.getViewType?.()===J&&typeof I.navigateTo=="function"&&typeof I.noteFolder=="string"},r=new Map;for(let p of this.app.vault.getMarkdownFiles()){let I=(p.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(p)?.frontmatter?.id;typeof f=="string"&&f&&(r.get(I)??r.set(I,new Set).get(I)).add(f)}let l=0,c=[];for(let p of t){let I=s(p),f=n(p);if(I&&f&&f!==F){let m=!p.isDeferred&&!!p.view?.tree?.get?.(f),C=r.get(I)?.has(f)??!1;if(!m&&!C){p.detach(),l++;continue}}c.push(p)}let A=new Map;for(let p of c){let I=s(p);if(!I)continue;let f=I+" "+n(p);(A.get(f)??A.set(f,[]).get(f)).push(p)}let h=0;for(let p of A.values()){if(p.length<=1)continue;p.sort((f,m)=>{let C=B=>B===e?2:B.isDeferred?0:1;return C(m)-C(f)});let I=null;for(let f of p){try{await f.loadIfDeferred?.()}catch{}if(o(f)){I=f;break}}I||(I=p[0]);for(let f of p)f!==I&&(f.detach(),h++)}let g=this.app.workspace.getLeavesOfType(J).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(J).find(o=>(o.view?.noteFolder??"").replace(/\/+$/,"")===s)?.view??this.lastActiveStashpadLeaf?.view;if(n&&typeof n.navigateTo=="function"&&(!n.tree||typeof n.tree.get!="function"||!!n.tree.get(e))){n.navigateTo(e);return}i>0?window.setTimeout(()=>this.navigateWhenReady(t,e,i-1),90):n&&typeof n.navigateTo=="function"&&n.navigateTo(e)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,i=this.discoverStashpadFolders(),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let r=typeof o.author=="string"?o.author:"",l=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],c=r.includes(e),A=l.some(p=>p.includes(e));if(!c&&!A)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++,A&&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 ue(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),A=typeof r.due=="number"?r.due:Date.parse(c);if(!Number.isFinite(A)||A>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:A,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 (${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 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 A=e.get(c.id);!A.name&&c.name&&(A.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(I=>typeof I=="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),A=`${o}/${c}-${l.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(A))continue;await this.app.vault.create(A,this.buildAuthorStub(l,l.firstSeen??new Date().toISOString())),s++}catch(h){console.warn("[Stashpad] restore author stub failed",A,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+"/")||Ve(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),A=typeof l=="string"&&l.trim().length>0;if(!(!c&&!A||!(A?!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()?Yt(u):u):typeof g.attachments=="string"&&g.attachments.trim()&&(g.attachments=[Yt(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 Uo(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={...me,...t,shortcuts:{...me.shortcuts,...t?.shortcuts??{}},mod:{...me.mod,...t?.mod??{}},bindings:Uc(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:Rc(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...$t]},jn(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?.[Kt];if(Array.isArray(i)&&i.some(s=>t.has(es(s)??"")))try{await this.app.fileManager.processFrontMatter(e,s=>{let o=(Array.isArray(s[Kt])?s[Kt]:[]).filter(r=>!t.has(es(r)??""));o.length?s[Kt]=o:delete s[Kt]})}catch{}}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),jn(this.settings),Ft.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 p=this.app.metadataCache.getFileCache(h)?.frontmatter,u=typeof p?.id=="string"?p.id.trim():"";u&&e.add(u)}let{newId:s}=await Promise.resolve().then(()=>(Ut(),as)),n=()=>{for(let h=0;h<100;h++){let p=s();if(!e.has(p))return e.add(p),p}for(let h=8;h<=16;h+=2){let p=s(h);if(!e.has(p))return e.add(p),p}throw new Error("Could not generate a unique id")},o=[];for(let h of i){let p=h.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(p))continue;let u=this.app.metadataCache.getFileCache(h)?.frontmatter,g=typeof u?.id=="string"?u.id.trim():"",I=u?.parent,m=typeof I=="string"?I.trim()!=="":I!=null,f=typeof u?.created=="string"&&u.created.trim()!=="",C=!g,B=!m,Q=!f;!C&&!B&&!Q||o.push({file:h,addId:C,addParent:B,addCreated:Q})}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 p;await this.app.fileManager.processFrontMatter(h.file,I=>{if(h.addId&&(typeof I.id=="string"&&I.id.trim()||(p=n(),I.id=p)),h.addParent){let m=I.parent;(typeof m=="string"?m.trim()!=="":m!=null)||(I.parent=F)}h.addCreated&&(typeof I.created=="string"&&I.created.trim()||(I.created=new Date(h.file.stat.ctime).toISOString()))});let u=this.app.metadataCache.getFileCache(h.file)?.frontmatter,g=p??u?.id??"";g&&await c.append({type:"parent_change",id:g,payload:{from:null,to:F,reason:"orphan_fix",path:h.file.path,addedId:h.addId,addedParent:h.addParent,addedCreated:h.addCreated}}),r++}catch(p){console.warn("Stashpad: orphan fix failed for",h.file.path,p),l++}let A=l?` (${l} failed \u2014 see console)`:"";new M.Notice(`Fixed ${r} note${r===1?"":"s"} in Stashpad folders${A}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Ut(),as)),i=new Set;for(let c of this.app.vault.getMarkdownFiles()){if(c.path===t.path)continue;let A=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id.trim():"";h&&i.add(h)}let s=()=>{for(let c=0;c<50;c++){let A=e();if(!i.has(A))return A}for(let c=8;c<=16;c+=2){let A=e(c);if(!i.has(A))return A}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,c=>{let A=typeof c.id=="string"?c.id.trim():"";!A||/\s/.test(A)||i.has(A)?(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=F,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,A=typeof c?.id=="string"?c.id.trim():"";if(A&&t.basename&&!t.basename.endsWith(`-${A}`)){let h=`${t.parent?t.parent.path+"/":""}${t.basename}-${A}.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(),A=this.app.metadataCache.getFileCache(t)?.frontmatter,h=A?.id??"";h&&await c.append({type:"create",id:h,payload:{path:t.path,parent:A?.parent??F,source:"adopt",added:n}})}catch{}}};_i.DEBUG_BUFFER_MAX=300;var gn=_i;function Uc(d,a,t){let e=Zn();for(let i of ni){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(d&&typeof d=="object")for(let i of ni){let s=d[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 Rc(d){let a={};if(!d||typeof d!="object")return a;for(let[t,e]of Object.entries(d))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 To=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)}}; +${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={...me,...t,shortcuts:{...me.shortcuts,...t?.shortcuts??{}},mod:{...me.mod,...t?.mod??{}},bindings:Gc(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:Lc(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...$t]},eo(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?.[Kt];if(Array.isArray(i)&&i.some(s=>t.has(is(s)??"")))try{await this.app.fileManager.processFrontMatter(e,s=>{let o=(Array.isArray(s[Kt])?s[Kt]:[]).filter(r=>!t.has(is(r)??""));o.length?s[Kt]=o:delete s[Kt]})}catch{}}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),eo(this.settings),Ft.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(()=>(Ut(),rs)),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():"",I=u?.parent,f=typeof I=="string"?I.trim()!=="":I!=null,m=typeof u?.created=="string"&&u.created.trim()!=="",C=!p,B=!f,Q=!m;!C&&!B&&!Q||o.push({file:h,addId:C,addParent:B,addCreated:Q})}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,I=>{if(h.addId&&(typeof I.id=="string"&&I.id.trim()||(g=n(),I.id=g)),h.addParent){let f=I.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(I.parent=F)}h.addCreated&&(typeof I.created=="string"&&I.created.trim()||(I.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:F,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 A=l?` (${l} failed \u2014 see console)`:"";new M.Notice(`Fixed ${r} note${r===1?"":"s"} in Stashpad folders${A}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Ut(),rs)),i=new Set;for(let c of this.app.vault.getMarkdownFiles()){if(c.path===t.path)continue;let A=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof A?.id=="string"?A.id.trim():"";h&&i.add(h)}let s=()=>{for(let c=0;c<50;c++){let A=e();if(!i.has(A))return A}for(let c=8;c<=16;c+=2){let A=e(c);if(!i.has(A))return A}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,c=>{let A=typeof c.id=="string"?c.id.trim():"";!A||/\s/.test(A)||i.has(A)?(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=F,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,A=typeof c?.id=="string"?c.id.trim():"";if(A&&t.basename&&!t.basename.endsWith(`-${A}`)){let h=`${t.parent?t.parent.path+"/":""}${t.basename}-${A}.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(),A=this.app.metadataCache.getFileCache(t)?.frontmatter,h=A?.id??"";h&&await c.append({type:"create",id:h,payload:{path:t.path,parent:A?.parent??F,source:"adopt",added:n}})}catch{}}};ts.DEBUG_BUFFER_MAX=300;var fn=ts;function Gc(d,a,t){let e=to();for(let i of ni){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(d&&typeof d=="object")for(let i of ni){let s=d[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 Lc(d){let a={};if(!d||typeof d!="object")return a;for(let[t,e]of Object.entries(d))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 Uo=class extends M.SuggestModal{constructor(t,e,i,s){super(t);this.def=e;this.folders=i;this.onPick=s;this.setPlaceholder("Choose a Stashpad folder to import into\u2026")}getSuggestions(t){let e=t.toLowerCase();return[this.def,...this.folders.filter(s=>s!==this.def)].filter(s=>s.toLowerCase().includes(e)).map(s=>({label:s,folder:s,current:s===this.def}))}renderSuggestion(t,e){e.createDiv({text:t.label}),t.current&&(e.createDiv({cls:"stashpad-suggest-note",text:"current"}),e.addClass("is-pinned-import-target"))}onChooseSuggestion(t){this.onPick(t.folder)}}; /*! Bundled license information: hash-wasm/dist/index.esm.js: diff --git a/manifest.json b/manifest.json index 246601a..374438b 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.114.16", + "version": "0.115.6", "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 b517330..6f86b13 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.114.16", + "version": "0.115.6", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.115.6.md b/release-notes/0.115.6.md new file mode 100644 index 0000000..49b158c --- /dev/null +++ b/release-notes/0.115.6.md @@ -0,0 +1,36 @@ +# 0.115.6 β€” Per-folder encryption polish + four follow-up features + +Builds on the per-folder encryption release with subfolder support, plaintext +archives, an encrypt-from-file-explorer entry point, and settings polish. + +## Important fix +- **Rotating a folder's key no longer leaves it temporarily "stuck."** A regression + in the previous release zeroed the folder's in-memory key right after a rotation, so + folder actions failed until you re-entered the password. Fixed β€” rotation keeps the + folder unlocked. (No data was ever lost; re-entering the password worked around it.) + +## Per-folder encryption +- **Subfolders inherit the parent folder's password.** A note in a subfolder of an + encrypted folder uses that folder's key β€” set the password once, on the top folder. + You can't set a separate password on a subfolder that already inherits one. +- **Per-subfolder options.** Selecting a folder in the encryption settings now lists + its subfolders, each with its own "encrypt notes" + "hide filenames" toggles (they + still share the parent's password). +- **Per-folder trash keys.** Notes deleted from a folder with its own password are now + encrypted under *that* key (not the vault key), and rotating the folder's key + re-encrypts its trash too, so restore keeps working. + +## Folders & import +- **Exclude subfolders by prefix.** A new setting (default `_`): any subfolder whose + name starts with a listed prefix is kept local β€” not surfaced as a Stashpad folder + or pulled into import. +- **πŸ”’ Encrypt with Stashpad** β€” a new right-click action on folders in Obsidian's + file explorer: give a folder its own Stashpad password (and lock the notes in it) + without opening settings. +- **Archive command works with plaintext archives.** Archiving into a folder whose + "Encrypt archived notes" is off now moves the notes there (de-indexed, not + encrypted) instead of refusing. + +## Settings +- Section names are now Title Case with an emoji per section (πŸ“ Folders & Storage, + πŸ”’ Encryption, πŸ—‘οΈ Deleting, …) for faster scanning. diff --git a/src/encryption-ops.ts b/src/encryption-ops.ts index 4e2cf71..a79d6fc 100644 --- a/src/encryption-ops.ts +++ b/src/encryption-ops.ts @@ -278,6 +278,11 @@ export interface DeletedMeta { originalFolderEnc?: string; parentId: string | null; title: string; count: number; created: string; rootId: string; deletedAt: string; + /** Per-folder trash keys: the FOLDER key id this blob was encrypted under + * (plaintext β€” just an identifier, safe to expose). Absent β‡’ encrypted under the + * vault DEK (legacy / vault-keyed folders). Restore resolves the right key by this + * id; rotation re-encrypts the trash blobs whose keyId matches the rotated key. */ + keyId?: string; } function bytesToB64(bytes: Uint8Array): string { @@ -326,7 +331,7 @@ export async function deletedRestoreDest(app: App, blobPath: string, meta: Delet * trash store + the sidecar records the original folder so Restore can put it * back. `deletedAt` is passed in (callers stamp it β€” keeps this pure-ish). */ export async function deleteEncryptSubtree( - app: App, folder: string, rootId: StashpadId, dek: Uint8Array, deletedAt: string, hideTitle = false, + app: App, folder: string, rootId: StashpadId, dek: Uint8Array, deletedAt: string, hideTitle = false, keyId?: string, ): Promise<{ blobPath: string; noteCount: number; rootId: StashpadId; originalFolder: string; title: string; unpurged: string[] }> { const sub = await collectSubtree(app, folder, rootId); if (!sub) throw new Error("Couldn't find that note to delete."); @@ -368,6 +373,7 @@ export async function deleteEncryptSubtree( parentId, title: hideTitle ? "" : titleFromFile(rootNote.file), count: all.length, created: rootNote.created, rootId, deletedAt, + ...(keyId ? { keyId } : {}), }; try { await app.vault.adapter.write(sidecarPath(blobPath), JSON.stringify(meta)); } catch (e) { console.warn("[Stashpad] couldn't write deleted sidecar", e); } @@ -546,6 +552,28 @@ export async function writeRotatedBlob(app: App, blobPath: string, oldDek: Uint8 } finally { plain.fill(0); } } +/** During a folder-key rotation, re-wrap a deleted blob's sidecar field that is + * itself encrypted with the folder DEK (`originalFolderEnc`, hidden-titles deletes) + * old β†’ new. No-op if absent. Run AFTER the blob's `.rot` is committed. */ +export async function rewrapDeletedSidecar(app: App, blobPath: string, oldDek: Uint8Array, newDek: Uint8Array): Promise<void> { + const meta = await readDeletedMeta(app, blobPath); + if (!meta?.originalFolderEnc) return; + const plain = await decryptWithKey(b64ToBytes(meta.originalFolderEnc), oldDek); + try { meta.originalFolderEnc = bytesToB64(await encryptWithKey(plain, newDek)); } + finally { plain.fill(0); } + await app.vault.adapter.write(sidecarPath(blobPath), JSON.stringify(meta)); +} + +/** Trash blob paths in `_deleted/` whose sidecar `keyId` matches `keyId`. */ +export async function deletedBlobsForKeyId(app: App, keyId: string): Promise<string[]> { + const out: string[] = []; + for (const b of await listDeletedBlobs(app)) { + const m = await readDeletedMeta(app, b); + if (m?.keyId === keyId) out.push(b); + } + return out; +} + /** Commit a re-encrypted blob: replace the original with its verified `.rot`, then * remove the temp. No-op if the `.rot` is missing (already committed). */ export async function commitRotatedBlob(app: App, blobPath: string): Promise<void> { @@ -556,25 +584,24 @@ export async function commitRotatedBlob(app: App, blobPath: string): Promise<voi try { await app.vault.adapter.remove(rot); } catch { /* leave temp; original is good */ } } -/** Remove any leftover `.rot` temp files in a folder (cleanup after an aborted - * rotation β€” originals are intact, so the temps are just orphans). */ +/** Remove any leftover `.rot` temp files under a folder SUBTREE (cleanup after an + * aborted rotation β€” originals are intact, so the temps are just orphans). + * Recursive: subfolders inherit the parent key, so their blobs rotate too. */ export async function cleanupRotTemps(app: App, folder: string): Promise<void> { const cleaned = folder.replace(/\/+$/, ""); - try { - const listing = await app.vault.adapter.list(cleaned); - for (const f of listing.files) if (f.endsWith(`.${STASHENC_EXT}.rot`)) { try { await app.vault.adapter.remove(f); } catch { /* */ } } - } catch { /* no folder */ } + for (const f of await listFilesRecursive(app, cleaned)) { + if (f.endsWith(`.${STASHENC_EXT}.rot`)) { try { await app.vault.adapter.remove(f); } catch { /* */ } } + } } -/** The original blob paths that have a pending `.rot` temp in a folder β€” read from - * the ADAPTER (authoritative), not the in-memory file index, so rotation resume - * works during onload before the index is populated. */ +/** The original blob paths that have a pending `.rot` temp anywhere under a folder + * SUBTREE β€” read from the ADAPTER (authoritative), not the in-memory file index, so + * rotation resume works during onload before the index is populated. */ export async function listRotTemps(app: App, folder: string): Promise<string[]> { const cleaned = folder.replace(/\/+$/, ""); - try { - const listing = await app.vault.adapter.list(cleaned); - return listing.files.filter((f) => f.endsWith(`.${STASHENC_EXT}.rot`)).map((f) => f.replace(/\.rot$/, "")); - } catch { return []; } + return (await listFilesRecursive(app, cleaned)) + .filter((f) => f.endsWith(`.${STASHENC_EXT}.rot`)) + .map((f) => f.replace(/\.rot$/, "")); } /** All encrypted-deleted blob paths in `_deleted/`. */ diff --git a/src/encryption-service.ts b/src/encryption-service.ts index b3a58b7..ecf2316 100644 --- a/src/encryption-service.ts +++ b/src/encryption-service.ts @@ -325,11 +325,37 @@ export class EncryptionService { // unaffected. UNVERIFIED: no live crypto test yet; wiring into the lock/unlock // ops is intentionally deferred to an attended pass. - /** The keyfile entry for a folder, or null (folder uses the vault DEK). */ - folderKeyEntry(folder: string): FolderKeyEntry | null { - return this.kf?.folderKeys?.[this.cleanFolder(folder)] ?? null; + /** The nearest ancestor folder (including the folder itself) that has its OWN + * key, or null. Implements the "subfolders inherit the parent's key" decision: + * a note in `Projects/Sub` is owned by `Projects` if only `Projects` has a key. */ + private owningFolder(folder: string): string | null { + const fks = this.kf?.folderKeys; + if (!fks) return null; + let p = this.cleanFolder(folder); + while (p) { + if (fks[p]) return p; + const i = p.lastIndexOf("/"); + if (i < 0) break; + p = p.slice(0, i); + } + return null; + } + /** True only if THIS exact folder has its own key (not inherited) β€” for settings + * UI decisions ("Set folder password" vs "Unlock/Change"). */ + hasOwnFolderKey(folder: string): boolean { return !!this.kf?.folderKeys?.[this.cleanFolder(folder)]; } + /** The keyfile entry governing a folder β€” its own, or the nearest ancestor's + * (inheritance). Null β†’ the folder uses the vault DEK. */ + folderKeyEntry(folder: string): FolderKeyEntry | null { + const owner = this.owningFolder(folder); + return owner ? (this.kf!.folderKeys![owner] ?? null) : null; + } + hasFolderKey(folder: string): boolean { return this.owningFolder(folder) !== null; } + /** The folder path whose key has this keyId, or null β€” for resolving which key a + * trash blob was encrypted under (its sidecar stores the keyId). */ + folderPathByKeyId(keyId: string): string | null { + for (const [path, e] of Object.entries(this.kf?.folderKeys ?? {})) if (e.keyId === keyId) return path; + return null; } - hasFolderKey(folder: string): boolean { return !!this.folderKeyEntry(folder); } /** Active (non-deprecated) password slots for a folder, newest first. Deprecated * slots are NEVER returned β€” an old/retired password must not unlock current * content (matches the vault shared-password path). If there are somehow zero @@ -337,18 +363,18 @@ export class EncryptionService { private folderActiveSlots(entry: FolderKeyEntry): KeyfilePasswordSlot[] { return entry.passwordSlots.filter((s) => !s.label.startsWith("[deprecated]")); } - /** Is the effective key for this folder available right now? */ + /** Is the effective key for this folder available right now? (Session is keyed by + * the OWNING folder, so an inheriting subfolder reports the owner's state.) */ isFolderUnlocked(folder: string): boolean { - const entry = this.folderKeyEntry(folder); - return entry ? this.folderSessionKeys.has(this.cleanFolder(folder)) : this.isUnlocked(); + const owner = this.owningFolder(folder); + return owner ? this.folderSessionKeys.has(owner) : this.isUnlocked(); } - /** The DEK to use for `folder`: the unlocked folder key if it has its own, - * otherwise the vault DEK. Returns a COPY (caller may zero), or null if the - * needed key isn't unlocked. Arms the idle timer like getSessionKey. */ + /** The DEK to use for `folder`: the unlocked owning-folder key, else the vault DEK. + * Returns a COPY (caller may zero), or null if the needed key isn't unlocked. */ getFolderKey(folder: string): Uint8Array | null { - const entry = this.folderKeyEntry(folder); - if (!entry) return this.getSessionKey(); - const k = this.folderSessionKeys.get(this.cleanFolder(folder)); + const owner = this.owningFolder(folder); + if (!owner) return this.getSessionKey(); + const k = this.folderSessionKeys.get(owner); if (!k) return null; this.armIdle(); return k.slice(); @@ -363,6 +389,10 @@ export class EncryptionService { if (!this.kf) throw new Error("Set up vault encryption first."); const f = this.cleanFolder(folder); if (this.kf.folderKeys?.[f]) throw new Error("This folder already has its own key."); + // Inheritance: a subfolder of an already-keyed folder uses the ancestor's key β€” + // don't let it mint a separate (nested) key. + const ancestor = this.owningFolder(f); + if (ancestor && ancestor !== f) throw new Error(`A parent folder (β€œ${ancestor.split("/").pop()}”) already has its own password; this folder inherits it.`); const dek = crypto.getRandomValues(new Uint8Array(DEK_LEN)); const wrapped = await encryptStash(dek, password); const keyId = newId(8); @@ -387,7 +417,7 @@ export class EncryptionService { for (const slot of this.folderActiveSlots(entry)) { try { const dek = await decryptStash(fromB64(slot.wrapped), password); - this.folderSessionKeys.set(f, dek); + this.folderSessionKeys.set(entry.folderPath, dek); // key the session by the OWNING folder const kcId = this.folderKcIdFor(entry); if (remember || this.isFolderRemembered(kcId)) await this.rememberFolder(kcId, password); this.armIdle(); @@ -417,11 +447,12 @@ export class EncryptionService { async changeFolderPassword(folder: string, newPassword: string, remember = false): Promise<void> { if (!newPassword) throw new Error("Password required."); const f = this.cleanFolder(folder); - const dek = this.folderSessionKeys.get(f); - if (!dek) throw new Error("Unlock this folder first."); await this.refresh(); const entry = this.folderKeyEntry(f); if (!entry || !this.kf) throw new Error("This folder has no key."); + const owner = entry.folderPath; // inheritance: operate on the key-owning folder + const dek = this.folderSessionKeys.get(owner); + if (!dek) throw new Error("Unlock this folder first."); // Retain the OLD keychain password under a deprecated id (never delete) so an // old export emailed months ago can still be looked up / decrypted. const prevActive = entry.passwordSlots.filter((s) => !s.label.startsWith("[deprecated]")); @@ -441,7 +472,7 @@ export class EncryptionService { ...retained, ], }; - this.kf.folderKeys = { ...(this.kf.folderKeys ?? {}), [f]: next }; + this.kf.folderKeys = { ...(this.kf.folderKeys ?? {}), [owner]: next }; await this.keyfiles.save(this.kf); if (remember || this.isFolderRemembered(kcId)) await this.rememberFolder(this.folderKcIdFor(next), newPassword); } @@ -458,6 +489,7 @@ export class EncryptionService { if (!this.kf) throw new Error("Encryption is not set up."); const f = this.cleanFolder(folder); const entry = this.folderKeyEntry(f); + const owner = entry?.folderPath ?? f; // inheritance: rotate the key-owning folder const keyId = entry?.keyId ?? newId(8); const oldKcId = entry ? this.folderKcIdFor(entry) : null; // Park the old active keychain password (retain, never delete). @@ -470,17 +502,19 @@ export class EncryptionService { const retained = (entry?.passwordSlots ?? []).map((s) => s.label.startsWith("[deprecated]") ? s : { ...s, label: `[deprecated] ${s.label}` }); const newLabel = label ?? entry?.label ?? `rotated - ${f.split("/").pop() || f}`; const next: FolderKeyEntry = { - keyId, folderPath: f, label: newLabel, kcId: this.folderKcId(newLabel, keyId), rotId, + keyId, folderPath: owner, label: newLabel, kcId: this.folderKcId(newLabel, keyId), rotId, passwordSlots: [{ id: newId(8), label: "Folder password", wrapped: toB64(wrapped.data), kdf: wrapped.kdf, createdAt: new Date().toISOString() }, ...retained], createdAt: entry?.createdAt ?? new Date().toISOString(), }; - this.kf.folderKeys = { ...(this.kf.folderKeys ?? {}), [f]: next }; + this.kf.folderKeys = { ...(this.kf.folderKeys ?? {}), [owner]: next }; await this.keyfiles.save(this.kf); // Zero the OLD folder DEK before replacing it β€” after a true-invalidation rotation // the prior key shouldn't linger in memory. - const prevSess = this.folderSessionKeys.get(f); + const prevSess = this.folderSessionKeys.get(owner); if (prevSess && prevSess !== newDek) prevSess.fill(0); - this.folderSessionKeys.set(f, newDek); + // Store a COPY β€” the caller (rotateFolderKey) zeros its own newDek buffer in a + // finally, which would otherwise zero the live session key we just set here. + this.folderSessionKeys.set(owner, newDek.slice()); if (remember || (oldKcId && this.isFolderRemembered(oldKcId))) await this.rememberFolder(this.folderKcIdFor(next), newPassword); } @@ -620,11 +654,13 @@ export class EncryptionService { this.clearIdle(); } - /** Lock a SINGLE folder's key (leave the vault key + other folders unlocked). */ + /** Lock a SINGLE folder's key (leave the vault key + other folders unlocked). + * Resolves to the OWNING folder so locking an inheriting subfolder drops the + * shared key. */ lockFolder(folder: string): void { - const f = this.cleanFolder(folder); - const k = this.folderSessionKeys.get(f); - if (k) { k.fill(0); this.folderSessionKeys.delete(f); } + const owner = this.owningFolder(folder) ?? this.cleanFolder(folder); + const k = this.folderSessionKeys.get(owner); + if (k) { k.fill(0); this.folderSessionKeys.delete(owner); } } private cleanFolder(p: string): string { return (p || "").replace(/\/+$/, ""); } diff --git a/src/main.ts b/src/main.ts index 204259a..cc098d7 100644 --- a/src/main.ts +++ b/src/main.ts @@ -10,7 +10,7 @@ import { STASHPAD_TRASH_VIEW_TYPE, STASHPAD_AGGREGATE_VIEW_TYPE } from "./types" import { StashpadPanelsView, openStashpadPanelsView, PANEL_REGISTRY, type PanelId } from "./panels-view"; import { StashpadFolderPanelView, openFolderPanelView } from "./folder-panel-view"; import { EncryptionService, defaultEncryptionConfig } from "./encryption-service"; -import { lockSubtree, unlockBundle, readLockedMeta, type LockResult, deleteEncryptSubtree, restoreDeleted, listDeletedBlobs, readDeletedMeta, deletedRestoreDest, backfillTrashEncrypt, restoreRawTrash, purgeDeletedBlob, OBSIDIAN_TRASH_DIR, type DeletedMeta, collectSubtree, writeRotatedBlob, commitRotatedBlob, cleanupRotTemps, listRotTemps } from "./encryption-ops"; +import { lockSubtree, unlockBundle, readLockedMeta, type LockResult, deleteEncryptSubtree, restoreDeleted, listDeletedBlobs, readDeletedMeta, deletedRestoreDest, backfillTrashEncrypt, restoreRawTrash, purgeDeletedBlob, OBSIDIAN_TRASH_DIR, type DeletedMeta, collectSubtree, writeRotatedBlob, commitRotatedBlob, cleanupRotTemps, listRotTemps, deletedBlobsForKeyId, rewrapDeletedSidecar } from "./encryption-ops"; import { EncryptionPasswordModal } from "./modals"; import { DEFAULT_SETTINGS, StashpadSettings, StashpadSettingTab, setSettings, SETTINGS_TABS, @@ -433,6 +433,18 @@ export default class StashpadPlugin extends Plugin { * still tell whether the deleted folder was a Stashpad. */ knownStashpadFolders = new Set<string>(); + /** Subfolder name prefixes (user-configurable, comma-separated; default "_") that + * EXCLUDE a folder from Stashpad discovery + import β€” it stays local, not pulled + * in. A path is excluded if ANY of its segments starts with a listed prefix. */ + importExcludePrefixList(): string[] { + return (this.settings.importExcludePrefixes ?? "_").split(",").map((s) => s.trim()).filter(Boolean); + } + pathHasExcludedSegment(path: string): boolean { + const prefixes = this.importExcludePrefixList(); + if (!prefixes.length) return false; + return path.replace(/\/+$/, "").split("/").some((seg) => prefixes.some((p) => seg.startsWith(p))); + } + discoverStashpadFolders(): string[] { const folders = new Set<string>(); for (const f of this.app.vault.getMarkdownFiles()) { @@ -444,7 +456,7 @@ export default class StashpadPlugin extends Plugin { // field isn't a Stashpad note. if (!fm || !("parent" in fm)) continue; const dir = f.parent?.path?.replace(/\/+$/, "") ?? ""; - if (dir) folders.add(dir); + if (dir && !this.pathHasExcludedSegment(dir)) folders.add(dir); } const sorted = [...folders].sort(); this.knownStashpadFolders = new Set(sorted); @@ -920,6 +932,10 @@ export default class StashpadPlugin extends Plugin { this.registerEvent(this.app.workspace.on("file-menu", (menu, file) => { if (!(file instanceof TFolder)) return; const path = file.path.replace(/\/+$/, ""); + // "Encrypt with Stashpad" on ANY folder (incl. import-excluded subfolders that + // aren't surfaced as Stashpad folders) β€” the entry point for encrypting a + // folder straight from Obsidian's file explorer. + menu.addItem((item) => item.setTitle("πŸ”’ Encrypt with Stashpad").setIcon("lock").onClick(() => void this.encryptFolderFromExplorer(path))); if (!this.discoverStashpadFolders().includes(path)) return; menu.addItem((item) => { item @@ -3464,6 +3480,32 @@ export default class StashpadPlugin extends Plugin { * protected `.stash` β€” original blob untouched (feedback #4 / Option B). */ exportLockedSubtree(blobPath: string): Promise<void> { return cmdExportLockedBlob(this, blobPath); } + /** "Encrypt with Stashpad" from the file-explorer folder menu. Gives the folder its + * own Stashpad password (works for any folder path, incl. import-excluded + * subfolders) and locks any Stashpad notes inside it. */ + async encryptFolderFromExplorer(folder: string): Promise<void> { + if (this.encryption.hasOwnFolderKey(folder)) { if (await this.ensureFolderUnlocked(folder)) await this.lockFolder(folder); return; } + if (!this.encryption.isConfigured()) { new Notice("Set up Stashpad vault encryption first (Settings β†’ Stashpad β†’ Encryption), then try again."); return; } + const name = folder.split("/").pop() || folder; + const d = new Date(); const p = (n: number) => String(n).padStart(2, "0"); + const stamp = `${d.getFullYear()}${p(d.getMonth() + 1)}${p(d.getDate())}-${p(d.getHours())}${p(d.getMinutes())}`; + const who = (this.settings.authorName || "").trim(); + const initials = who ? who.split(/\s+/).map((w) => w[0]).join("") : (this.settings.authorId || "anon").slice(0, 4); + const label = `${stamp} - ${name} - ${initials}`; + new EncryptionPasswordModal(this.app, { + mode: "setup", offerKeychain: true, title: `Encrypt β€œ${name}” 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, remember }) => { + if (!next) return "Enter a password."; + try { await this.encryption.setupFolderKey(folder, next, label, remember); } catch (e) { return (e as Error).message; } + const n = await this.lockFolder(folder); + new Notice(n > 0 ? `Encrypted ${n} note${n === 1 ? "" : "s"} in β€œ${name}”.` : `β€œ${name}” now has a Stashpad password β€” notes added here will use it.`); + this.refreshFolderPanels?.(); + return null; + }, + }).open(); + } + // --- Phase B: per-folder key ROTATION (true invalidation β€” re-encrypt) --- private rotationLockPath(folder: string): string { const cleaned = folder.replace(/\/+$/, ""); @@ -3491,15 +3533,24 @@ export default class StashpadPlugin extends Plugin { * resumeRotations() compares the lock's rotId to the keyfile entry's rotId to know * whether the swap landed (β†’ commit) or not (β†’ drop temps). */ async rotateFolderKey(folder: string, newPassword: string, remember = false): Promise<number> { - const cleaned = folder.replace(/\/+$/, ""); + const requested = folder.replace(/\/+$/, ""); if (!newPassword) { new Notice("A new password is required to rotate."); return -1; } - const oldDek = await this.ensureFolderUnlocked(cleaned); + const oldDek = await this.ensureFolderUnlocked(requested); if (!oldDek) return -1; + // Inheritance: rotate the key-OWNING folder, and re-encrypt every blob under its + // whole subtree (subfolders share the owner's key). + const cleaned = this.encryption.folderKeyEntry(requested)?.folderPath ?? requested; const lock = this.rotationLockPath(cleaned); if (await this.app.vault.adapter.exists(lock)) { new Notice("A rotation is already in progress for this folder (or one was interrupted β€” reload to recover)."); return -1; } - const blobs = this.app.vault.getFiles() - .filter((f) => f.extension === "stashenc" && (f.parent?.path?.replace(/\/+$/, "") ?? "") === cleaned) + const inSubtree = (p: string) => p === cleaned || p.startsWith(cleaned + "/"); + const liveBlobs = this.app.vault.getFiles() + .filter((f) => f.extension === "stashenc" && inSubtree(f.parent?.path?.replace(/\/+$/, "") ?? "")) .map((f) => f.path); + // Per-folder trash keys: the folder's TRASH blobs (in _deleted/, identified by + // the sidecar keyId) must rotate too, or they'd be orphaned under the old DEK. + const ownerKeyId = this.encryption.folderKeyEntry(cleaned)?.keyId; + const trashBlobs = ownerKeyId ? await deletedBlobsForKeyId(this.app, ownerKeyId) : []; + const blobs = [...liveBlobs, ...trashBlobs]; const newDek = crypto.getRandomValues(new Uint8Array(32)); const rotId = [...crypto.getRandomValues(new Uint8Array(8))].map((b) => b.toString(16).padStart(2, "0")).join(""); const prog = blobs.length > 0 ? new Notice("", 0) : null; @@ -3511,7 +3562,11 @@ export default class StashpadPlugin extends Plugin { await this.app.vault.adapter.write(lock, JSON.stringify({ folder: cleaned, phase: "committing", rotId, at: new Date().toISOString() })); await this.encryption.commitFolderRotation(cleaned, newPassword, newDek, rotId, undefined, remember); prog?.setMessage("πŸ”„ Finalizing…"); - await this.commitRotTemps(cleaned); + await this.commitRotTemps(cleaned); // live subtree + for (const tb of trashBlobs) { // trash blobs live in _deleted/, outside the subtree + await commitRotatedBlob(this.app, tb); + try { await rewrapDeletedSidecar(this.app, tb, oldDek, newDek); } catch (e) { console.warn("[Stashpad] trash sidecar rewrap failed", tb, e); } + } try { await this.app.vault.adapter.remove(lock); } catch { /* */ } prog?.hide(); new Notice(`πŸ”‘ Rotated the key for β€œ${cleaned.split("/").pop()}” β€” ${blobs.length} item${blobs.length === 1 ? "" : "s"} re-encrypted. The OLD password no longer unlocks it; share the new one with anyone who should keep access.`, 0); @@ -3520,6 +3575,7 @@ export default class StashpadPlugin extends Plugin { prog?.hide(); // Failure before the keyfile swap β†’ originals intact; just drop the temps. try { await cleanupRotTemps(this.app, cleaned); } catch { /* */ } + for (const tb of trashBlobs) { try { await this.app.vault.adapter.remove(`${tb}.rot`); } catch { /* */ } } try { await this.app.vault.adapter.remove(lock); } catch { /* */ } console.warn("[Stashpad] rotation failed", e); new Notice(`Rotation failed: ${(e as Error).message}. Nothing was changed (originals intact).`, 0); @@ -3541,12 +3597,18 @@ export default class StashpadPlugin extends Plugin { try { info = JSON.parse(await this.app.vault.adapter.read(lockPath)); } catch { /* */ } const folder = (info.folder ?? "").replace(/\/+$/, ""); if (!folder) { try { await this.app.vault.adapter.remove(lockPath); } catch { /* */ } continue; } - const swapped = !!info.rotId && this.encryption.folderKeyEntry(folder)?.rotId === info.rotId; + const entry = this.encryption.folderKeyEntry(folder); + const swapped = !!info.rotId && entry?.rotId === info.rotId; if (swapped) { - await this.commitRotTemps(folder); + await this.commitRotTemps(folder); // live subtree + // Trash blobs (in _deleted/) keyed to this folder β€” commit their .rot too + // (byte copy; the keyfile already holds the new DEK). Hidden-origin sidecars + // can't be re-wrapped here (the old DEK is gone) β€” a rare crash edge. + if (entry?.keyId) { for (const tb of await deletedBlobsForKeyId(this.app, entry.keyId)) { try { await commitRotatedBlob(this.app, tb); } catch (e) { console.warn("[Stashpad] resume trash-commit failed", tb, e); } } } new Notice(`Finished an interrupted key rotation for β€œ${folder.split("/").pop()}”.`, 0); } else { try { await cleanupRotTemps(this.app, folder); } catch { /* */ } + try { await cleanupRotTemps(this.app, "_deleted"); } catch { /* */ } } try { await this.app.vault.adapter.remove(lockPath); } catch { /* */ } } @@ -3557,20 +3619,21 @@ export default class StashpadPlugin extends Plugin { /** Encrypt-delete a subtree into `_deleted/` (recoverable, encrypted) and * permanently remove the plaintext. Returns the blob path, or null on failure. */ async encryptDeleteSubtree(folder: string, rootId: StashpadId): Promise<string | null> { - if (!(await this.ensureEncryptionUnlocked())) return null; - const dek = this.encryption.getSessionKey(); + // Per-folder trash keys: encrypt the trash blob under the FOLDER's key (or the + // vault DEK as fallback) and stamp its keyId into the sidecar so restore can + // resolve the right key β€” even for hidden-origin deletes. + const dek = await this.ensureFolderUnlocked(folder); if (!dek) return null; try { // Plugin runtime (not a workflow script) β€” Date is available. const deletedAt = new Date().toISOString(); // "Encrypt trash filenames" hides the trash blob's name/origin even when - // the general hide-locked-titles setting is off. Per-folder overhaul: this - // folder's trashEncryptFilenames pref takes precedence over the globals. - // (Trash blobs still use the vault DEK for now β€” per-folder trash KEYS + - // hidden-origin restore are a later increment.) + // the general hide-locked-titles setting is off. This folder's + // trashEncryptFilenames pref takes precedence over the globals. const _trFp = (this.settings.folderEncPrefs ?? {})[folder.replace(/\/+$/, "")] ?? {}; const hideTitle = (_trFp.trashEncryptFilenames ?? false) || (this.settings.hideLockedTitles ?? false) || (this.settings.encryptTrashFilenames ?? false); - const r = await deleteEncryptSubtree(this.app, folder, rootId, dek, deletedAt, hideTitle); + const keyId = this.encryption.folderKeyEntry(folder)?.keyId; // undefined β‡’ vault-keyed + const r = await deleteEncryptSubtree(this.app, folder, rootId, dek, deletedAt, hideTitle, keyId); this.pendingEncBlobs.add(r.blobPath); // fast-state index if (r.unpurged.length > 0) { new Notice(`⚠️ Sent to encrypted trash, but ${r.unpurged.length} file${r.unpurged.length === 1 ? " is" : "s are"} still in plaintext (couldn't be removed or changed during the delete):\n${r.unpurged.join("\n")}`, 0); @@ -3585,10 +3648,19 @@ export default class StashpadPlugin extends Plugin { /** Restore an encrypted-deleted blob back into its original folder. */ async restoreDeletedAt(blobPath: string, opts: { silent?: boolean } = {}): Promise<boolean> { - if (!(await this.ensureEncryptionUnlocked())) return false; - const dek = this.encryption.getSessionKey(); - if (!dek) return false; const meta = await readDeletedMeta(this.app, blobPath); + // Per-folder trash keys: resolve the key this blob was encrypted under via its + // sidecar keyId (the owning folder's key); else the vault DEK (legacy/vault-keyed). + let dek: Uint8Array | null; + if (meta?.keyId) { + const owner = this.encryption.folderPathByKeyId(meta.keyId); + dek = owner ? await this.ensureFolderUnlocked(owner) : null; + if (!dek) { if (!opts.silent) new Notice("Couldn't unlock the folder key this trashed note was encrypted with."); return false; } + } else { + if (!(await this.ensureEncryptionUnlocked())) return false; + dek = this.encryption.getSessionKey(); + } + if (!dek) return false; // Backfill blobs are raw `.trash/` zips, not Stashpad bundles β€” different // restore path (plain unzip back into `.trash/`). if (meta?.kind === "rawtrash") { diff --git a/src/settings.ts b/src/settings.ts index ec79e05..9581249 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -306,6 +306,10 @@ export interface StashpadSettings { * keyed by cleaned folder path. See `FolderEncPrefs`. Empty default β†’ no folder * is encrypted until the user opts in, so existing vaults are unaffected. */ folderEncPrefs: Record<string, FolderEncPrefs>; + /** Comma-separated subfolder-name prefixes (default "_") that EXCLUDE a folder from + * Stashpad discovery + import β€” it stays local, not surfaced/pulled in. A path is + * excluded if any of its segments starts with a listed prefix. */ + importExcludePrefixes: string; /** 0.98.1: registry of locked subtrees, so the list can render a placeholder * where the note was (and find the blob to unlock). One entry per `.stashenc` * bundle. `parentId` = where the locked root was attached (null/ROOT = top). */ @@ -547,6 +551,7 @@ export const DEFAULT_SETTINGS: StashpadSettings = { hideLockedTitles: false, archiveFolders: [], folderEncPrefs: {}, + importExcludePrefixes: "_", lockedSubtrees: [], searchOpensInNewTab: true, pinnedNotes: [], @@ -639,28 +644,33 @@ export type SettingsTabId = | "encryption" | "authorship" | "templates" | "jdindex" | "okf" | "maintenance" | "diagnostics" | "misc" | "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" }, - { id: "notifications", label: "Notifications" }, - { id: "encryption", label: "Encryption" }, - { id: "authorship", label: "Authorship" }, - { id: "templates", label: "Templates" }, - { id: "jdindex", label: "JD Index" }, - { id: "okf", label: "Open Knowledge Format (OKF)" }, - { id: "maintenance", label: "Maintenance" }, - { id: "diagnostics", label: "Diagnostics" }, - { id: "misc", label: "Misc" }, - { id: "hotkeys", label: "Hotkeys" }, + { id: "foldersStorage", label: "πŸ“ Folders & Storage" }, + { id: "importExport", label: "πŸ”„ Import & Export" }, + { id: "noteTitles", label: "🏷️ Note Titles" }, + { id: "datesTime", label: "πŸ•’ Dates & Time" }, + { id: "listDisplay", label: "πŸ“‹ List & Display" }, + { id: "movingNotes", label: "↕️ Moving Notes" }, + { id: "deleting", label: "πŸ—‘οΈ Deleting" }, + { id: "composerCopy", label: "✍️ Composer & Copying" }, + { id: "windowsTabs", label: "πŸͺŸ Windows & Tabs" }, + { id: "notifications", label: "πŸ”” Notifications" }, + { id: "encryption", label: "πŸ”’ Encryption" }, + { id: "authorship", label: "βœ’οΈ Authorship" }, + { id: "templates", label: "πŸ“„ Templates" }, + { id: "jdindex", label: "πŸ”’ JD Index" }, + { id: "okf", label: "πŸ“š Open Knowledge Format (OKF)" }, + { id: "maintenance", label: "πŸ› οΈ Maintenance" }, + { id: "diagnostics", label: "🩺 Diagnostics" }, + { id: "misc", label: "βš™οΈ Misc" }, + { id: "hotkeys", label: "⌨️ Hotkeys" }, // 0.112.9: sections shown alphabetically by label. Display order only β€” the // `id`-keyed itemsForTab dispatch is unaffected, and new tabs auto-sort in. -] as Array<{ id: SettingsTabId; label: string }>).sort((a, b) => a.label.localeCompare(b.label)); +] as Array<{ id: SettingsTabId; label: string }>).sort((a, b) => { + // Sort by the label TEXT, ignoring the leading emoji prefix (else the order would + // scramble by emoji codepoint). + const strip = (s: string) => s.replace(/^[^\p{L}\p{N}]+/u, ""); + return strip(a.label).localeCompare(strip(b.label)); +}); /** 0.94.0: a declarative sub-page that renders one of Stashpad's settings tabs * via the existing imperative `renderTabContent`. Used by @@ -1042,13 +1052,21 @@ export class StashpadSettingTab extends PluginSettingTab { * associations). */ private renderFolderEncPanel(host: HTMLElement, folder: string): void { const enc = this.plugin.encryption; - const hasKey = enc.hasFolderKey(folder); + const hasOwn = enc.hasOwnFolderKey(folder); // this exact folder has a key + const owner = enc.folderKeyEntry(folder)?.folderPath ?? null; // key-owning folder (self or ancestor) + const inherited = !!owner && !hasOwn; // subfolder inheriting an ancestor's key const unlocked = enc.isFolderUnlocked(folder); const prefs = (this.plugin.settings.folderEncPrefs ?? {})[folder] ?? {}; - const status = hasKey ? (unlocked ? "Has its own password Β· unlocked" : "Has its own password Β· locked") : "Uses the vault password"; + const status = hasOwn + ? (unlocked ? "Has its own password Β· unlocked" : "Has its own password Β· locked") + : inherited + ? `Inherits β€œ${(owner!.split("/").pop()) || owner}”'s password Β· ${unlocked ? "unlocked" : "locked"}` + : "Uses the vault password"; const head = new Setting(host).setName("Password").setDesc(status); - if (!hasKey) { + if (inherited) { + head.addButton((b) => b.setButtonText("Manage on parent folder").onClick(() => { this.pfeSelected = owner; this.update?.(); })); + } else if (!hasOwn) { head.addButton((b) => b.setButtonText("Set folder password…").setCta().onClick(() => this.promptSetFolderPassword(folder))); } else if (!unlocked) { head.addButton((b) => b.setButtonText("Unlock…").setCta().onClick(() => this.promptUnlockFolder(folder))); @@ -1111,6 +1129,31 @@ export class StashpadSettingTab extends PluginSettingTab { }); pair("Encrypt archived notes", "archiveEncryptContent", "archiveEncryptFilenames"); pair("Encrypt trashed notes", "trashEncryptContent", "trashEncryptFilenames"); + + // Subfolders: each shares this folder's key (inheritance), but you can encrypt + // their notes / hide their filenames individually. + const subs = this.plugin.discoverStashpadFolders().filter((sf) => sf !== folder && sf.startsWith(folder + "/")).sort(); + if (subs.length) { + new Setting(host).setName("Subfolders").setDesc(`${subs.length} subfolder${subs.length === 1 ? "" : "s"} β€” they use β€œ${folder.split("/").pop()}”'s password. Encrypt each individually.`).setHeading(); + for (const sub of subs) { + const sp = (this.plugin.settings.folderEncPrefs ?? {})[sub] ?? {}; + const setSubPref = async (patch: Partial<FolderEncPrefs>) => { + this.plugin.settings.folderEncPrefs = { ...(this.plugin.settings.folderEncPrefs ?? {}), [sub]: { ...((this.plugin.settings.folderEncPrefs ?? {})[sub] ?? {}), ...patch } }; + await this.plugin.saveSettings(); + }; + const subLocked = (this.plugin.settings.lockedSubtrees ?? []).some((e) => (e.folder || "").replace(/\/+$/, "") === sub); + const rel = sub.slice(folder.length + 1); + new Setting(host).setName(rel) + .addToggle((t) => t.setValue(subLocked).onChange(async (v) => { + if (v) await this.plugin.lockFolder(sub); else await this.plugin.unlockFolder(sub); + const has = (this.plugin.settings.lockedSubtrees ?? []).some((e) => (e.folder || "").replace(/\/+$/, "") === sub); + await setSubPref({ encryptContent: has, ...(has ? {} : { encryptFilenames: false }) }); + this.update?.(); + })); + new Setting(host).setName(`↳ ${rel} β€” hide filenames`).setClass("stashpad-subsetting") + .addToggle((t) => { t.setValue(!!sp.encryptFilenames); t.setDisabled(!subLocked); t.onChange((v) => void setSubPref({ encryptFilenames: v })); }); + } + } } /** 0.94.3: General tab decomposed into per-setting items (render at DISPLAY @@ -1186,6 +1229,10 @@ export class StashpadSettingTab extends PluginSettingTab { this.plugin.settings.exportFolder = (v || "").trim().replace(/^\/+|\/+$/g, "") || DEFAULT_SETTINGS.exportFolder; await set(); })), ["export", "stash", "subfolder"])); + cats.importExport.push(this.renderDef("Exclude subfolders by prefix", "Comma-separated name prefixes (default β€œ_”). A subfolder whose name starts with any of these β€” at any depth β€” 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 β†’ β€œπŸ”’ Encrypt with Stashpad”.", (s) => + s.addText((t) => t.setValue(this.plugin.settings.importExcludePrefixes ?? "_").setPlaceholder("_").onChange(async (v) => { + this.plugin.settings.importExcludePrefixes = v; await set(); + })), ["import", "exclude", "prefix", "subfolder", "underscore", "ignore"])); cats.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((b) => @@ -1304,10 +1351,10 @@ export class StashpadSettingTab extends PluginSettingTab { })); }, ["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) => { + 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) - .setName("Cross-Stashpad search scope") + .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 β€” their notes just don't appear in search results from elsewhere."); if (folders.length === 0) { host.createEl("p", { cls: "setting-item-description" }).setText( @@ -1338,9 +1385,9 @@ export class StashpadSettingTab extends PluginSettingTab { })); }, ["search", "scope", "exclude", "include", "create", "new", "stashpad", "folder"])); - cats.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 β€œHidden” section.", (host) => { + cats.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 β€œHidden” section.", (host) => { new Setting(host) - .setName("Folder panel placement") + .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 β€œHidden” section."); this.renderFolderPlacementList(host); }, ["folder", "panel", "pin", "pinned", "downrank", "hide", "hidden", "restore", "placement"])); @@ -1364,7 +1411,7 @@ export class StashpadSettingTab extends PluginSettingTab { const enc = this.plugin.encryption; const items: SettingDefinitionItem[] = []; - items.push(this.sectionDef("Vault encryption", "Set one password to encrypt content in this vault. Stored only on this device β€” there is no recovery if you lose it.", (host) => { + items.push(this.sectionDef("Vault Encryption", "Set one password to encrypt content in this vault. Stored only on this device β€” there is no recovery if you lose it.", (host) => { host.addClass("stashpad-encryption-section"); const betaRow = host.createDiv({ cls: "stashpad-beta-row" }); betaRow.createEl("span", { cls: "stashpad-beta-badge", text: "BETA" }); @@ -1700,7 +1747,7 @@ export class StashpadSettingTab extends PluginSettingTab { const n = Math.max(0, Math.floor(Number(v) || 0)); this.plugin.settings.encryptionIdleLockMinutes = n; await this.plugin.saveSettings(); })), ["auto-lock", "idle", "timeout", "lock"])); - items.push(this.renderDef("Hide titles of locked notes (default)", "The DEFAULT for hiding πŸ”’ locked-placeholder titles β€” used by any folder/trash that doesn't set its own β€œhide filenames” 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.", (s) => + items.push(this.renderDef("Hide titles of locked notes (default)", "The DEFAULT for hiding πŸ”’ locked-placeholder titles β€” used by any folder/trash that doesn't set its own β€œhide filenames” 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.", (s) => s.addToggle((t) => t.setValue(this.plugin.settings.hideLockedTitles ?? false).onChange(async (v) => { if (v && !this.encryptionOrOnboard()) { this.update?.(); return; } this.plugin.settings.hideLockedTitles = v; await this.plugin.saveSettings(); @@ -1719,7 +1766,7 @@ export class StashpadSettingTab extends PluginSettingTab { }, ["archive", "default", "move", "encrypt", "folder"])); // ---- Per-folder passwords (per-folder overhaul) β€” below the global settings ---- - items.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.", (host) => { + items.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.", (host) => { this.renderPerFolderEncryption(host); }, ["folder", "per-folder", "password", "encrypt", "key", "share", "collaborator", "archive", "unlock", "lock"])); @@ -2054,11 +2101,11 @@ export class StashpadSettingTab extends PluginSettingTab { items.push(footerToggle("Show author in note footer", () => this.plugin.settings.showAuthor, (v) => { this.plugin.settings.showAuthor = v; }, ["author", "footer", "show"])); items.push(footerToggle("Show contributors in note footer", () => this.plugin.settings.showContributors, (v) => { this.plugin.settings.showContributors = v; }, ["contributors", "footer", "show"])); items.push(footerToggle("Show last edit time in note footer", () => this.plugin.settings.showLastEdit, (v) => { this.plugin.settings.showLastEdit = v; }, ["last edit", "modified", "footer", "time"])); - items.push(this.sectionDef("Folders you've worked in", + items.push(this.sectionDef("Folders You've Worked In", "Folders where you've authored or contributed notes. Click one to open it.", (host) => this.renderAuthoredFolders(host), ["folders", "authored", "contributed", "worked"])); - items.push(this.sectionDef("Known authors", + items.push(this.sectionDef("Known Authors", "Everyone the plugin has seen, with role/department + rename history; rebuild/restore the registry.", (host) => this.renderKnownAuthorsSection(host), ["authors", "registry", "rename", "known", "rebuild"])); @@ -2085,11 +2132,11 @@ export class StashpadSettingTab extends PluginSettingTab { /** 0.99.15: Templates tab β€” the two per-folder editors as searchable sections. */ private templatesItems(): SettingDefinitionItem[] { return [ - this.sectionDef("Color aliases", + this.sectionDef("Color Aliases", "Give your note colors friendly names, per Stashpad folder.", (host) => this.renderColorAliasesSection(host), ["color", "colour", "alias", "name", "swatch", "palette", "label"]), - this.sectionDef("Note templates", + this.sectionDef("Note Templates", "Per-Stashpad note templates β€” content stamped into new notes.", (host) => this.renderNoteTemplatesSection(host), ["template", "note", "default", "boilerplate", "snippet"]), @@ -2299,7 +2346,7 @@ export class StashpadSettingTab extends PluginSettingTab { // Stashpad tab via the per-leaf folderOverride mechanism. const folders = this.plugin.collectAuthoredFolders(); if (folders.length > 0) { - new Setting(parent).setName("Folders you've worked in").setHeading(); + new Setting(parent).setName("Folders You've Worked In").setHeading(); const list = parent.createDiv({ cls: "stashpad-authored-folders-list" }); for (const f of folders) { const row = list.createDiv({ cls: "stashpad-authored-folder-row" }); @@ -2321,7 +2368,7 @@ export class StashpadSettingTab extends PluginSettingTab { * The registry is NOT authoritative (the id baked into note frontmatter * is); this is recovery + an audit trail. */ private renderKnownAuthorsSection(parent: HTMLElement): void { - new Setting(parent).setName("Known authors (registry)").setHeading(); + new Setting(parent).setName("Known Authors (registry)").setHeading(); parent.createEl("div", { cls: "setting-item-description", text: "A rebuildable cache of every author Stashpad has seen, with rename history. Not a source of truth β€” the author id stored in each note is authoritative. Use it to recover deleted author pages or audit name changes.", diff --git a/src/view.ts b/src/view.ts index 6701304..8dec676 100644 --- a/src/view.ts +++ b/src/view.ts @@ -6101,7 +6101,31 @@ export class StashpadView extends ItemView { const cleanDest = dest.replace(/\/+$/, ""); const encryptDest = (this.plugin.settings.folderEncPrefs ?? {})[cleanDest]?.archiveEncryptContent ?? true; if (!encryptDest) { - new Notice(`β€œ${cleanDest.split("/").pop()}” is a plaintext archive (encryption off). Moving notes into a plaintext archive from the command isn't wired yet β€” drag them in, or turn on β€œEncrypt archived notes” for that folder.`, 9000); + // Plaintext archive (encryption off): MOVE the subtree's files into the + // destination (de-indexed via the archive flag, but not encrypted). Stashpad's + // re-home listener reparents the moved roots in the destination folder. + const ids0 = new Set(sources.map((t) => t.id)); + const roots0 = sources.filter((t) => { let p = t.parent; while (p) { if (ids0.has(p)) return false; p = this.tree.get(p)?.parent ?? null; } return true; }); + if (roots0.length === 0) return; + const files: TFile[] = []; + const seen0 = new Set<string>(); + const walk0 = (n: TreeNode) => { if (seen0.has(n.id)) return; seen0.add(n.id); if (n.file) files.push(n.file); for (const c of this.tree.getChildren(n.id)) walk0(c); }; + for (const r of roots0) walk0(r); + const moves: Array<{ from: string; to: string }> = []; + for (const f of files) { + const fromPath = f.path; + const name = f.name; const dot = name.lastIndexOf("."); const stem = dot > 0 ? name.slice(0, dot) : name; const ext = dot > 0 ? name.slice(dot) : ""; + let to = `${cleanDest}/${name}`; + for (let n = 1; await this.app.vault.adapter.exists(to); n++) to = `${cleanDest}/${stem}-${n}${ext}`; + try { await this.app.fileManager.renameFile(f, to); moves.push({ from: fromPath, to }); } catch (e) { console.warn("[Stashpad] plaintext archive move failed", fromPath, e); } + } + this.selection.clear(); this.lastSelected = null; this.tree.rebuild(src); this.render(); + const nm = cleanDest.split("/").pop() || cleanDest; + this.plugin.notifications.show({ message: `Moved ${moves.length} note${moves.length === 1 ? "" : "s"} β†’ plaintext archive β€œ${nm}” (de-indexed, not encrypted). Undo to bring ${moves.length === 1 ? "it" : "them"} back.`, kind: "success", category: "system", folder: src }); + this.plugin.getUndoStack(src).push({ + label: `Archive (plaintext, ${roots0.length})`, + undo: async () => { for (const m of moves) { const fl = this.app.vault.getAbstractFileByPath(m.to); if (fl instanceof TFile) { try { await this.app.fileManager.renameFile(fl, m.from); } catch (e) { console.warn("[Stashpad] plaintext archive undo failed", m.to, e); } } } this.tree.rebuild(src); this.render(); }, + }); return; } if (!this.plugin.encryption?.isConfigured?.()) {