diff --git a/main.js b/main.js index 9be48e9..cd05843 100644 --- a/main.js +++ b/main.js @@ -1,116 +1,117 @@ -"use strict";var ta=Object.create;var ki=Object.defineProperty;var ea=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,na=Object.prototype.hasOwnProperty;var Ie=(h,A)=>()=>(h&&(A=h(h=0)),A);var oa=(h,A)=>()=>(A||h((A={exports:{}}).exports,A),A.exports),Si=(h,A)=>{for(var t in A)ki(h,t,{get:A[t],enumerable:!0})},Nn=(h,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of ia(A))!na.call(h,i)&&i!==t&&ki(h,i,{get:()=>A[i],enumerable:!(e=ea(A,i))||e.enumerable});return h};var Ns=(h,A,t)=>(t=h!=null?ta(sa(h)):{},Nn(A||!h||!h.__esModule?ki(t,"default",{value:h,enumerable:!0}):t,h)),aa=h=>Nn(ki({},"__esModule",{value:!0}),h);function xs(h){return Array.isArray(h)?h.filter(A=>typeof A=="string"):typeof h=="string"?h.split(/[,\s]+/).filter(Boolean):[]}function De(h,A){let t=A.replace(/^#/,"");return xs(h?.tags).some(e=>e.replace(/^#/,"")===t)}function Ms(h,A){let t=A.replace(/^#/,""),e=xs(h.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),h.tags=e}function Hs(h,A){let t=A.replace(/^#/,""),e=xs(h.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?h.tags=e:delete h.tags}function be(h){return h.split("/").some(A=>Ze.has(A))}function xn(h){return h.split("/").some(A=>A==="_archive"||A===".archive")}function Ot(h){let A=(h??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function Ce(h){let A=(h??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function Mn(h){let A=h.match(/\.([^./]+)$/);return!!A&&ra.has(A[1].toLowerCase())}function Hn(h,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(h))return!0}catch{}else if(h===e||h.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Di(h,A){let t=h.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function ne(h){if(typeof h!="string")return null;let A=h.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function me(h){let A=h?.assignedTo,t=Array.isArray(A)?A:A!=null?[A]:[],e=[];for(let i of t){let s=ne(i);s&&e.push(s)}return e}var ct,ie,ue,fe,Se,M,se,Ze,ra,yt=Ie(()=>{"use strict";ct="stashpad-view",ie="stashpad-panels",ue="stashpad-folder-panel",fe="stashpad-detail",Se="stashpad-trash",M="__root__";se=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],Ze=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ra=new Set(["edtz"])});function Aa(h,A){return h>12?h>=24?0:h:A==="am"?h===12?0:h:h===12?12:h+12}function Ni(h,A){h.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=h.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let a=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});a.type="button";let r=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};r(),o.addEventListener("mousedown",E=>E.preventDefault()),a.addEventListener("mousedown",E=>E.preventDefault()),o.addEventListener("click",E=>{E.preventDefault(),t="am",r()}),a.addEventListener("click",E=>{E.preventDefault(),t="pm",r()});let l=i;i.addEventListener("focus",()=>{l=i,i.select()}),s.addEventListener("focus",()=>{l=s,s.select()});let c=()=>{let w=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",w),a.toggleClass("is-disabled",w),o.disabled=w,a.disabled=w},g=E=>{let w=E.value.replace(/\D/g,"").slice(0,2);if(w===""){E.value="",E===i&&c();return}let y=parseInt(w,10);E===i?y>24&&(y=24):y>59&&(y=59),E.value=String(y),E===i&&c()};for(let E of[i,s])E.addEventListener("input",()=>g(E));c();let p=()=>{let E=parseInt(i.value||"12",10)||12,w=parseInt(s.value||"0",10)||0,y=E>12;A.onFinalize({hours24:Aa(E,t),minutes:w,raw:{hh:E,mm:w,period:t,is24:y}}),A.close()};A.setOnEnter?.(p);let d=[i,s,o,a],I=(E,w)=>{let y=d.indexOf(E);if(y===-1)return;let v=(y+w+d.length)%d.length;d[v].focus()},u=E=>{E.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),p()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),A.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),I(E,w.shiftKey?-1:1))})},f=h.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let E of C){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",E==="backspace"?(0,Rn.setIcon)(w,"delete"):E==="insert"?(w.setText("OK"),m=w):w.setText(E),E==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{if(y.preventDefault(),E==="insert"){p();return}if(E==="backspace"){l.value=l.value.slice(0,-1),g(l),l.focus();return}let v=l.selectionStart===0&&l.selectionEnd===l.value.length&&l.value.length>0,S=2,U=v||l.value.length>=S?E:l.value+E;l.value=U,g(l),l.focus(),l.setSelectionRange(l.value.length,l.value.length),l===i&&l.value.length>=S&&(s.focus(),s.select())})}m&&d.push(m);for(let E of d)u(E);i.focus(),i.select()}function Gn(h){let{hh:A,mm:t,period:e,is24:i}=h.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var Rn,Ts=Ie(()=>{"use strict";Rn=require("obsidian")});function Jn(h){let A=Math.floor(4294967296/h)*h,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%h}function Us(h=5){let A=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),la.has(h.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function ca(h){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function _e(h){let A="stashpad-",t=ca(h),e=64-A.length-1-t.length,i=h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var Ln,la,xi=Ie(()=>{"use strict";Ln="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((h,A,t)=>t.indexOf(h)===A);la=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 Mi={};Si(Mi,{newId:()=>Bt});function Bt(h=6){let A="",t=new Uint8Array(h);crypto.getRandomValues(t);for(let e=0;e{"use strict";qn="abcdefghijkmnpqrstuvwxyz23456789"});var Ai={};Si(Ai,{AssignModal:()=>ni,ColorPickerModal:()=>Ee,ConfirmDeleteModal:()=>xe,ConfirmModal:()=>Ft,CustomColorModal:()=>Hi,DueDatePickerModal:()=>oi,EncryptionPasswordModal:()=>$t,ExportStashModal:()=>ei,ImportDupChoiceModal:()=>ri,ImportLogModal:()=>Rs,LogModal:()=>Ne,NotificationHistoryModal:()=>ai,SplitNoteModal:()=>ti,StashPasswordModal:()=>ii,TypeToConfirmModal:()=>si,buildAssigneePicker:()=>Gs});function Gs(h,A){let t=[...A.initial],e=A.knownAuthors,i=h.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),a=n.createDiv({cls:"stashpad-assign-suggest"});a.style.display="none";let r=()=>A.onChange([...t]),l=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let p of t){let d=s.createSpan({cls:"stashpad-assign-chip"});d.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let I=d.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});I.title=`Remove ${p.name}`,I.onclick=()=>{t=t.filter(u=>u.id!==p.id),r(),l()}}},c=p=>{p.name.trim()&&(t.some(d=>d.id===p.id)||t.push(p),o.value="",a.style.display="none",r(),l(),o.focus())},g=()=>{let p=o.value.trim();a.empty();let d=new Set(t.map(f=>f.id)),u=e.filter(f=>!d.has(f.id)&&Di(p,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>c(f)}));if(p&&!e.some(f=>f.name.toLowerCase()===p.toLowerCase())&&u.push({label:`Create \u201C${p}\u201D`,onPick:()=>c({id:Bt(6),name:p})}),u.length===0){a.style.display="none";return}a.style.display="";for(let f of u){let C=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});C.onmousedown=m=>{m.preventDefault(),f.onPick()}}};o.addEventListener("input",g),o.addEventListener("focus",g),o.addEventListener("keydown",p=>{if(p.key==="Enter"){p.preventDefault();let d=a.querySelector(".stashpad-assign-suggest-item");d&&d.dispatchEvent(new MouseEvent("mousedown"))}else p.key==="Escape"&&a.style.display!=="none"&&(p.stopPropagation(),a.style.display="none")}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.style.display="none"},120)}),l()}var at,da,Be,Ne,xe,ti,ei,ii,$t,si,Hi,je,Ee,Ft,ni,oi,Qe,ai,Rs,ri,Ht=Ie(()=>{"use strict";at=require("obsidian");Ts();yt();xi();Kt();da=at.moment,Be=class Be extends at.Modal{constructor(t,e,i){super(t);this.text=e;this.jsonlPath=i;this.events=[];this.visible=[];this.shownCount=0;this.typeFilter=null;this.listEl=null;this.footerEl=null;this.countEl=null;this.filterSelEl=null}onOpen(){this.contentEl.empty(),this.titleEl.setText("Stashpad log"),this.modalEl.addClass("stashpad-log-modal"),this.events=[];for(let r of this.text.trim().split(/\r?\n/))if(r)try{this.events.push(JSON.parse(r))}catch{}this.events.reverse();let t=this.contentEl.createDiv({cls:"stashpad-log-toolbar"});this.countEl=t.createSpan({cls:"stashpad-log-count"}),this.updateCount(),this.filterSelEl=t.createEl("select",{cls:"stashpad-log-type-filter"}),this.filterSelEl.onchange=()=>this.setTypeFilter(this.filterSelEl.value||null),this.refreshTypeFilter();let e=t.createEl("button",{text:"Reveal JSONL"});e.onclick=()=>this.shellAct("reveal");let i=t.createEl("button",{text:"Open in default app"});i.onclick=()=>this.shellAct("open");let s=t.createEl("button",{text:"Copy raw JSONL"}),n=null;s.onclick=async()=>{await navigator.clipboard.writeText(this.text),s.setText("Copied"),n!=null&&window.clearTimeout(n),n=window.setTimeout(()=>{s.setText("Copy raw JSONL"),n=null},1500)};let o=t.createEl("button",{text:"Export copy"});o.onclick=()=>this.exportCopy();let a=t.createEl("button",{cls:"mod-warning",text:"Clear log"});a.onclick=()=>this.clearLog(),this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter()}refreshList(){if(this.listEl){if(this.visible=this.typeFilter?this.events.filter(t=>t.type===this.typeFilter):this.events.slice(),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.typeFilter?`No "${this.typeFilter}" events.`:"No events yet."}),this.updateCount();return}this.appendMore(Be.PAGE)}}setTypeFilter(t){(this.typeFilter??null)!==(t??null)&&(this.typeFilter=t,this.refreshList(),this.renderFooter())}refreshTypeFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.events)e.set(n.type,(e.get(n.type)??0)+1);let i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All types (${this.events.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});a.value=n}this.typeFilter&&!e.has(this.typeFilter)&&(this.typeFilter=null),t.value=this.typeFilter??""}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.typeFilter?`${t} ${this.typeFilter} event${t===1?"":"s"}`:`${t} event${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i{this.appendMore(Be.PAGE),this.renderFooter()},t>Be.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}shellAct(t){try{let e=this.app.vault.adapter.getFullPath?.(this.jsonlPath);if(!e)throw new Error("no full path");let{shell:i}=window.require("electron");t==="reveal"?i.showItemInFolder(e):i.openPath(e)}catch(e){new at.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,at.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 at.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new at.Notice(`Export failed: ${t.message}`),null}}clearLog(){new Ft(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 at.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 at.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,at.moment)(t.ts).isValid()?(0,at.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,s=document.createElement("span");s.className="stashpad-log-ts",s.textContent=i,e.appendChild(s);let n=document.createElement("span");n.className="stashpad-log-type",n.textContent=t.type,e.appendChild(n);let o=document.createElement("span");o.className="stashpad-log-author",o.textContent=t.author?t.author:"\u2014",t.author||o.classList.add("is-empty"),e.appendChild(o);let a=document.createElement("span");return a.className="stashpad-log-msg",a.textContent=this.describe(t),e.appendChild(a),e}describe(t){let e=t.payload??{};switch(t.type){case"create":return`Created "${e.path??t.id}" under ${e.parent??"?"}`;case"delete":{let i=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,s=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${s}${i?` \u2014 also removed ${i} attachment${i===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let i=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${i}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let i=e.count??1,s=e.dir??"?",n=e.parent??t.id??"?";return`Reordered ${i} note${i===1?"":"s"} (${s}) under ${n}`}case"complete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${i} note${i===1?"":"s"} complete${s}`}case"uncomplete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${i} note${i===1?"":"s"}${s}`}case"stash_export":{let i=e.noteCount??"?";return`Exported ${i} note${i===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let i=e.noteCount??"?",s=[];e.attachmentsWritten&&s.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&s.push(`${e.collisionsRenamed} renamed`);let n=s.length?` (${s.join(", ")})`:"";return`Imported ${i} note${i===1?"":"s"} from ${e.from??"?"} \u2192 ${e.into??"?"}${n}`}case"attachment_add":return`Added attachment ${e.path??t.id}`;case"attachment_remove":return`Removed attachment ${e.path??t.id}`;case"palette_color_add":return`Added palette color ${e.color??t.id}`;case"palette_color_remove":return`Removed palette color ${e.color??t.id}`;default:return JSON.stringify(e)}}onClose(){this.contentEl.empty()}};Be.PAGE=100;Ne=Be,xe=class extends at.Modal{constructor(t,e,i,s,n,o){super(t);this.noteTitle=e;this.descendantCount=i;this.attachmentCount=s;this.offerAttachmentDelete=n;this.onChoose=o}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText(`Delete "${this.noteTitle}"?`);let t=[];this.descendantCount>0&&t.push(`${this.descendantCount} descendant note${this.descendantCount===1?"":"s"} will also be deleted.`),this.attachmentCount>0&&t.push(`${this.attachmentCount} attachment${this.attachmentCount===1?"":"s"} found across these notes.`),this.contentEl.createEl("p",{text:t.join(" ")});let e=this.offerAttachmentDelete&&this.attachmentCount>0;if(this.offerAttachmentDelete&&this.attachmentCount>0){let o=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=o.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},o.createSpan({text:" Also delete attachments"})}let i=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.close();let n=i.createEl("button",{cls:"mod-warning",text:"Delete"});n.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},ti=class extends at.Modal{constructor(t,e,i,s){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` +"use strict";var ta=Object.create;var Si=Object.defineProperty;var ea=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,na=Object.prototype.hasOwnProperty;var Ie=(h,A)=>()=>(h&&(A=h(h=0)),A);var oa=(h,A)=>()=>(A||h((A={exports:{}}).exports,A),A.exports),Di=(h,A)=>{for(var t in A)Si(h,t,{get:A[t],enumerable:!0})},Mn=(h,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of ia(A))!na.call(h,i)&&i!==t&&Si(h,i,{get:()=>A[i],enumerable:!(e=ea(A,i))||e.enumerable});return h};var Ms=(h,A,t)=>(t=h!=null?ta(sa(h)):{},Mn(A||!h||!h.__esModule?Si(t,"default",{value:h,enumerable:!0}):t,h)),aa=h=>Mn(Si({},"__esModule",{value:!0}),h);function Ts(h){return Array.isArray(h)?h.filter(A=>typeof A=="string"):typeof h=="string"?h.split(/[,\s]+/).filter(Boolean):[]}function Ne(h,A){let t=A.replace(/^#/,"");return Ts(h?.tags).some(e=>e.replace(/^#/,"")===t)}function Hs(h,A){let t=A.replace(/^#/,""),e=Ts(h.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),h.tags=e}function Us(h,A){let t=A.replace(/^#/,""),e=Ts(h.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?h.tags=e:delete h.tags}function xe(h){return h.split("/").some(A=>je.has(A))}function Tn(h){return h.split("/").some(A=>A==="_archive"||A===".archive")}function Ot(h){let A=(h??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function Ce(h){let A=(h??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function Hn(h){let A=h.match(/\.([^./]+)$/);return!!A&&ra.has(A[1].toLowerCase())}function Un(h,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(h))return!0}catch{}else if(h===e||h.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function bi(h,A){let t=h.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function ne(h){if(typeof h!="string")return null;let A=h.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function me(h){let A=h?.assignedTo,t=Array.isArray(A)?A:A!=null?[A]:[],e=[];for(let i of t){let s=ne(i);s&&e.push(s)}return e}var ct,ie,ue,fe,be,T,se,je,ra,yt=Ie(()=>{"use strict";ct="stashpad-view",ie="stashpad-panels",ue="stashpad-folder-panel",fe="stashpad-detail",be="stashpad-trash",T="__root__";se=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],je=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ra=new Set(["edtz"])});function Aa(h,A){return h>12?h>=24?0:h:A==="am"?h===12?0:h:h===12?12:h+12}function xi(h,A){h.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=h.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let a=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});a.type="button";let r=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};r(),o.addEventListener("mousedown",E=>E.preventDefault()),a.addEventListener("mousedown",E=>E.preventDefault()),o.addEventListener("click",E=>{E.preventDefault(),t="am",r()}),a.addEventListener("click",E=>{E.preventDefault(),t="pm",r()});let l=i;i.addEventListener("focus",()=>{l=i,i.select()}),s.addEventListener("focus",()=>{l=s,s.select()});let c=()=>{let w=(parseInt(i.value||"0",10)||0)>12;o.toggleClass("is-disabled",w),a.toggleClass("is-disabled",w),o.disabled=w,a.disabled=w},g=E=>{let w=E.value.replace(/\D/g,"").slice(0,2);if(w===""){E.value="",E===i&&c();return}let y=parseInt(w,10);E===i?y>24&&(y=24):y>59&&(y=59),E.value=String(y),E===i&&c()};for(let E of[i,s])E.addEventListener("input",()=>g(E));c();let p=()=>{let E=parseInt(i.value||"12",10)||12,w=parseInt(s.value||"0",10)||0,y=E>12;A.onFinalize({hours24:Aa(E,t),minutes:w,raw:{hh:E,mm:w,period:t,is24:y}}),A.close()};A.setOnEnter?.(p);let d=[i,s,o,a],I=(E,w)=>{let y=d.indexOf(E);if(y===-1)return;let v=(y+w+d.length)%d.length;d[v].focus()},u=E=>{E.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),p()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),A.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),I(E,w.shiftKey?-1:1))})},f=h.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let E of C){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",E==="backspace"?(0,Ln.setIcon)(w,"delete"):E==="insert"?(w.setText("OK"),m=w):w.setText(E),E==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{if(y.preventDefault(),E==="insert"){p();return}if(E==="backspace"){l.value=l.value.slice(0,-1),g(l),l.focus();return}let v=l.selectionStart===0&&l.selectionEnd===l.value.length&&l.value.length>0,S=2,M=v||l.value.length>=S?E:l.value+E;l.value=M,g(l),l.focus(),l.setSelectionRange(l.value.length,l.value.length),l===i&&l.value.length>=S&&(s.focus(),s.select())})}m&&d.push(m);for(let E of d)u(E);i.focus(),i.select()}function Jn(h){let{hh:A,mm:t,period:e,is24:i}=h.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var Ln,Ps=Ie(()=>{"use strict";Ln=require("obsidian")});function On(h){let A=Math.floor(4294967296/h)*h,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%h}function Rs(h=5){let A=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),la.has(h.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function ca(h){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function ti(h){let A="stashpad-",t=ca(h),e=64-A.length-1-t.length,i=h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var qn,la,Mi=Ie(()=>{"use strict";qn="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((h,A,t)=>t.indexOf(h)===A);la=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 Ti={};Di(Ti,{newId:()=>mt});function mt(h=6){let A="",t=new Uint8Array(h);crypto.getRandomValues(t);for(let e=0;e{"use strict";Kn="abcdefghijkmnpqrstuvwxyz23456789"});var ci={};Di(ci,{AssignModal:()=>ai,ColorPickerModal:()=>Ee,ConfirmDeleteModal:()=>Te,ConfirmModal:()=>Ft,CustomColorModal:()=>Hi,DueDatePickerModal:()=>ri,EncryptionPasswordModal:()=>Xt,ExportStashModal:()=>si,ImportDupChoiceModal:()=>li,ImportLogModal:()=>Ls,LogModal:()=>Me,NotificationHistoryModal:()=>Ai,SplitNoteModal:()=>ii,StashPasswordModal:()=>ni,TypeToConfirmModal:()=>oi,buildAssigneePicker:()=>Js});function Js(h,A){let t=[...A.initial],e=A.knownAuthors,i=h.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),a=n.createDiv({cls:"stashpad-assign-suggest"});a.style.display="none";let r=()=>A.onChange([...t]),l=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let p of t){let d=s.createSpan({cls:"stashpad-assign-chip"});d.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let I=d.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});I.title=`Remove ${p.name}`,I.onclick=()=>{t=t.filter(u=>u.id!==p.id),r(),l()}}},c=p=>{p.name.trim()&&(t.some(d=>d.id===p.id)||t.push(p),o.value="",a.style.display="none",r(),l(),o.focus())},g=()=>{let p=o.value.trim();a.empty();let d=new Set(t.map(f=>f.id)),u=e.filter(f=>!d.has(f.id)&&bi(p,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>c(f)}));if(p&&!e.some(f=>f.name.toLowerCase()===p.toLowerCase())&&u.push({label:`Create \u201C${p}\u201D`,onPick:()=>c({id:mt(6),name:p})}),u.length===0){a.style.display="none";return}a.style.display="";for(let f of u){let C=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});C.onmousedown=m=>{m.preventDefault(),f.onPick()}}};o.addEventListener("input",g),o.addEventListener("focus",g),o.addEventListener("keydown",p=>{if(p.key==="Enter"){p.preventDefault();let d=a.querySelector(".stashpad-assign-suggest-item");d&&d.dispatchEvent(new MouseEvent("mousedown"))}else p.key==="Escape"&&a.style.display!=="none"&&(p.stopPropagation(),a.style.display="none")}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.style.display="none"},120)}),l()}var at,da,Be,Me,Te,ii,si,ni,Xt,oi,Hi,ei,Ee,Ft,ai,ri,Qe,Ai,Ls,li,Tt=Ie(()=>{"use strict";at=require("obsidian");Ps();yt();Mi();Kt();da=at.moment,Be=class Be extends at.Modal{constructor(t,e,i){super(t);this.text=e;this.jsonlPath=i;this.events=[];this.visible=[];this.shownCount=0;this.typeFilter=null;this.listEl=null;this.footerEl=null;this.countEl=null;this.filterSelEl=null}onOpen(){this.contentEl.empty(),this.titleEl.setText("Stashpad log"),this.modalEl.addClass("stashpad-log-modal"),this.events=[];for(let r of this.text.trim().split(/\r?\n/))if(r)try{this.events.push(JSON.parse(r))}catch{}this.events.reverse();let t=this.contentEl.createDiv({cls:"stashpad-log-toolbar"});this.countEl=t.createSpan({cls:"stashpad-log-count"}),this.updateCount(),this.filterSelEl=t.createEl("select",{cls:"stashpad-log-type-filter"}),this.filterSelEl.onchange=()=>this.setTypeFilter(this.filterSelEl.value||null),this.refreshTypeFilter();let e=t.createEl("button",{text:"Reveal JSONL"});e.onclick=()=>this.shellAct("reveal");let i=t.createEl("button",{text:"Open in default app"});i.onclick=()=>this.shellAct("open");let s=t.createEl("button",{text:"Copy raw JSONL"}),n=null;s.onclick=async()=>{await navigator.clipboard.writeText(this.text),s.setText("Copied"),n!=null&&window.clearTimeout(n),n=window.setTimeout(()=>{s.setText("Copy raw JSONL"),n=null},1500)};let o=t.createEl("button",{text:"Export copy"});o.onclick=()=>this.exportCopy();let a=t.createEl("button",{cls:"mod-warning",text:"Clear log"});a.onclick=()=>this.clearLog(),this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter()}refreshList(){if(this.listEl){if(this.visible=this.typeFilter?this.events.filter(t=>t.type===this.typeFilter):this.events.slice(),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.typeFilter?`No "${this.typeFilter}" events.`:"No events yet."}),this.updateCount();return}this.appendMore(Be.PAGE)}}setTypeFilter(t){(this.typeFilter??null)!==(t??null)&&(this.typeFilter=t,this.refreshList(),this.renderFooter())}refreshTypeFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.events)e.set(n.type,(e.get(n.type)??0)+1);let i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All types (${this.events.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});a.value=n}this.typeFilter&&!e.has(this.typeFilter)&&(this.typeFilter=null),t.value=this.typeFilter??""}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.typeFilter?`${t} ${this.typeFilter} event${t===1?"":"s"}`:`${t} event${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i{this.appendMore(Be.PAGE),this.renderFooter()},t>Be.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}shellAct(t){try{let e=this.app.vault.adapter.getFullPath?.(this.jsonlPath);if(!e)throw new Error("no full path");let{shell:i}=window.require("electron");t==="reveal"?i.showItemInFolder(e):i.openPath(e)}catch(e){new at.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,at.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 at.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new at.Notice(`Export failed: ${t.message}`),null}}clearLog(){new Ft(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 at.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 at.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,at.moment)(t.ts).isValid()?(0,at.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,s=document.createElement("span");s.className="stashpad-log-ts",s.textContent=i,e.appendChild(s);let n=document.createElement("span");n.className="stashpad-log-type",n.textContent=t.type,e.appendChild(n);let o=document.createElement("span");o.className="stashpad-log-author",o.textContent=t.author?t.author:"\u2014",t.author||o.classList.add("is-empty"),e.appendChild(o);let a=document.createElement("span");return a.className="stashpad-log-msg",a.textContent=this.describe(t),e.appendChild(a),e}describe(t){let e=t.payload??{};switch(t.type){case"create":return`Created "${e.path??t.id}" under ${e.parent??"?"}`;case"delete":{let i=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,s=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${s}${i?` \u2014 also removed ${i} attachment${i===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let i=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${i}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let i=e.count??1,s=e.dir??"?",n=e.parent??t.id??"?";return`Reordered ${i} note${i===1?"":"s"} (${s}) under ${n}`}case"complete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${i} note${i===1?"":"s"} complete${s}`}case"uncomplete":{let i=e.count??1,s=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${i} note${i===1?"":"s"}${s}`}case"stash_export":{let i=e.noteCount??"?";return`Exported ${i} note${i===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let i=e.noteCount??"?",s=[];e.attachmentsWritten&&s.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&s.push(`${e.collisionsRenamed} renamed`);let n=s.length?` (${s.join(", ")})`:"";return`Imported ${i} note${i===1?"":"s"} from ${e.from??"?"} \u2192 ${e.into??"?"}${n}`}case"attachment_add":return`Added attachment ${e.path??t.id}`;case"attachment_remove":return`Removed attachment ${e.path??t.id}`;case"palette_color_add":return`Added palette color ${e.color??t.id}`;case"palette_color_remove":return`Removed palette color ${e.color??t.id}`;default:return JSON.stringify(e)}}onClose(){this.contentEl.empty()}};Be.PAGE=100;Me=Be,Te=class extends at.Modal{constructor(t,e,i,s,n,o){super(t);this.noteTitle=e;this.descendantCount=i;this.attachmentCount=s;this.offerAttachmentDelete=n;this.onChoose=o}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText(`Delete "${this.noteTitle}"?`);let t=[];this.descendantCount>0&&t.push(`${this.descendantCount} descendant note${this.descendantCount===1?"":"s"} will also be deleted.`),this.attachmentCount>0&&t.push(`${this.attachmentCount} attachment${this.attachmentCount===1?"":"s"} found across these notes.`),this.contentEl.createEl("p",{text:t.join(" ")});let e=this.offerAttachmentDelete&&this.attachmentCount>0;if(this.offerAttachmentDelete&&this.attachmentCount>0){let o=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=o.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},o.createSpan({text:" Also delete attachments"})}let i=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),s=i.createEl("button",{text:"Cancel"});s.onclick=()=>this.close();let n=i.createEl("button",{cls:"mod-warning",text:"Delete"});n.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},ii=class extends at.Modal{constructor(t,e,i,s){super(t);this.body=e;this.onSplitAtLine=i;this.onSplitAtChar=s;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` `).split(` -`),this.lineCursorIdx=Math.max(1,Math.min(this.lines.length-1,Math.floor(this.lines.length/2))),this.lines.length<2&&(this.mode="cursor")}onOpen(){this.titleEl.setText("Split note"),this.modalEl.addClass("stashpad-split-modal"),this.render(),this.scope.register([],"Tab",t=>{this.lines.length<2||(t.preventDefault(),this.mode=this.mode==="line"?"cursor":"line",this.render())}),this.scope.register([],"Enter",t=>{this.mode==="line"&&(t.preventDefault(),this.commitLine())}),this.scope.register(["Mod"],"Enter",t=>{this.mode==="cursor"&&(t.preventDefault(),this.commitCursor())}),this.scope.register([],"ArrowUp",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.max(1,this.lineCursorIdx-1),this.render())}),this.scope.register([],"ArrowDown",t=>{this.mode==="line"&&(t.preventDefault(),this.lineCursorIdx=Math.min(this.lines.length-1,this.lineCursorIdx+1),this.render())})}commitLine(){let t=this.lineCursorIdx;this.close(),this.onSplitAtLine(t)}commitCursor(){let t=this.cursorTextarea;if(!t)return;let e=t.selectionStart;if(e<=0||e>=t.value.length){new at.Notice("Move the cursor inside the text \u2014 neither end can be empty.");return}this.close(),this.onSplitAtChar(e)}render(){this.contentEl.empty();let t=this.contentEl.createDiv({cls:"stashpad-split-toggle-bar"});if(this.lines.length>=2){let n=t.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&n.addClass("is-active"),n.onclick=()=>{this.mode="line",this.render()}}let e=t.createEl("button",{text:"Cursor split",cls:"stashpad-split-mode-btn"});this.mode==="cursor"&&e.addClass("is-active"),e.onclick=()=>{this.mode="cursor",this.render()};let i=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});i.onmousedown=n=>n.preventDefault(),i.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let s=this.contentEl.createDiv({cls:"stashpad-split-help"});at.Platform.isMobile?s.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):s.setText(this.mode==="line"?"\u2191/\u2193 pick split line \xB7 Enter or Split confirm \xB7 Tab \u2192 cursor mode \xB7 Esc cancel \xB7 Children stay with the first part":"Click or arrow to position cursor \xB7 Mod+Enter or Split confirm \xB7 Tab \u2192 line mode \xB7 Esc cancel \xB7 Children stay with the first part")}renderLineMode(){let t=this.contentEl.createDiv({cls:"stashpad-split-list"});for(let e=0;e{let s=Math.max(1,Math.min(this.lines.length-1,e));s!==this.lineCursorIdx&&(this.lineCursorIdx=s,this.render())}}}renderCursorMode(){let e=this.contentEl.createDiv({cls:"stashpad-split-cursor-wrap"}).createEl("textarea",{cls:"stashpad-split-cursor-ta"});e.value=this.body,e.readOnly=!1,this.cursorTextarea=e;let i=parseFloat(getComputedStyle(e).lineHeight)||22,s=at.Platform.isMobile?3:12,n=2,o=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,i*s+16);e.style.height=`${Math.max(a,i*n+16)}px`};requestAnimationFrame(()=>{o();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",o)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},ei=class extends at.Modal{constructor(t,e,i,s,n){super(t);this.defaultBaseName=e;this.noteCount=i;this.onConfirm=s;this.kdfProbe=n;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Export to .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`${this.noteCount} note${this.noteCount===1?"":"s"} will be bundled into a single .stash file.`});let t=this.contentEl.createDiv({cls:"stashpad-export-field"});t.createEl("label",{cls:"stashpad-export-label",text:"File name"});let e=t.createEl("input",{type:"text"});e.addClass("stashpad-export-name"),e.value=this.defaultBaseName;let i=this.contentEl.createEl("div",{cls:"stashpad-export-preview"}),s=this.contentEl.createDiv({cls:"stashpad-export-encrypt"}),n=s.createDiv({cls:"stashpad-export-toggle"}),o=n.createEl("input",{type:"checkbox"});o.id="stashpad-export-encrypt-cb";let a=n.createEl("label",{text:"Encrypt with a password"});a.htmlFor=o.id;let r=s.createDiv({cls:"stashpad-export-pw-area"});r.style.display="none";let l=[],c=O=>{let V=r.createDiv({cls:"stashpad-export-pw-row"}),rt=V.createEl("input",{type:"password"});rt.addClass("stashpad-export-name"),rt.placeholder=O;let gt=V.createEl("button",{cls:"stashpad-export-copy"}),nt=()=>{let At=rt.value.length===0;gt.setText(At?"Paste":"Copy"),gt.toggleClass("is-paste",At),gt.setAttr("aria-label",`${At?"Paste into":"Copy"} ${O.toLowerCase()}`)};return gt.onclick=async At=>{if(At.preventDefault(),rt.value.length===0)try{let lt=(await navigator.clipboard?.readText())?.trim();if(!lt){new at.Notice("Clipboard is empty.");return}rt.value=lt,rt.dispatchEvent(new Event("input")),new at.Notice("Pasted from clipboard.")}catch{new at.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(rt.value).then(()=>new at.Notice("Passphrase copied to clipboard."),()=>new at.Notice("Couldn't access the clipboard."))},nt(),l.push(nt),rt},g=c("Password"),p=c("Confirm password"),d=r.createDiv({cls:"stashpad-export-strength"}),I=d.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),f=d.createEl("span",{cls:"stashpad-strength-label"}),C=r.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),E=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=r.createEl("div",{cls:"stashpad-export-pw-hint"}),y=r.createEl("div",{cls:"stashpad-export-pw-suite"});y.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(O=>{y.toggleClass("is-weak",!O),y.setText(O?"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 v=this.app.secretStorage,S=r.createDiv({cls:"stashpad-export-remember"}),U=S.createEl("input",{type:"checkbox"});U.id="stashpad-export-remember-cb";let F=S.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});F.htmlFor=U.id;let x=r.createDiv({cls:"stashpad-export-remember-note"});x.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."),x.style.display="none",U.onchange=()=>{x.style.display=U.checked?"":"none"},v||(S.style.display="none");let Q=()=>{let O=e.value.trim()||this.defaultBaseName;return o.checked?`${O}-encrypted`:O},D=()=>i.setText(`Saves as: ${Q()}-.stash`);e.oninput=D;let K=this.contentEl.createDiv({cls:"stashpad-export-footer"}),N=K.createEl("button",{text:"Cancel"});N.onclick=()=>this.close();let Y=K.createEl("button",{cls:"mod-cta",text:"Export"}),q=()=>{let O=Ps(g.value);d.style.visibility=g.value?"visible":"hidden",u.forEach((V,rt)=>V.toggleClass("is-on",g.value!==""&&rt<=O.level)),I.dataset.level=String(O.level),f.setText(O.label)},_=()=>{let O=o.checked;r.style.display=O?"":"none";let V=!0;O&&(g.value?g.value!==p.value?(w.setText("Passwords don't match."),w.addClass("is-error"),V=!1):(w.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),w.removeClass("is-error")):(w.setText("Enter a password to encrypt this export."),w.removeClass("is-error"),V=!1)),q(),l.forEach(rt=>rt()),Y.disabled=!V,Y.toggleClass("is-disabled",!V),D()},L=!1,T=O=>{L=O,g.type=p.type=O?"text":"password",E.setText(O?"Hide":"Show")};E.onclick=O=>{O.preventDefault(),T(!L)},m.onclick=O=>{O.preventDefault(),g.value=p.value=Us(),T(!1),new at.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),_()},o.onchange=_,g.oninput=_,p.oninput=_,_();let tt=()=>this.commit(Q(),o.checked?g.value:null,o.checked&&U.checked);Y.onclick=tt,this.scope.register([],"Enter",O=>{O.preventDefault(),Y.disabled||tt()}),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()}},ii=class extends at.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()}},$t=class extends at.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(t==="setup"?"Set up encryption password":t==="change"?"Change encryption password":"Unlock encryption"),t==="setup"&&this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This single password protects everything you encrypt in this vault. It is stored only on this device. There is NO recovery \u2014 if you lose it, anything you've encrypted is gone for good."});let e=[],i=u=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),C=f.createEl("input",{type:"password"});C.addClass("stashpad-export-name","stashpad-encryption-field"),C.placeholder=u;let m=f.createEl("button",{cls:"stashpad-export-copy"}),E=()=>{let w=C.value.length===0;m.setText(w?"Paste":"Copy"),m.toggleClass("is-paste",w),m.setAttr("aria-label",`${w?"Paste into":"Copy"} ${u.toLowerCase()}`)};return m.onclick=async w=>{if(w.preventDefault(),C.value.length===0)try{let y=(await navigator.clipboard?.readText())?.trim();if(!y){new at.Notice("Clipboard is empty.");return}C.value=y,C.dispatchEvent(new Event("input")),new at.Notice("Pasted from clipboard.")}catch{new at.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(C.value).then(()=>new at.Notice("Copied to clipboard."),()=>new at.Notice("Couldn't access the clipboard."))},C.addEventListener("input",E),E(),e.push(E),C},s=null,n=null,o=null;if((t==="unlock"||t==="change")&&(s=i("Current password")),(t==="setup"||t==="change")&&(n=i(t==="change"?"New password":"Password"),o=i("Confirm password")),n){let u=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=u.createDiv({cls:"stashpad-strength-bar"}),C=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),m=u.createEl("span",{cls:"stashpad-strength-label"}),E=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),w=()=>{let U=n.value,F=Ps(U);C.forEach((x,Q)=>x.toggleClass("is-on",Q0&&U.length<6?" \u2014 use at least 6":""}`),E.toggleClass("is-weak",U.length>0&&U.length<6)};n.addEventListener("input",w),w();let y=this.contentEl.createDiv({cls:"stashpad-export-genrow"});y.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=U=>{U.preventDefault();let F=Us(5);n.value=F,o&&(o.value=F),w(),e.forEach(x=>x()),new at.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(F).catch(()=>{})};let v=y.createEl("button",{cls:"stashpad-export-show",text:"Show"});v.onclick=U=>{U.preventDefault();let F=n.type==="password";n.type=F?"text":"password",o&&(o.type=F?"text":"password"),v.setText(F?"Hide":"Show")};let S=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});S.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(U=>{S.toggleClass("is-weak",!U),S.setText(U?"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(()=>S.setText("Encryption: AES-256-GCM with a password-derived key.")):S.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let a=null,r=this.app.secretStorage;if(this.opts.offerKeychain&&r){let u=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=u.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let f=u.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});f.htmlFor=a.id;let C=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});C.setText("Stored only in this device's keychain \u2014 doesn't sync to your other devices. Anyone with access to this unlocked device + keychain could decrypt."),C.style.display="none",a.onchange=()=>{C.style.display=a.checked?"":"none"}}let l=this.contentEl.createEl("div",{cls:"stashpad-export-error"});l.style.display="none";let c=u=>{l.setText(u),l.style.display=""},g=this.contentEl.createDiv({cls:"stashpad-export-footer"});g.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let p=g.createEl("button",{cls:"mod-cta",text:t==="setup"?"Set up":t==="change"?"Change":"Unlock"}),d=!1,I=async()=>{if(d)return;let u=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!u){c("Enter your current password.");return}if(t==="setup"||t==="change"){if(!f){c("Enter a password.");return}if(f.length<6){c("Use at least 6 characters.");return}if(f!==o?.value){c("Passwords don't match.");return}}d=!0,p.disabled=!0,l.style.display="none";let C=p.textContent;p.setText("Working\u2026");try{let m=await this.opts.onSubmit({current:u,next:f,remember:!!a?.checked});if(m){c(m),d=!1,p.disabled=!1,p.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(m){c(`Failed: ${m.message}`),d=!1,p.disabled=!1,p.setText(C??"OK")}};p.onclick=()=>void I(),this.scope.register([],"Enter",u=>{u.preventDefault(),I()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},si=class extends at.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.style.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()===this.opts.phrase,a=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",a),t?.addEventListener("input",a),a();let r=!1,l=async()=>{if(!(r||!o())){if(this.opts.requirePassword&&(r=!0,n.disabled=!0,i.style.display="none",!await this.opts.requirePassword(t.value))){i.setText("Wrong password."),i.style.display="",r=!1,a();return}this.close(),await this.opts.onConfirm()}};n.onclick=()=>void l(),this.scope.register([],"Enter",c=>{c.preventDefault(),l()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},Hi=class extends at.Modal{constructor(t,e,i){super(t);this.onResult=i;this.delivered=!1;this.value=e&&/^#[0-9a-f]{6}$/i.test(e)?e:"#888888"}onOpen(){this.contentEl.empty(),this.titleEl.setText("Custom color"),this.modalEl.addClass("stashpad-custom-color-modal");let t=this.contentEl.createDiv({cls:"stashpad-custom-color-row"}),e=t.createDiv({cls:"stashpad-custom-color-preview"});e.style.background=this.value;let i=t.createEl("input",{type:"color"});i.value=this.value,i.addClass("stashpad-custom-color-wheel"),e.onclick=()=>i.click();let s=t.createEl("input",{type:"text"});s.addClass("stashpad-custom-color-hex"),s.placeholder="#RRGGBB",s.value=this.value,s.maxLength=7;let n=c=>{let g=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(g)&&(this.value=g,e.style.background=g,i.value=g,s.value!==g&&(s.value=g))};i.oninput=()=>n(i.value),s.oninput=()=>n(s.value);let o=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=o.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let r=o.createEl("button",{cls:"mod-cta",text:"Save"});r.title="Apply this color to the selection (without adding to your palette).",r.onclick=()=>this.commit({addToPalette:!1});let l=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});l.title="Apply and save this color so it appears as a tile next time.",l.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!0})}),requestAnimationFrame(()=>s.focus())}commit(t){this.delivered=!0,this.close(),this.onResult(this.value,t)}onClose(){this.delivered||(this.delivered=!0,this.onResult(this.value,{addToPalette:!1})),this.contentEl.empty()}},je=class je extends at.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=[...je.DEFAULT_PALETTE,...this.customPalette];for(let a of i){let r=t.createDiv({cls:"stashpad-color-tile"});r.style.background=a,r.title=a;let l=!je.DEFAULT_PALETTE.some(g=>g.toLowerCase()===a.toLowerCase()),c=this.items.length;if(r.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let g=r.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});g.title="Remove from palette",g.onclick=p=>{p.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:l?"custom":"preset",color:a,el:r})}let s=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});s.title="Custom color\u2026";let n=this.items.length;s.onclick=()=>this.activate(n),this.items.push({kind:"add",color:null,el:s});let o=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=o>=0?o:0,this.refreshActive(),this.scope.register([],"ArrowRight",a=>{a.preventDefault(),this.moveFocus(1)}),this.scope.register([],"ArrowLeft",a=>{a.preventDefault(),this.moveFocus(-1)}),this.scope.register([],"ArrowDown",a=>{a.preventDefault(),this.moveFocus(this.columns())}),this.scope.register([],"ArrowUp",a=>{a.preventDefault(),this.moveFocus(-this.columns())}),this.scope.register([],"Enter",a=>{a.preventDefault(),this.activate(this.focusIdx)}),requestAnimationFrame(()=>this.modalEl.focus())}activate(t){if(t<0||t>=this.items.length)return;this.focusIdx=t,this.refreshActive();let e=this.items[t];if(e.kind==="add"){this.close(),new Hi(this.app,this.currentColor,(i,s)=>{this.onPick(i,s)}).open();return}this.close(),this.onPick(e.color,{addToPalette:!1})}columns(){if(!this.items.length)return 1;let t=this.items[0].el.parentElement;if(!t)return 1;let e=t.getBoundingClientRect(),i=this.items[0].el.getBoundingClientRect();if(i.width<=0)return 1;let s=i.top,n=0;for(let o of this.items){let a=o.el.getBoundingClientRect();if(Math.abs(a.top-s)<1)n++;else break}return Math.max(1,n)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(i=>i.toLowerCase()!==t.toLowerCase()),this.onOpen()}catch(e){console.warn("Stashpad: palette delete failed",e)}}moveFocus(t){if(!this.items.length)return;let e=Math.max(0,Math.min(this.items.length-1,this.focusIdx+t));this.focusIdx=e,this.refreshActive()}refreshActive(){for(let t=0;t{this.didChoose=!0,this.close(),this.onChoose(!1)};let s=e.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};ni=class extends at.Modal{constructor(t,e,i){super(t);this.opts=e;this.onPick=i;this.didChoose=!1;this.assignees=[];this.assignees=[...e.currentAssignees]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Assign task");let t=this.contentEl.createDiv({cls:"stashpad-due-picker"});Gs(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Cancel"});i.onclick=()=>{this.didChoose=!0,this.close()};let s=e.createEl("button",{cls:"mod-cta",text:"Save"});s.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},oi=class extends at.Modal{constructor(t,e,i,s={}){super(t);this.current=e;this.onPick=i;this.opts=s;this.didChoose=!1;this.assignees=[];this.tinyClosePopover=null;this.assignees=[...s.currentAssignees??[]]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Set due date");let t=null;if(this.current){let f=Date.parse(this.current);Number.isNaN(f)||(t=new Date(f))}let e=this.contentEl.createDiv({cls:"stashpad-due-picker"}),i=e.createDiv({cls:"stashpad-due-fields"}),s=i.createDiv({cls:"stashpad-due-field"}),n=s.createSpan({cls:"stashpad-due-field-icon"});(0,at.setIcon)(n,"calendar");let o=s.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=i.createDiv({cls:"stashpad-due-field"}),r=a.createSpan({cls:"stashpad-due-field-icon"});(0,at.setIcon)(r,"clock");let l=a.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{o.showPicker?.()}catch{}},r.onclick=()=>this.openTimeNumpad(r,l),t&&(o.value=this.toDateValue(t),l.value=this.toTimeValue(t)),this.renderAssignSection(e);let c=e.createDiv({cls:"stashpad-due-grid"}),g=(f,C)=>{let m=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});m.onclick=()=>{let E=C();o.value=this.toDateValue(E),l.value||(l.value=this.toTimeValue(E))}},p=f=>(f.setHours(9,0,0,0),f);g("Today",()=>p(this.startOfTodayLocal())),g("Tomorrow",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+1),p(f)}),g("Next week",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+7),p(f)});let d=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});d.onclick=()=>{o.value="",l.value="",o.focus()};let I=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});I.onclick=()=>{this.didChoose=!0,this.close()};let u=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});u.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[f,C,m]=o.value.split("-").map(v=>parseInt(v,10)),E=9,w=0;if(l.value){let[v,S]=l.value.split(":").map(U=>parseInt(U,10));E=v,w=S}let y=new Date(f,C-1,m,E,w,0,0);this.didChoose=!0,this.close(),this.onPick({iso:y.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){Gs(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let i=9,s=0;if(e.value){let[d,I]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(d)&&(i=d),Number.isFinite(I)&&(s=I)}else{let d=new Date;i=d.getHours(),s=d.getMinutes()}let n=i>=12?"pm":"am",o=i===0?12:i>12?i-12:i,a=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});a.style.position="fixed",a.style.zIndex="9999";let r=null,l=()=>{a.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",g,!0),this.tinyClosePopover===l&&(this.tinyClosePopover=null)},c=d=>{!a.contains(d.target)&&d.target!==t&&!t.contains(d.target)&&l()},g=d=>{d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),l()):d.key==="Enter"&&r&&(d.preventDefault(),d.stopPropagation(),r())};this.tinyClosePopover=l,Ni(a,{seedH:o,seedM:s,seedPeriod:n,close:l,setOnEnter:d=>{r=d},onFinalize:d=>{e.value=`${String(d.hours24).padStart(2,"0")}:${String(d.minutes).padStart(2,"0")}`}});let p=t.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(p.left,window.innerWidth-220))}px`,a.style.top=`${p.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",c,!0),document.addEventListener("keydown",g,!0)},0)}startOfTodayLocal(){let t=new Date;return t.setHours(0,0,0,0),t}toDateValue(t){let e=t.getFullYear(),i=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0");return`${e}-${i}-${s}`}toTimeValue(t){let e=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${e}:${i}`}},Qe=class Qe extends at.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 Ft(this.app,"Clear notification history?",`This will permanently remove all ${this.records.length} stored notifications from the history. The current toasts on screen are unaffected. This can't be undone.`,"Clear history",i=>{i&&this.service.clearHistory()}).open()},this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter(),this.unsubscribe=this.service.onChange(()=>{this.records=this.service.recent(),this.refreshCategoryFilter(),this.refreshAuthorFilter(),this.refreshList(),this.renderFooter()})}setAuthorFilter(t){this.authorFilter!==t&&(this.authorFilter=t,this.refreshList(),this.renderFooter())}refreshAuthorFilter(){if(!this.authorSelEl)return;let t=this.authorSelEl;t.empty(),t.createEl("option",{text:"All authors"}).value="all",this.currentAuthorId&&(t.createEl("option",{text:"Me"}).value="me"),t.createEl("option",{text:"Cross-author"}).value="cross";let e=new Set;for(let s of this.records)s.authorId&&s.authorId!==this.currentAuthorId&&e.add(s.authorId);if(e.size>0){let s=t.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});s.disabled=!0;for(let n of[...e].sort())t.createEl("option",{text:n}).value=n}new Set(["all","cross",...this.currentAuthorId?["me"]:[],...e]).has(this.authorFilter)||(this.authorFilter="all"),t.value=this.authorFilter}isCrossAuthor(t){let e=t.authorId??null;if(!e)return!1;for(let i of t.affectedAuthorIds??[])if(i&&i!==e)return!0;if(!this.getNoteAuthorIds)return!1;for(let i of t.affectedIds){let s=this.getNoteAuthorIds(i);for(let n of s)if(n&&n!==e)return!0}return!1}onClose(){this.unsubscribe?.(),this.unsubscribe=null,this.contentEl.empty()}setCategoryFilter(t){(this.categoryFilter??null)!==(t??null)&&(this.categoryFilter=t,this.refreshList(),this.renderFooter())}refreshCategoryFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.records)e.set(n.category,(e.get(n.category)??0)+1);let i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All categories (${this.records.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});a.value=n}this.categoryFilter&&!e.has(this.categoryFilter)&&(this.categoryFilter=null),t.value=this.categoryFilter??""}refreshList(){if(this.listEl){if(this.visible=this.records.filter(t=>{if(this.categoryFilter&&t.category!==this.categoryFilter)return!1;switch(this.authorFilter){case"all":return!0;case"me":return!!this.currentAuthorId&&t.authorId===this.currentAuthorId;case"cross":return this.isCrossAuthor(t);default:return t.authorId===this.authorFilter}}),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.categoryFilter?`No "${this.categoryFilter}" notifications.`:"No notifications yet."}),this.updateCount();return}this.appendMore(Qe.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let l=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let c of e.actionLabels){let g=l.createSpan({cls:"stashpad-notif-action-chip"});g.setText(c),g.title="Action button was shown on the original toast (handler not retained)."}}}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.categoryFilter?`${t} ${this.categoryFilter} notification${t===1?"":"s"}`:`${t} notification${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}renderFooter(){if(!this.footerEl)return;this.footerEl.empty();let t=this.visible.length-this.shownCount;if(t<=0)return;let e=this.footerEl.createEl("button",{text:`Load ${Math.min(Qe.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Qe.PAGE),this.renderFooter()},t>Qe.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Qe.PAGE=100;ai=Qe,Rs=class extends at.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,at.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()}},ri=class extends at.Modal{constructor(t,e,i){super(t);this.message=e;this.onChoose=i;this.chose=!1}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Possible duplicate import");let t=this.contentEl.createDiv({cls:"stashpad-confirm-body"});for(let o of this.message.split(` -`))t.createDiv({cls:"stashpad-confirm-line",text:o});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Skip duplicates"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let s=e.createEl("button",{text:"Replace existing"});s.onclick=()=>{this.chose=!0,this.close(),this.onChoose("replace")};let n=e.createEl("button",{cls:"mod-cta",text:"Import anyway"});n.onclick=()=>{this.chose=!0,this.close(),this.onChoose("anyway")}}onClose(){this.chose||this.onChoose("skip"),this.contentEl.empty()}}});function Nt(h,A=Yt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(h.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function xt(h,A){return`${h}-${A}.md`}function we(h){let A=h.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var Yt,Me=Ie(()=>{"use strict";Yt=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var Gi={};Si(Gi,{JdBuildConfirmModal:()=>ci,buildJdIndexNotes:()=>Js,buildJdIndexPreview:()=>Pi,buildJdPreviewNotice:()=>Ri,scanForJdNotes:()=>He});function Ls(h,A){if(/^\d+-\d+$/.test(h))return null;if(h.includes(".")){let e=h.split(".").slice(0,-1).join(".");return A.has(e)?e:Ls(e,A)}if(/^\d+$/.test(h)){let t=parseInt(h,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function He(h,A,t){let e=h.vault.getMarkdownFiles(),i=ga(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=d=>s?!1:Array.from(n).some(I=>d===I||d.startsWith(I+"/")),a=[],r=[],l=[];for(let d of i){let I=d.parent?.path?.replace(/\/+$/,"")??"";if(o(I)){l.push(d);continue}let u=d.basename.match(On);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:d,folder:null}):r.push(d)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=d=>{let I=d.path.replace(/\/+$/,"");if(!(c&&I&&I!==c&&!I.startsWith(c+"/"))){if(I&&!o(I)){let u=d.name.match(On);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:d})}}for(let u of d.children)u instanceof kt.TFolder&&g(u)};g(h.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((d,I)=>pa(d,I,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:l}}async function Pi(h,A,t){let e=qs(t.jdIndexStashpadFolder??"");if(!e)return{...He(h,A,t),previewPath:null,error:"no-dest"};let i=He(h,A,t),s=ha(h,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Ia(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await h.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await h.vault.modify(s,r),{...i,previewPath:s.path}}function ha(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof kt.TFolder))return null;for(let e of t.children){if(!(e instanceof kt.TFile)||e.extension!=="md")continue;if((h.metadataCache.getFileCache(e)?.frontmatter??{}).id===M)return e}return null}async function Js(h,A,t){let e=qs(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=He(h,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let C=1;C{r.push(f);for(let C of a.get(f)??[])l(C)};for(let f of o)l(f);let c=new Map,g=h.vault.getAbstractFileByPath(e);if(g instanceof kt.TFolder)for(let f of g.children){if(!(f instanceof kt.TFile)||f.extension!=="md")continue;let C=h.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&c.set(C.jdPrefix,f)}let p=new Map,d=0,I=0,u=0;for(let f of r){let C=n.get(f)??null,m=Ls(f,new Set(n.keys())),E=m?p.get(m)??M:M,w=C?`${f} ${C.title}`:f,y=C?.file?`[[${C.file.basename}]]`:"",v=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 at.Notice("Move the cursor inside the text \u2014 neither end can be empty.");return}this.close(),this.onSplitAtChar(e)}render(){this.contentEl.empty();let t=this.contentEl.createDiv({cls:"stashpad-split-toggle-bar"});if(this.lines.length>=2){let n=t.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&n.addClass("is-active"),n.onclick=()=>{this.mode="line",this.render()}}let e=t.createEl("button",{text:"Cursor split",cls:"stashpad-split-mode-btn"});this.mode==="cursor"&&e.addClass("is-active"),e.onclick=()=>{this.mode="cursor",this.render()};let i=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});i.onmousedown=n=>n.preventDefault(),i.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let s=this.contentEl.createDiv({cls:"stashpad-split-help"});at.Platform.isMobile?s.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):s.setText(this.mode==="line"?"\u2191/\u2193 pick split line \xB7 Enter or Split confirm \xB7 Tab \u2192 cursor mode \xB7 Esc cancel \xB7 Children stay with the first part":"Click or arrow to position cursor \xB7 Mod+Enter or Split confirm \xB7 Tab \u2192 line mode \xB7 Esc cancel \xB7 Children stay with the first part")}renderLineMode(){let t=this.contentEl.createDiv({cls:"stashpad-split-list"});for(let e=0;e{let s=Math.max(1,Math.min(this.lines.length-1,e));s!==this.lineCursorIdx&&(this.lineCursorIdx=s,this.render())}}}renderCursorMode(){let e=this.contentEl.createDiv({cls:"stashpad-split-cursor-wrap"}).createEl("textarea",{cls:"stashpad-split-cursor-ta"});e.value=this.body,e.readOnly=!1,this.cursorTextarea=e;let i=parseFloat(getComputedStyle(e).lineHeight)||22,s=at.Platform.isMobile?3:12,n=2,o=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,i*s+16);e.style.height=`${Math.max(a,i*n+16)}px`};requestAnimationFrame(()=>{o();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",o)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},si=class extends at.Modal{constructor(t,e,i,s,n){super(t);this.defaultBaseName=e;this.noteCount=i;this.onConfirm=s;this.kdfProbe=n;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Export to .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`${this.noteCount} note${this.noteCount===1?"":"s"} will be bundled into a single .stash file.`});let t=this.contentEl.createDiv({cls:"stashpad-export-field"});t.createEl("label",{cls:"stashpad-export-label",text:"File name"});let e=t.createEl("input",{type:"text"});e.addClass("stashpad-export-name"),e.value=this.defaultBaseName;let i=this.contentEl.createEl("div",{cls:"stashpad-export-preview"}),s=this.contentEl.createDiv({cls:"stashpad-export-encrypt"}),n=s.createDiv({cls:"stashpad-export-toggle"}),o=n.createEl("input",{type:"checkbox"});o.id="stashpad-export-encrypt-cb";let a=n.createEl("label",{text:"Encrypt with a password"});a.htmlFor=o.id;let r=s.createDiv({cls:"stashpad-export-pw-area"});r.style.display="none";let l=[],c=O=>{let V=r.createDiv({cls:"stashpad-export-pw-row"}),rt=V.createEl("input",{type:"password"});rt.addClass("stashpad-export-name"),rt.placeholder=O;let gt=V.createEl("button",{cls:"stashpad-export-copy"}),nt=()=>{let At=rt.value.length===0;gt.setText(At?"Paste":"Copy"),gt.toggleClass("is-paste",At),gt.setAttr("aria-label",`${At?"Paste into":"Copy"} ${O.toLowerCase()}`)};return gt.onclick=async At=>{if(At.preventDefault(),rt.value.length===0)try{let lt=(await navigator.clipboard?.readText())?.trim();if(!lt){new at.Notice("Clipboard is empty.");return}rt.value=lt,rt.dispatchEvent(new Event("input")),new at.Notice("Pasted from clipboard.")}catch{new at.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(rt.value).then(()=>new at.Notice("Passphrase copied to clipboard."),()=>new at.Notice("Couldn't access the clipboard."))},nt(),l.push(nt),rt},g=c("Password"),p=c("Confirm password"),d=r.createDiv({cls:"stashpad-export-strength"}),I=d.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),f=d.createEl("span",{cls:"stashpad-strength-label"}),C=r.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),E=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=r.createEl("div",{cls:"stashpad-export-pw-hint"}),y=r.createEl("div",{cls:"stashpad-export-pw-suite"});y.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(O=>{y.toggleClass("is-weak",!O),y.setText(O?"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 v=this.app.secretStorage,S=r.createDiv({cls:"stashpad-export-remember"}),M=S.createEl("input",{type:"checkbox"});M.id="stashpad-export-remember-cb";let F=S.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});F.htmlFor=M.id;let N=r.createDiv({cls:"stashpad-export-remember-note"});N.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),N.style.display="none",M.onchange=()=>{N.style.display=M.checked?"":"none"},v||(S.style.display="none");let Q=()=>{let O=e.value.trim()||this.defaultBaseName;return o.checked?`${O}-encrypted`:O},D=()=>i.setText(`Saves as: ${Q()}-.stash`);e.oninput=D;let K=this.contentEl.createDiv({cls:"stashpad-export-footer"}),x=K.createEl("button",{text:"Cancel"});x.onclick=()=>this.close();let Y=K.createEl("button",{cls:"mod-cta",text:"Export"}),q=()=>{let O=Gs(g.value);d.style.visibility=g.value?"visible":"hidden",u.forEach((V,rt)=>V.toggleClass("is-on",g.value!==""&&rt<=O.level)),I.dataset.level=String(O.level),f.setText(O.label)},_=()=>{let O=o.checked;r.style.display=O?"":"none";let V=!0;O&&(g.value?g.value!==p.value?(w.setText("Passwords don't match."),w.addClass("is-error"),V=!1):(w.setText("\u26A0\uFE0F If you lose this password, the export can't be recovered."),w.removeClass("is-error")):(w.setText("Enter a password to encrypt this export."),w.removeClass("is-error"),V=!1)),q(),l.forEach(rt=>rt()),Y.disabled=!V,Y.toggleClass("is-disabled",!V),D()},L=!1,U=O=>{L=O,g.type=p.type=O?"text":"password",E.setText(O?"Hide":"Show")};E.onclick=O=>{O.preventDefault(),U(!L)},m.onclick=O=>{O.preventDefault(),g.value=p.value=Rs(),U(!1),new at.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),_()},o.onchange=_,g.oninput=_,p.oninput=_,_();let tt=()=>this.commit(Q(),o.checked?g.value:null,o.checked&&M.checked);Y.onclick=tt,this.scope.register([],"Enter",O=>{O.preventDefault(),Y.disabled||tt()}),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()}},ni=class extends at.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()}},Xt=class extends at.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(t==="setup"?"Set up encryption password":t==="change"?"Change encryption password":"Unlock encryption"),t==="setup"&&this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This single password protects everything you encrypt in this vault. It is stored only on this device. There is NO recovery \u2014 if you lose it, anything you've encrypted is gone for good."});let e=[],i=u=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),C=f.createEl("input",{type:"password"});C.addClass("stashpad-export-name","stashpad-encryption-field"),C.placeholder=u;let m=f.createEl("button",{cls:"stashpad-export-copy"}),E=()=>{let w=C.value.length===0;m.setText(w?"Paste":"Copy"),m.toggleClass("is-paste",w),m.setAttr("aria-label",`${w?"Paste into":"Copy"} ${u.toLowerCase()}`)};return m.onclick=async w=>{if(w.preventDefault(),C.value.length===0)try{let y=(await navigator.clipboard?.readText())?.trim();if(!y){new at.Notice("Clipboard is empty.");return}C.value=y,C.dispatchEvent(new Event("input")),new at.Notice("Pasted from clipboard.")}catch{new at.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(C.value).then(()=>new at.Notice("Copied to clipboard."),()=>new at.Notice("Couldn't access the clipboard."))},C.addEventListener("input",E),E(),e.push(E),C},s=null,n=null,o=null;if((t==="unlock"||t==="change")&&(s=i("Current password")),(t==="setup"||t==="change")&&(n=i(t==="change"?"New password":"Password"),o=i("Confirm password")),n){let u=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=u.createDiv({cls:"stashpad-strength-bar"}),C=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),m=u.createEl("span",{cls:"stashpad-strength-label"}),E=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),w=()=>{let M=n.value,F=Gs(M);C.forEach((N,Q)=>N.toggleClass("is-on",Q0&&M.length<6?" \u2014 use at least 6":""}`),E.toggleClass("is-weak",M.length>0&&M.length<6)};n.addEventListener("input",w),w();let y=this.contentEl.createDiv({cls:"stashpad-export-genrow"});y.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=M=>{M.preventDefault();let F=Rs(5);n.value=F,o&&(o.value=F),w(),e.forEach(N=>N()),new at.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(F).catch(()=>{})};let v=y.createEl("button",{cls:"stashpad-export-show",text:"Show"});v.onclick=M=>{M.preventDefault();let F=n.type==="password";n.type=F?"text":"password",o&&(o.type=F?"text":"password"),v.setText(F?"Hide":"Show")};let S=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});S.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(M=>{S.toggleClass("is-weak",!M),S.setText(M?"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(()=>S.setText("Encryption: AES-256-GCM with a password-derived key.")):S.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let a=null,r=this.app.secretStorage;if(this.opts.offerKeychain&&r){let u=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=u.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let f=u.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});f.htmlFor=a.id;let C=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});C.setText("Stored only in this device's keychain \u2014 doesn't sync to your other devices. Anyone with access to this unlocked device + keychain could decrypt."),C.style.display="none",a.onchange=()=>{C.style.display=a.checked?"":"none"}}let l=this.contentEl.createEl("div",{cls:"stashpad-export-error"});l.style.display="none";let c=u=>{l.setText(u),l.style.display=""},g=this.contentEl.createDiv({cls:"stashpad-export-footer"});g.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let p=g.createEl("button",{cls:"mod-cta",text:t==="setup"?"Set up":t==="change"?"Change":"Unlock"}),d=!1,I=async()=>{if(d)return;let u=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!u){c("Enter your current password.");return}if(t==="setup"||t==="change"){if(!f){c("Enter a password.");return}if(f.length<6){c("Use at least 6 characters.");return}if(f!==o?.value){c("Passwords don't match.");return}}d=!0,p.disabled=!0,l.style.display="none";let C=p.textContent;p.setText("Working\u2026");try{let m=await this.opts.onSubmit({current:u,next:f,remember:!!a?.checked});if(m){c(m),d=!1,p.disabled=!1,p.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(m){c(`Failed: ${m.message}`),d=!1,p.disabled=!1,p.setText(C??"OK")}};p.onclick=()=>void I(),this.scope.register([],"Enter",u=>{u.preventDefault(),I()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},oi=class extends at.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.style.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()===this.opts.phrase,a=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",a),t?.addEventListener("input",a),a();let r=!1,l=async()=>{if(!(r||!o())){if(this.opts.requirePassword&&(r=!0,n.disabled=!0,i.style.display="none",!await this.opts.requirePassword(t.value))){i.setText("Wrong password."),i.style.display="",r=!1,a();return}this.close(),await this.opts.onConfirm()}};n.onclick=()=>void l(),this.scope.register([],"Enter",c=>{c.preventDefault(),l()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},Hi=class extends at.Modal{constructor(t,e,i){super(t);this.onResult=i;this.delivered=!1;this.value=e&&/^#[0-9a-f]{6}$/i.test(e)?e:"#888888"}onOpen(){this.contentEl.empty(),this.titleEl.setText("Custom color"),this.modalEl.addClass("stashpad-custom-color-modal");let t=this.contentEl.createDiv({cls:"stashpad-custom-color-row"}),e=t.createDiv({cls:"stashpad-custom-color-preview"});e.style.background=this.value;let i=t.createEl("input",{type:"color"});i.value=this.value,i.addClass("stashpad-custom-color-wheel"),e.onclick=()=>i.click();let s=t.createEl("input",{type:"text"});s.addClass("stashpad-custom-color-hex"),s.placeholder="#RRGGBB",s.value=this.value,s.maxLength=7;let n=c=>{let g=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(g)&&(this.value=g,e.style.background=g,i.value=g,s.value!==g&&(s.value=g))};i.oninput=()=>n(i.value),s.oninput=()=>n(s.value);let o=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=o.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let r=o.createEl("button",{cls:"mod-cta",text:"Save"});r.title="Apply this color to the selection (without adding to your palette).",r.onclick=()=>this.commit({addToPalette:!1});let l=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});l.title="Apply and save this color so it appears as a tile next time.",l.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",c=>{c.preventDefault(),this.commit({addToPalette:!0})}),requestAnimationFrame(()=>s.focus())}commit(t){this.delivered=!0,this.close(),this.onResult(this.value,t)}onClose(){this.delivered||(this.delivered=!0,this.onResult(this.value,{addToPalette:!1})),this.contentEl.empty()}},ei=class ei extends at.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 a of i){let r=t.createDiv({cls:"stashpad-color-tile"});r.style.background=a,r.title=a;let l=!ei.DEFAULT_PALETTE.some(g=>g.toLowerCase()===a.toLowerCase()),c=this.items.length;if(r.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let g=r.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});g.title="Remove from palette",g.onclick=p=>{p.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:l?"custom":"preset",color:a,el:r})}let s=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});s.title="Custom color\u2026";let n=this.items.length;s.onclick=()=>this.activate(n),this.items.push({kind:"add",color:null,el:s});let o=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=o>=0?o:0,this.refreshActive(),this.scope.register([],"ArrowRight",a=>{a.preventDefault(),this.moveFocus(1)}),this.scope.register([],"ArrowLeft",a=>{a.preventDefault(),this.moveFocus(-1)}),this.scope.register([],"ArrowDown",a=>{a.preventDefault(),this.moveFocus(this.columns())}),this.scope.register([],"ArrowUp",a=>{a.preventDefault(),this.moveFocus(-this.columns())}),this.scope.register([],"Enter",a=>{a.preventDefault(),this.activate(this.focusIdx)}),requestAnimationFrame(()=>this.modalEl.focus())}activate(t){if(t<0||t>=this.items.length)return;this.focusIdx=t,this.refreshActive();let e=this.items[t];if(e.kind==="add"){this.close(),new Hi(this.app,this.currentColor,(i,s)=>{this.onPick(i,s)}).open();return}this.close(),this.onPick(e.color,{addToPalette:!1})}columns(){if(!this.items.length)return 1;let t=this.items[0].el.parentElement;if(!t)return 1;let e=t.getBoundingClientRect(),i=this.items[0].el.getBoundingClientRect();if(i.width<=0)return 1;let s=i.top,n=0;for(let o of this.items){let a=o.el.getBoundingClientRect();if(Math.abs(a.top-s)<1)n++;else break}return Math.max(1,n)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(i=>i.toLowerCase()!==t.toLowerCase()),this.onOpen()}catch(e){console.warn("Stashpad: palette delete failed",e)}}moveFocus(t){if(!this.items.length)return;let e=Math.max(0,Math.min(this.items.length-1,this.focusIdx+t));this.focusIdx=e,this.refreshActive()}refreshActive(){for(let t=0;t{this.didChoose=!0,this.close(),this.onChoose(!1)};let s=e.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};ai=class extends at.Modal{constructor(t,e,i){super(t);this.opts=e;this.onPick=i;this.didChoose=!1;this.assignees=[];this.assignees=[...e.currentAssignees]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Assign task");let t=this.contentEl.createDiv({cls:"stashpad-due-picker"});Js(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Cancel"});i.onclick=()=>{this.didChoose=!0,this.close()};let s=e.createEl("button",{cls:"mod-cta",text:"Save"});s.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},ri=class extends at.Modal{constructor(t,e,i,s={}){super(t);this.current=e;this.onPick=i;this.opts=s;this.didChoose=!1;this.assignees=[];this.tinyClosePopover=null;this.assignees=[...s.currentAssignees??[]]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Set due date");let t=null;if(this.current){let f=Date.parse(this.current);Number.isNaN(f)||(t=new Date(f))}let e=this.contentEl.createDiv({cls:"stashpad-due-picker"}),i=e.createDiv({cls:"stashpad-due-fields"}),s=i.createDiv({cls:"stashpad-due-field"}),n=s.createSpan({cls:"stashpad-due-field-icon"});(0,at.setIcon)(n,"calendar");let o=s.createEl("input",{type:"date",cls:"stashpad-due-date"}),a=i.createDiv({cls:"stashpad-due-field"}),r=a.createSpan({cls:"stashpad-due-field-icon"});(0,at.setIcon)(r,"clock");let l=a.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{o.showPicker?.()}catch{}},r.onclick=()=>this.openTimeNumpad(r,l),t&&(o.value=this.toDateValue(t),l.value=this.toTimeValue(t)),this.renderAssignSection(e);let c=e.createDiv({cls:"stashpad-due-grid"}),g=(f,C)=>{let m=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});m.onclick=()=>{let E=C();o.value=this.toDateValue(E),l.value||(l.value=this.toTimeValue(E))}},p=f=>(f.setHours(9,0,0,0),f);g("Today",()=>p(this.startOfTodayLocal())),g("Tomorrow",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+1),p(f)}),g("Next week",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+7),p(f)});let d=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});d.onclick=()=>{o.value="",l.value="",o.focus()};let I=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});I.onclick=()=>{this.didChoose=!0,this.close()};let u=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});u.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[f,C,m]=o.value.split("-").map(v=>parseInt(v,10)),E=9,w=0;if(l.value){let[v,S]=l.value.split(":").map(M=>parseInt(M,10));E=v,w=S}let y=new Date(f,C-1,m,E,w,0,0);this.didChoose=!0,this.close(),this.onPick({iso:y.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){Js(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let i=9,s=0;if(e.value){let[d,I]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(d)&&(i=d),Number.isFinite(I)&&(s=I)}else{let d=new Date;i=d.getHours(),s=d.getMinutes()}let n=i>=12?"pm":"am",o=i===0?12:i>12?i-12:i,a=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});a.style.position="fixed",a.style.zIndex="9999";let r=null,l=()=>{a.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",g,!0),this.tinyClosePopover===l&&(this.tinyClosePopover=null)},c=d=>{!a.contains(d.target)&&d.target!==t&&!t.contains(d.target)&&l()},g=d=>{d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),l()):d.key==="Enter"&&r&&(d.preventDefault(),d.stopPropagation(),r())};this.tinyClosePopover=l,xi(a,{seedH:o,seedM:s,seedPeriod:n,close:l,setOnEnter:d=>{r=d},onFinalize:d=>{e.value=`${String(d.hours24).padStart(2,"0")}:${String(d.minutes).padStart(2,"0")}`}});let p=t.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(p.left,window.innerWidth-220))}px`,a.style.top=`${p.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",c,!0),document.addEventListener("keydown",g,!0)},0)}startOfTodayLocal(){let t=new Date;return t.setHours(0,0,0,0),t}toDateValue(t){let e=t.getFullYear(),i=String(t.getMonth()+1).padStart(2,"0"),s=String(t.getDate()).padStart(2,"0");return`${e}-${i}-${s}`}toTimeValue(t){let e=String(t.getHours()).padStart(2,"0"),i=String(t.getMinutes()).padStart(2,"0");return`${e}:${i}`}},Qe=class Qe extends at.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 Ft(this.app,"Clear notification history?",`This will permanently remove all ${this.records.length} stored notifications from the history. The current toasts on screen are unaffected. This can't be undone.`,"Clear history",i=>{i&&this.service.clearHistory()}).open()},this.listEl=this.contentEl.createDiv({cls:"stashpad-log-list"}),this.refreshList(),this.footerEl=this.contentEl.createDiv({cls:"stashpad-log-footer"}),this.renderFooter(),this.unsubscribe=this.service.onChange(()=>{this.records=this.service.recent(),this.refreshCategoryFilter(),this.refreshAuthorFilter(),this.refreshList(),this.renderFooter()})}setAuthorFilter(t){this.authorFilter!==t&&(this.authorFilter=t,this.refreshList(),this.renderFooter())}refreshAuthorFilter(){if(!this.authorSelEl)return;let t=this.authorSelEl;t.empty(),t.createEl("option",{text:"All authors"}).value="all",this.currentAuthorId&&(t.createEl("option",{text:"Me"}).value="me"),t.createEl("option",{text:"Cross-author"}).value="cross";let e=new Set;for(let s of this.records)s.authorId&&s.authorId!==this.currentAuthorId&&e.add(s.authorId);if(e.size>0){let s=t.createEl("option",{text:"\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500"});s.disabled=!0;for(let n of[...e].sort())t.createEl("option",{text:n}).value=n}new Set(["all","cross",...this.currentAuthorId?["me"]:[],...e]).has(this.authorFilter)||(this.authorFilter="all"),t.value=this.authorFilter}isCrossAuthor(t){let e=t.authorId??null;if(!e)return!1;for(let i of t.affectedAuthorIds??[])if(i&&i!==e)return!0;if(!this.getNoteAuthorIds)return!1;for(let i of t.affectedIds){let s=this.getNoteAuthorIds(i);for(let n of s)if(n&&n!==e)return!0}return!1}onClose(){this.unsubscribe?.(),this.unsubscribe=null,this.contentEl.empty()}setCategoryFilter(t){(this.categoryFilter??null)!==(t??null)&&(this.categoryFilter=t,this.refreshList(),this.renderFooter())}refreshCategoryFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.records)e.set(n.category,(e.get(n.category)??0)+1);let i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All categories (${this.records.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});a.value=n}this.categoryFilter&&!e.has(this.categoryFilter)&&(this.categoryFilter=null),t.value=this.categoryFilter??""}refreshList(){if(this.listEl){if(this.visible=this.records.filter(t=>{if(this.categoryFilter&&t.category!==this.categoryFilter)return!1;switch(this.authorFilter){case"all":return!0;case"me":return!!this.currentAuthorId&&t.authorId===this.currentAuthorId;case"cross":return this.isCrossAuthor(t);default:return t.authorId===this.authorFilter}}),this.shownCount=0,this.listEl.empty(),!this.visible.length){this.listEl.createDiv({cls:"stashpad-log-empty",text:this.categoryFilter?`No "${this.categoryFilter}" notifications.`:"No notifications yet."}),this.updateCount();return}this.appendMore(Qe.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let l=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let c of e.actionLabels){let g=l.createSpan({cls:"stashpad-notif-action-chip"});g.setText(c),g.title="Action button was shown on the original toast (handler not retained)."}}}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.categoryFilter?`${t} ${this.categoryFilter} notification${t===1?"":"s"}`:`${t} notification${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}renderFooter(){if(!this.footerEl)return;this.footerEl.empty();let t=this.visible.length-this.shownCount;if(t<=0)return;let e=this.footerEl.createEl("button",{text:`Load ${Math.min(Qe.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Qe.PAGE),this.renderFooter()},t>Qe.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Qe.PAGE=100;Ai=Qe,Ls=class extends at.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,at.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()}},li=class extends at.Modal{constructor(t,e,i){super(t);this.message=e;this.onChoose=i;this.chose=!1}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Possible duplicate import");let t=this.contentEl.createDiv({cls:"stashpad-confirm-body"});for(let o of this.message.split(` +`))t.createDiv({cls:"stashpad-confirm-line",text:o});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Skip duplicates"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let s=e.createEl("button",{text:"Replace existing"});s.onclick=()=>{this.chose=!0,this.close(),this.onChoose("replace")};let n=e.createEl("button",{cls:"mod-cta",text:"Import anyway"});n.onclick=()=>{this.chose=!0,this.close(),this.onChoose("anyway")}}onClose(){this.chose||this.onChoose("skip"),this.contentEl.empty()}}});function xt(h,A=Yt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(h.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function Mt(h,A){return`${h}-${A}.md`}function we(h){let A=h.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var Yt,He=Ie(()=>{"use strict";Yt=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var Li={};Di(Li,{JdBuildConfirmModal:()=>hi,buildJdIndexNotes:()=>Os,buildJdIndexPreview:()=>Ri,buildJdPreviewNotice:()=>Gi,scanForJdNotes:()=>Ue});function qs(h,A){if(/^\d+-\d+$/.test(h))return null;if(h.includes(".")){let e=h.split(".").slice(0,-1).join(".");return A.has(e)?e:qs(e,A)}if(/^\d+$/.test(h)){let t=parseInt(h,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function Ue(h,A,t){let e=h.vault.getMarkdownFiles(),i=ga(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=d=>s?!1:Array.from(n).some(I=>d===I||d.startsWith(I+"/")),a=[],r=[],l=[];for(let d of i){let I=d.parent?.path?.replace(/\/+$/,"")??"";if(o(I)){l.push(d);continue}let u=d.basename.match(Yn);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:d,folder:null}):r.push(d)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=d=>{let I=d.path.replace(/\/+$/,"");if(!(c&&I&&I!==c&&!I.startsWith(c+"/"))){if(I&&!o(I)){let u=d.name.match(Yn);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:d})}}for(let u of d.children)u instanceof kt.TFolder&&g(u)};g(h.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((d,I)=>pa(d,I,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:l}}async function Ri(h,A,t){let e=Ks(t.jdIndexStashpadFolder??"");if(!e)return{...Ue(h,A,t),previewPath:null,error:"no-dest"};let i=Ue(h,A,t),s=ha(h,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Ia(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await h.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await h.vault.modify(s,r),{...i,previewPath:s.path}}function ha(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof kt.TFolder))return null;for(let e of t.children){if(!(e instanceof kt.TFile)||e.extension!=="md")continue;if((h.metadataCache.getFileCache(e)?.frontmatter??{}).id===T)return e}return null}async function Os(h,A,t){let e=Ks(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=Ue(h,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let C=1;C{r.push(f);for(let C of a.get(f)??[])l(C)};for(let f of o)l(f);let c=new Map,g=h.vault.getAbstractFileByPath(e);if(g instanceof kt.TFolder)for(let f of g.children){if(!(f instanceof kt.TFile)||f.extension!=="md")continue;let C=h.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&c.set(C.jdPrefix,f)}let p=new Map,d=0,I=0,u=0;for(let f of r){let C=n.get(f)??null,m=qs(f,new Set(n.keys())),E=m?p.get(m)??T:T,w=C?`${f} ${C.title}`:f,y=C?.file?`[[${C.file.basename}]]`:"",v=y?`${y} `:`${w} -`,S=c.get(f);if(S){try{let U=null;await h.fileManager.processFrontMatter(S,D=>{D.jdPrefix=f,E&&(D.parent=E),(!D.id||typeof D.id!="string")&&(D.id=Bt()),D.created||(D.created=new Date().toISOString()),D.attachments||(D.attachments=[]),U=D.id});let x=(await h.vault.read(S)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=x?`${x[0]}${v}`:v;await h.vault.modify(S,Q),U&&p.set(f,U),I++}catch(U){console.error("[stashpad] buildJdIndexNotes: update failed",U),u++}continue}try{let U=Bt();p.set(f,U);let F=Nt(w,t.slugStopWords),x=xt(F,U),Q=`${e}/${x}`,D=["---",`id: ${U}`,`parent: ${E}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` -`);await h.vault.create(Q,D+v),d++}catch(U){console.error("[stashpad] buildJdIndexNotes: create failed for",f,U),u++}}return{created:d,updated:I,skipped:u,destFolder:e}}function qs(h){return(h||"").trim().replace(/^\/+|\/+$/g,"")}function ga(h,A){if((A.jdIndexScope??"vault")==="vault")return h;let t=qs(A.jdIndexScopeFolder??"");return t?h.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):h}function pa(h,A,t){if(t==="created"){let e=h.file?.stat?.ctime??0,i=A.file?.stat?.ctime??0;if(e!==i)return e-i}return Yn(h.segments,A.segments)}function Kn(h,A){let t=h.match(/^(\d+)-(\d+)$/),e=A.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:h.split("."),s=e?[e[1]]:A.split(".");return Yn(i,s)}function Yn(h,A){let t=Math.min(h.length,A.length);for(let e=0;e{s.set(o,a);for(let r of e.get(o)??[])n(r,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function Ia(h,A,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),h.length===0){let s=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(s)}else{let s=new Map;for(let l of h)s.set(l.prefix,l);for(let l of h)if(l.prefix.includes("."))for(let c=1;c{let c=s.get(l),g=a.get(l)??0,p=" ".repeat(g),d=i(g),I=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${p}- ${d} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${p}- ${d} ${c.prefix}${I}`):e.push(`${p}- ${d} ${l}`);for(let u of o.get(l)??[])r(u)};for(let l of n)r(l)}if(A.length>0){e.push(""),e.push(`# Non-indexed (${A.length})`),e.push(""),e.push("_These notes don't match the JD-prefix convention. Rename them to ` ` and re-run to include them._"),e.push("");for(let s of A)e.push(`- # [[${s.basename}]] \xB7 \`${s.path}\``)}if(t.length>0){let s=new Map;for(let o of t){let a=o.parent?.path?.replace(/\/+$/,"")??"";s.set(a,(s.get(a)??0)+1)}let n=Array.from(s.entries()).sort((o,a)=>o[0].localeCompare(a[0]));e.push(""),e.push(`# Excluded folders (${n.length})`),e.push(""),e.push(`_Stashpad folders are excluded by default so the index doesn't reference itself. Toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder to include them._`),e.push("");for(let[o,a]of n)e.push(`- # All ${a} file${a===1?"":"s"} in \`${o||"(vault root)"}\``)}return e.join(` +`,S=c.get(f);if(S){try{let M=null;await h.fileManager.processFrontMatter(S,D=>{D.jdPrefix=f,E&&(D.parent=E),(!D.id||typeof D.id!="string")&&(D.id=mt()),D.created||(D.created=new Date().toISOString()),D.attachments||(D.attachments=[]),M=D.id});let N=(await h.vault.read(S)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=N?`${N[0]}${v}`:v;await h.vault.modify(S,Q),M&&p.set(f,M),I++}catch(M){console.error("[stashpad] buildJdIndexNotes: update failed",M),u++}continue}try{let M=mt();p.set(f,M);let F=xt(w,t.slugStopWords),N=Mt(F,M),Q=`${e}/${N}`,D=["---",`id: ${M}`,`parent: ${E}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` +`);await h.vault.create(Q,D+v),d++}catch(M){console.error("[stashpad] buildJdIndexNotes: create failed for",f,M),u++}}return{created:d,updated:I,skipped:u,destFolder:e}}function Ks(h){return(h||"").trim().replace(/^\/+|\/+$/g,"")}function ga(h,A){if((A.jdIndexScope??"vault")==="vault")return h;let t=Ks(A.jdIndexScopeFolder??"");return t?h.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):h}function pa(h,A,t){if(t==="created"){let e=h.file?.stat?.ctime??0,i=A.file?.stat?.ctime??0;if(e!==i)return e-i}return Vn(h.segments,A.segments)}function zn(h,A){let t=h.match(/^(\d+)-(\d+)$/),e=A.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:h.split("."),s=e?[e[1]]:A.split(".");return Vn(i,s)}function Vn(h,A){let t=Math.min(h.length,A.length);for(let e=0;e<t;e++){let i=h[e],s=A[e],n=/^\d+$/.test(i),o=/^\d+$/.test(s);if(n&&o){let a=parseInt(i,10)-parseInt(s,10);if(a!==0)return a}else{if(n&&!o)return-1;if(!n&&o)return 1;{let a=i.localeCompare(s,void 0,{numeric:!0,sensitivity:"base"});if(a!==0)return a}}}return h.length-A.length}function Wn(h){let A=new Set(h.keys()),t=new Map,e=new Map;for(let o of A){let a=qs(o,A);if(t.set(o,a),a!==null){let r=e.get(a)??[];r.push(o),e.set(a,r)}}let i=[];for(let o of A)t.get(o)===null&&i.push(o);i.sort(zn);for(let o of e.values())o.sort(zn);let s=new Map,n=(o,a)=>{s.set(o,a);for(let r of e.get(o)??[])n(r,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function Ia(h,A,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),h.length===0){let s=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(s)}else{let s=new Map;for(let l of h)s.set(l.prefix,l);for(let l of h)if(l.prefix.includes("."))for(let c=1;c<l.segments.length;c++){let g=l.segments.slice(0,c).join(".");s.has(g)||s.set(g,null)}let{roots:n,childrenOf:o,depthOf:a}=Wn(s),r=l=>{let c=s.get(l),g=a.get(l)??0,p=" ".repeat(g),d=i(g),I=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${p}- ${d} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${p}- ${d} ${c.prefix}${I}`):e.push(`${p}- ${d} ${l}`);for(let u of o.get(l)??[])r(u)};for(let l of n)r(l)}if(A.length>0){e.push(""),e.push(`# Non-indexed (${A.length})`),e.push(""),e.push("_These notes don't match the JD-prefix convention. Rename them to `<prefix> <title>` and re-run to include them._"),e.push("");for(let s of A)e.push(`- # [[${s.basename}]] \xB7 \`${s.path}\``)}if(t.length>0){let s=new Map;for(let o of t){let a=o.parent?.path?.replace(/\/+$/,"")??"";s.set(a,(s.get(a)??0)+1)}let n=Array.from(s.entries()).sort((o,a)=>o[0].localeCompare(a[0]));e.push(""),e.push(`# Excluded folders (${n.length})`),e.push(""),e.push(`_Stashpad folders are excluded by default so the index doesn't reference itself. Toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder to include them._`),e.push("");for(let[o,a]of n)e.push(`- # All ${a} file${a===1?"":"s"} in \`${o||"(vault root)"}\``)}return e.join(` `)+` -`}function Ri(h,A){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let i=t.createEl("ul");i.style.margin="0 0 8px 0",i.style.paddingLeft="18px",i.createEl("li",{text:`${A.indexed.length} indexed`}),i.createEl("li",{text:`${A.nonIndex.length+A.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.style.padding="2px 10px",s.style.fontSize="var(--font-ui-smaller)";let n;return s.onclick=async o=>{if(o.stopPropagation(),A.previewPath){let a=h.vault.getAbstractFileByPath(A.previewPath);a instanceof kt.TFile&&await h.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new kt.Notice(t,0),n}var kt,On,ci,di=Ie(()=>{"use strict";kt=require("obsidian");Kt();Me();yt();On=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;ci=class extends kt.Modal{constructor(t,e,i,s,n){super(t);this.plugin=e;this.settings=i;this.indexedCount=s;this.onBuild=n;this.LARGE_BUILD=50;this.previewRan=!1;this.previewPath=null}onOpen(){let{contentEl:t,titleEl:e}=this,i=!this.settings.jdIndexHasBuilt,s=this.indexedCount>this.LARGE_BUILD;e.setText(i?"Build JD index \u2014 first time?":"Build JD index");let n=this.settings.jdIndexStashpadFolder,o=t.createEl("p"),a=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;i?(o.appendText(`Stashpad is about to create ${a} (plus synthetic parents as needed) inside "`),o.createEl("code",{text:n}),o.appendText('". Existing notes with the same '),o.createEl("code",{text:"jdPrefix"}),o.appendText(" are updated, never deleted \u2014 but if the prefix detection picks up notes you didn't mean to index, you'll end up with a lot of unwanted notes."),t.createEl("p").setText("Running Preview first writes a single Markdown file showing exactly what would be built (and what wouldn't), so you can sanity-check before committing.")):s?(o.appendText(`You're about to create ${this.indexedCount} notes in "`),o.createEl("code",{text:n}),o.appendText(`". That's a big batch \u2014 if anything looks off, Preview the single-file output first.`)):(o.appendText('Build the JD index into "'),o.createEl("code",{text:n}),o.appendText(`"? Stashpad will create / update ${a}. Existing notes with matching `),o.createEl("code",{text:"jdPrefix"}),o.appendText(" are updated in place.")),this.previewRan&&this.previewPath&&t.createEl("p",{cls:"setting-item-description"}).setText(`\u2713 Preview written to home note (${this.previewPath}). Open it before building if you haven't.`);let r=new kt.Setting(t);(i||s)&&r.addButton(l=>{l.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),l.setCta(),l.onClick(async()=>{try{let c=await Pi(this.app,this.plugin,this.settings);if(c.error==="no-dest"){new kt.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(c.error==="no-home"){new kt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=c.previewPath,Ri(this.app,c),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(c){new kt.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}),r.addButton(l=>{l.setButtonText(i?"Build anyway":"Build"),!i&&!s&&l.setCta(),l.onClick(async()=>{this.close(),await this.onBuild()})}),r.addButton(l=>{l.setButtonText("Cancel"),l.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var Vi=oa((lo,an)=>{(function(h){typeof lo=="object"&&typeof an<"u"?an.exports=h():typeof define=="function"&&define.amd?define([],h):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=h()})(function(){return function h(A,t,e){function i(o,a){if(!t[o]){if(!A[o]){var r=typeof require=="function"&&require;if(!a&&r)return r(o,!0);if(s)return s(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[o]={exports:{}};A[o][0].call(c.exports,function(g){var p=A[o][1][g];return i(p||g)},c,c.exports,h,A,t,e)}return t[o].exports}for(var s=typeof require=="function"&&require,n=0;n<e.length;n++)i(e[n]);return i}({1:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,l,c,g,p,d=[],I=0,u=n.length,f=u,C=e.getTypeOf(n)!=="string";I<n.length;)f=u-I,r=C?(o=n[I++],a=I<u?n[I++]:0,I<u?n[I++]:0):(o=n.charCodeAt(I++),a=I<u?n.charCodeAt(I++):0,I<u?n.charCodeAt(I++):0),l=o>>2,c=(3&o)<<4|a>>4,g=1<f?(15&a)<<2|r>>6:64,p=2<f?63&r:64,d.push(s.charAt(l)+s.charAt(c)+s.charAt(g)+s.charAt(p));return d.join("")},t.decode=function(n){var o,a,r,l,c,g,p=0,d=0,I="data:";if(n.substr(0,I.length)===I)throw new Error("Invalid base64 input, it looks like a data url.");var u,f=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===s.charAt(64)&&f--,n.charAt(n.length-2)===s.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=i.uint8array?new Uint8Array(0|f):new Array(0|f);p<n.length;)o=s.indexOf(n.charAt(p++))<<2|(l=s.indexOf(n.charAt(p++)))>>4,a=(15&l)<<4|(c=s.indexOf(n.charAt(p++)))>>2,r=(3&c)<<6|(g=s.indexOf(n.charAt(p++))),u[d++]=o,c!==64&&(u[d++]=a),g!==64&&(u[d++]=r);return u}},{"./support":30,"./utils":32}],2:[function(h,A,t){"use strict";var e=h("./external"),i=h("./stream/DataWorker"),s=h("./stream/Crc32Probe"),n=h("./stream/DataLengthProbe");function o(a,r,l,c,g){this.compressedSize=a,this.uncompressedSize=r,this.crc32=l,this.compression=c,this.compressedContent=g}o.prototype={getContentWorker:function(){var a=new i(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),r=this;return a.on("end",function(){if(this.streamInfo.data_length!==r.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new i(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(a,r,l){return a.pipe(new s).pipe(new n("uncompressedSize")).pipe(r.compressWorker(l)).pipe(new n("compressedSize")).withStreamInfo("compression",r)},A.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(h,A,t){"use strict";var e=h("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=h("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(h,A,t){"use strict";var e=h("./utils"),i=function(){for(var s,n=[],o=0;o<256;o++){s=o;for(var a=0;a<8;a++)s=1&s?3988292384^s>>>1:s>>>1;n[o]=s}return n}();A.exports=function(s,n){return s!==void 0&&s.length?e.getTypeOf(s)!=="string"?function(o,a,r,l){var c=i,g=l+r;o^=-1;for(var p=l;p<g;p++)o=o>>>8^c[255&(o^a[p])];return-1^o}(0|n,s,s.length,0):function(o,a,r,l){var c=i,g=l+r;o^=-1;for(var p=l;p<g;p++)o=o>>>8^c[255&(o^a.charCodeAt(p))];return-1^o}(0|n,s,s.length,0):0}},{"./utils":32}],5:[function(h,A,t){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},{}],6:[function(h,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:h("lie"),A.exports={Promise:e}},{lie:37}],7:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=h("pako"),s=h("./utils"),n=h("./stream/GenericWorker"),o=e?"uint8array":"array";function a(r,l){n.call(this,"FlateWorker/"+r),this._pako=null,this._pakoAction=r,this._pakoOptions=l,this.meta={}}t.magic="\b\0",s.inherits(a,n),a.prototype.processChunk=function(r){this.meta=r.meta,this._pako===null&&this._createPako(),this._pako.push(s.transformTo(o,r.data),!1)},a.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},a.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},a.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var r=this;this._pako.onData=function(l){r.push({data:l,meta:r.meta})}},t.compressWorker=function(r){return new a("Deflate",r)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(h,A,t){"use strict";function e(c,g){var p,d="";for(p=0;p<g;p++)d+=String.fromCharCode(255&c),c>>>=8;return d}function i(c,g,p,d,I,u){var f,C,m=c.file,E=c.compression,w=u!==o.utf8encode,y=s.transformTo("string",u(m.name)),v=s.transformTo("string",o.utf8encode(m.name)),S=m.comment,U=s.transformTo("string",u(S)),F=s.transformTo("string",o.utf8encode(S)),x=v.length!==m.name.length,Q=F.length!==S.length,D="",K="",N="",Y=m.dir,q=m.date,_={crc32:0,compressedSize:0,uncompressedSize:0};g&&!p||(_.crc32=c.crc32,_.compressedSize=c.compressedSize,_.uncompressedSize=c.uncompressedSize);var L=0;g&&(L|=8),w||!x&&!Q||(L|=2048);var T=0,tt=0;Y&&(T|=16),I==="UNIX"?(tt=798,T|=function(V,rt){var gt=V;return V||(gt=rt?16893:33204),(65535>)<<16}(m.unixPermissions,Y)):(tt=20,T|=function(V){return 63&(V||0)}(m.dosPermissions)),f=q.getUTCHours(),f<<=6,f|=q.getUTCMinutes(),f<<=5,f|=q.getUTCSeconds()/2,C=q.getUTCFullYear()-1980,C<<=4,C|=q.getUTCMonth()+1,C<<=5,C|=q.getUTCDate(),x&&(K=e(1,1)+e(a(y),4)+v,D+="up"+e(K.length,2)+K),Q&&(N=e(1,1)+e(a(U),4)+F,D+="uc"+e(N.length,2)+N);var O="";return O+=` -\0`,O+=e(L,2),O+=E.magic,O+=e(f,2),O+=e(C,2),O+=e(_.crc32,4),O+=e(_.compressedSize,4),O+=e(_.uncompressedSize,4),O+=e(y.length,2),O+=e(D.length,2),{fileRecord:r.LOCAL_FILE_HEADER+O+y+D,dirRecord:r.CENTRAL_FILE_HEADER+e(tt,2)+O+e(U.length,2)+"\0\0\0\0"+e(T,4)+e(d,4)+y+D+U}}var s=h("../utils"),n=h("../stream/GenericWorker"),o=h("../utf8"),a=h("../crc32"),r=h("../signature");function l(c,g,p,d){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=p,this.encodeFileName=d,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(l,n),l.prototype.push=function(c){var g=c.meta.percent||0,p=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(c):(this.bytesWritten+=c.data.length,n.prototype.push.call(this,{data:c.data,meta:{currentFile:this.currentFile,percent:p?(g+100*(p-d-1))/p:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var g=this.streamFiles&&!c.file.dir;if(g){var p=i(c,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var g=this.streamFiles&&!c.file.dir,p=i(c,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),g)this.push({data:function(d){return r.DATA_DESCRIPTOR+e(d.crc32,4)+e(d.compressedSize,4)+e(d.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var p=this.bytesWritten-c,d=function(I,u,f,C,m){var E=s.transformTo("string",m(C));return r.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(I,2)+e(I,2)+e(u,4)+e(f,4)+e(E.length,2)+E}(this.dirRecords.length,p,c,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},l.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},l.prototype.registerPrevious=function(c){this._sources.push(c);var g=this;return c.on("data",function(p){g.processChunk(p)}),c.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),c.on("error",function(p){g.error(p)}),this},l.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},l.prototype.error=function(c){var g=this._sources;if(!n.prototype.error.call(this,c))return!1;for(var p=0;p<g.length;p++)try{g[p].error(c)}catch{}return!0},l.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,g=0;g<c.length;g++)c[g].lock()},A.exports=l},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(h,A,t){"use strict";var e=h("../compressions"),i=h("./ZipFileWorker");t.generateWorker=function(s,n,o){var a=new i(n.streamFiles,o,n.platform,n.encodeFileName),r=0;try{s.forEach(function(l,c){r++;var g=function(u,f){var C=u||f,m=e[C];if(!m)throw new Error(C+" is not a valid compression method !");return m}(c.options.compression,n.compression),p=c.options.compressionOptions||n.compressionOptions||{},d=c.dir,I=c.date;c._compressWorker(g,p).withStreamInfo("file",{name:l,dir:d,date:I,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(a)}),a.entriesCount=r}catch(l){a.error(l)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(h,A,t){"use strict";function e(){if(!(this instanceof e))return new e;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var i=new e;for(var s in this)typeof this[s]!="function"&&(i[s]=this[s]);return i}}(e.prototype=h("./object")).loadAsync=h("./load"),e.support=h("./support"),e.defaults=h("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=h("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./external"),s=h("./utf8"),n=h("./zipEntries"),o=h("./stream/Crc32Probe"),a=h("./nodejsUtils");function r(l){return new i.Promise(function(c,g){var p=l.decompressed.getContentWorker().pipe(new o);p.on("error",function(d){g(d)}).on("end",function(){p.streamInfo.crc32!==l.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}A.exports=function(l,c){var g=this;return c=e.extend(c||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),a.isNode&&a.isStream(l)?i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",l,!0,c.optimizedBinaryString,c.base64).then(function(p){var d=new n(c);return d.load(p),d}).then(function(p){var d=[i.Promise.resolve(p)],I=p.files;if(c.checkCRC32)for(var u=0;u<I.length;u++)d.push(r(I[u]));return i.Promise.all(d)}).then(function(p){for(var d=p.shift(),I=d.files,u=0;u<I.length;u++){var f=I[u],C=f.fileNameStr,m=e.resolve(f.fileNameStr);g.file(m,f.decompressed,{binary:!0,optimizedBinaryString:!0,date:f.date,dir:f.dir,comment:f.fileCommentStr.length?f.fileCommentStr:null,unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions,createFolders:c.createFolders}),f.dir||(g.file(m).unsafeOriginalName=C)}return d.zipComment.length&&(g.comment=d.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../stream/GenericWorker");function s(n,o){i.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(o)}e.inherits(s,i),s.prototype._bindStream=function(n){var o=this;(this._stream=n).pause(),n.on("data",function(a){o.push({data:a,meta:{percent:0}})}).on("error",function(a){o.isPaused?this.generatedError=a:o.error(a)}).on("end",function(){o.isPaused?o._upstreamEnded=!0:o.end()})},s.prototype.pause=function(){return!!i.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},A.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(h,A,t){"use strict";var e=h("readable-stream").Readable;function i(s,n,o){e.call(this,n),this._helper=s;var a=this;s.on("data",function(r,l){a.push(r)||a._helper.pause(),o&&o(l)}).on("error",function(r){a.emit("error",r)}).on("end",function(){a.push(null)})}h("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(h,A,t){"use strict";A.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,i){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,i);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,i)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var i=new Buffer(e);return i.fill(0),i},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}},{}],15:[function(h,A,t){"use strict";function e(m,E,w){var y,v=s.getTypeOf(E),S=s.extend(w||{},a);S.date=S.date||new Date,S.compression!==null&&(S.compression=S.compression.toUpperCase()),typeof S.unixPermissions=="string"&&(S.unixPermissions=parseInt(S.unixPermissions,8)),S.unixPermissions&&16384&S.unixPermissions&&(S.dir=!0),S.dosPermissions&&16&S.dosPermissions&&(S.dir=!0),S.dir&&(m=I(m)),S.createFolders&&(y=d(m))&&u.call(this,y,!0);var U=v==="string"&&S.binary===!1&&S.base64===!1;w&&w.binary!==void 0||(S.binary=!U),(E instanceof r&&E.uncompressedSize===0||S.dir||!E||E.length===0)&&(S.base64=!1,S.binary=!0,E="",S.compression="STORE",v="string");var F=null;F=E instanceof r||E instanceof n?E:g.isNode&&g.isStream(E)?new p(m,E):s.prepareContent(m,E,S.binary,S.optimizedBinaryString,S.base64);var x=new l(m,F,S);this.files[m]=x}var i=h("./utf8"),s=h("./utils"),n=h("./stream/GenericWorker"),o=h("./stream/StreamHelper"),a=h("./defaults"),r=h("./compressedObject"),l=h("./zipObject"),c=h("./generate"),g=h("./nodejsUtils"),p=h("./nodejs/NodejsStreamInputAdapter"),d=function(m){m.slice(-1)==="/"&&(m=m.substring(0,m.length-1));var E=m.lastIndexOf("/");return 0<E?m.substring(0,E):""},I=function(m){return m.slice(-1)!=="/"&&(m+="/"),m},u=function(m,E){return E=E!==void 0?E:a.createFolders,m=I(m),this.files[m]||e.call(this,m,null,{dir:!0,createFolders:E}),this.files[m]};function f(m){return Object.prototype.toString.call(m)==="[object RegExp]"}var C={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(m){var E,w,y;for(E in this.files)y=this.files[E],(w=E.slice(this.root.length,E.length))&&E.slice(0,this.root.length)===this.root&&m(w,y)},filter:function(m){var E=[];return this.forEach(function(w,y){m(w,y)&&E.push(y)}),E},file:function(m,E,w){if(arguments.length!==1)return m=this.root+m,e.call(this,m,E,w),this;if(f(m)){var y=m;return this.filter(function(S,U){return!U.dir&&y.test(S)})}var v=this.files[this.root+m];return v&&!v.dir?v:null},folder:function(m){if(!m)return this;if(f(m))return this.filter(function(v,S){return S.dir&&m.test(v)});var E=this.root+m,w=u.call(this,E),y=this.clone();return y.root=w.name,y},remove:function(m){m=this.root+m;var E=this.files[m];if(E||(m.slice(-1)!=="/"&&(m+="/"),E=this.files[m]),E&&!E.dir)delete this.files[m];else for(var w=this.filter(function(v,S){return S.name.slice(0,m.length)===m}),y=0;y<w.length;y++)delete this.files[w[y].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(m){var E,w={};try{if((w=s.extend(m||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:i.utf8encode})).type=w.type.toLowerCase(),w.compression=w.compression.toUpperCase(),w.type==="binarystring"&&(w.type="string"),!w.type)throw new Error("No output type specified.");s.checkSupport(w.type),w.platform!=="darwin"&&w.platform!=="freebsd"&&w.platform!=="linux"&&w.platform!=="sunos"||(w.platform="UNIX"),w.platform==="win32"&&(w.platform="DOS");var y=w.comment||this.comment||"";E=c.generateWorker(this,w,y)}catch(v){(E=new n("error")).error(v)}return new o(E,w.type||"string",w.mimeType)},generateAsync:function(m,E){return this.generateInternalStream(m).accumulate(E)},generateNodeStream:function(m,E){return(m=m||{}).type||(m.type="nodebuffer"),this.generateInternalStream(m).toNodejsStream(E)}};A.exports=C},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(h,A,t){"use strict";A.exports=h("stream")},{stream:void 0}],17:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data[this.zero+s]},i.prototype.lastIndexOfSignature=function(s){for(var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.length-4;0<=l;--l)if(this.data[l]===n&&this.data[l+1]===o&&this.data[l+2]===a&&this.data[l+3]===r)return l-this.zero;return-1},i.prototype.readAndCheckSignature=function(s){var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.readData(4);return n===l[0]&&o===l[1]&&a===l[2]&&r===l[3]},i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],18:[function(h,A,t){"use strict";var e=h("../utils");function i(s){this.data=s,this.length=s.length,this.index=0,this.zero=0}i.prototype={checkOffset:function(s){this.checkIndex(this.index+s)},checkIndex:function(s){if(this.length<this.zero+s||s<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+s+"). Corrupted zip ?")},setIndex:function(s){this.checkIndex(s),this.index=s},skip:function(s){this.setIndex(this.index+s)},byteAt:function(){},readInt:function(s){var n,o=0;for(this.checkOffset(s),n=this.index+s-1;n>=this.index;n--)o=(o<<8)+this.byteAt(n);return this.index+=s,o},readString:function(s){return e.transformTo("string",this.readData(s))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var s=this.readInt(4);return new Date(Date.UTC(1980+(s>>25&127),(s>>21&15)-1,s>>16&31,s>>11&31,s>>5&63,(31&s)<<1))}},A.exports=i},{"../utils":32}],19:[function(h,A,t){"use strict";var e=h("./Uint8ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data.charCodeAt(this.zero+s)},i.prototype.lastIndexOfSignature=function(s){return this.data.lastIndexOf(s)-this.zero},i.prototype.readAndCheckSignature=function(s){return s===this.readData(4)},i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],21:[function(h,A,t){"use strict";var e=h("./ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../support"),s=h("./ArrayReader"),n=h("./StringReader"),o=h("./NodeBufferReader"),a=h("./Uint8ArrayReader");A.exports=function(r){var l=e.getTypeOf(r);return e.checkSupport(l),l!=="string"||i.uint8array?l==="nodebuffer"?new o(r):i.uint8array?new a(e.transformTo("uint8array",r)):new s(e.transformTo("array",r)):new n(r)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(h,A,t){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../utils");function s(n){e.call(this,"ConvertWorker to "+n),this.destType=n}i.inherits(s,e),s.prototype.processChunk=function(n){this.push({data:i.transformTo(this.destType,n.data),meta:n.meta})},A.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}h("../utils").inherits(s,e),s.prototype.processChunk=function(n){this.streamInfo.crc32=i(n.data,this.streamInfo.crc32||0),this.push(n)},A.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(s,i),s.prototype.processChunk=function(n){if(n){var o=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=o+n.data.length}i.prototype.processChunk.call(this,n)},A.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataWorker");var o=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(a){o.dataIsReady=!0,o.data=a,o.max=a&&a.length||0,o.type=e.getTypeOf(a),o.isPaused||o._tickAndRepeat()},function(a){o.error(a)})}e.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,o=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,o);break;case"uint8array":n=this.data.subarray(this.index,o);break;case"array":case"nodebuffer":n=this.data.slice(this.index,o)}return this.index=o,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},A.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(h,A,t){"use strict";function e(i){this.name=i||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}e.prototype={push:function(i){this.emit("data",i)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(i){this.emit("error",i)}return!0},error:function(i){return!this.isFinished&&(this.isPaused?this.generatedError=i:(this.isFinished=!0,this.emit("error",i),this.previous&&this.previous.error(i),this.cleanUp()),!0)},on:function(i,s){return this._listeners[i].push(s),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(i,s){if(this._listeners[i])for(var n=0;n<this._listeners[i].length;n++)this._listeners[i][n].call(this,s)},pipe:function(i){return i.registerPrevious(this)},registerPrevious:function(i){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=i.streamInfo,this.mergeStreamInfo(),this.previous=i;var s=this;return i.on("data",function(n){s.processChunk(n)}),i.on("end",function(){s.end()}),i.on("error",function(n){s.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var i=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),i=!0),this.previous&&this.previous.resume(),!i},flush:function(){},processChunk:function(i){this.push(i)},withStreamInfo:function(i,s){return this.extraStreamInfo[i]=s,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var i in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,i)&&(this.streamInfo[i]=this.extraStreamInfo[i])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var i="Worker "+this.name;return this.previous?this.previous+" -> "+i:i}},A.exports=e},{}],29:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./ConvertWorker"),s=h("./GenericWorker"),n=h("../base64"),o=h("../support"),a=h("../external"),r=null;if(o.nodestream)try{r=h("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(g,p){return new a.Promise(function(d,I){var u=[],f=g._internalType,C=g._outputType,m=g._mimeType;g.on("data",function(E,w){u.push(E),p&&p(w)}).on("error",function(E){u=[],I(E)}).on("end",function(){try{var E=function(w,y,v){switch(w){case"blob":return e.newBlob(e.transformTo("arraybuffer",y),v);case"base64":return n.encode(y);default:return e.transformTo(w,y)}}(C,function(w,y){var v,S=0,U=null,F=0;for(v=0;v<y.length;v++)F+=y[v].length;switch(w){case"string":return y.join("");case"array":return Array.prototype.concat.apply([],y);case"uint8array":for(U=new Uint8Array(F),v=0;v<y.length;v++)U.set(y[v],S),S+=y[v].length;return U;case"nodebuffer":return Buffer.concat(y);default:throw new Error("concat : unsupported type '"+w+"'")}}(f,u),m);d(E)}catch(w){I(w)}u=[]}).resume()})}function c(g,p,d){var I=p;switch(p){case"blob":case"arraybuffer":I="uint8array";break;case"base64":I="string"}try{this._internalType=I,this._outputType=p,this._mimeType=d,e.checkSupport(I),this._worker=g.pipe(new i(I)),g.lock()}catch(u){this._worker=new s("error"),this._worker.error(u)}}c.prototype={accumulate:function(g){return l(this,g)},on:function(g,p){var d=this;return g==="data"?this._worker.on(g,function(I){p.call(d,I.data,I.meta)}):this._worker.on(g,function(){e.delay(p,arguments,d)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(g){if(e.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new r(this,{objectMode:this._outputType!=="nodebuffer"},g)}},A.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(h,A,t){"use strict";if(t.base64=!0,t.array=!0,t.string=!0,t.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",t.nodebuffer=typeof Buffer<"u",t.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(e),t.blob=i.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!h("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(h,A,t){"use strict";for(var e=h("./utils"),i=h("./support"),s=h("./nodejsUtils"),n=h("./stream/GenericWorker"),o=new Array(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;o[254]=o[254]=1;function r(){n.call(this,"utf-8 decode"),this.leftOver=null}function l(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return i.nodebuffer?s.newBufferFrom(c,"utf-8"):function(g){var p,d,I,u,f,C=g.length,m=0;for(u=0;u<C;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),m+=d<128?1:d<2048?2:d<65536?3:4;for(p=i.uint8array?new Uint8Array(m):new Array(m),u=f=0;f<m;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),d<128?p[f++]=d:(d<2048?p[f++]=192|d>>>6:(d<65536?p[f++]=224|d>>>12:(p[f++]=240|d>>>18,p[f++]=128|d>>>12&63),p[f++]=128|d>>>6&63),p[f++]=128|63&d);return p}(c)},t.utf8decode=function(c){return i.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(g){var p,d,I,u,f=g.length,C=new Array(2*f);for(p=d=0;p<f;)if((I=g[p++])<128)C[d++]=I;else if(4<(u=o[I]))C[d++]=65533,p+=u-1;else{for(I&=u===2?31:u===3?15:7;1<u&&p<f;)I=I<<6|63&g[p++],u--;1<u?C[d++]=65533:I<65536?C[d++]=I:(I-=65536,C[d++]=55296|I>>10&1023,C[d++]=56320|1023&I)}return C.length!==d&&(C.subarray?C=C.subarray(0,d):C.length=d),e.applyFromCharCode(C)}(c=e.transformTo(i.uint8array?"uint8array":"array",c))},e.inherits(r,n),r.prototype.processChunk=function(c){var g=e.transformTo(i.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var p=g;(g=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),g.set(p,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var d=function(u,f){var C;for((f=f||u.length)>u.length&&(f=u.length),C=f-1;0<=C&&(192&u[C])==128;)C--;return C<0||C===0?f:C+o[u[C]]>f?C:f}(g),I=g;d!==g.length&&(i.uint8array?(I=g.subarray(0,d),this.leftOver=g.subarray(d,g.length)):(I=g.slice(0,d),this.leftOver=g.slice(d,g.length))),this.push({data:t.utf8decode(I),meta:c.meta})},r.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=r,e.inherits(l,n),l.prototype.processChunk=function(c){this.push({data:t.utf8encode(c.data),meta:c.meta})},t.Utf8EncodeWorker=l},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(h,A,t){"use strict";var e=h("./support"),i=h("./base64"),s=h("./nodejsUtils"),n=h("./external");function o(p){return p}function a(p,d){for(var I=0;I<p.length;++I)d[I]=255&p.charCodeAt(I);return d}h("setimmediate"),t.newBlob=function(p,d){t.checkSupport("blob");try{return new Blob([p],{type:d})}catch{try{var I=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return I.append(p),I.getBlob(d)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,d,I){var u=[],f=0,C=p.length;if(C<=I)return String.fromCharCode.apply(null,p);for(;f<C;)d==="array"||d==="nodebuffer"?u.push(String.fromCharCode.apply(null,p.slice(f,Math.min(f+I,C)))):u.push(String.fromCharCode.apply(null,p.subarray(f,Math.min(f+I,C)))),f+=I;return u.join("")},stringifyByChar:function(p){for(var d="",I=0;I<p.length;I++)d+=String.fromCharCode(p[I]);return d},applyCanBeUsed:{uint8array:function(){try{return e.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}}(),nodebuffer:function(){try{return e.nodebuffer&&String.fromCharCode.apply(null,s.allocBuffer(1)).length===1}catch{return!1}}()}};function l(p){var d=65536,I=t.getTypeOf(p),u=!0;if(I==="uint8array"?u=r.applyCanBeUsed.uint8array:I==="nodebuffer"&&(u=r.applyCanBeUsed.nodebuffer),u)for(;1<d;)try{return r.stringifyByChunk(p,I,d)}catch{d=Math.floor(d/2)}return r.stringifyByChar(p)}function c(p,d){for(var I=0;I<p.length;I++)d[I]=p[I];return d}t.applyFromCharCode=l;var g={};g.string={string:o,array:function(p){return a(p,new Array(p.length))},arraybuffer:function(p){return g.string.uint8array(p).buffer},uint8array:function(p){return a(p,new Uint8Array(p.length))},nodebuffer:function(p){return a(p,s.allocBuffer(p.length))}},g.array={string:l,array:o,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(p)}},g.arraybuffer={string:function(p){return l(new Uint8Array(p))},array:function(p){return c(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:o,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(new Uint8Array(p))}},g.uint8array={string:l,array:function(p){return c(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:o,nodebuffer:function(p){return s.newBufferFrom(p)}},g.nodebuffer={string:l,array:function(p){return c(p,new Array(p.length))},arraybuffer:function(p){return g.nodebuffer.uint8array(p).buffer},uint8array:function(p){return c(p,new Uint8Array(p.length))},nodebuffer:o},t.transformTo=function(p,d){if(d=d||"",!p)return d;t.checkSupport(p);var I=t.getTypeOf(d);return g[I][p](d)},t.resolve=function(p){for(var d=p.split("/"),I=[],u=0;u<d.length;u++){var f=d[u];f==="."||f===""&&u!==0&&u!==d.length-1||(f===".."?I.pop():I.push(f))}return I.join("/")},t.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":e.nodebuffer&&s.isBuffer(p)?"nodebuffer":e.uint8array&&p instanceof Uint8Array?"uint8array":e.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(p){if(!e[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(p){var d,I,u="";for(I=0;I<(p||"").length;I++)u+="\\x"+((d=p.charCodeAt(I))<16?"0":"")+d.toString(16).toUpperCase();return u},t.delay=function(p,d,I){setImmediate(function(){p.apply(I||null,d||[])})},t.inherits=function(p,d){function I(){}I.prototype=d.prototype,p.prototype=new I},t.extend=function(){var p,d,I={};for(p=0;p<arguments.length;p++)for(d in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],d)&&I[d]===void 0&&(I[d]=arguments[p][d]);return I},t.prepareContent=function(p,d,I,u,f){return n.Promise.resolve(d).then(function(C){return e.blob&&(C instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(C))!==-1)&&typeof FileReader<"u"?new n.Promise(function(m,E){var w=new FileReader;w.onload=function(y){m(y.target.result)},w.onerror=function(y){E(y.target.error)},w.readAsArrayBuffer(C)}):C}).then(function(C){var m=t.getTypeOf(C);return m?(m==="arraybuffer"?C=t.transformTo("uint8array",C):m==="string"&&(f?C=i.decode(C):I&&u!==!0&&(C=function(E){return a(E,e.uint8array?new Uint8Array(E.length):new Array(E.length))}(C))),C):n.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./signature"),n=h("./zipEntry"),o=h("./support");function a(r){this.files=[],this.loadOptions=r}a.prototype={checkSignature:function(r){if(!this.reader.readAndCheckSignature(r)){this.reader.index-=4;var l=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(l)+", expected "+i.pretty(r)+")")}},isSignature:function(r,l){var c=this.reader.index;this.reader.setIndex(r);var g=this.reader.readString(4)===l;return this.reader.setIndex(c),g},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var r=this.reader.readData(this.zipCommentLength),l=o.uint8array?"uint8array":"array",c=i.transformTo(l,r);this.zipComment=this.loadOptions.decodeFileName(c)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var r,l,c,g=this.zip64EndOfCentralSize-44;0<g;)r=this.reader.readInt(2),l=this.reader.readInt(4),c=this.reader.readData(l),this.zip64ExtensibleData[r]={id:r,length:l,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var r,l;for(r=0;r<this.files.length;r++)l=this.files[r],this.reader.setIndex(l.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),l.readLocalPart(this.reader),l.handleUTF8(),l.processAttributes()},readCentralDir:function(){var r;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(r=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(r);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var r=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(r<0)throw this.isSignature(0,s.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(r);var l=r;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===i.MAX_VALUE_16BITS||this.diskWithCentralDirStart===i.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===i.MAX_VALUE_16BITS||this.centralDirRecords===i.MAX_VALUE_16BITS||this.centralDirSize===i.MAX_VALUE_32BITS||this.centralDirOffset===i.MAX_VALUE_32BITS){if(this.zip64=!0,(r=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(r),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var c=this.centralDirOffset+this.centralDirSize;this.zip64&&(c+=20,c+=12+this.zip64EndOfCentralSize);var g=l-c;if(0<g)this.isSignature(l,s.CENTRAL_FILE_HEADER)||(this.reader.zero=g);else if(g<0)throw new Error("Corrupted zip: missing "+Math.abs(g)+" bytes.")},prepareReader:function(r){this.reader=e(r)},load:function(r){this.prepareReader(r),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},A.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./compressedObject"),n=h("./crc32"),o=h("./utf8"),a=h("./compressions"),r=h("./support");function l(c,g){this.options=c,this.loadOptions=g}l.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(c){var g,p;if(c.skip(22),this.fileNameLength=c.readInt(2),p=c.readInt(2),this.fileName=c.readData(this.fileNameLength),c.skip(p),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((g=function(d){for(var I in a)if(Object.prototype.hasOwnProperty.call(a,I)&&a[I].magic===d)return a[I];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+i.pretty(this.compressionMethod)+" unknown (inner file : "+i.transformTo("string",this.fileName)+")");this.decompressed=new s(this.compressedSize,this.uncompressedSize,this.crc32,g,c.readData(this.compressedSize))},readCentralPart:function(c){this.versionMadeBy=c.readInt(2),c.skip(2),this.bitFlag=c.readInt(2),this.compressionMethod=c.readString(2),this.date=c.readDate(),this.crc32=c.readInt(4),this.compressedSize=c.readInt(4),this.uncompressedSize=c.readInt(4);var g=c.readInt(2);if(this.extraFieldsLength=c.readInt(2),this.fileCommentLength=c.readInt(2),this.diskNumberStart=c.readInt(2),this.internalFileAttributes=c.readInt(2),this.externalFileAttributes=c.readInt(4),this.localHeaderOffset=c.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");c.skip(g),this.readExtraFields(c),this.parseZIP64ExtraField(c),this.fileComment=c.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var c=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),c==0&&(this.dosPermissions=63&this.externalFileAttributes),c==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var c=e(this.extraFields[1].value);this.uncompressedSize===i.MAX_VALUE_32BITS&&(this.uncompressedSize=c.readInt(8)),this.compressedSize===i.MAX_VALUE_32BITS&&(this.compressedSize=c.readInt(8)),this.localHeaderOffset===i.MAX_VALUE_32BITS&&(this.localHeaderOffset=c.readInt(8)),this.diskNumberStart===i.MAX_VALUE_32BITS&&(this.diskNumberStart=c.readInt(4))}},readExtraFields:function(c){var g,p,d,I=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<I;)g=c.readInt(2),p=c.readInt(2),d=c.readData(p),this.extraFields[g]={id:g,length:p,value:d};c.setIndex(I)},handleUTF8:function(){var c=r.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=o.utf8decode(this.fileName),this.fileCommentStr=o.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var p=i.transformTo(c,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var d=this.findExtraFieldUnicodeComment();if(d!==null)this.fileCommentStr=d;else{var I=i.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(I)}}},findExtraFieldUnicodePath:function(){var c=this.extraFields[28789];if(c){var g=e(c.value);return g.readInt(1)!==1||n(this.fileName)!==g.readInt(4)?null:o.utf8decode(g.readData(c.length-5))}return null},findExtraFieldUnicodeComment:function(){var c=this.extraFields[25461];if(c){var g=e(c.value);return g.readInt(1)!==1||n(this.fileComment)!==g.readInt(4)?null:o.utf8decode(g.readData(c.length-5))}return null}},A.exports=l},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(h,A,t){"use strict";function e(g,p,d){this.name=g,this.dir=d.dir,this.date=d.date,this.comment=d.comment,this.unixPermissions=d.unixPermissions,this.dosPermissions=d.dosPermissions,this._data=p,this._dataBinary=d.binary,this.options={compression:d.compression,compressionOptions:d.compressionOptions}}var i=h("./stream/StreamHelper"),s=h("./stream/DataWorker"),n=h("./utf8"),o=h("./compressedObject"),a=h("./stream/GenericWorker");e.prototype={internalStream:function(g){var p=null,d="string";try{if(!g)throw new Error("No output type specified.");var I=(d=g.toLowerCase())==="string"||d==="text";d!=="binarystring"&&d!=="text"||(d="string"),p=this._decompressWorker();var u=!this._dataBinary;u&&!I&&(p=p.pipe(new n.Utf8EncodeWorker)),!u&&I&&(p=p.pipe(new n.Utf8DecodeWorker))}catch(f){(p=new a("error")).error(f)}return new i(p,d,"")},async:function(g,p){return this.internalStream(g).accumulate(p)},nodeStream:function(g,p){return this.internalStream(g||"nodebuffer").toNodejsStream(p)},_compressWorker:function(g,p){if(this._data instanceof o&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var d=this._decompressWorker();return this._dataBinary||(d=d.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(d,g,p)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof a?this._data:new s(this._data)}};for(var r=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],l=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<r.length;c++)e.prototype[r[c]]=l;A.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(h,A,t){(function(e){"use strict";var i,s,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var o=0,a=new n(g),r=e.document.createTextNode("");a.observe(r,{characterData:!0}),i=function(){r.data=o=++o%2}}else if(e.setImmediate||e.MessageChannel===void 0)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var p=e.document.createElement("script");p.onreadystatechange=function(){g(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},e.document.documentElement.appendChild(p)}:function(){setTimeout(g,0)};else{var l=new e.MessageChannel;l.port1.onmessage=g,i=function(){l.port2.postMessage(0)}}var c=[];function g(){var p,d;s=!0;for(var I=c.length;I;){for(d=c,c=[],p=-1;++p<I;)d[p]();I=c.length}s=!1}A.exports=function(p){c.push(p)!==1||s||i()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(h,A,t){"use strict";var e=h("immediate");function i(){}var s={},n=["REJECTED"],o=["FULFILLED"],a=["PENDING"];function r(I){if(typeof I!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,I!==i&&p(this,I)}function l(I,u,f){this.promise=I,typeof u=="function"&&(this.onFulfilled=u,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function c(I,u,f){e(function(){var C;try{C=u(f)}catch(m){return s.reject(I,m)}C===I?s.reject(I,new TypeError("Cannot resolve promise with itself")):s.resolve(I,C)})}function g(I){var u=I&&I.then;if(I&&(typeof I=="object"||typeof I=="function")&&typeof u=="function")return function(){u.apply(I,arguments)}}function p(I,u){var f=!1;function C(w){f||(f=!0,s.reject(I,w))}function m(w){f||(f=!0,s.resolve(I,w))}var E=d(function(){u(m,C)});E.status==="error"&&C(E.value)}function d(I,u){var f={};try{f.value=I(u),f.status="success"}catch(C){f.status="error",f.value=C}return f}(A.exports=r).prototype.finally=function(I){if(typeof I!="function")return this;var u=this.constructor;return this.then(function(f){return u.resolve(I()).then(function(){return f})},function(f){return u.resolve(I()).then(function(){throw f})})},r.prototype.catch=function(I){return this.then(null,I)},r.prototype.then=function(I,u){if(typeof I!="function"&&this.state===o||typeof u!="function"&&this.state===n)return this;var f=new this.constructor(i);return this.state!==a?c(f,this.state===o?I:u,this.outcome):this.queue.push(new l(f,I,u)),f},l.prototype.callFulfilled=function(I){s.resolve(this.promise,I)},l.prototype.otherCallFulfilled=function(I){c(this.promise,this.onFulfilled,I)},l.prototype.callRejected=function(I){s.reject(this.promise,I)},l.prototype.otherCallRejected=function(I){c(this.promise,this.onRejected,I)},s.resolve=function(I,u){var f=d(g,u);if(f.status==="error")return s.reject(I,f.value);var C=f.value;if(C)p(I,C);else{I.state=o,I.outcome=u;for(var m=-1,E=I.queue.length;++m<E;)I.queue[m].callFulfilled(u)}return I},s.reject=function(I,u){I.state=n,I.outcome=u;for(var f=-1,C=I.queue.length;++f<C;)I.queue[f].callRejected(u);return I},r.resolve=function(I){return I instanceof this?I:s.resolve(new this(i),I)},r.reject=function(I){var u=new this(i);return s.reject(u,I)},r.all=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=new Array(f),E=0,w=-1,y=new this(i);++w<f;)v(I[w],w);return y;function v(S,U){u.resolve(S).then(function(F){m[U]=F,++E!==f||C||(C=!0,s.resolve(y,m))},function(F){C||(C=!0,s.reject(y,F))})}},r.race=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=-1,E=new this(i);++m<f;)w=I[m],u.resolve(w).then(function(y){C||(C=!0,s.resolve(E,y))},function(y){C||(C=!0,s.reject(E,y))});var w;return E}},{immediate:36}],38:[function(h,A,t){"use strict";var e={};(0,h("./lib/utils/common").assign)(e,h("./lib/deflate"),h("./lib/inflate"),h("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(h,A,t){"use strict";var e=h("./zlib/deflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/messages"),o=h("./zlib/zstream"),a=Object.prototype.toString,r=0,l=-1,c=0,g=8;function p(I){if(!(this instanceof p))return new p(I);this.options=i.assign({level:l,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},I||{});var u=this.options;u.raw&&0<u.windowBits?u.windowBits=-u.windowBits:u.gzip&&0<u.windowBits&&u.windowBits<16&&(u.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var f=e.deflateInit2(this.strm,u.level,u.method,u.windowBits,u.memLevel,u.strategy);if(f!==r)throw new Error(n[f]);if(u.header&&e.deflateSetHeader(this.strm,u.header),u.dictionary){var C;if(C=typeof u.dictionary=="string"?s.string2buf(u.dictionary):a.call(u.dictionary)==="[object ArrayBuffer]"?new Uint8Array(u.dictionary):u.dictionary,(f=e.deflateSetDictionary(this.strm,C))!==r)throw new Error(n[f]);this._dict_set=!0}}function d(I,u){var f=new p(u);if(f.push(I,!0),f.err)throw f.msg||n[f.err];return f.result}p.prototype.push=function(I,u){var f,C,m=this.strm,E=this.options.chunkSize;if(this.ended)return!1;C=u===~~u?u:u===!0?4:0,typeof I=="string"?m.input=s.string2buf(I):a.call(I)==="[object ArrayBuffer]"?m.input=new Uint8Array(I):m.input=I,m.next_in=0,m.avail_in=m.input.length;do{if(m.avail_out===0&&(m.output=new i.Buf8(E),m.next_out=0,m.avail_out=E),(f=e.deflate(m,C))!==1&&f!==r)return this.onEnd(f),!(this.ended=!0);m.avail_out!==0&&(m.avail_in!==0||C!==4&&C!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(i.shrinkBuf(m.output,m.next_out))):this.onData(i.shrinkBuf(m.output,m.next_out)))}while((0<m.avail_in||m.avail_out===0)&&f!==1);return C===4?(f=e.deflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===r):C!==2||(this.onEnd(r),!(m.avail_out=0))},p.prototype.onData=function(I){this.chunks.push(I)},p.prototype.onEnd=function(I){I===r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=I,this.msg=this.strm.msg},t.Deflate=p,t.deflate=d,t.deflateRaw=function(I,u){return(u=u||{}).raw=!0,d(I,u)},t.gzip=function(I,u){return(u=u||{}).gzip=!0,d(I,u)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(h,A,t){"use strict";var e=h("./zlib/inflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/constants"),o=h("./zlib/messages"),a=h("./zlib/zstream"),r=h("./zlib/gzheader"),l=Object.prototype.toString;function c(p){if(!(this instanceof c))return new c(p);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},p||{});var d=this.options;d.raw&&0<=d.windowBits&&d.windowBits<16&&(d.windowBits=-d.windowBits,d.windowBits===0&&(d.windowBits=-15)),!(0<=d.windowBits&&d.windowBits<16)||p&&p.windowBits||(d.windowBits+=32),15<d.windowBits&&d.windowBits<48&&!(15&d.windowBits)&&(d.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var I=e.inflateInit2(this.strm,d.windowBits);if(I!==n.Z_OK)throw new Error(o[I]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,d){var I=new c(d);if(I.push(p,!0),I.err)throw I.msg||o[I.err];return I.result}c.prototype.push=function(p,d){var I,u,f,C,m,E,w=this.strm,y=this.options.chunkSize,v=this.options.dictionary,S=!1;if(this.ended)return!1;u=d===~~d?d:d===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof p=="string"?w.input=s.binstring2buf(p):l.call(p)==="[object ArrayBuffer]"?w.input=new Uint8Array(p):w.input=p,w.next_in=0,w.avail_in=w.input.length;do{if(w.avail_out===0&&(w.output=new i.Buf8(y),w.next_out=0,w.avail_out=y),(I=e.inflate(w,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&v&&(E=typeof v=="string"?s.string2buf(v):l.call(v)==="[object ArrayBuffer]"?new Uint8Array(v):v,I=e.inflateSetDictionary(this.strm,E)),I===n.Z_BUF_ERROR&&S===!0&&(I=n.Z_OK,S=!1),I!==n.Z_STREAM_END&&I!==n.Z_OK)return this.onEnd(I),!(this.ended=!0);w.next_out&&(w.avail_out!==0&&I!==n.Z_STREAM_END&&(w.avail_in!==0||u!==n.Z_FINISH&&u!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(f=s.utf8border(w.output,w.next_out),C=w.next_out-f,m=s.buf2string(w.output,f),w.next_out=C,w.avail_out=y-C,C&&i.arraySet(w.output,w.output,f,C,0),this.onData(m)):this.onData(i.shrinkBuf(w.output,w.next_out)))),w.avail_in===0&&w.avail_out===0&&(S=!0)}while((0<w.avail_in||w.avail_out===0)&&I!==n.Z_STREAM_END);return I===n.Z_STREAM_END&&(u=n.Z_FINISH),u===n.Z_FINISH?(I=e.inflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===n.Z_OK):u!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(w.avail_out=0))},c.prototype.onData=function(p){this.chunks.push(p)},c.prototype.onEnd=function(p){p===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},t.Inflate=c,t.inflate=g,t.inflateRaw=function(p,d){return(d=d||{}).raw=!0,g(p,d)},t.ungzip=g},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var a=o.shift();if(a){if(typeof a!="object")throw new TypeError(a+"must be non-object");for(var r in a)a.hasOwnProperty(r)&&(n[r]=a[r])}}return n},t.shrinkBuf=function(n,o){return n.length===o?n:n.subarray?n.subarray(0,o):(n.length=o,n)};var i={arraySet:function(n,o,a,r,l){if(o.subarray&&n.subarray)n.set(o.subarray(a,a+r),l);else for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){var o,a,r,l,c,g;for(o=r=0,a=n.length;o<a;o++)r+=n[o].length;for(g=new Uint8Array(r),o=l=0,a=n.length;o<a;o++)c=n[o],g.set(c,l),l+=c.length;return g}},s={arraySet:function(n,o,a,r,l){for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){return[].concat.apply([],n)}};t.setTyped=function(n){n?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,i)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,s))},t.setTyped(e)},{}],42:[function(h,A,t){"use strict";var e=h("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch{i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{s=!1}for(var n=new e.Buf8(256),o=0;o<256;o++)n[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;function a(r,l){if(l<65537&&(r.subarray&&s||!r.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(r,l));for(var c="",g=0;g<l;g++)c+=String.fromCharCode(r[g]);return c}n[254]=n[254]=1,t.string2buf=function(r){var l,c,g,p,d,I=r.length,u=0;for(p=0;p<I;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),u+=c<128?1:c<2048?2:c<65536?3:4;for(l=new e.Buf8(u),p=d=0;d<u;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),c<128?l[d++]=c:(c<2048?l[d++]=192|c>>>6:(c<65536?l[d++]=224|c>>>12:(l[d++]=240|c>>>18,l[d++]=128|c>>>12&63),l[d++]=128|c>>>6&63),l[d++]=128|63&c);return l},t.buf2binstring=function(r){return a(r,r.length)},t.binstring2buf=function(r){for(var l=new e.Buf8(r.length),c=0,g=l.length;c<g;c++)l[c]=r.charCodeAt(c);return l},t.buf2string=function(r,l){var c,g,p,d,I=l||r.length,u=new Array(2*I);for(c=g=0;c<I;)if((p=r[c++])<128)u[g++]=p;else if(4<(d=n[p]))u[g++]=65533,c+=d-1;else{for(p&=d===2?31:d===3?15:7;1<d&&c<I;)p=p<<6|63&r[c++],d--;1<d?u[g++]=65533:p<65536?u[g++]=p:(p-=65536,u[g++]=55296|p>>10&1023,u[g++]=56320|1023&p)}return a(u,g)},t.utf8border=function(r,l){var c;for((l=l||r.length)>r.length&&(l=r.length),c=l-1;0<=c&&(192&r[c])==128;)c--;return c<0||c===0?l:c+n[r[c]]>l?c:l}},{"./common":41}],43:[function(h,A,t){"use strict";A.exports=function(e,i,s,n){for(var o=65535&e|0,a=e>>>16&65535|0,r=0;s!==0;){for(s-=r=2e3<s?2e3:s;a=a+(o=o+i[n++]|0)|0,--r;);o%=65521,a%=65521}return o|a<<16|0}},{}],44:[function(h,A,t){"use strict";A.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(h,A,t){"use strict";var e=function(){for(var i,s=[],n=0;n<256;n++){i=n;for(var o=0;o<8;o++)i=1&i?3988292384^i>>>1:i>>>1;s[n]=i}return s}();A.exports=function(i,s,n,o){var a=e,r=o+n;i^=-1;for(var l=o;l<r;l++)i=i>>>8^a[255&(i^s[l])];return-1^i}},{}],46:[function(h,A,t){"use strict";var e,i=h("../utils/common"),s=h("./trees"),n=h("./adler32"),o=h("./crc32"),a=h("./messages"),r=0,l=4,c=0,g=-2,p=-1,d=4,I=2,u=8,f=9,C=286,m=30,E=19,w=2*C+1,y=15,v=3,S=258,U=S+v+1,F=42,x=113,Q=1,D=2,K=3,N=4;function Y(B,J){return B.msg=a[J],J}function q(B){return(B<<1)-(4<B?9:0)}function _(B){for(var J=B.length;0<=--J;)B[J]=0}function L(B){var J=B.state,G=J.pending;G>B.avail_out&&(G=B.avail_out),G!==0&&(i.arraySet(B.output,J.pending_buf,J.pending_out,G,B.next_out),B.next_out+=G,J.pending_out+=G,B.total_out+=G,B.avail_out-=G,J.pending-=G,J.pending===0&&(J.pending_out=0))}function T(B,J){s._tr_flush_block(B,0<=B.block_start?B.block_start:-1,B.strstart-B.block_start,J),B.block_start=B.strstart,L(B.strm)}function tt(B,J){B.pending_buf[B.pending++]=J}function O(B,J){B.pending_buf[B.pending++]=J>>>8&255,B.pending_buf[B.pending++]=255&J}function V(B,J){var G,b,k=B.max_chain_length,H=B.strstart,z=B.prev_length,W=B.nice_match,R=B.strstart>B.w_size-U?B.strstart-(B.w_size-U):0,X=B.window,et=B.w_mask,Z=B.prev,it=B.strstart+S,ut=X[H+z-1],ht=X[H+z];B.prev_length>=B.good_match&&(k>>=2),W>B.lookahead&&(W=B.lookahead);do if(X[(G=J)+z]===ht&&X[G+z-1]===ut&&X[G]===X[H]&&X[++G]===X[H+1]){H+=2,G++;do;while(X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&H<it);if(b=S-(it-H),H=it-S,z<b){if(B.match_start=J,W<=(z=b))break;ut=X[H+z-1],ht=X[H+z]}}while((J=Z[J&et])>R&&--k!=0);return z<=B.lookahead?z:B.lookahead}function rt(B){var J,G,b,k,H,z,W,R,X,et,Z=B.w_size;do{if(k=B.window_size-B.lookahead-B.strstart,B.strstart>=Z+(Z-U)){for(i.arraySet(B.window,B.window,Z,Z,0),B.match_start-=Z,B.strstart-=Z,B.block_start-=Z,J=G=B.hash_size;b=B.head[--J],B.head[J]=Z<=b?b-Z:0,--G;);for(J=G=Z;b=B.prev[--J],B.prev[J]=Z<=b?b-Z:0,--G;);k+=Z}if(B.strm.avail_in===0)break;if(z=B.strm,W=B.window,R=B.strstart+B.lookahead,X=k,et=void 0,et=z.avail_in,X<et&&(et=X),G=et===0?0:(z.avail_in-=et,i.arraySet(W,z.input,z.next_in,et,R),z.state.wrap===1?z.adler=n(z.adler,W,et,R):z.state.wrap===2&&(z.adler=o(z.adler,W,et,R)),z.next_in+=et,z.total_in+=et,et),B.lookahead+=G,B.lookahead+B.insert>=v)for(H=B.strstart-B.insert,B.ins_h=B.window[H],B.ins_h=(B.ins_h<<B.hash_shift^B.window[H+1])&B.hash_mask;B.insert&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[H+v-1])&B.hash_mask,B.prev[H&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=H,H++,B.insert--,!(B.lookahead+B.insert<v)););}while(B.lookahead<U&&B.strm.avail_in!==0)}function gt(B,J){for(var G,b;;){if(B.lookahead<U){if(rt(B),B.lookahead<U&&J===r)return Q;if(B.lookahead===0)break}if(G=0,B.lookahead>=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),G!==0&&B.strstart-G<=B.w_size-U&&(B.match_length=V(B,G)),B.match_length>=v)if(b=s._tr_tally(B,B.strstart-B.match_start,B.match_length-v),B.lookahead-=B.match_length,B.match_length<=B.max_lazy_match&&B.lookahead>=v){for(B.match_length--;B.strstart++,B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart,--B.match_length!=0;);B.strstart++}else B.strstart+=B.match_length,B.match_length=0,B.ins_h=B.window[B.strstart],B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+1])&B.hash_mask;else b=s._tr_tally(B,0,B.window[B.strstart]),B.lookahead--,B.strstart++;if(b&&(T(B,!1),B.strm.avail_out===0))return Q}return B.insert=B.strstart<v-1?B.strstart:v-1,J===l?(T(B,!0),B.strm.avail_out===0?K:N):B.last_lit&&(T(B,!1),B.strm.avail_out===0)?Q:D}function nt(B,J){for(var G,b,k;;){if(B.lookahead<U){if(rt(B),B.lookahead<U&&J===r)return Q;if(B.lookahead===0)break}if(G=0,B.lookahead>=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),B.prev_length=B.match_length,B.prev_match=B.match_start,B.match_length=v-1,G!==0&&B.prev_length<B.max_lazy_match&&B.strstart-G<=B.w_size-U&&(B.match_length=V(B,G),B.match_length<=5&&(B.strategy===1||B.match_length===v&&4096<B.strstart-B.match_start)&&(B.match_length=v-1)),B.prev_length>=v&&B.match_length<=B.prev_length){for(k=B.strstart+B.lookahead-v,b=s._tr_tally(B,B.strstart-1-B.prev_match,B.prev_length-v),B.lookahead-=B.prev_length-1,B.prev_length-=2;++B.strstart<=k&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),--B.prev_length!=0;);if(B.match_available=0,B.match_length=v-1,B.strstart++,b&&(T(B,!1),B.strm.avail_out===0))return Q}else if(B.match_available){if((b=s._tr_tally(B,0,B.window[B.strstart-1]))&&T(B,!1),B.strstart++,B.lookahead--,B.strm.avail_out===0)return Q}else B.match_available=1,B.strstart++,B.lookahead--}return B.match_available&&(b=s._tr_tally(B,0,B.window[B.strstart-1]),B.match_available=0),B.insert=B.strstart<v-1?B.strstart:v-1,J===l?(T(B,!0),B.strm.avail_out===0?K:N):B.last_lit&&(T(B,!1),B.strm.avail_out===0)?Q:D}function At(B,J,G,b,k){this.good_length=B,this.max_lazy=J,this.nice_length=G,this.max_chain=b,this.func=k}function lt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=u,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new i.Buf16(2*w),this.dyn_dtree=new i.Buf16(2*(2*m+1)),this.bl_tree=new i.Buf16(2*(2*E+1)),_(this.dyn_ltree),_(this.dyn_dtree),_(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(y+1),this.heap=new i.Buf16(2*C+1),_(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*C+1),_(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function ot(B){var J;return B&&B.state?(B.total_in=B.total_out=0,B.data_type=I,(J=B.state).pending=0,J.pending_out=0,J.wrap<0&&(J.wrap=-J.wrap),J.status=J.wrap?F:x,B.adler=J.wrap===2?0:1,J.last_flush=r,s._tr_init(J),c):Y(B,g)}function Qt(B){var J=ot(B);return J===c&&function(G){G.window_size=2*G.w_size,_(G.head),G.max_lazy_match=e[G.level].max_lazy,G.good_match=e[G.level].good_length,G.nice_match=e[G.level].nice_length,G.max_chain_length=e[G.level].max_chain,G.strstart=0,G.block_start=0,G.lookahead=0,G.insert=0,G.match_length=G.prev_length=v-1,G.match_available=0,G.ins_h=0}(B.state),J}function ft(B,J,G,b,k,H){if(!B)return g;var z=1;if(J===p&&(J=6),b<0?(z=0,b=-b):15<b&&(z=2,b-=16),k<1||f<k||G!==u||b<8||15<b||J<0||9<J||H<0||d<H)return Y(B,g);b===8&&(b=9);var W=new lt;return(B.state=W).strm=B,W.wrap=z,W.gzhead=null,W.w_bits=b,W.w_size=1<<W.w_bits,W.w_mask=W.w_size-1,W.hash_bits=k+7,W.hash_size=1<<W.hash_bits,W.hash_mask=W.hash_size-1,W.hash_shift=~~((W.hash_bits+v-1)/v),W.window=new i.Buf8(2*W.w_size),W.head=new i.Buf16(W.hash_size),W.prev=new i.Buf16(W.w_size),W.lit_bufsize=1<<k+6,W.pending_buf_size=4*W.lit_bufsize,W.pending_buf=new i.Buf8(W.pending_buf_size),W.d_buf=1*W.lit_bufsize,W.l_buf=3*W.lit_bufsize,W.level=J,W.strategy=H,W.method=G,Qt(B)}e=[new At(0,0,0,0,function(B,J){var G=65535;for(G>B.pending_buf_size-5&&(G=B.pending_buf_size-5);;){if(B.lookahead<=1){if(rt(B),B.lookahead===0&&J===r)return Q;if(B.lookahead===0)break}B.strstart+=B.lookahead,B.lookahead=0;var b=B.block_start+G;if((B.strstart===0||B.strstart>=b)&&(B.lookahead=B.strstart-b,B.strstart=b,T(B,!1),B.strm.avail_out===0)||B.strstart-B.block_start>=B.w_size-U&&(T(B,!1),B.strm.avail_out===0))return Q}return B.insert=0,J===l?(T(B,!0),B.strm.avail_out===0?K:N):(B.strstart>B.block_start&&(T(B,!1),B.strm.avail_out),Q)}),new At(4,4,8,4,gt),new At(4,5,16,8,gt),new At(4,6,32,32,gt),new At(4,4,16,16,nt),new At(8,16,32,32,nt),new At(8,16,128,128,nt),new At(8,32,128,256,nt),new At(32,128,258,1024,nt),new At(32,258,258,4096,nt)],t.deflateInit=function(B,J){return ft(B,J,u,15,8,0)},t.deflateInit2=ft,t.deflateReset=Qt,t.deflateResetKeep=ot,t.deflateSetHeader=function(B,J){return B&&B.state?B.state.wrap!==2?g:(B.state.gzhead=J,c):g},t.deflate=function(B,J){var G,b,k,H;if(!B||!B.state||5<J||J<0)return B?Y(B,g):g;if(b=B.state,!B.output||!B.input&&B.avail_in!==0||b.status===666&&J!==l)return Y(B,B.avail_out===0?-5:g);if(b.strm=B,G=b.last_flush,b.last_flush=J,b.status===F)if(b.wrap===2)B.adler=0,tt(b,31),tt(b,139),tt(b,8),b.gzhead?(tt(b,(b.gzhead.text?1:0)+(b.gzhead.hcrc?2:0)+(b.gzhead.extra?4:0)+(b.gzhead.name?8:0)+(b.gzhead.comment?16:0)),tt(b,255&b.gzhead.time),tt(b,b.gzhead.time>>8&255),tt(b,b.gzhead.time>>16&255),tt(b,b.gzhead.time>>24&255),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,255&b.gzhead.os),b.gzhead.extra&&b.gzhead.extra.length&&(tt(b,255&b.gzhead.extra.length),tt(b,b.gzhead.extra.length>>8&255)),b.gzhead.hcrc&&(B.adler=o(B.adler,b.pending_buf,b.pending,0)),b.gzindex=0,b.status=69):(tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,3),b.status=x);else{var z=u+(b.w_bits-8<<4)<<8;z|=(2<=b.strategy||b.level<2?0:b.level<6?1:b.level===6?2:3)<<6,b.strstart!==0&&(z|=32),z+=31-z%31,b.status=x,O(b,z),b.strstart!==0&&(O(b,B.adler>>>16),O(b,65535&B.adler)),B.adler=1}if(b.status===69)if(b.gzhead.extra){for(k=b.pending;b.gzindex<(65535&b.gzhead.extra.length)&&(b.pending!==b.pending_buf_size||(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending!==b.pending_buf_size));)tt(b,255&b.gzhead.extra[b.gzindex]),b.gzindex++;b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),b.gzindex===b.gzhead.extra.length&&(b.gzindex=0,b.status=73)}else b.status=73;if(b.status===73)if(b.gzhead.name){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.name.length?255&b.gzhead.name.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.gzindex=0,b.status=91)}else b.status=91;if(b.status===91)if(b.gzhead.comment){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.comment.length?255&b.gzhead.comment.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.status=103)}else b.status=103;if(b.status===103&&(b.gzhead.hcrc?(b.pending+2>b.pending_buf_size&&L(B),b.pending+2<=b.pending_buf_size&&(tt(b,255&B.adler),tt(b,B.adler>>8&255),B.adler=0,b.status=x)):b.status=x),b.pending!==0){if(L(B),B.avail_out===0)return b.last_flush=-1,c}else if(B.avail_in===0&&q(J)<=q(G)&&J!==l)return Y(B,-5);if(b.status===666&&B.avail_in!==0)return Y(B,-5);if(B.avail_in!==0||b.lookahead!==0||J!==r&&b.status!==666){var W=b.strategy===2?function(R,X){for(var et;;){if(R.lookahead===0&&(rt(R),R.lookahead===0)){if(X===r)return Q;break}if(R.match_length=0,et=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++,et&&(T(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,X===l?(T(R,!0),R.strm.avail_out===0?K:N):R.last_lit&&(T(R,!1),R.strm.avail_out===0)?Q:D}(b,J):b.strategy===3?function(R,X){for(var et,Z,it,ut,ht=R.window;;){if(R.lookahead<=S){if(rt(R),R.lookahead<=S&&X===r)return Q;if(R.lookahead===0)break}if(R.match_length=0,R.lookahead>=v&&0<R.strstart&&(Z=ht[it=R.strstart-1])===ht[++it]&&Z===ht[++it]&&Z===ht[++it]){ut=R.strstart+S;do;while(Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&it<ut);R.match_length=S-(ut-it),R.match_length>R.lookahead&&(R.match_length=R.lookahead)}if(R.match_length>=v?(et=s._tr_tally(R,1,R.match_length-v),R.lookahead-=R.match_length,R.strstart+=R.match_length,R.match_length=0):(et=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++),et&&(T(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,X===l?(T(R,!0),R.strm.avail_out===0?K:N):R.last_lit&&(T(R,!1),R.strm.avail_out===0)?Q:D}(b,J):e[b.level].func(b,J);if(W!==K&&W!==N||(b.status=666),W===Q||W===K)return B.avail_out===0&&(b.last_flush=-1),c;if(W===D&&(J===1?s._tr_align(b):J!==5&&(s._tr_stored_block(b,0,0,!1),J===3&&(_(b.head),b.lookahead===0&&(b.strstart=0,b.block_start=0,b.insert=0))),L(B),B.avail_out===0))return b.last_flush=-1,c}return J!==l?c:b.wrap<=0?1:(b.wrap===2?(tt(b,255&B.adler),tt(b,B.adler>>8&255),tt(b,B.adler>>16&255),tt(b,B.adler>>24&255),tt(b,255&B.total_in),tt(b,B.total_in>>8&255),tt(b,B.total_in>>16&255),tt(b,B.total_in>>24&255)):(O(b,B.adler>>>16),O(b,65535&B.adler)),L(B),0<b.wrap&&(b.wrap=-b.wrap),b.pending!==0?c:1)},t.deflateEnd=function(B){var J;return B&&B.state?(J=B.state.status)!==F&&J!==69&&J!==73&&J!==91&&J!==103&&J!==x&&J!==666?Y(B,g):(B.state=null,J===x?Y(B,-3):c):g},t.deflateSetDictionary=function(B,J){var G,b,k,H,z,W,R,X,et=J.length;if(!B||!B.state||(H=(G=B.state).wrap)===2||H===1&&G.status!==F||G.lookahead)return g;for(H===1&&(B.adler=n(B.adler,J,et,0)),G.wrap=0,et>=G.w_size&&(H===0&&(_(G.head),G.strstart=0,G.block_start=0,G.insert=0),X=new i.Buf8(G.w_size),i.arraySet(X,J,et-G.w_size,G.w_size,0),J=X,et=G.w_size),z=B.avail_in,W=B.next_in,R=B.input,B.avail_in=et,B.next_in=0,B.input=J,rt(G);G.lookahead>=v;){for(b=G.strstart,k=G.lookahead-(v-1);G.ins_h=(G.ins_h<<G.hash_shift^G.window[b+v-1])&G.hash_mask,G.prev[b&G.w_mask]=G.head[G.ins_h],G.head[G.ins_h]=b,b++,--k;);G.strstart=b,G.lookahead=v-1,rt(G)}return G.strstart+=G.lookahead,G.block_start=G.strstart,G.insert=G.lookahead,G.lookahead=0,G.match_length=G.prev_length=v-1,G.match_available=0,B.next_in=W,B.input=R,B.avail_in=z,G.wrap=H,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(h,A,t){"use strict";A.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(h,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,l,c,g,p,d,I,u,f,C,m,E,w,y,v,S,U,F,x,Q,D;s=e.state,n=e.next_in,Q=e.input,o=n+(e.avail_in-5),a=e.next_out,D=e.output,r=a-(i-e.avail_out),l=a+(e.avail_out-257),c=s.dmax,g=s.wsize,p=s.whave,d=s.wnext,I=s.window,u=s.hold,f=s.bits,C=s.lencode,m=s.distcode,E=(1<<s.lenbits)-1,w=(1<<s.distbits)-1;t:do{f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=C[u&E];e:for(;;){if(u>>>=v=y>>>24,f-=v,(v=y>>>16&255)===0)D[a++]=65535&y;else{if(!(16&v)){if(!(64&v)){y=C[(65535&y)+(u&(1<<v)-1)];continue e}if(32&v){s.mode=12;break t}e.msg="invalid literal/length code",s.mode=30;break t}S=65535&y,(v&=15)&&(f<v&&(u+=Q[n++]<<f,f+=8),S+=u&(1<<v)-1,u>>>=v,f-=v),f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=m[u&w];i:for(;;){if(u>>>=v=y>>>24,f-=v,!(16&(v=y>>>16&255))){if(!(64&v)){y=m[(65535&y)+(u&(1<<v)-1)];continue i}e.msg="invalid distance code",s.mode=30;break t}if(U=65535&y,f<(v&=15)&&(u+=Q[n++]<<f,(f+=8)<v&&(u+=Q[n++]<<f,f+=8)),c<(U+=u&(1<<v)-1)){e.msg="invalid distance too far back",s.mode=30;break t}if(u>>>=v,f-=v,(v=a-r)<U){if(p<(v=U-v)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break t}if(x=I,(F=0)===d){if(F+=g-v,v<S){for(S-=v;D[a++]=I[F++],--v;);F=a-U,x=D}}else if(d<v){if(F+=g+d-v,(v-=d)<S){for(S-=v;D[a++]=I[F++],--v;);if(F=0,d<S){for(S-=v=d;D[a++]=I[F++],--v;);F=a-U,x=D}}}else if(F+=d-v,v<S){for(S-=v;D[a++]=I[F++],--v;);F=a-U,x=D}for(;2<S;)D[a++]=x[F++],D[a++]=x[F++],D[a++]=x[F++],S-=3;S&&(D[a++]=x[F++],1<S&&(D[a++]=x[F++]))}else{for(F=a-U;D[a++]=D[F++],D[a++]=D[F++],D[a++]=D[F++],2<(S-=3););S&&(D[a++]=D[F++],1<S&&(D[a++]=D[F++]))}break}}break}}while(n<o&&a<l);n-=S=f>>3,u&=(1<<(f-=S<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<l?l-a+257:257-(a-l),s.hold=u,s.bits=f}},{}],49:[function(h,A,t){"use strict";var e=h("../utils/common"),i=h("./adler32"),s=h("./crc32"),n=h("./inffast"),o=h("./inftrees"),a=1,r=2,l=0,c=-2,g=1,p=852,d=592;function I(F){return(F>>>24&255)+(F>>>8&65280)+((65280&F)<<8)+((255&F)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(F){var x;return F&&F.state?(x=F.state,F.total_in=F.total_out=x.total=0,F.msg="",x.wrap&&(F.adler=1&x.wrap),x.mode=g,x.last=0,x.havedict=0,x.dmax=32768,x.head=null,x.hold=0,x.bits=0,x.lencode=x.lendyn=new e.Buf32(p),x.distcode=x.distdyn=new e.Buf32(d),x.sane=1,x.back=-1,l):c}function C(F){var x;return F&&F.state?((x=F.state).wsize=0,x.whave=0,x.wnext=0,f(F)):c}function m(F,x){var Q,D;return F&&F.state?(D=F.state,x<0?(Q=0,x=-x):(Q=1+(x>>4),x<48&&(x&=15)),x&&(x<8||15<x)?c:(D.window!==null&&D.wbits!==x&&(D.window=null),D.wrap=Q,D.wbits=x,C(F))):c}function E(F,x){var Q,D;return F?(D=new u,(F.state=D).window=null,(Q=m(F,x))!==l&&(F.state=null),Q):c}var w,y,v=!0;function S(F){if(v){var x;for(w=new e.Buf32(512),y=new e.Buf32(32),x=0;x<144;)F.lens[x++]=8;for(;x<256;)F.lens[x++]=9;for(;x<280;)F.lens[x++]=7;for(;x<288;)F.lens[x++]=8;for(o(a,F.lens,0,288,w,0,F.work,{bits:9}),x=0;x<32;)F.lens[x++]=5;o(r,F.lens,0,32,y,0,F.work,{bits:5}),v=!1}F.lencode=w,F.lenbits=9,F.distcode=y,F.distbits=5}function U(F,x,Q,D){var K,N=F.state;return N.window===null&&(N.wsize=1<<N.wbits,N.wnext=0,N.whave=0,N.window=new e.Buf8(N.wsize)),D>=N.wsize?(e.arraySet(N.window,x,Q-N.wsize,N.wsize,0),N.wnext=0,N.whave=N.wsize):(D<(K=N.wsize-N.wnext)&&(K=D),e.arraySet(N.window,x,Q-D,K,N.wnext),(D-=K)?(e.arraySet(N.window,x,Q-D,D,0),N.wnext=D,N.whave=N.wsize):(N.wnext+=K,N.wnext===N.wsize&&(N.wnext=0),N.whave<N.wsize&&(N.whave+=K))),0}t.inflateReset=C,t.inflateReset2=m,t.inflateResetKeep=f,t.inflateInit=function(F){return E(F,15)},t.inflateInit2=E,t.inflate=function(F,x){var Q,D,K,N,Y,q,_,L,T,tt,O,V,rt,gt,nt,At,lt,ot,Qt,ft,B,J,G,b,k=0,H=new e.Buf8(4),z=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!F||!F.state||!F.output||!F.input&&F.avail_in!==0)return c;(Q=F.state).mode===12&&(Q.mode=13),Y=F.next_out,K=F.output,_=F.avail_out,N=F.next_in,D=F.input,q=F.avail_in,L=Q.hold,T=Q.bits,tt=q,O=_,J=l;t:for(;;)switch(Q.mode){case g:if(Q.wrap===0){Q.mode=13;break}for(;T<16;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(2&Q.wrap&&L===35615){H[Q.check=0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0),T=L=0,Q.mode=2;break}if(Q.flags=0,Q.head&&(Q.head.done=!1),!(1&Q.wrap)||(((255&L)<<8)+(L>>8))%31){F.msg="incorrect header check",Q.mode=30;break}if((15&L)!=8){F.msg="unknown compression method",Q.mode=30;break}if(T-=4,B=8+(15&(L>>>=4)),Q.wbits===0)Q.wbits=B;else if(B>Q.wbits){F.msg="invalid window size",Q.mode=30;break}Q.dmax=1<<B,F.adler=Q.check=1,Q.mode=512&L?10:12,T=L=0;break;case 2:for(;T<16;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(Q.flags=L,(255&Q.flags)!=8){F.msg="unknown compression method",Q.mode=30;break}if(57344&Q.flags){F.msg="unknown header flags set",Q.mode=30;break}Q.head&&(Q.head.text=L>>8&1),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0)),T=L=0,Q.mode=3;case 3:for(;T<32;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}Q.head&&(Q.head.time=L),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,H[2]=L>>>16&255,H[3]=L>>>24&255,Q.check=s(Q.check,H,4,0)),T=L=0,Q.mode=4;case 4:for(;T<16;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}Q.head&&(Q.head.xflags=255&L,Q.head.os=L>>8),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0)),T=L=0,Q.mode=5;case 5:if(1024&Q.flags){for(;T<16;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}Q.length=L,Q.head&&(Q.head.extra_len=L),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0)),T=L=0}else Q.head&&(Q.head.extra=null);Q.mode=6;case 6:if(1024&Q.flags&&(q<(V=Q.length)&&(V=q),V&&(Q.head&&(B=Q.head.extra_len-Q.length,Q.head.extra||(Q.head.extra=new Array(Q.head.extra_len)),e.arraySet(Q.head.extra,D,N,V,B)),512&Q.flags&&(Q.check=s(Q.check,D,V,N)),q-=V,N+=V,Q.length-=V),Q.length))break t;Q.length=0,Q.mode=7;case 7:if(2048&Q.flags){if(q===0)break t;for(V=0;B=D[N+V++],Q.head&&B&&Q.length<65536&&(Q.head.name+=String.fromCharCode(B)),B&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,N)),q-=V,N+=V,B)break t}else Q.head&&(Q.head.name=null);Q.length=0,Q.mode=8;case 8:if(4096&Q.flags){if(q===0)break t;for(V=0;B=D[N+V++],Q.head&&B&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(B)),B&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,N)),q-=V,N+=V,B)break t}else Q.head&&(Q.head.comment=null);Q.mode=9;case 9:if(512&Q.flags){for(;T<16;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(L!==(65535&Q.check)){F.msg="header crc mismatch",Q.mode=30;break}T=L=0}Q.head&&(Q.head.hcrc=Q.flags>>9&1,Q.head.done=!0),F.adler=Q.check=0,Q.mode=12;break;case 10:for(;T<32;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}F.adler=Q.check=I(L),T=L=0,Q.mode=11;case 11:if(Q.havedict===0)return F.next_out=Y,F.avail_out=_,F.next_in=N,F.avail_in=q,Q.hold=L,Q.bits=T,2;F.adler=Q.check=1,Q.mode=12;case 12:if(x===5||x===6)break t;case 13:if(Q.last){L>>>=7&T,T-=7&T,Q.mode=27;break}for(;T<3;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}switch(Q.last=1&L,T-=1,3&(L>>>=1)){case 0:Q.mode=14;break;case 1:if(S(Q),Q.mode=20,x!==6)break;L>>>=2,T-=2;break t;case 2:Q.mode=17;break;case 3:F.msg="invalid block type",Q.mode=30}L>>>=2,T-=2;break;case 14:for(L>>>=7&T,T-=7&T;T<32;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if((65535&L)!=(L>>>16^65535)){F.msg="invalid stored block lengths",Q.mode=30;break}if(Q.length=65535&L,T=L=0,Q.mode=15,x===6)break t;case 15:Q.mode=16;case 16:if(V=Q.length){if(q<V&&(V=q),_<V&&(V=_),V===0)break t;e.arraySet(K,D,N,V,Y),q-=V,N+=V,_-=V,Y+=V,Q.length-=V;break}Q.mode=12;break;case 17:for(;T<14;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(Q.nlen=257+(31&L),L>>>=5,T-=5,Q.ndist=1+(31&L),L>>>=5,T-=5,Q.ncode=4+(15&L),L>>>=4,T-=4,286<Q.nlen||30<Q.ndist){F.msg="too many length or distance symbols",Q.mode=30;break}Q.have=0,Q.mode=18;case 18:for(;Q.have<Q.ncode;){for(;T<3;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}Q.lens[z[Q.have++]]=7&L,L>>>=3,T-=3}for(;Q.have<19;)Q.lens[z[Q.have++]]=0;if(Q.lencode=Q.lendyn,Q.lenbits=7,G={bits:Q.lenbits},J=o(0,Q.lens,0,19,Q.lencode,0,Q.work,G),Q.lenbits=G.bits,J){F.msg="invalid code lengths set",Q.mode=30;break}Q.have=0,Q.mode=19;case 19:for(;Q.have<Q.nlen+Q.ndist;){for(;At=(k=Q.lencode[L&(1<<Q.lenbits)-1])>>>16&255,lt=65535&k,!((nt=k>>>24)<=T);){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(lt<16)L>>>=nt,T-=nt,Q.lens[Q.have++]=lt;else{if(lt===16){for(b=nt+2;T<b;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(L>>>=nt,T-=nt,Q.have===0){F.msg="invalid bit length repeat",Q.mode=30;break}B=Q.lens[Q.have-1],V=3+(3&L),L>>>=2,T-=2}else if(lt===17){for(b=nt+3;T<b;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}T-=nt,B=0,V=3+(7&(L>>>=nt)),L>>>=3,T-=3}else{for(b=nt+7;T<b;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}T-=nt,B=0,V=11+(127&(L>>>=nt)),L>>>=7,T-=7}if(Q.have+V>Q.nlen+Q.ndist){F.msg="invalid bit length repeat",Q.mode=30;break}for(;V--;)Q.lens[Q.have++]=B}}if(Q.mode===30)break;if(Q.lens[256]===0){F.msg="invalid code -- missing end-of-block",Q.mode=30;break}if(Q.lenbits=9,G={bits:Q.lenbits},J=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,G),Q.lenbits=G.bits,J){F.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,G={bits:Q.distbits},J=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,G),Q.distbits=G.bits,J){F.msg="invalid distances set",Q.mode=30;break}if(Q.mode=20,x===6)break t;case 20:Q.mode=21;case 21:if(6<=q&&258<=_){F.next_out=Y,F.avail_out=_,F.next_in=N,F.avail_in=q,Q.hold=L,Q.bits=T,n(F,O),Y=F.next_out,K=F.output,_=F.avail_out,N=F.next_in,D=F.input,q=F.avail_in,L=Q.hold,T=Q.bits,Q.mode===12&&(Q.back=-1);break}for(Q.back=0;At=(k=Q.lencode[L&(1<<Q.lenbits)-1])>>>16&255,lt=65535&k,!((nt=k>>>24)<=T);){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(At&&!(240&At)){for(ot=nt,Qt=At,ft=lt;At=(k=Q.lencode[ft+((L&(1<<ot+Qt)-1)>>ot)])>>>16&255,lt=65535&k,!(ot+(nt=k>>>24)<=T);){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}L>>>=ot,T-=ot,Q.back+=ot}if(L>>>=nt,T-=nt,Q.back+=nt,Q.length=lt,At===0){Q.mode=26;break}if(32&At){Q.back=-1,Q.mode=12;break}if(64&At){F.msg="invalid literal/length code",Q.mode=30;break}Q.extra=15&At,Q.mode=22;case 22:if(Q.extra){for(b=Q.extra;T<b;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}Q.length+=L&(1<<Q.extra)-1,L>>>=Q.extra,T-=Q.extra,Q.back+=Q.extra}Q.was=Q.length,Q.mode=23;case 23:for(;At=(k=Q.distcode[L&(1<<Q.distbits)-1])>>>16&255,lt=65535&k,!((nt=k>>>24)<=T);){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(!(240&At)){for(ot=nt,Qt=At,ft=lt;At=(k=Q.distcode[ft+((L&(1<<ot+Qt)-1)>>ot)])>>>16&255,lt=65535&k,!(ot+(nt=k>>>24)<=T);){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}L>>>=ot,T-=ot,Q.back+=ot}if(L>>>=nt,T-=nt,Q.back+=nt,64&At){F.msg="invalid distance code",Q.mode=30;break}Q.offset=lt,Q.extra=15&At,Q.mode=24;case 24:if(Q.extra){for(b=Q.extra;T<b;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}Q.offset+=L&(1<<Q.extra)-1,L>>>=Q.extra,T-=Q.extra,Q.back+=Q.extra}if(Q.offset>Q.dmax){F.msg="invalid distance too far back",Q.mode=30;break}Q.mode=25;case 25:if(_===0)break t;if(V=O-_,Q.offset>V){if((V=Q.offset-V)>Q.whave&&Q.sane){F.msg="invalid distance too far back",Q.mode=30;break}rt=V>Q.wnext?(V-=Q.wnext,Q.wsize-V):Q.wnext-V,V>Q.length&&(V=Q.length),gt=Q.window}else gt=K,rt=Y-Q.offset,V=Q.length;for(_<V&&(V=_),_-=V,Q.length-=V;K[Y++]=gt[rt++],--V;);Q.length===0&&(Q.mode=21);break;case 26:if(_===0)break t;K[Y++]=Q.length,_--,Q.mode=21;break;case 27:if(Q.wrap){for(;T<32;){if(q===0)break t;q--,L|=D[N++]<<T,T+=8}if(O-=_,F.total_out+=O,Q.total+=O,O&&(F.adler=Q.check=Q.flags?s(Q.check,K,O,Y-O):i(Q.check,K,O,Y-O)),O=_,(Q.flags?L:I(L))!==Q.check){F.msg="incorrect data check",Q.mode=30;break}T=L=0}Q.mode=28;case 28:if(Q.wrap&&Q.flags){for(;T<32;){if(q===0)break t;q--,L+=D[N++]<<T,T+=8}if(L!==(4294967295&Q.total)){F.msg="incorrect length check",Q.mode=30;break}T=L=0}Q.mode=29;case 29:J=1;break t;case 30:J=-3;break t;case 31:return-4;case 32:default:return c}return F.next_out=Y,F.avail_out=_,F.next_in=N,F.avail_in=q,Q.hold=L,Q.bits=T,(Q.wsize||O!==F.avail_out&&Q.mode<30&&(Q.mode<27||x!==4))&&U(F,F.output,F.next_out,O-F.avail_out)?(Q.mode=31,-4):(tt-=F.avail_in,O-=F.avail_out,F.total_in+=tt,F.total_out+=O,Q.total+=O,Q.wrap&&O&&(F.adler=Q.check=Q.flags?s(Q.check,K,O,F.next_out-O):i(Q.check,K,O,F.next_out-O)),F.data_type=Q.bits+(Q.last?64:0)+(Q.mode===12?128:0)+(Q.mode===20||Q.mode===15?256:0),(tt==0&&O===0||x===4)&&J===l&&(J=-5),J)},t.inflateEnd=function(F){if(!F||!F.state)return c;var x=F.state;return x.window&&(x.window=null),F.state=null,l},t.inflateGetHeader=function(F,x){var Q;return F&&F.state&&2&(Q=F.state).wrap?((Q.head=x).done=!1,l):c},t.inflateSetDictionary=function(F,x){var Q,D=x.length;return F&&F.state?(Q=F.state).wrap!==0&&Q.mode!==11?c:Q.mode===11&&i(1,x,D,0)!==Q.check?-3:U(F,x,D,D)?(Q.mode=31,-4):(Q.havedict=1,l):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(h,A,t){"use strict";var e=h("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],s=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],o=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];A.exports=function(a,r,l,c,g,p,d,I){var u,f,C,m,E,w,y,v,S,U=I.bits,F=0,x=0,Q=0,D=0,K=0,N=0,Y=0,q=0,_=0,L=0,T=null,tt=0,O=new e.Buf16(16),V=new e.Buf16(16),rt=null,gt=0;for(F=0;F<=15;F++)O[F]=0;for(x=0;x<c;x++)O[r[l+x]]++;for(K=U,D=15;1<=D&&O[D]===0;D--);if(D<K&&(K=D),D===0)return g[p++]=20971520,g[p++]=20971520,I.bits=1,0;for(Q=1;Q<D&&O[Q]===0;Q++);for(K<Q&&(K=Q),F=q=1;F<=15;F++)if(q<<=1,(q-=O[F])<0)return-1;if(0<q&&(a===0||D!==1))return-1;for(V[1]=0,F=1;F<15;F++)V[F+1]=V[F]+O[F];for(x=0;x<c;x++)r[l+x]!==0&&(d[V[r[l+x]]++]=x);if(w=a===0?(T=rt=d,19):a===1?(T=i,tt-=257,rt=s,gt-=257,256):(T=n,rt=o,-1),F=Q,E=p,Y=x=L=0,C=-1,m=(_=1<<(N=K))-1,a===1&&852<_||a===2&&592<_)return 1;for(;;){for(y=F-Y,S=d[x]<w?(v=0,d[x]):d[x]>w?(v=rt[gt+d[x]],T[tt+d[x]]):(v=96,0),u=1<<F-Y,Q=f=1<<N;g[E+(L>>Y)+(f-=u)]=y<<24|v<<16|S|0,f!==0;);for(u=1<<F-1;L&u;)u>>=1;if(u!==0?(L&=u-1,L+=u):L=0,x++,--O[F]==0){if(F===D)break;F=r[l+d[x]]}if(K<F&&(L&m)!==C){for(Y===0&&(Y=K),E+=Q,q=1<<(N=F-Y);N+Y<D&&!((q-=O[N+Y])<=0);)N++,q<<=1;if(_+=1<<N,a===1&&852<_||a===2&&592<_)return 1;g[C=L&m]=K<<24|N<<16|E-p|0}}return L!==0&&(g[E+L]=F-Y<<24|64<<16|0),I.bits=K,0}},{"../utils/common":41}],51:[function(h,A,t){"use strict";A.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(h,A,t){"use strict";var e=h("../utils/common"),i=0,s=1;function n(k){for(var H=k.length;0<=--H;)k[H]=0}var o=0,a=29,r=256,l=r+1+a,c=30,g=19,p=2*l+1,d=15,I=16,u=7,f=256,C=16,m=17,E=18,w=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],y=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],v=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],U=new Array(2*(l+2));n(U);var F=new Array(2*c);n(F);var x=new Array(512);n(x);var Q=new Array(256);n(Q);var D=new Array(a);n(D);var K,N,Y,q=new Array(c);function _(k,H,z,W,R){this.static_tree=k,this.extra_bits=H,this.extra_base=z,this.elems=W,this.max_length=R,this.has_stree=k&&k.length}function L(k,H){this.dyn_tree=k,this.max_code=0,this.stat_desc=H}function T(k){return k<256?x[k]:x[256+(k>>>7)]}function tt(k,H){k.pending_buf[k.pending++]=255&H,k.pending_buf[k.pending++]=H>>>8&255}function O(k,H,z){k.bi_valid>I-z?(k.bi_buf|=H<<k.bi_valid&65535,tt(k,k.bi_buf),k.bi_buf=H>>I-k.bi_valid,k.bi_valid+=z-I):(k.bi_buf|=H<<k.bi_valid&65535,k.bi_valid+=z)}function V(k,H,z){O(k,z[2*H],z[2*H+1])}function rt(k,H){for(var z=0;z|=1&k,k>>>=1,z<<=1,0<--H;);return z>>>1}function gt(k,H,z){var W,R,X=new Array(d+1),et=0;for(W=1;W<=d;W++)X[W]=et=et+z[W-1]<<1;for(R=0;R<=H;R++){var Z=k[2*R+1];Z!==0&&(k[2*R]=rt(X[Z]++,Z))}}function nt(k){var H;for(H=0;H<l;H++)k.dyn_ltree[2*H]=0;for(H=0;H<c;H++)k.dyn_dtree[2*H]=0;for(H=0;H<g;H++)k.bl_tree[2*H]=0;k.dyn_ltree[2*f]=1,k.opt_len=k.static_len=0,k.last_lit=k.matches=0}function At(k){8<k.bi_valid?tt(k,k.bi_buf):0<k.bi_valid&&(k.pending_buf[k.pending++]=k.bi_buf),k.bi_buf=0,k.bi_valid=0}function lt(k,H,z,W){var R=2*H,X=2*z;return k[R]<k[X]||k[R]===k[X]&&W[H]<=W[z]}function ot(k,H,z){for(var W=k.heap[z],R=z<<1;R<=k.heap_len&&(R<k.heap_len&<(H,k.heap[R+1],k.heap[R],k.depth)&&R++,!lt(H,W,k.heap[R],k.depth));)k.heap[z]=k.heap[R],z=R,R<<=1;k.heap[z]=W}function Qt(k,H,z){var W,R,X,et,Z=0;if(k.last_lit!==0)for(;W=k.pending_buf[k.d_buf+2*Z]<<8|k.pending_buf[k.d_buf+2*Z+1],R=k.pending_buf[k.l_buf+Z],Z++,W===0?V(k,R,H):(V(k,(X=Q[R])+r+1,H),(et=w[X])!==0&&O(k,R-=D[X],et),V(k,X=T(--W),z),(et=y[X])!==0&&O(k,W-=q[X],et)),Z<k.last_lit;);V(k,f,H)}function ft(k,H){var z,W,R,X=H.dyn_tree,et=H.stat_desc.static_tree,Z=H.stat_desc.has_stree,it=H.stat_desc.elems,ut=-1;for(k.heap_len=0,k.heap_max=p,z=0;z<it;z++)X[2*z]!==0?(k.heap[++k.heap_len]=ut=z,k.depth[z]=0):X[2*z+1]=0;for(;k.heap_len<2;)X[2*(R=k.heap[++k.heap_len]=ut<2?++ut:0)]=1,k.depth[R]=0,k.opt_len--,Z&&(k.static_len-=et[2*R+1]);for(H.max_code=ut,z=k.heap_len>>1;1<=z;z--)ot(k,X,z);for(R=it;z=k.heap[1],k.heap[1]=k.heap[k.heap_len--],ot(k,X,1),W=k.heap[1],k.heap[--k.heap_max]=z,k.heap[--k.heap_max]=W,X[2*R]=X[2*z]+X[2*W],k.depth[R]=(k.depth[z]>=k.depth[W]?k.depth[z]:k.depth[W])+1,X[2*z+1]=X[2*W+1]=R,k.heap[1]=R++,ot(k,X,1),2<=k.heap_len;);k.heap[--k.heap_max]=k.heap[1],function(ht,Tt){var We,qt,$e,Et,vi,bs,zt=Tt.dyn_tree,Dn=Tt.max_code,Zo=Tt.stat_desc.static_tree,_o=Tt.stat_desc.has_stree,jo=Tt.stat_desc.extra_bits,bn=Tt.stat_desc.extra_base,Xe=Tt.stat_desc.max_length,Fi=0;for(Et=0;Et<=d;Et++)ht.bl_count[Et]=0;for(zt[2*ht.heap[ht.heap_max]+1]=0,We=ht.heap_max+1;We<p;We++)Xe<(Et=zt[2*zt[2*(qt=ht.heap[We])+1]+1]+1)&&(Et=Xe,Fi++),zt[2*qt+1]=Et,Dn<qt||(ht.bl_count[Et]++,vi=0,bn<=qt&&(vi=jo[qt-bn]),bs=zt[2*qt],ht.opt_len+=bs*(Et+vi),_o&&(ht.static_len+=bs*(Zo[2*qt+1]+vi)));if(Fi!==0){do{for(Et=Xe-1;ht.bl_count[Et]===0;)Et--;ht.bl_count[Et]--,ht.bl_count[Et+1]+=2,ht.bl_count[Xe]--,Fi-=2}while(0<Fi);for(Et=Xe;Et!==0;Et--)for(qt=ht.bl_count[Et];qt!==0;)Dn<($e=ht.heap[--We])||(zt[2*$e+1]!==Et&&(ht.opt_len+=(Et-zt[2*$e+1])*zt[2*$e],zt[2*$e+1]=Et),qt--)}}(k,H),gt(X,ut,k.bl_count)}function B(k,H,z){var W,R,X=-1,et=H[1],Z=0,it=7,ut=4;for(et===0&&(it=138,ut=3),H[2*(z+1)+1]=65535,W=0;W<=z;W++)R=et,et=H[2*(W+1)+1],++Z<it&&R===et||(Z<ut?k.bl_tree[2*R]+=Z:R!==0?(R!==X&&k.bl_tree[2*R]++,k.bl_tree[2*C]++):Z<=10?k.bl_tree[2*m]++:k.bl_tree[2*E]++,X=R,ut=(Z=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4))}function J(k,H,z){var W,R,X=-1,et=H[1],Z=0,it=7,ut=4;for(et===0&&(it=138,ut=3),W=0;W<=z;W++)if(R=et,et=H[2*(W+1)+1],!(++Z<it&&R===et)){if(Z<ut)for(;V(k,R,k.bl_tree),--Z!=0;);else R!==0?(R!==X&&(V(k,R,k.bl_tree),Z--),V(k,C,k.bl_tree),O(k,Z-3,2)):Z<=10?(V(k,m,k.bl_tree),O(k,Z-3,3)):(V(k,E,k.bl_tree),O(k,Z-11,7));X=R,ut=(Z=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4)}}n(q);var G=!1;function b(k,H,z,W){O(k,(o<<1)+(W?1:0),3),function(R,X,et,Z){At(R),Z&&(tt(R,et),tt(R,~et)),e.arraySet(R.pending_buf,R.window,X,et,R.pending),R.pending+=et}(k,H,z,!0)}t._tr_init=function(k){G||(function(){var H,z,W,R,X,et=new Array(d+1);for(R=W=0;R<a-1;R++)for(D[R]=W,H=0;H<1<<w[R];H++)Q[W++]=R;for(Q[W-1]=R,R=X=0;R<16;R++)for(q[R]=X,H=0;H<1<<y[R];H++)x[X++]=R;for(X>>=7;R<c;R++)for(q[R]=X<<7,H=0;H<1<<y[R]-7;H++)x[256+X++]=R;for(z=0;z<=d;z++)et[z]=0;for(H=0;H<=143;)U[2*H+1]=8,H++,et[8]++;for(;H<=255;)U[2*H+1]=9,H++,et[9]++;for(;H<=279;)U[2*H+1]=7,H++,et[7]++;for(;H<=287;)U[2*H+1]=8,H++,et[8]++;for(gt(U,l+1,et),H=0;H<c;H++)F[2*H+1]=5,F[2*H]=rt(H,5);K=new _(U,w,r+1,l,d),N=new _(F,y,0,c,d),Y=new _(new Array(0),v,0,g,u)}(),G=!0),k.l_desc=new L(k.dyn_ltree,K),k.d_desc=new L(k.dyn_dtree,N),k.bl_desc=new L(k.bl_tree,Y),k.bi_buf=0,k.bi_valid=0,nt(k)},t._tr_stored_block=b,t._tr_flush_block=function(k,H,z,W){var R,X,et=0;0<k.level?(k.strm.data_type===2&&(k.strm.data_type=function(Z){var it,ut=4093624447;for(it=0;it<=31;it++,ut>>>=1)if(1&ut&&Z.dyn_ltree[2*it]!==0)return i;if(Z.dyn_ltree[18]!==0||Z.dyn_ltree[20]!==0||Z.dyn_ltree[26]!==0)return s;for(it=32;it<r;it++)if(Z.dyn_ltree[2*it]!==0)return s;return i}(k)),ft(k,k.l_desc),ft(k,k.d_desc),et=function(Z){var it;for(B(Z,Z.dyn_ltree,Z.l_desc.max_code),B(Z,Z.dyn_dtree,Z.d_desc.max_code),ft(Z,Z.bl_desc),it=g-1;3<=it&&Z.bl_tree[2*S[it]+1]===0;it--);return Z.opt_len+=3*(it+1)+5+5+4,it}(k),R=k.opt_len+3+7>>>3,(X=k.static_len+3+7>>>3)<=R&&(R=X)):R=X=z+5,z+4<=R&&H!==-1?b(k,H,z,W):k.strategy===4||X===R?(O(k,2+(W?1:0),3),Qt(k,U,F)):(O(k,4+(W?1:0),3),function(Z,it,ut,ht){var Tt;for(O(Z,it-257,5),O(Z,ut-1,5),O(Z,ht-4,4),Tt=0;Tt<ht;Tt++)O(Z,Z.bl_tree[2*S[Tt]+1],3);J(Z,Z.dyn_ltree,it-1),J(Z,Z.dyn_dtree,ut-1)}(k,k.l_desc.max_code+1,k.d_desc.max_code+1,et+1),Qt(k,k.dyn_ltree,k.dyn_dtree)),nt(k),W&&At(k)},t._tr_tally=function(k,H,z){return k.pending_buf[k.d_buf+2*k.last_lit]=H>>>8&255,k.pending_buf[k.d_buf+2*k.last_lit+1]=255&H,k.pending_buf[k.l_buf+k.last_lit]=255&z,k.last_lit++,H===0?k.dyn_ltree[2*z]++:(k.matches++,H--,k.dyn_ltree[2*(Q[z]+r+1)]++,k.dyn_dtree[2*T(H)]++),k.last_lit===k.lit_bufsize-1},t._tr_align=function(k){O(k,2,3),V(k,f,U),function(H){H.bi_valid===16?(tt(H,H.bi_buf),H.bi_buf=0,H.bi_valid=0):8<=H.bi_valid&&(H.pending_buf[H.pending++]=255&H.bi_buf,H.bi_buf>>=8,H.bi_valid-=8)}(k)}},{"../utils/common":41}],53:[function(h,A,t){"use strict";A.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(h,A,t){(function(e){(function(i,s){"use strict";if(!i.setImmediate){var n,o,a,r,l=1,c={},g=!1,p=i.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(i);d=d&&d.setTimeout?d:i,n={}.toString.call(i.process)==="[object process]"?function(C){process.nextTick(function(){u(C)})}:function(){if(i.postMessage&&!i.importScripts){var C=!0,m=i.onmessage;return i.onmessage=function(){C=!1},i.postMessage("","*"),i.onmessage=m,C}}()?(r="setImmediate$"+Math.random()+"$",i.addEventListener?i.addEventListener("message",f,!1):i.attachEvent("onmessage",f),function(C){i.postMessage(r+C,"*")}):i.MessageChannel?((a=new MessageChannel).port1.onmessage=function(C){u(C.data)},function(C){a.port2.postMessage(C)}):p&&"onreadystatechange"in p.createElement("script")?(o=p.documentElement,function(C){var m=p.createElement("script");m.onreadystatechange=function(){u(C),m.onreadystatechange=null,o.removeChild(m),m=null},o.appendChild(m)}):function(C){setTimeout(u,0,C)},d.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var m=new Array(arguments.length-1),E=0;E<m.length;E++)m[E]=arguments[E+1];var w={callback:C,args:m};return c[l]=w,n(l),l++},d.clearImmediate=I}function I(C){delete c[C]}function u(C){if(g)setTimeout(u,0,C);else{var m=c[C];if(m){g=!0;try{(function(E){var w=E.callback,y=E.args;switch(y.length){case 0:w();break;case 1:w(y[0]);break;case 2:w(y[0],y[1]);break;case 3:w(y[0],y[1],y[2]);break;default:w.apply(s,y)}})(m)}finally{I(C),g=!1}}}}function f(C){C.source===i&&typeof C.data=="string"&&C.data.indexOf(r)===0&&u(+C.data.slice(r.length))}})(typeof self>"u"?e===void 0?this:e:self)}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})});var Qr={};Si(Qr,{default:()=>Ds});module.exports=aa(Qr);var $=require("obsidian");yt();var Dt=require("obsidian");var mt=require("obsidian");yt();function bi(h){let A=(h.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function Vt(h,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(h))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(h))}}function Wt(h,A){let t=bi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Pn(h,A,!0);case"us":return Vt(h,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Vt(h,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Vt(h,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Vt(h,{...t,dateStyle:"medium",timeStyle:"short"})}}function Tn(h,A){let t=bi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Pn(h,A,!1);case"us":return Vt(h,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Vt(h,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Vt(h,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(h).getFullYear()===e.getFullYear();return Vt(h,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Un(h,A){let t=bi(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return Vt(h,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Pn(h,A,t){let e=bi(A),i=new Intl.DateTimeFormat("en-CA",{...e,year:"numeric",month:"2-digit",day:"2-digit",...t?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:{}}).formatToParts(new Date(h)),s=o=>i.find(a=>a.type===o)?.value??"",n=`${s("year")}-${s("month")}-${s("day")}`;return t?`${n} ${s("hour")}:${s("minute")}`:n}function ye(h,A,t){let e=h.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(A>99?"99+":String(A))}var li={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},Ti=class extends mt.ItemView{constructor(t,e){super(t);this.plugin=e;this.activePanel="pinned";this.taskFilter="all";this.taskAssignFilter="all";this.taskFolderFilter="all";this.expanded=new Set;this.renderTimer=null;this.sharedAuthorFilter="all";this.sharedContribOnly=!1}setActivePanel(t){this.activePanel=t,this.containerEl.isConnected&&this.render()}getViewType(){return ie}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()===ct&&this.scheduleRender()}))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},80))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-panels-root");let e=t.createDiv({cls:"stashpad-panels-globals"}),i=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(i.createSpan({cls:"stashpad-panels-global-btn-icon"}),"search"),i.createSpan({cls:"stashpad-panels-global-btn-text",text:"Search"}),i.onclick=()=>this.openSearchFromPanel();let s=e.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(s.createSpan({cls:"stashpad-panels-global-btn-icon"}),"folder-tree"),s.createSpan({cls:"stashpad-panels-global-btn-text",text:"Folder Switcher"}),s.onclick=()=>this.plugin.openFolderPicker();let n=e.createDiv({cls:"stashpad-panels-globals-row"}),o=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(o.createSpan({cls:"stashpad-panels-global-btn-icon"}),"scroll-text"),o.createSpan({cls:"stashpad-panels-global-btn-text",text:"Log"}),o.onclick=()=>this.openLogFromPanel();let a=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,mt.setIcon)(a.createSpan({cls:"stashpad-panels-global-btn-icon"}),"bell"),a.createSpan({cls:"stashpad-panels-global-btn-text",text:"Notifications"}),a.onclick=()=>this.openNotificationsFromPanel();let r=t.createDiv({cls:"stashpad-panels-bar"});for(let c of Object.keys(li)){let g=li[c],p=r.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,mt.setIcon)(p.createSpan({cls:"stashpad-panels-bar-btn-icon"}),g.icon),p.createSpan({cls:"stashpad-panels-bar-btn-text",text:g.label}),this.activePanel===c&&p.addClass("is-active"),p.onclick=()=>{this.activePanel!==c&&(this.activePanel=c,this.render())}}let l=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(l):this.activePanel==="shared"?this.renderSharedPanel(l):this.activePanel==="tasks"&&this.renderTasksPanel(l)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new mt.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinnedPanel(t){let e=t.createDiv({cls:"stashpad-panel-pinned"});(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"&&e.addClass("is-flat");let i=e.createDiv({cls:"stashpad-pinned-headrow"}),s=i.createEl("button",{cls:"stashpad-pinned-row stashpad-pinned-home"}),n=s.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(n,"home"),s.createSpan({cls:"stashpad-pinned-label",text:"Home"}),s.onclick=()=>this.openHomeFromPanel();let o=i.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-pinned-opts"});(0,mt.setIcon)(o,"list"),o.setAttr("aria-label","Pinned view options"),o.onclick=p=>{p.stopPropagation(),this.openPinnedOptionsMenu(p)};let a=this.plugin.listPinnedNotes();if(a.length===0){e.createDiv({cls:"stashpad-pinned-empty"}).setText("No pinned notes yet \u2014 right-click a note and choose \u201CPin to sidebar.\u201D");return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"){a.forEach((p,d)=>this.renderPinnedRow(e,p,d));return}let l=new Map;a.forEach((p,d)=>{let I=l.get(p.folder);I||(I=[],l.set(p.folder,I)),I.push({pin:p,idx:d})});let c=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,g=Array.from(l.keys());c&&l.has(c)&&(g.splice(g.indexOf(c),1),g.unshift(c));for(let p of g){let d=p.split("/").pop()||p,I=e.createDiv({cls:"stashpad-pinned-group-header"});p===c&&I.addClass("is-active-folder"),I.createSpan({cls:"stashpad-pinned-group-name",text:d});let u=l.get(p)??[];for(let{pin:f,idx:C}of u)this.renderPinnedRow(e,f,C)}}renderPinnedRow(t,e,i){let s=this.findFileFor(e);if(!s)return;let n=this.app.metadataCache.getFileCache(s)?.frontmatter??{},o=this.titleFromFile(s),a=typeof n.color=="string"?n.color:null,r=n.completed===!0,l=this.childrenOf(e.folder,e.id).length,c=l>0,g=this.expanded.has(`${e.folder}|${e.id}`),p=t.createDiv({cls:"stashpad-pinned-row"});a&&p.addClass("has-color"),r&&p.addClass("is-completed"),p.draggable=!0,p.dataset.pinIdx=String(i),p.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=p.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;p.toggleClass("drop-before",E),p.toggleClass("drop-after",!E)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",C=>{C.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let E=p.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?i:i+1)});let d=p.createSpan({cls:"stashpad-pinned-toggle"});c&&(ye(d,l,g),d.onclick=C=>{C.stopPropagation();let m=`${e.folder}|${e.id}`;this.expanded.has(m)?this.expanded.delete(m):this.expanded.add(m),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(I,c?"folder-tree":"file-text"),a&&(I.style.color=a);let u=p.createSpan({cls:"stashpad-pinned-label",text:o});u.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(p.createSpan({cls:"stashpad-pinned-folder",text:f}),p.oncontextmenu=C=>{C.preventDefault();let m=new mt.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},c&&g){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(C,e.folder,e.id,1)}}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],l;!a&&!r?l=Date.now():a?r?l=(a.pinnedAt+r.pinnedAt)/2:l=a.pinnedAt+1e3:l=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=l})}catch(c){console.warn("[Stashpad] pin reorder failed",c)}this.render()}renderPinnedSubtree(t,e,i,s){let n=this.childrenOf(e,i);for(let o of n){let a=this.app.metadataCache.getFileCache(o)?.frontmatter??{},r=typeof a.id=="string"?a.id:null;if(!r)continue;let l=typeof a.color=="string"?a.color:null,c=a.completed===!0,g=this.childrenOf(e,r).length,p=g>0,d=this.expanded.has(`${e}|${r}`),I=t.createDiv({cls:"stashpad-pinned-subrow"});c&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});p&&(ye(u,g,d),u.onclick=m=>{m.stopPropagation();let E=`${e}|${r}`;this.expanded.has(E)?this.expanded.delete(E):this.expanded.add(E),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(f,"file-text"),l&&(f.style.color=l);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:r}),p&&d&&this.renderPinnedSubtree(t,e,r,s+1)}}findFileFor(t){for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==t.folder)continue;if(this.app.metadataCache.getFileCache(e)?.frontmatter?.id===t.id)return e}return null}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===M&&(a==null||a===M)){if(o.id===M)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.created??"",l=a?.created??"";return r.localeCompare(l)}),i}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new mt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Ht(),Ai));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(M)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===ct)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(ct);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()===ct?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let c of s){let g=c.authorId;g&&!n.has(g)&&n.set(g,c.authorDisplay||g)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(c,g,p)=>{let d=o.createEl("button",{cls:"stashpad-shared-chip",text:c});return g&&d.addClass("is-active"),d.onclick=p,d};if(a("All",this.sharedAuthorFilter==="all",()=>{this.sharedAuthorFilter="all",this.render()}),a("Mine",this.sharedAuthorFilter==="mine",()=>{this.sharedAuthorFilter="mine",this.render()}),a("Others",this.sharedAuthorFilter==="others",()=>{this.sharedAuthorFilter="others",this.render()}),n.size>1){let c=o.createEl("select",{cls:"stashpad-shared-author-select"}),g=c.createEl("option",{text:"Any author"});g.value="__any__";for(let[d,I]of n){let u=c.createEl("option",{text:I});u.value=d}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=p,c.onchange=()=>{let d=c.value;d==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=d,this.render()}}let r=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&r.addClass("is-active"),r.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let l=s.filter(c=>{if(this.sharedContribOnly&&c.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return c.authorId===i;case"others":return c.authorId!==i;default:return c.authorId===this.sharedAuthorFilter}});if(l.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let c of l){let g=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),p=g.createSpan({cls:"stashpad-pinned-icon"});(0,mt.setIcon)(p,"users"),c.color&&(p.style.color=c.color);let d=g.createSpan({cls:"stashpad-pinned-label",text:c.title});d.onclick=()=>this.openSharedFromPanel(c.folder,c.id);let I=c.folder.split("/").pop()||c.folder;g.createSpan({cls:"stashpad-pinned-folder",text:I}),c.authorDisplay&&g.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===i?`you \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:`by ${c.authorDisplay}${c.contributorCount>0?` \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),i=new Set(e),s=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};r.id===M&&s.set(a,this.extractAuthorId(r.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a)||a.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof r.id!="string"||r.id===M)continue;let l=this.extractAuthorId(r.author),c=Array.isArray(r.contributors)?r.contributors.filter(m=>typeof m=="string"):[],g=s.get(a)??null;if(!(c.length>0||g===t&&(l!==null&&l!==t)))continue;let f=this.titleFromFile(o),C=typeof r.color=="string"?r.color:null;n.push({file:o,folder:a,id:r.id,title:f,color:C,authorId:l,authorDisplay:this.extractAuthorDisplay(r.author)||(l??""),contributorCount:c.length})}return n.sort((o,a)=>{let r=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},l=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},c=r.modified??r.created??"";return(l.modified??l.created??"").localeCompare(c)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.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=N=>!!s&&N.assignedTo.some(Y=>Y.id===s),o=N=>{let Y=this.taskAssignFilter;if(Y.startsWith("person:")){let q=Y.slice(7);return N.assignedTo.some(_=>_.id===q)}switch(Y){case"mine":return n(N);case"others":return N.assignedTo.length>0&&!n(N);case"byme":return!!s&&N.assignedBy?.id===s;case"unassigned":return N.assignedTo.length===0;default:return!0}},a=new Map;for(let N of i){for(let Y of N.assignedTo)Y.id!==s&&a.set(Y.id,Y.name);N.assignedBy&&N.assignedBy.id!==s&&a.set(N.assignedBy.id,N.assignedBy.name)}let r=[...a.entries()].map(([N,Y])=>({id:N,name:Y})).sort((N,Y)=>N.name.localeCompare(Y.name)),l=e.createDiv({cls:"stashpad-task-assign-bar"});l.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let c=l.createEl("select",{cls:"stashpad-task-assign-select"}),g=N=>{let Y={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return N.startsWith("person:")?a.get(N.slice(7))??"Person":Y[N]??N},p=N=>{let Y=c.createEl("option",{text:g(N),value:N});this.taskAssignFilter===N&&(Y.selected=!0)};for(let N of["all","mine","others","byme","unassigned"])p(N);if(r.length>0){let N=c.createEl("optgroup");N.setAttr("label","By person");for(let Y of r){let q=N.createEl("option",{text:Y.name,value:`person:${Y.id}`});this.taskAssignFilter===`person:${Y.id}`&&(q.selected=!0)}}c.onchange=()=>{this.taskAssignFilter=c.value,this.render()};let d=[...new Set(i.map(N=>N.folder))].sort((N,Y)=>N.localeCompare(Y));this.taskFolderFilter!=="all"&&!d.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let I=e.createDiv({cls:"stashpad-task-assign-bar"});I.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let u=I.createEl("select",{cls:"stashpad-task-assign-select"}),f=u.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let N of d){let Y=u.createEl("option",{text:N.split("/").pop()||N,value:N});this.taskFolderFilter===N&&(Y.selected=!0)}u.onchange=()=>{this.taskFolderFilter=u.value,this.render()};let C=N=>this.taskFolderFilter==="all"||N.folder===this.taskFolderFilter,m=i.filter(N=>o(N)&&C(N));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let E=new Date;E.setHours(0,0,0,0);let w=E.getTime(),y=w+24*60*60*1e3,v={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let N of m){if(N.completed){v.completed.push(N);continue}if(N.due==null){v.nodate.push(N);continue}N.due<w?v.overdue.push(N):N.due<y?v.today.push(N):v.upcoming.push(N)}let S=(N,Y)=>N.due==null&&Y.due==null?N.title.localeCompare(Y.title):N.due==null?1:Y.due==null?-1:N.due-Y.due,U=[{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"}],F=e.createDiv({cls:"stashpad-task-filters"}),x=m.length,Q=(N,Y,q)=>{let _=F.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===N&&_.addClass("is-active"),_.createSpan({cls:"stashpad-task-filter-label",text:Y}),_.createSpan({cls:"stashpad-task-filter-count",text:String(q)}),_.onclick=()=>{this.taskFilter=N,this.render()}};Q("all","All",x),Q("overdue","Overdue",v.overdue.length),Q("today","Today",v.today.length),Q("upcoming","Upcoming",v.upcoming.length),Q("nodate","No date",v.nodate.length),Q("completed","Done",v.completed.length);let D=this.taskFilter==="all"?U:U.filter(N=>N.key===this.taskFilter),K=!1;for(let N of D){let Y=v[N.key];if(Y.length!==0){if(K=!0,Y.sort(N.key==="completed"?(q,_)=>S(_,q):S),this.taskFilter==="all"){let q=e.createDiv({cls:`stashpad-task-section-header is-${N.key}`});(0,mt.setIcon)(q.createSpan({cls:"stashpad-task-section-icon"}),N.icon),q.createSpan({cls:"stashpad-task-section-name",text:N.label}),q.createSpan({cls:"stashpad-task-section-count",text:String(Y.length)})}for(let q of Y)this.renderTaskRow(e,q,N.key==="today")}}if(!K&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${D[0]?.label??this.taskFilter}".`);return}K||e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks to show.")}renderTaskRow(t,e,i){let s=t.createDiv({cls:"stashpad-pinned-row stashpad-task-row"});e.color&&s.addClass("has-color"),e.completed&&s.addClass("is-completed");let n=s.createSpan({cls:"stashpad-pinned-icon stashpad-task-checkbox"});(0,mt.setIcon)(n,e.completed?"check-square":"square"),e.color&&(n.style.color=e.color),n.title=e.completed?"Mark not done":"Mark done",n.onclick=a=>{a.stopPropagation(),this.toggleTaskCompleted(e)};let o=s.createSpan({cls:"stashpad-pinned-label",text:e.title});if(o.onclick=()=>this.openTaskFromPanel(e.folder,e.id),s.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let a=s.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,i)});e.due<Date.now()&&!e.completed&&a.addClass("is-overdue")}else e.dueRaw&&s.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let a=(this.plugin.settings.authorId??"").trim(),r=s.createSpan({cls:"stashpad-task-assignees"});for(let l of e.assignedTo){let c=r.createSpan({cls:"stashpad-task-assignee"});a&&l.id===a&&c.addClass("is-me"),c.setText(this.initials(l.name)),c.title=a&&l.id===a?`${l.name} (you)`:l.name}}s.oncontextmenu=a=>{a.preventDefault();let r=new mt.Menu;r.addItem(l=>l.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),r.showAtMouseEvent(a)}}formatDueShort(t,e){return e?Un(t,this.plugin.settings):Tn(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 mt.Notice(`Couldn't update task: ${e.message}`);return}this.scheduleRender()}initials(t){let e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}collectTasks(){let t=this.plugin.discoverStashpadFolders(),e=new Set(t),i=[];for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a||a===M)continue;let r=o.completed===!0,l=De(o,"task")||o.task===!0||o.completed!==void 0,c=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,g=null;if(c){let p=Date.parse(c);Number.isNaN(p)||(g=p)}!l&&!r&&g==null&&!c||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:l,completed:r,due:g,dueRaw:c,color:typeof o.color=="string"?o.color:null,assignedTo:me(o),assignedBy:ne(o.assignedBy)})}return i}};async function Ui(h){let A=h.workspace.getLeavesOfType(ie);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new mt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:ie,active:!0}),h.workspace.revealLeaf(t)}var No=require("obsidian");yt();var j=require("obsidian");di();var Li=require("obsidian");yt();var Te=class extends Li.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),i=o=>e.every(a=>o.toLowerCase().includes(a)),s=[],n=o=>{if(!(o.path!=="/"&&Ze.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof Li.TFolder&&n(a)}};return n(this.app.vault.getRoot()),s.slice(0,100)}renderSuggestion(t,e){e.setText(t.path)}selectSuggestion(t){this.setValue(t.path),this.inputEl.dispatchEvent(new Event("input",{bubbles:!0})),this.close()}};yt();Ht();var ve=require("obsidian"),Os={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."}},ua={info:4e3,success:4e3,warning:6e3,error:1e4},Vn=5e3,Ji=class{constructor(A){this.app=A;this.history=[];this.nextId=1;this.historyLimit=Vn;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??ua[t];return new ve.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:Vn,this.history=this.applyLimit(this.history),this.emit()}applyLimit(A){return this.historyLimit<=0||A.length<=this.historyLimit?A:A.slice(A.length-this.historyLimit)}pushHistory(A){this.history.push(A),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let A of this.changeListeners)try{A()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(A,t){let e=document.createDocumentFragment(),i=document.createElement("div");i.className=`stashpad-notice stashpad-notice-${t}`;let s=document.createElement("div");s.className="stashpad-notice-message";let n=A.message.split(/(`[^`\n]+`)/);for(let o of n)if(o.length>1&&o.startsWith("`")&&o.endsWith("`")){let a=document.createElement("code");a.textContent=o.slice(1,-1),s.appendChild(a)}else o.length>0&&s.appendChild(document.createTextNode(o));if(i.appendChild(s),A.actions&&A.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of A.actions){let r=document.createElement("button");r.className="stashpad-notice-action",r.textContent=a.label,r.addEventListener("click",l=>{if(l.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(c=>console.warn("[Stashpad] notification action failed",c)),!a.keepOpen){let c=r.closest(".notice");c&&c.parentElement&&c.parentElement.removeChild(c)}}),o.appendChild(r)}i.appendChild(o)}return e.appendChild(i),e}};function qi(h,A,t){let e=h.vault.getAbstractFileByPath(A);if(!(e instanceof ve.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=h.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;h.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=ve.Platform.isMacOS?"Finder":ve.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=h.vault.adapter?.getFullPath?.(A);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var Ks=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function hi(h){if(!h)return"(none)";let A=h.replace(/\bMod\b/g,Ks?"Cmd":"Ctrl");return Ks&&(A=A.replace(/\bAlt\b/g,"Option")),A}function Wn(h,A,t={allowSingleKey:!0}){let e=h.placeholder,i=h.value;h.placeholder="Press a key\u2026 (Backspace to cancel)",h.value="",h.classList.add("is-recording");let s=!1,n=()=>{h.placeholder=e,h.classList.remove("is-recording"),s||(h.value=i),h.removeEventListener("keydown",o,!0),h.removeEventListener("blur",a)},o=r=>{if(r.key==="Control"||r.key==="Shift"||r.key==="Alt"||r.key==="Meta"||r.key==="OS")return;let l=!!r.code&&(/^Key[A-Z]$/.test(r.code)||/^Digit\d$/.test(r.code));if((r.key==="Dead"||r.key==="Process"||r.key==="Unidentified")&&!l)return;if(r.preventDefault(),r.stopPropagation(),r.key==="Backspace"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.shiftKey){n();return}let c=[];Ks?(r.metaKey&&c.push("Mod"),r.ctrlKey&&c.push("Ctrl")):r.ctrlKey&&c.push("Mod"),r.altKey&&c.push("Alt"),r.shiftKey&&c.push("Shift");let g=fa(r.key,r.code);if(!g||c.length===0&&!t.allowSingleKey)return;c.push(g);let p=c.join("+");s=!0,n(),A(p)},a=()=>n();return h.addEventListener("keydown",o,!0),h.addEventListener("blur",a),n}function fa(h,A){if(!h)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return h.length===1?h.toUpperCase():h}Me();Kt();function Fe(h,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(l){try{r(e.next(l))}catch(c){n(c)}}function a(l){try{r(e.throw(l))}catch(c){n(c)}}function r(l){l.done?s(l.value):i(l.value).then(o,a)}r((e=e.apply(h,A||[])).next())})}var Ct=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 Fe(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(A())}finally{t()}})}},Ys;function Ca(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var $s=Ca(),zs=(Ys=$s.Buffer)!==null&&Ys!==void 0?Ys:null,ma=$s.TextEncoder?new $s.TextEncoder:null;function to(h,A){return(h&15)+(h>>6|h>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function eo(h,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;h[e]=to(A.charCodeAt(i),A.charCodeAt(i+1))}}function Ba(h,A){if(h.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==to(h.charCodeAt(e),h.charCodeAt(e+1)))return!1}return!0}var $n=87,Xn=48;function Xs(h,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;h[e++]=s>9?s+$n:s+Xn,s=A[i]&15,h[e++]=s>9?s+$n:s+Xn}return String.fromCharCode.apply(null,h)}var Zt=zs!==null?h=>{if(typeof h=="string"){let A=zs.from(h,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(zs.isBuffer(h))return new Uint8Array(h.buffer,h.byteOffset,h.length);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")}:h=>{if(typeof h=="string")return ma.encode(h);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")},Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pi=new Uint8Array(256);for(let h=0;h<Rt.length;h++)pi[Rt.charCodeAt(h)]=h;function Zn(h,A=!0){let t=h.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(h[n]<<16&16711680)+(h[n+1]<<8&65280)+(h[n+2]&255),a=Rt.charAt(o>>18&63)+Rt.charAt(o>>12&63)+Rt.charAt(o>>6&63)+Rt.charAt(o&63);i.push(a)}if(e===1){let n=h[t-1],o=Rt.charAt(n>>2),a=Rt.charAt(n<<4&63);i.push(`${o}${a}`),A&&i.push("==")}else if(e===2){let n=(h[t-2]<<8)+h[t-1],o=Rt.charAt(n>>10),a=Rt.charAt(n>>4&63),r=Rt.charAt(n<<2&63);i.push(`${o}${a}${r}`),A&&i.push("=")}return i.join("")}function Qa(h){let A=Math.floor(h.length*.75),t=h.length;return h[t-1]==="="&&(A-=1,h[t-2]==="="&&(A-=1)),A}function Ea(h){let A=Qa(h),t=h.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=pi[h.charCodeAt(s)],o=pi[h.charCodeAt(s+1)],a=pi[h.charCodeAt(s+2)],r=pi[h.charCodeAt(s+3)];e[i]=n<<2|o>>4,i+=1,e[i]=(o&15)<<4|a>>2,i+=1,e[i]=(a&3)<<6|r&63,i+=1}return e}var Oi=16*1024,gi=4,ya=new Ct,Vs=new Map;function io(h,A){return Fe(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,v=0)=>{e.set(y,v)},n=()=>e,o=()=>t.exports,a=y=>{t.exports.Hash_SetMemorySize(y);let v=t.exports.Hash_GetBuffer(),S=t.exports.memory.buffer;e=new Uint8Array(S,v,y)},r=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),l=ya.dispatch(()=>Fe(this,void 0,void 0,function*(){if(!Vs.has(h.name)){let v=Ea(h.data),S=WebAssembly.compile(v);Vs.set(h.name,S)}let y=yield Vs.get(h.name);t=yield WebAssembly.instantiate(y,{})})),c=()=>Fe(this,void 0,void 0,function*(){t||(yield l);let y=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,y,Oi)}),g=(y=null)=>{i=!0,t.exports.Hash_Init(y)},p=y=>{let v=0;for(;v<y.length;){let S=y.subarray(v,v+Oi);v+=S.length,e.set(S),t.exports.Hash_Update(S.length)}},d=y=>{if(!i)throw new Error("update() called before init()");let v=Zt(y);p(v)},I=new Uint8Array(A*2),u=(y,v=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(v),y==="binary"?e.slice(0,A):Xs(I,e,A)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),v=r(),S=t.exports.memory.buffer,U=new Uint8Array(S,y,v),F=new Uint8Array(gi+v);return eo(F,h.hash),F.set(U,gi),F},C=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let v=t.exports.Hash_GetState(),S=r(),U=gi+S,F=t.exports.memory.buffer;if(y.length!==U)throw new Error(`Bad state length (expected ${U} bytes, got ${y.length})`);if(!Ba(h.hash,y.subarray(0,gi)))throw new Error("This state was written by an incompatible hash implementation");let x=y.subarray(gi);new Uint8Array(F,v,S).set(x),i=!0},m=y=>typeof y=="string"?y.length<Oi/4:y.byteLength<Oi,E=m;switch(h.name){case"argon2":case"scrypt":E=()=>!0;break;case"blake2b":case"blake2s":E=(y,v)=>v<=512&&m(y);break;case"blake3":E=(y,v)=>v===0&&m(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":E=()=>!1;break}let w=(y,v=null,S=null)=>{if(!E(y,v))return g(v),d(y),u("hex",S);let U=Zt(y);return e.set(U),t.exports.Hash_Calculate(U.length,v,S),Xs(I,e,A)};return yield c(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:g,update:d,digest:u,save:f,load:C,calculate:w,hashLength:A}})}var Wr=new Ct;var wa="argon2",va="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",Fa="e4cdc523",ka={name:wa,data:va,hash:Fa},Sa="blake2b",Da="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=",ba="c6f286e6",Na={name:Sa,data:Da,hash:ba},$r=new Ct;function _n(h){return!Number.isInteger(h)||h<8||h>512||h%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function xa(h,A){return h|A<<16}function Zs(h=512,A=null){if(_n(h))return Promise.reject(_n(h));let t=null,e=h;if(A!==null){if(t=Zt(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=xa(h,t.length)}let i=h/8;return io(Na,i).then(s=>{e>512&&s.writeMemory(t),s.init(e);let n={init:e>512?()=>(s.writeMemory(t),s.init(e),n):()=>(s.init(e),n),update:o=>(s.update(o),n),digest:o=>s.digest(o),save:()=>s.save(),load:o=>(s.load(o),n),blockSize:128,digestSize:i};return n})}function Ma(h,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${Zn(h,!1)}$${Zn(t,!1)}`}var jn=new DataView(new ArrayBuffer(4));function Xt(h){return jn.setInt32(0,h,!0),new Uint8Array(jn.buffer)}function Ws(h,A,t){return Fe(this,void 0,void 0,function*(){if(t<=64){let a=yield Zs(t*8);return a.update(Xt(t)),a.update(A),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);h.init(),h.update(Xt(t)),h.update(A);let s=h.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)h.init(),h.update(s),s=h.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=h,o.init()):o=yield Zs(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function Ha(h){switch(h){case"d":return 0;case"i":return 1;default:return 2}}function Ta(h){return Fe(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=h,s=Zt(h.password),n=Zt(h.salt),o=19,a=Ha(h.hashType),{memorySize:r}=h,l=Zt((A=h.secret)!==null&&A!==void 0?A:""),[c,g]=yield Promise.all([io(ka,1024),Zs(512)]);c.setMemorySize(r*1024+1024);let p=new Uint8Array(24),d=new DataView(p.buffer);d.setInt32(0,t,!0),d.setInt32(4,i,!0),d.setInt32(8,r,!0),d.setInt32(12,e,!0),d.setInt32(16,o,!0),d.setInt32(20,a,!0),c.writeMemory(p,r*1024),g.init(),g.update(p),g.update(Xt(s.length)),g.update(s),g.update(Xt(n.length)),g.update(n),g.update(Xt(l.length)),g.update(l),g.update(Xt(0));let u=Math.floor(r/(t*4))*4,f=new Uint8Array(72),C=g.digest("binary");f.set(C);for(let w=0;w<t;w++){f.set(Xt(0),64),f.set(Xt(w),68);let y=w*u,v=yield Ws(g,f,1024);c.writeMemory(v,y*1024),y+=1,f.set(Xt(1),64),v=yield Ws(g,f,1024),c.writeMemory(v,y*1024)}let m=new Uint8Array(1024);eo(m,c.calculate(new Uint8Array([]),r));let E=yield Ws(g,m,i);if(h.outputType==="hex"){let w=new Uint8Array(i*2);return Xs(w,E,i)}return h.outputType==="encoded"?Ma(n,h,E):E})}var Ua=h=>{var A;if(!h||typeof h!="object")throw new Error("Invalid options parameter. It requires an object.");if(!h.password)throw new Error("Password must be specified");if(h.password=Zt(h.password),h.password.length<1)throw new Error("Password must be specified");if(!h.salt)throw new Error("Salt must be specified");if(h.salt=Zt(h.salt),h.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(h.secret=Zt((A=h.secret)!==null&&A!==void 0?A:""),!Number.isInteger(h.iterations)||h.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(h.parallelism)||h.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(h.hashLength)||h.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(h.memorySize))throw new Error("Memory size should be specified.");if(h.memorySize<8*h.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(h.outputType===void 0&&(h.outputType="hex"),!["hex","binary","encoded"].includes(h.outputType))throw new Error(`Insupported output type ${h.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function _s(h){return Fe(this,void 0,void 0,function*(){return Ua(h),Ta(Object.assign(Object.assign({},h),{hashType:"id"}))})}var Xr=new Ct;var Zr=new Ct;var _r=new Ct;var jr=new Ct;var tA=new Uint8Array(8);var eA=new Ct;var iA=new Ct;var sA=new Ct;var nA=new Ct;var oA=new Ct;var aA=new Ct;var rA=new Ct;var AA=new Ct;var lA=new Ct;var cA=new Ct;var dA=new Ct;var hA=new Uint8Array(8);var gA=new Ct;var pA=new Uint8Array(8);var IA=new Ct;var uA=new Uint8Array(8);var fA=new Ct;var CA=new Ct;var mA=new Ct;Ht();var Gt=new Uint8Array([83,84,65,83,72,69,78,67]),en=2,sn=1,nn=2,oo=3,Pa=32,Ue=12,js=32,Ra=6e5,Ga=47104,La=3,Ja=1,wt=h=>h;function Lt(h){if(h.length<Gt.length+1)return!1;for(let A=0;A<Gt.length;A++)if(h[A]!==Gt[A])return!1;return!0}function so(h,A,t){h[A]=t>>>24&255,h[A+1]=t>>>16&255,h[A+2]=t>>>8&255,h[A+3]=t&255}function no(h,A){return h[A]*16777216+(h[A+1]<<16)+(h[A+2]<<8)+h[A+3]}async function tn(h,A,t){if(t.id===nn)return await _s({password:h,salt:A,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:js,outputType:"binary"});if(t.id===sn){let e=await crypto.subtle.importKey("raw",wt(new TextEncoder().encode(h)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:wt(A),iterations:t.a,hash:"SHA-256"},e,js*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function Ki(h){return crypto.subtle.importKey("raw",wt(h),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var ao={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function ui(h,A){let t=crypto.getRandomValues(new Uint8Array(Pa)),e=crypto.getRandomValues(new Uint8Array(Ue)),i,s,n;try{i={id:nn,a:Ga,b:La,c:Ja},n=await tn(A,t,i),s="argon2id"}catch(c){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",c),i={id:sn,a:Ra,b:0,c:0},n=await tn(A,t,i),s="pbkdf2"}let o=ro(i,t,e),a=await Ki(n),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(e),additionalData:wt(o)},a,wt(h))),l=new Uint8Array(o.length+r.length);return l.set(o,0),l.set(r,o.length),{data:l,kdf:s}}var Ii=null;async function Yi(){if(Ii!==null)return Ii;try{await _s({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Ii=!0}catch{Ii=!1}return Ii}function ro(h,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++]=en,e[i++]=h.id,so(e,i,h.a),i+=4,so(e,i,h.b),i+=4,e[i++]=h.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function Pe(h,A){if(!Lt(h))throw new Error("Not an encrypted Stashpad file.");let t=h[Gt.length];if(t===1)return qa(h,A);if(t!==en)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Gt.length+1,i={id:h[e++],a:0,b:0,c:0};if(i.a=no(h,e),e+=4,i.b=no(h,e),e+=4,i.c=h[e++],i.id===nn){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===sn&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=h[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=h.slice(e,e+s);e+=s;let o=h.slice(e,e+Ue);e+=Ue;let a=h.slice(0,e),r=h.slice(e),l=await tn(A,n,i),c=await Ki(l),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(o),additionalData:wt(a)},c,wt(r));return new Uint8Array(g)}async function qa(h,A){let t=Gt.length+1,e=h.slice(t,t+16);t+=16;let i=h.slice(t,t+12);t+=12;let s=h.slice(t),n=await crypto.subtle.importKey("raw",wt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:wt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(i)},o,wt(s));return new Uint8Array(a)}async function fi(h,A){if(A.length!==js)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Ue)),i=ro({id:oo,a:0,b:0,c:0},new Uint8Array(0),t),s=await Ki(A),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(t),additionalData:wt(i)},s,wt(h))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function oe(h,A){if(!Lt(h))throw new Error("Not an encrypted Stashpad file.");let t=h[Gt.length];if(t!==en)throw new Error(`Unsupported encrypted version (${t}).`);let e=Gt.length+1;if(h[e++]!==oo)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=h[e++];e+=s;let n=h.slice(e,e+Ue);e+=Ue;let o=h.slice(0,e),a=h.slice(e),r=await Ki(A),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(n),additionalData:wt(o)},r,wt(a));return new Uint8Array(l)}async function Re(h,A,t={}){if(!Lt(A))return A;if(t.secretId){let i=h.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Pe(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new ii(h,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Pe(A,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}var Ci="stashpad-vault-encryption";function mi(){return{wrappedKey:null,kdf:null}}function Ao(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function on(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}var Oa=32,zi=class{constructor(A,t,e,i=()=>0){this.app=A;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.idleTimer=null}argonProbe(){return Yi()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}isRemembered(){try{return!!this.secretStore()?.getSecret(Ci)}catch{return!1}}async remember(A){try{await this.secretStore()?.setSecret(Ci,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(Ci):await A.setSecret(Ci,"")}catch(t){console.warn("[Stashpad] couldn't clear keychain",t)}}async tryAutoUnlock(){if(!this.isConfigured()||this.isUnlocked())return this.isUnlocked();let A=null;try{A=this.secretStore()?.getSecret(Ci)??null}catch{A=null}return A?this.unlock(A):!1}isConfigured(){return!!this.load().wrappedKey}isUnlocked(){return this.sessionKey!==null}kdf(){return this.load().kdf}async setup(A,t=!1){if(this.isConfigured())throw new Error("Encryption is already set up.");if(!A)throw new Error("Password required.");let e=crypto.getRandomValues(new Uint8Array(Oa)),i=await ui(e,A);await this.save({wrappedKey:Ao(i.data),kdf:i.kdf}),this.sessionKey=e,t?await this.remember(A):await this.forgetKeychain(),this.armIdle()}async unlock(A,t=!1){let e=this.load();if(!e.wrappedKey)throw new Error("Encryption is not set up.");try{let i=await Pe(on(e.wrappedKey),A);return this.sessionKey=i,t&&await this.remember(A),this.armIdle(),!0}catch{return!1}}async changePassword(A,t,e=!1){let i=this.load();if(!i.wrappedKey)throw new Error("Encryption is not set up.");if(!t)throw new Error("New password required.");let s;try{s=await Pe(on(i.wrappedKey),A)}catch{return!1}let n=await ui(s,t);return await this.save({wrappedKey:Ao(n.data),kdf:n.kdf}),this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=s,e?await this.remember(t):await this.forgetKeychain(),this.armIdle(),!0}async verifyPassword(A){let t=this.load();if(!t.wrappedKey)return!1;try{return(await Pe(on(t.wrappedKey),A)).fill(0),!0}catch{return!1}}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null,this.clearIdle()}async clear(){this.lock(),await this.forgetKeychain(),await this.save(mi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}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 An=Ns(Vi()),Wi=require("obsidian");Kt();yt();var ae="stash",go=1;function co(h){let t=(h.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var rn=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Bi(h,A){let t=new An.default,e=Ka([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await h.vault.read(o.file),r=a,l=po(a);for(let c of l){let g=h.metadataCache.getFirstLinkpathDest(c,o.file.path);if(!g){s.push(`Missing attachment "${c}" in ${o.file.path}`);continue}let p=g.name;i.has(p)||i.set(p,await h.vault.readBinary(g)),r=Ya(r,c,p)}r=Wa(r,h,o.file.path),t.file(`notes/${o.file.name}`,r)}for(let[o,a]of i)t.file(`attachments/${o}`,a);let n={stashSchema:go,exportedAt:new Date().toISOString(),sourceFolder:A.sourceFolder,noteCount:e.length,rootIds:A.rootNotes.map(o=>o.id)};return t.file("manifest.json",JSON.stringify(n,null,2)),s.length&&t.file("warnings.txt",s.join(` -`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function _t(h,A,t,e,i={}){let s=await An.default.loadAsync(A),n=s.file("manifest.json");if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(await n.async("string"));if(typeof o.stashSchema!="number"||o.stashSchema>go)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await ho(h,t);let a=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("notes/")&&v.name.endsWith(".md")),r=[];for(let v of a){let S=await v.async("string"),{fm:U,body:F}=Mt(S),x=co(v.name.slice(6))||`${U.id||"imported-"+Bt(4)}.md`;r.push({originalName:x,fm:U,body:F})}let l=new Map,c=0;for(let v of r){let S=v.fm.id;S&&(e.has(S)||l.has(S)?(l.set(S,`${S}-${Bt(4)}-Imported`),c++):l.set(S,S))}let g=new Date().toISOString(),p=[],d=`${t}/_attachments`,I=0,u=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("attachments/")),f=new Map,C=null;if(i.dedupeExisting){C=new Map;for(let v of h.vault.getFiles())C.has(v.name)||C.set(v.name,v.path)}let m=(v,S)=>{if(v.length!==S.length)return!1;for(let U=0;U<v.length;U++)if(v[U]!==S[U])return!1;return!0},E=!1;for(let v of u){let S=co(v.name.slice(12));if(!S)continue;let U=new Uint8Array(await v.async("arraybuffer")),F=[],x=C?.get(S);x&&F.push(x);let Q=`${d}/${S}`;await h.vault.adapter.exists(Q)&&F.push(Q);let D=null;for(let N of F)try{if(m(new Uint8Array(await h.vault.adapter.readBinary(N)),U)){D=N;break}}catch{}if(D){f.set(S,D);continue}let K=Q;for(let N=1;await h.vault.adapter.exists(K);N++)K=`${d}/${za(S,N)}`;f.set(S,K),E||(await ho(h,d),E=!0),await h.vault.createBinary(K,U.buffer),I++}let w=0;for(let v of r){let S=v.fm.id;if(!S){p.push(`Skipped ${v.originalName} \u2014 no id in frontmatter`);continue}let U=l.get(S),F=v.fm.parent??null,x=F;F&&F!==M&&l.has(F)?x=l.get(F):F&&F!==M&&!l.has(F)&&(x=e.has(F)?F:M);let Q=Va(v.body,f,d),D={...v.fm,id:U,parent:x,import_date:g};Array.isArray(D.attachments)&&(D.attachments=D.attachments.map(q=>{let _=uo(Ce(q));return Ot(f.get(_)??`${d}/${_}`)}));let K=re(D,Q),N=U===S?v.originalName:Xa(v.originalName,S,U),Y=`${t}/${N}`;await h.vault.adapter.exists(Y)&&(N=`${N.replace(/\.md$/,"")}-${Bt(4)}.md`,Y=`${t}/${N}`),await h.vault.create(Y,K),w++}let y;if(o.colorAliases&&typeof o.colorAliases=="object"){let v={};for(let[S,U]of Object.entries(o.colorAliases)){let F=String(S).trim().toLowerCase(),x=String(U??"").trim();/^#([0-9a-f]{6})$/.test(F)&&x&&(v[F]=x.slice(0,60))}Object.keys(v).length&&(y=v)}return{notesWritten:w,attachmentsWritten:I,collisionsRenamed:c,warnings:p,colorAliases:y}}function Ka(h){let A=new Set,t=[];for(let e of h)A.has(e.id)||(A.add(e.id),t.push(e));return t}function po(h){let A=new Set,t;for(rn.lastIndex=0;(t=rn.exec(h))!==null;)A.add(t[1]);return[...A]}async function Io(h,A){let t=await h.vault.read(A),e=[],i=new Set;for(let s of po(t)){let n=h.metadataCache.getFirstLinkpathDest(s,A.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Ya(h,A,t){return h.replace(new RegExp(`!\\[\\[${$a(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function za(h,A){let t=h.lastIndexOf(".");return t>0?`${h.slice(0,t)}-${A}${h.slice(t)}`:`${h}-${A}`}function Va(h,A,t){return h.replace(rn,(e,i,s)=>{if(i.includes("/"))return e;let n=A.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Wa(h,A,t){let e=Mt(h);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return h;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:uo(n)}),s={...e.fm,attachments:i};return re(s,e.body)}function $a(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uo(h){let A=h.lastIndexOf("/");return A<0?h:h.slice(A+1)}function Xa(h,A,t){return h.includes(A)?h.replace(A,t):h.replace(/\.md$/,`-${t}.md`)}function Mt(h){if(!h.startsWith("---"))return{fm:{},body:h};let A=h.indexOf(` ----`,3);if(A<0)return{fm:{},body:h};let t=h.slice(3,A).replace(/^\n/,""),e=h.slice(A+4),i={};try{i=(0,Wi.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` +`}function Gi(h,A){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let i=t.createEl("ul");i.style.margin="0 0 8px 0",i.style.paddingLeft="18px",i.createEl("li",{text:`${A.indexed.length} indexed`}),i.createEl("li",{text:`${A.nonIndex.length+A.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.style.padding="2px 10px",s.style.fontSize="var(--font-ui-smaller)";let n;return s.onclick=async o=>{if(o.stopPropagation(),A.previewPath){let a=h.vault.getAbstractFileByPath(A.previewPath);a instanceof kt.TFile&&await h.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new kt.Notice(t,0),n}var kt,Yn,hi,gi=Ie(()=>{"use strict";kt=require("obsidian");Kt();He();yt();Yn=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;hi=class extends kt.Modal{constructor(t,e,i,s,n){super(t);this.plugin=e;this.settings=i;this.indexedCount=s;this.onBuild=n;this.LARGE_BUILD=50;this.previewRan=!1;this.previewPath=null}onOpen(){let{contentEl:t,titleEl:e}=this,i=!this.settings.jdIndexHasBuilt,s=this.indexedCount>this.LARGE_BUILD;e.setText(i?"Build JD index \u2014 first time?":"Build JD index");let n=this.settings.jdIndexStashpadFolder,o=t.createEl("p"),a=`${this.indexedCount} note${this.indexedCount===1?"":"s"}`;i?(o.appendText(`Stashpad is about to create ${a} (plus synthetic parents as needed) inside "`),o.createEl("code",{text:n}),o.appendText('". Existing notes with the same '),o.createEl("code",{text:"jdPrefix"}),o.appendText(" are updated, never deleted \u2014 but if the prefix detection picks up notes you didn't mean to index, you'll end up with a lot of unwanted notes."),t.createEl("p").setText("Running Preview first writes a single Markdown file showing exactly what would be built (and what wouldn't), so you can sanity-check before committing.")):s?(o.appendText(`You're about to create ${this.indexedCount} notes in "`),o.createEl("code",{text:n}),o.appendText(`". That's a big batch \u2014 if anything looks off, Preview the single-file output first.`)):(o.appendText('Build the JD index into "'),o.createEl("code",{text:n}),o.appendText(`"? Stashpad will create / update ${a}. Existing notes with matching `),o.createEl("code",{text:"jdPrefix"}),o.appendText(" are updated in place.")),this.previewRan&&this.previewPath&&t.createEl("p",{cls:"setting-item-description"}).setText(`\u2713 Preview written to home note (${this.previewPath}). Open it before building if you haven't.`);let r=new kt.Setting(t);(i||s)&&r.addButton(l=>{l.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),l.setCta(),l.onClick(async()=>{try{let c=await Ri(this.app,this.plugin,this.settings);if(c.error==="no-dest"){new kt.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(c.error==="no-home"){new kt.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first.`,7e3),this.close();return}this.previewRan=!0,this.previewPath=c.previewPath,Gi(this.app,c),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(c){new kt.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}),r.addButton(l=>{l.setButtonText(i?"Build anyway":"Build"),!i&&!s&&l.setCta(),l.onClick(async()=>{this.close(),await this.onBuild()})}),r.addButton(l=>{l.setButtonText("Cancel"),l.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var Wi=oa((ho,An)=>{(function(h){typeof ho=="object"&&typeof An<"u"?An.exports=h():typeof define=="function"&&define.amd?define([],h):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=h()})(function(){return function h(A,t,e){function i(o,a){if(!t[o]){if(!A[o]){var r=typeof require=="function"&&require;if(!a&&r)return r(o,!0);if(s)return s(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[o]={exports:{}};A[o][0].call(c.exports,function(g){var p=A[o][1][g];return i(p||g)},c,c.exports,h,A,t,e)}return t[o].exports}for(var s=typeof require=="function"&&require,n=0;n<e.length;n++)i(e[n]);return i}({1:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,l,c,g,p,d=[],I=0,u=n.length,f=u,C=e.getTypeOf(n)!=="string";I<n.length;)f=u-I,r=C?(o=n[I++],a=I<u?n[I++]:0,I<u?n[I++]:0):(o=n.charCodeAt(I++),a=I<u?n.charCodeAt(I++):0,I<u?n.charCodeAt(I++):0),l=o>>2,c=(3&o)<<4|a>>4,g=1<f?(15&a)<<2|r>>6:64,p=2<f?63&r:64,d.push(s.charAt(l)+s.charAt(c)+s.charAt(g)+s.charAt(p));return d.join("")},t.decode=function(n){var o,a,r,l,c,g,p=0,d=0,I="data:";if(n.substr(0,I.length)===I)throw new Error("Invalid base64 input, it looks like a data url.");var u,f=3*(n=n.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(n.charAt(n.length-1)===s.charAt(64)&&f--,n.charAt(n.length-2)===s.charAt(64)&&f--,f%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=i.uint8array?new Uint8Array(0|f):new Array(0|f);p<n.length;)o=s.indexOf(n.charAt(p++))<<2|(l=s.indexOf(n.charAt(p++)))>>4,a=(15&l)<<4|(c=s.indexOf(n.charAt(p++)))>>2,r=(3&c)<<6|(g=s.indexOf(n.charAt(p++))),u[d++]=o,c!==64&&(u[d++]=a),g!==64&&(u[d++]=r);return u}},{"./support":30,"./utils":32}],2:[function(h,A,t){"use strict";var e=h("./external"),i=h("./stream/DataWorker"),s=h("./stream/Crc32Probe"),n=h("./stream/DataLengthProbe");function o(a,r,l,c,g){this.compressedSize=a,this.uncompressedSize=r,this.crc32=l,this.compression=c,this.compressedContent=g}o.prototype={getContentWorker:function(){var a=new i(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),r=this;return a.on("end",function(){if(this.streamInfo.data_length!==r.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new i(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(a,r,l){return a.pipe(new s).pipe(new n("uncompressedSize")).pipe(r.compressWorker(l)).pipe(new n("compressedSize")).withStreamInfo("compression",r)},A.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(h,A,t){"use strict";var e=h("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=h("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(h,A,t){"use strict";var e=h("./utils"),i=function(){for(var s,n=[],o=0;o<256;o++){s=o;for(var a=0;a<8;a++)s=1&s?3988292384^s>>>1:s>>>1;n[o]=s}return n}();A.exports=function(s,n){return s!==void 0&&s.length?e.getTypeOf(s)!=="string"?function(o,a,r,l){var c=i,g=l+r;o^=-1;for(var p=l;p<g;p++)o=o>>>8^c[255&(o^a[p])];return-1^o}(0|n,s,s.length,0):function(o,a,r,l){var c=i,g=l+r;o^=-1;for(var p=l;p<g;p++)o=o>>>8^c[255&(o^a.charCodeAt(p))];return-1^o}(0|n,s,s.length,0):0}},{"./utils":32}],5:[function(h,A,t){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},{}],6:[function(h,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:h("lie"),A.exports={Promise:e}},{lie:37}],7:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=h("pako"),s=h("./utils"),n=h("./stream/GenericWorker"),o=e?"uint8array":"array";function a(r,l){n.call(this,"FlateWorker/"+r),this._pako=null,this._pakoAction=r,this._pakoOptions=l,this.meta={}}t.magic="\b\0",s.inherits(a,n),a.prototype.processChunk=function(r){this.meta=r.meta,this._pako===null&&this._createPako(),this._pako.push(s.transformTo(o,r.data),!1)},a.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},a.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},a.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var r=this;this._pako.onData=function(l){r.push({data:l,meta:r.meta})}},t.compressWorker=function(r){return new a("Deflate",r)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(h,A,t){"use strict";function e(c,g){var p,d="";for(p=0;p<g;p++)d+=String.fromCharCode(255&c),c>>>=8;return d}function i(c,g,p,d,I,u){var f,C,m=c.file,E=c.compression,w=u!==o.utf8encode,y=s.transformTo("string",u(m.name)),v=s.transformTo("string",o.utf8encode(m.name)),S=m.comment,M=s.transformTo("string",u(S)),F=s.transformTo("string",o.utf8encode(S)),N=v.length!==m.name.length,Q=F.length!==S.length,D="",K="",x="",Y=m.dir,q=m.date,_={crc32:0,compressedSize:0,uncompressedSize:0};g&&!p||(_.crc32=c.crc32,_.compressedSize=c.compressedSize,_.uncompressedSize=c.uncompressedSize);var L=0;g&&(L|=8),w||!N&&!Q||(L|=2048);var U=0,tt=0;Y&&(U|=16),I==="UNIX"?(tt=798,U|=function(V,rt){var gt=V;return V||(gt=rt?16893:33204),(65535>)<<16}(m.unixPermissions,Y)):(tt=20,U|=function(V){return 63&(V||0)}(m.dosPermissions)),f=q.getUTCHours(),f<<=6,f|=q.getUTCMinutes(),f<<=5,f|=q.getUTCSeconds()/2,C=q.getUTCFullYear()-1980,C<<=4,C|=q.getUTCMonth()+1,C<<=5,C|=q.getUTCDate(),N&&(K=e(1,1)+e(a(y),4)+v,D+="up"+e(K.length,2)+K),Q&&(x=e(1,1)+e(a(M),4)+F,D+="uc"+e(x.length,2)+x);var O="";return O+=` +\0`,O+=e(L,2),O+=E.magic,O+=e(f,2),O+=e(C,2),O+=e(_.crc32,4),O+=e(_.compressedSize,4),O+=e(_.uncompressedSize,4),O+=e(y.length,2),O+=e(D.length,2),{fileRecord:r.LOCAL_FILE_HEADER+O+y+D,dirRecord:r.CENTRAL_FILE_HEADER+e(tt,2)+O+e(M.length,2)+"\0\0\0\0"+e(U,4)+e(d,4)+y+D+M}}var s=h("../utils"),n=h("../stream/GenericWorker"),o=h("../utf8"),a=h("../crc32"),r=h("../signature");function l(c,g,p,d){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=p,this.encodeFileName=d,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(l,n),l.prototype.push=function(c){var g=c.meta.percent||0,p=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(c):(this.bytesWritten+=c.data.length,n.prototype.push.call(this,{data:c.data,meta:{currentFile:this.currentFile,percent:p?(g+100*(p-d-1))/p:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var g=this.streamFiles&&!c.file.dir;if(g){var p=i(c,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:p.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var g=this.streamFiles&&!c.file.dir,p=i(c,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(p.dirRecord),g)this.push({data:function(d){return r.DATA_DESCRIPTOR+e(d.crc32,4)+e(d.compressedSize,4)+e(d.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:p.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,g=0;g<this.dirRecords.length;g++)this.push({data:this.dirRecords[g],meta:{percent:100}});var p=this.bytesWritten-c,d=function(I,u,f,C,m){var E=s.transformTo("string",m(C));return r.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(I,2)+e(I,2)+e(u,4)+e(f,4)+e(E.length,2)+E}(this.dirRecords.length,p,c,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},l.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},l.prototype.registerPrevious=function(c){this._sources.push(c);var g=this;return c.on("data",function(p){g.processChunk(p)}),c.on("end",function(){g.closedSource(g.previous.streamInfo),g._sources.length?g.prepareNextSource():g.end()}),c.on("error",function(p){g.error(p)}),this},l.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},l.prototype.error=function(c){var g=this._sources;if(!n.prototype.error.call(this,c))return!1;for(var p=0;p<g.length;p++)try{g[p].error(c)}catch{}return!0},l.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,g=0;g<c.length;g++)c[g].lock()},A.exports=l},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(h,A,t){"use strict";var e=h("../compressions"),i=h("./ZipFileWorker");t.generateWorker=function(s,n,o){var a=new i(n.streamFiles,o,n.platform,n.encodeFileName),r=0;try{s.forEach(function(l,c){r++;var g=function(u,f){var C=u||f,m=e[C];if(!m)throw new Error(C+" is not a valid compression method !");return m}(c.options.compression,n.compression),p=c.options.compressionOptions||n.compressionOptions||{},d=c.dir,I=c.date;c._compressWorker(g,p).withStreamInfo("file",{name:l,dir:d,date:I,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(a)}),a.entriesCount=r}catch(l){a.error(l)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(h,A,t){"use strict";function e(){if(!(this instanceof e))return new e;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var i=new e;for(var s in this)typeof this[s]!="function"&&(i[s]=this[s]);return i}}(e.prototype=h("./object")).loadAsync=h("./load"),e.support=h("./support"),e.defaults=h("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=h("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./external"),s=h("./utf8"),n=h("./zipEntries"),o=h("./stream/Crc32Probe"),a=h("./nodejsUtils");function r(l){return new i.Promise(function(c,g){var p=l.decompressed.getContentWorker().pipe(new o);p.on("error",function(d){g(d)}).on("end",function(){p.streamInfo.crc32!==l.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}A.exports=function(l,c){var g=this;return c=e.extend(c||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),a.isNode&&a.isStream(l)?i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",l,!0,c.optimizedBinaryString,c.base64).then(function(p){var d=new n(c);return d.load(p),d}).then(function(p){var d=[i.Promise.resolve(p)],I=p.files;if(c.checkCRC32)for(var u=0;u<I.length;u++)d.push(r(I[u]));return i.Promise.all(d)}).then(function(p){for(var d=p.shift(),I=d.files,u=0;u<I.length;u++){var f=I[u],C=f.fileNameStr,m=e.resolve(f.fileNameStr);g.file(m,f.decompressed,{binary:!0,optimizedBinaryString:!0,date:f.date,dir:f.dir,comment:f.fileCommentStr.length?f.fileCommentStr:null,unixPermissions:f.unixPermissions,dosPermissions:f.dosPermissions,createFolders:c.createFolders}),f.dir||(g.file(m).unsafeOriginalName=C)}return d.zipComment.length&&(g.comment=d.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../stream/GenericWorker");function s(n,o){i.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(o)}e.inherits(s,i),s.prototype._bindStream=function(n){var o=this;(this._stream=n).pause(),n.on("data",function(a){o.push({data:a,meta:{percent:0}})}).on("error",function(a){o.isPaused?this.generatedError=a:o.error(a)}).on("end",function(){o.isPaused?o._upstreamEnded=!0:o.end()})},s.prototype.pause=function(){return!!i.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},A.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(h,A,t){"use strict";var e=h("readable-stream").Readable;function i(s,n,o){e.call(this,n),this._helper=s;var a=this;s.on("data",function(r,l){a.push(r)||a._helper.pause(),o&&o(l)}).on("error",function(r){a.emit("error",r)}).on("end",function(){a.push(null)})}h("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(h,A,t){"use strict";A.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,i){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,i);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,i)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var i=new Buffer(e);return i.fill(0),i},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}},{}],15:[function(h,A,t){"use strict";function e(m,E,w){var y,v=s.getTypeOf(E),S=s.extend(w||{},a);S.date=S.date||new Date,S.compression!==null&&(S.compression=S.compression.toUpperCase()),typeof S.unixPermissions=="string"&&(S.unixPermissions=parseInt(S.unixPermissions,8)),S.unixPermissions&&16384&S.unixPermissions&&(S.dir=!0),S.dosPermissions&&16&S.dosPermissions&&(S.dir=!0),S.dir&&(m=I(m)),S.createFolders&&(y=d(m))&&u.call(this,y,!0);var M=v==="string"&&S.binary===!1&&S.base64===!1;w&&w.binary!==void 0||(S.binary=!M),(E instanceof r&&E.uncompressedSize===0||S.dir||!E||E.length===0)&&(S.base64=!1,S.binary=!0,E="",S.compression="STORE",v="string");var F=null;F=E instanceof r||E instanceof n?E:g.isNode&&g.isStream(E)?new p(m,E):s.prepareContent(m,E,S.binary,S.optimizedBinaryString,S.base64);var N=new l(m,F,S);this.files[m]=N}var i=h("./utf8"),s=h("./utils"),n=h("./stream/GenericWorker"),o=h("./stream/StreamHelper"),a=h("./defaults"),r=h("./compressedObject"),l=h("./zipObject"),c=h("./generate"),g=h("./nodejsUtils"),p=h("./nodejs/NodejsStreamInputAdapter"),d=function(m){m.slice(-1)==="/"&&(m=m.substring(0,m.length-1));var E=m.lastIndexOf("/");return 0<E?m.substring(0,E):""},I=function(m){return m.slice(-1)!=="/"&&(m+="/"),m},u=function(m,E){return E=E!==void 0?E:a.createFolders,m=I(m),this.files[m]||e.call(this,m,null,{dir:!0,createFolders:E}),this.files[m]};function f(m){return Object.prototype.toString.call(m)==="[object RegExp]"}var C={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(m){var E,w,y;for(E in this.files)y=this.files[E],(w=E.slice(this.root.length,E.length))&&E.slice(0,this.root.length)===this.root&&m(w,y)},filter:function(m){var E=[];return this.forEach(function(w,y){m(w,y)&&E.push(y)}),E},file:function(m,E,w){if(arguments.length!==1)return m=this.root+m,e.call(this,m,E,w),this;if(f(m)){var y=m;return this.filter(function(S,M){return!M.dir&&y.test(S)})}var v=this.files[this.root+m];return v&&!v.dir?v:null},folder:function(m){if(!m)return this;if(f(m))return this.filter(function(v,S){return S.dir&&m.test(v)});var E=this.root+m,w=u.call(this,E),y=this.clone();return y.root=w.name,y},remove:function(m){m=this.root+m;var E=this.files[m];if(E||(m.slice(-1)!=="/"&&(m+="/"),E=this.files[m]),E&&!E.dir)delete this.files[m];else for(var w=this.filter(function(v,S){return S.name.slice(0,m.length)===m}),y=0;y<w.length;y++)delete this.files[w[y].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(m){var E,w={};try{if((w=s.extend(m||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:i.utf8encode})).type=w.type.toLowerCase(),w.compression=w.compression.toUpperCase(),w.type==="binarystring"&&(w.type="string"),!w.type)throw new Error("No output type specified.");s.checkSupport(w.type),w.platform!=="darwin"&&w.platform!=="freebsd"&&w.platform!=="linux"&&w.platform!=="sunos"||(w.platform="UNIX"),w.platform==="win32"&&(w.platform="DOS");var y=w.comment||this.comment||"";E=c.generateWorker(this,w,y)}catch(v){(E=new n("error")).error(v)}return new o(E,w.type||"string",w.mimeType)},generateAsync:function(m,E){return this.generateInternalStream(m).accumulate(E)},generateNodeStream:function(m,E){return(m=m||{}).type||(m.type="nodebuffer"),this.generateInternalStream(m).toNodejsStream(E)}};A.exports=C},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(h,A,t){"use strict";A.exports=h("stream")},{stream:void 0}],17:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data[this.zero+s]},i.prototype.lastIndexOfSignature=function(s){for(var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.length-4;0<=l;--l)if(this.data[l]===n&&this.data[l+1]===o&&this.data[l+2]===a&&this.data[l+3]===r)return l-this.zero;return-1},i.prototype.readAndCheckSignature=function(s){var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.readData(4);return n===l[0]&&o===l[1]&&a===l[2]&&r===l[3]},i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],18:[function(h,A,t){"use strict";var e=h("../utils");function i(s){this.data=s,this.length=s.length,this.index=0,this.zero=0}i.prototype={checkOffset:function(s){this.checkIndex(this.index+s)},checkIndex:function(s){if(this.length<this.zero+s||s<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+s+"). Corrupted zip ?")},setIndex:function(s){this.checkIndex(s),this.index=s},skip:function(s){this.setIndex(this.index+s)},byteAt:function(){},readInt:function(s){var n,o=0;for(this.checkOffset(s),n=this.index+s-1;n>=this.index;n--)o=(o<<8)+this.byteAt(n);return this.index+=s,o},readString:function(s){return e.transformTo("string",this.readData(s))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var s=this.readInt(4);return new Date(Date.UTC(1980+(s>>25&127),(s>>21&15)-1,s>>16&31,s>>11&31,s>>5&63,(31&s)<<1))}},A.exports=i},{"../utils":32}],19:[function(h,A,t){"use strict";var e=h("./Uint8ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data.charCodeAt(this.zero+s)},i.prototype.lastIndexOfSignature=function(s){return this.data.lastIndexOf(s)-this.zero},i.prototype.readAndCheckSignature=function(s){return s===this.readData(4)},i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],21:[function(h,A,t){"use strict";var e=h("./ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../support"),s=h("./ArrayReader"),n=h("./StringReader"),o=h("./NodeBufferReader"),a=h("./Uint8ArrayReader");A.exports=function(r){var l=e.getTypeOf(r);return e.checkSupport(l),l!=="string"||i.uint8array?l==="nodebuffer"?new o(r):i.uint8array?new a(e.transformTo("uint8array",r)):new s(e.transformTo("array",r)):new n(r)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(h,A,t){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../utils");function s(n){e.call(this,"ConvertWorker to "+n),this.destType=n}i.inherits(s,e),s.prototype.processChunk=function(n){this.push({data:i.transformTo(this.destType,n.data),meta:n.meta})},A.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}h("../utils").inherits(s,e),s.prototype.processChunk=function(n){this.streamInfo.crc32=i(n.data,this.streamInfo.crc32||0),this.push(n)},A.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(s,i),s.prototype.processChunk=function(n){if(n){var o=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=o+n.data.length}i.prototype.processChunk.call(this,n)},A.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataWorker");var o=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(a){o.dataIsReady=!0,o.data=a,o.max=a&&a.length||0,o.type=e.getTypeOf(a),o.isPaused||o._tickAndRepeat()},function(a){o.error(a)})}e.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,o=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,o);break;case"uint8array":n=this.data.subarray(this.index,o);break;case"array":case"nodebuffer":n=this.data.slice(this.index,o)}return this.index=o,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},A.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(h,A,t){"use strict";function e(i){this.name=i||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}e.prototype={push:function(i){this.emit("data",i)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(i){this.emit("error",i)}return!0},error:function(i){return!this.isFinished&&(this.isPaused?this.generatedError=i:(this.isFinished=!0,this.emit("error",i),this.previous&&this.previous.error(i),this.cleanUp()),!0)},on:function(i,s){return this._listeners[i].push(s),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(i,s){if(this._listeners[i])for(var n=0;n<this._listeners[i].length;n++)this._listeners[i][n].call(this,s)},pipe:function(i){return i.registerPrevious(this)},registerPrevious:function(i){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=i.streamInfo,this.mergeStreamInfo(),this.previous=i;var s=this;return i.on("data",function(n){s.processChunk(n)}),i.on("end",function(){s.end()}),i.on("error",function(n){s.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var i=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),i=!0),this.previous&&this.previous.resume(),!i},flush:function(){},processChunk:function(i){this.push(i)},withStreamInfo:function(i,s){return this.extraStreamInfo[i]=s,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var i in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,i)&&(this.streamInfo[i]=this.extraStreamInfo[i])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var i="Worker "+this.name;return this.previous?this.previous+" -> "+i:i}},A.exports=e},{}],29:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./ConvertWorker"),s=h("./GenericWorker"),n=h("../base64"),o=h("../support"),a=h("../external"),r=null;if(o.nodestream)try{r=h("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(g,p){return new a.Promise(function(d,I){var u=[],f=g._internalType,C=g._outputType,m=g._mimeType;g.on("data",function(E,w){u.push(E),p&&p(w)}).on("error",function(E){u=[],I(E)}).on("end",function(){try{var E=function(w,y,v){switch(w){case"blob":return e.newBlob(e.transformTo("arraybuffer",y),v);case"base64":return n.encode(y);default:return e.transformTo(w,y)}}(C,function(w,y){var v,S=0,M=null,F=0;for(v=0;v<y.length;v++)F+=y[v].length;switch(w){case"string":return y.join("");case"array":return Array.prototype.concat.apply([],y);case"uint8array":for(M=new Uint8Array(F),v=0;v<y.length;v++)M.set(y[v],S),S+=y[v].length;return M;case"nodebuffer":return Buffer.concat(y);default:throw new Error("concat : unsupported type '"+w+"'")}}(f,u),m);d(E)}catch(w){I(w)}u=[]}).resume()})}function c(g,p,d){var I=p;switch(p){case"blob":case"arraybuffer":I="uint8array";break;case"base64":I="string"}try{this._internalType=I,this._outputType=p,this._mimeType=d,e.checkSupport(I),this._worker=g.pipe(new i(I)),g.lock()}catch(u){this._worker=new s("error"),this._worker.error(u)}}c.prototype={accumulate:function(g){return l(this,g)},on:function(g,p){var d=this;return g==="data"?this._worker.on(g,function(I){p.call(d,I.data,I.meta)}):this._worker.on(g,function(){e.delay(p,arguments,d)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(g){if(e.checkSupport("nodestream"),this._outputType!=="nodebuffer")throw new Error(this._outputType+" is not supported by this method");return new r(this,{objectMode:this._outputType!=="nodebuffer"},g)}},A.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(h,A,t){"use strict";if(t.base64=!0,t.array=!0,t.string=!0,t.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",t.nodebuffer=typeof Buffer<"u",t.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(e),t.blob=i.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!h("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(h,A,t){"use strict";for(var e=h("./utils"),i=h("./support"),s=h("./nodejsUtils"),n=h("./stream/GenericWorker"),o=new Array(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;o[254]=o[254]=1;function r(){n.call(this,"utf-8 decode"),this.leftOver=null}function l(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return i.nodebuffer?s.newBufferFrom(c,"utf-8"):function(g){var p,d,I,u,f,C=g.length,m=0;for(u=0;u<C;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),m+=d<128?1:d<2048?2:d<65536?3:4;for(p=i.uint8array?new Uint8Array(m):new Array(m),u=f=0;f<m;u++)(64512&(d=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(d=65536+(d-55296<<10)+(I-56320),u++),d<128?p[f++]=d:(d<2048?p[f++]=192|d>>>6:(d<65536?p[f++]=224|d>>>12:(p[f++]=240|d>>>18,p[f++]=128|d>>>12&63),p[f++]=128|d>>>6&63),p[f++]=128|63&d);return p}(c)},t.utf8decode=function(c){return i.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(g){var p,d,I,u,f=g.length,C=new Array(2*f);for(p=d=0;p<f;)if((I=g[p++])<128)C[d++]=I;else if(4<(u=o[I]))C[d++]=65533,p+=u-1;else{for(I&=u===2?31:u===3?15:7;1<u&&p<f;)I=I<<6|63&g[p++],u--;1<u?C[d++]=65533:I<65536?C[d++]=I:(I-=65536,C[d++]=55296|I>>10&1023,C[d++]=56320|1023&I)}return C.length!==d&&(C.subarray?C=C.subarray(0,d):C.length=d),e.applyFromCharCode(C)}(c=e.transformTo(i.uint8array?"uint8array":"array",c))},e.inherits(r,n),r.prototype.processChunk=function(c){var g=e.transformTo(i.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var p=g;(g=new Uint8Array(p.length+this.leftOver.length)).set(this.leftOver,0),g.set(p,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var d=function(u,f){var C;for((f=f||u.length)>u.length&&(f=u.length),C=f-1;0<=C&&(192&u[C])==128;)C--;return C<0||C===0?f:C+o[u[C]]>f?C:f}(g),I=g;d!==g.length&&(i.uint8array?(I=g.subarray(0,d),this.leftOver=g.subarray(d,g.length)):(I=g.slice(0,d),this.leftOver=g.slice(d,g.length))),this.push({data:t.utf8decode(I),meta:c.meta})},r.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=r,e.inherits(l,n),l.prototype.processChunk=function(c){this.push({data:t.utf8encode(c.data),meta:c.meta})},t.Utf8EncodeWorker=l},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(h,A,t){"use strict";var e=h("./support"),i=h("./base64"),s=h("./nodejsUtils"),n=h("./external");function o(p){return p}function a(p,d){for(var I=0;I<p.length;++I)d[I]=255&p.charCodeAt(I);return d}h("setimmediate"),t.newBlob=function(p,d){t.checkSupport("blob");try{return new Blob([p],{type:d})}catch{try{var I=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return I.append(p),I.getBlob(d)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,d,I){var u=[],f=0,C=p.length;if(C<=I)return String.fromCharCode.apply(null,p);for(;f<C;)d==="array"||d==="nodebuffer"?u.push(String.fromCharCode.apply(null,p.slice(f,Math.min(f+I,C)))):u.push(String.fromCharCode.apply(null,p.subarray(f,Math.min(f+I,C)))),f+=I;return u.join("")},stringifyByChar:function(p){for(var d="",I=0;I<p.length;I++)d+=String.fromCharCode(p[I]);return d},applyCanBeUsed:{uint8array:function(){try{return e.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}}(),nodebuffer:function(){try{return e.nodebuffer&&String.fromCharCode.apply(null,s.allocBuffer(1)).length===1}catch{return!1}}()}};function l(p){var d=65536,I=t.getTypeOf(p),u=!0;if(I==="uint8array"?u=r.applyCanBeUsed.uint8array:I==="nodebuffer"&&(u=r.applyCanBeUsed.nodebuffer),u)for(;1<d;)try{return r.stringifyByChunk(p,I,d)}catch{d=Math.floor(d/2)}return r.stringifyByChar(p)}function c(p,d){for(var I=0;I<p.length;I++)d[I]=p[I];return d}t.applyFromCharCode=l;var g={};g.string={string:o,array:function(p){return a(p,new Array(p.length))},arraybuffer:function(p){return g.string.uint8array(p).buffer},uint8array:function(p){return a(p,new Uint8Array(p.length))},nodebuffer:function(p){return a(p,s.allocBuffer(p.length))}},g.array={string:l,array:o,arraybuffer:function(p){return new Uint8Array(p).buffer},uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(p)}},g.arraybuffer={string:function(p){return l(new Uint8Array(p))},array:function(p){return c(new Uint8Array(p),new Array(p.byteLength))},arraybuffer:o,uint8array:function(p){return new Uint8Array(p)},nodebuffer:function(p){return s.newBufferFrom(new Uint8Array(p))}},g.uint8array={string:l,array:function(p){return c(p,new Array(p.length))},arraybuffer:function(p){return p.buffer},uint8array:o,nodebuffer:function(p){return s.newBufferFrom(p)}},g.nodebuffer={string:l,array:function(p){return c(p,new Array(p.length))},arraybuffer:function(p){return g.nodebuffer.uint8array(p).buffer},uint8array:function(p){return c(p,new Uint8Array(p.length))},nodebuffer:o},t.transformTo=function(p,d){if(d=d||"",!p)return d;t.checkSupport(p);var I=t.getTypeOf(d);return g[I][p](d)},t.resolve=function(p){for(var d=p.split("/"),I=[],u=0;u<d.length;u++){var f=d[u];f==="."||f===""&&u!==0&&u!==d.length-1||(f===".."?I.pop():I.push(f))}return I.join("/")},t.getTypeOf=function(p){return typeof p=="string"?"string":Object.prototype.toString.call(p)==="[object Array]"?"array":e.nodebuffer&&s.isBuffer(p)?"nodebuffer":e.uint8array&&p instanceof Uint8Array?"uint8array":e.arraybuffer&&p instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(p){if(!e[p.toLowerCase()])throw new Error(p+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(p){var d,I,u="";for(I=0;I<(p||"").length;I++)u+="\\x"+((d=p.charCodeAt(I))<16?"0":"")+d.toString(16).toUpperCase();return u},t.delay=function(p,d,I){setImmediate(function(){p.apply(I||null,d||[])})},t.inherits=function(p,d){function I(){}I.prototype=d.prototype,p.prototype=new I},t.extend=function(){var p,d,I={};for(p=0;p<arguments.length;p++)for(d in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],d)&&I[d]===void 0&&(I[d]=arguments[p][d]);return I},t.prepareContent=function(p,d,I,u,f){return n.Promise.resolve(d).then(function(C){return e.blob&&(C instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(C))!==-1)&&typeof FileReader<"u"?new n.Promise(function(m,E){var w=new FileReader;w.onload=function(y){m(y.target.result)},w.onerror=function(y){E(y.target.error)},w.readAsArrayBuffer(C)}):C}).then(function(C){var m=t.getTypeOf(C);return m?(m==="arraybuffer"?C=t.transformTo("uint8array",C):m==="string"&&(f?C=i.decode(C):I&&u!==!0&&(C=function(E){return a(E,e.uint8array?new Uint8Array(E.length):new Array(E.length))}(C))),C):n.Promise.reject(new Error("Can't read the data of '"+p+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./signature"),n=h("./zipEntry"),o=h("./support");function a(r){this.files=[],this.loadOptions=r}a.prototype={checkSignature:function(r){if(!this.reader.readAndCheckSignature(r)){this.reader.index-=4;var l=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(l)+", expected "+i.pretty(r)+")")}},isSignature:function(r,l){var c=this.reader.index;this.reader.setIndex(r);var g=this.reader.readString(4)===l;return this.reader.setIndex(c),g},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var r=this.reader.readData(this.zipCommentLength),l=o.uint8array?"uint8array":"array",c=i.transformTo(l,r);this.zipComment=this.loadOptions.decodeFileName(c)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var r,l,c,g=this.zip64EndOfCentralSize-44;0<g;)r=this.reader.readInt(2),l=this.reader.readInt(4),c=this.reader.readData(l),this.zip64ExtensibleData[r]={id:r,length:l,value:c}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var r,l;for(r=0;r<this.files.length;r++)l=this.files[r],this.reader.setIndex(l.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),l.readLocalPart(this.reader),l.handleUTF8(),l.processAttributes()},readCentralDir:function(){var r;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(s.CENTRAL_FILE_HEADER);)(r=new n({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(r);if(this.centralDirRecords!==this.files.length&&this.centralDirRecords!==0&&this.files.length===0)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var r=this.reader.lastIndexOfSignature(s.CENTRAL_DIRECTORY_END);if(r<0)throw this.isSignature(0,s.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(r);var l=r;if(this.checkSignature(s.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===i.MAX_VALUE_16BITS||this.diskWithCentralDirStart===i.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===i.MAX_VALUE_16BITS||this.centralDirRecords===i.MAX_VALUE_16BITS||this.centralDirSize===i.MAX_VALUE_32BITS||this.centralDirOffset===i.MAX_VALUE_32BITS){if(this.zip64=!0,(r=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(r),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,s.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(s.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var c=this.centralDirOffset+this.centralDirSize;this.zip64&&(c+=20,c+=12+this.zip64EndOfCentralSize);var g=l-c;if(0<g)this.isSignature(l,s.CENTRAL_FILE_HEADER)||(this.reader.zero=g);else if(g<0)throw new Error("Corrupted zip: missing "+Math.abs(g)+" bytes.")},prepareReader:function(r){this.reader=e(r)},load:function(r){this.prepareReader(r),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},A.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./compressedObject"),n=h("./crc32"),o=h("./utf8"),a=h("./compressions"),r=h("./support");function l(c,g){this.options=c,this.loadOptions=g}l.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(c){var g,p;if(c.skip(22),this.fileNameLength=c.readInt(2),p=c.readInt(2),this.fileName=c.readData(this.fileNameLength),c.skip(p),this.compressedSize===-1||this.uncompressedSize===-1)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if((g=function(d){for(var I in a)if(Object.prototype.hasOwnProperty.call(a,I)&&a[I].magic===d)return a[I];return null}(this.compressionMethod))===null)throw new Error("Corrupted zip : compression "+i.pretty(this.compressionMethod)+" unknown (inner file : "+i.transformTo("string",this.fileName)+")");this.decompressed=new s(this.compressedSize,this.uncompressedSize,this.crc32,g,c.readData(this.compressedSize))},readCentralPart:function(c){this.versionMadeBy=c.readInt(2),c.skip(2),this.bitFlag=c.readInt(2),this.compressionMethod=c.readString(2),this.date=c.readDate(),this.crc32=c.readInt(4),this.compressedSize=c.readInt(4),this.uncompressedSize=c.readInt(4);var g=c.readInt(2);if(this.extraFieldsLength=c.readInt(2),this.fileCommentLength=c.readInt(2),this.diskNumberStart=c.readInt(2),this.internalFileAttributes=c.readInt(2),this.externalFileAttributes=c.readInt(4),this.localHeaderOffset=c.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");c.skip(g),this.readExtraFields(c),this.parseZIP64ExtraField(c),this.fileComment=c.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var c=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),c==0&&(this.dosPermissions=63&this.externalFileAttributes),c==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var c=e(this.extraFields[1].value);this.uncompressedSize===i.MAX_VALUE_32BITS&&(this.uncompressedSize=c.readInt(8)),this.compressedSize===i.MAX_VALUE_32BITS&&(this.compressedSize=c.readInt(8)),this.localHeaderOffset===i.MAX_VALUE_32BITS&&(this.localHeaderOffset=c.readInt(8)),this.diskNumberStart===i.MAX_VALUE_32BITS&&(this.diskNumberStart=c.readInt(4))}},readExtraFields:function(c){var g,p,d,I=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<I;)g=c.readInt(2),p=c.readInt(2),d=c.readData(p),this.extraFields[g]={id:g,length:p,value:d};c.setIndex(I)},handleUTF8:function(){var c=r.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=o.utf8decode(this.fileName),this.fileCommentStr=o.utf8decode(this.fileComment);else{var g=this.findExtraFieldUnicodePath();if(g!==null)this.fileNameStr=g;else{var p=i.transformTo(c,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(p)}var d=this.findExtraFieldUnicodeComment();if(d!==null)this.fileCommentStr=d;else{var I=i.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(I)}}},findExtraFieldUnicodePath:function(){var c=this.extraFields[28789];if(c){var g=e(c.value);return g.readInt(1)!==1||n(this.fileName)!==g.readInt(4)?null:o.utf8decode(g.readData(c.length-5))}return null},findExtraFieldUnicodeComment:function(){var c=this.extraFields[25461];if(c){var g=e(c.value);return g.readInt(1)!==1||n(this.fileComment)!==g.readInt(4)?null:o.utf8decode(g.readData(c.length-5))}return null}},A.exports=l},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(h,A,t){"use strict";function e(g,p,d){this.name=g,this.dir=d.dir,this.date=d.date,this.comment=d.comment,this.unixPermissions=d.unixPermissions,this.dosPermissions=d.dosPermissions,this._data=p,this._dataBinary=d.binary,this.options={compression:d.compression,compressionOptions:d.compressionOptions}}var i=h("./stream/StreamHelper"),s=h("./stream/DataWorker"),n=h("./utf8"),o=h("./compressedObject"),a=h("./stream/GenericWorker");e.prototype={internalStream:function(g){var p=null,d="string";try{if(!g)throw new Error("No output type specified.");var I=(d=g.toLowerCase())==="string"||d==="text";d!=="binarystring"&&d!=="text"||(d="string"),p=this._decompressWorker();var u=!this._dataBinary;u&&!I&&(p=p.pipe(new n.Utf8EncodeWorker)),!u&&I&&(p=p.pipe(new n.Utf8DecodeWorker))}catch(f){(p=new a("error")).error(f)}return new i(p,d,"")},async:function(g,p){return this.internalStream(g).accumulate(p)},nodeStream:function(g,p){return this.internalStream(g||"nodebuffer").toNodejsStream(p)},_compressWorker:function(g,p){if(this._data instanceof o&&this._data.compression.magic===g.magic)return this._data.getCompressedWorker();var d=this._decompressWorker();return this._dataBinary||(d=d.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(d,g,p)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof a?this._data:new s(this._data)}};for(var r=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],l=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<r.length;c++)e.prototype[r[c]]=l;A.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(h,A,t){(function(e){"use strict";var i,s,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var o=0,a=new n(g),r=e.document.createTextNode("");a.observe(r,{characterData:!0}),i=function(){r.data=o=++o%2}}else if(e.setImmediate||e.MessageChannel===void 0)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var p=e.document.createElement("script");p.onreadystatechange=function(){g(),p.onreadystatechange=null,p.parentNode.removeChild(p),p=null},e.document.documentElement.appendChild(p)}:function(){setTimeout(g,0)};else{var l=new e.MessageChannel;l.port1.onmessage=g,i=function(){l.port2.postMessage(0)}}var c=[];function g(){var p,d;s=!0;for(var I=c.length;I;){for(d=c,c=[],p=-1;++p<I;)d[p]();I=c.length}s=!1}A.exports=function(p){c.push(p)!==1||s||i()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(h,A,t){"use strict";var e=h("immediate");function i(){}var s={},n=["REJECTED"],o=["FULFILLED"],a=["PENDING"];function r(I){if(typeof I!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,I!==i&&p(this,I)}function l(I,u,f){this.promise=I,typeof u=="function"&&(this.onFulfilled=u,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function c(I,u,f){e(function(){var C;try{C=u(f)}catch(m){return s.reject(I,m)}C===I?s.reject(I,new TypeError("Cannot resolve promise with itself")):s.resolve(I,C)})}function g(I){var u=I&&I.then;if(I&&(typeof I=="object"||typeof I=="function")&&typeof u=="function")return function(){u.apply(I,arguments)}}function p(I,u){var f=!1;function C(w){f||(f=!0,s.reject(I,w))}function m(w){f||(f=!0,s.resolve(I,w))}var E=d(function(){u(m,C)});E.status==="error"&&C(E.value)}function d(I,u){var f={};try{f.value=I(u),f.status="success"}catch(C){f.status="error",f.value=C}return f}(A.exports=r).prototype.finally=function(I){if(typeof I!="function")return this;var u=this.constructor;return this.then(function(f){return u.resolve(I()).then(function(){return f})},function(f){return u.resolve(I()).then(function(){throw f})})},r.prototype.catch=function(I){return this.then(null,I)},r.prototype.then=function(I,u){if(typeof I!="function"&&this.state===o||typeof u!="function"&&this.state===n)return this;var f=new this.constructor(i);return this.state!==a?c(f,this.state===o?I:u,this.outcome):this.queue.push(new l(f,I,u)),f},l.prototype.callFulfilled=function(I){s.resolve(this.promise,I)},l.prototype.otherCallFulfilled=function(I){c(this.promise,this.onFulfilled,I)},l.prototype.callRejected=function(I){s.reject(this.promise,I)},l.prototype.otherCallRejected=function(I){c(this.promise,this.onRejected,I)},s.resolve=function(I,u){var f=d(g,u);if(f.status==="error")return s.reject(I,f.value);var C=f.value;if(C)p(I,C);else{I.state=o,I.outcome=u;for(var m=-1,E=I.queue.length;++m<E;)I.queue[m].callFulfilled(u)}return I},s.reject=function(I,u){I.state=n,I.outcome=u;for(var f=-1,C=I.queue.length;++f<C;)I.queue[f].callRejected(u);return I},r.resolve=function(I){return I instanceof this?I:s.resolve(new this(i),I)},r.reject=function(I){var u=new this(i);return s.reject(u,I)},r.all=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=new Array(f),E=0,w=-1,y=new this(i);++w<f;)v(I[w],w);return y;function v(S,M){u.resolve(S).then(function(F){m[M]=F,++E!==f||C||(C=!0,s.resolve(y,m))},function(F){C||(C=!0,s.reject(y,F))})}},r.race=function(I){var u=this;if(Object.prototype.toString.call(I)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=I.length,C=!1;if(!f)return this.resolve([]);for(var m=-1,E=new this(i);++m<f;)w=I[m],u.resolve(w).then(function(y){C||(C=!0,s.resolve(E,y))},function(y){C||(C=!0,s.reject(E,y))});var w;return E}},{immediate:36}],38:[function(h,A,t){"use strict";var e={};(0,h("./lib/utils/common").assign)(e,h("./lib/deflate"),h("./lib/inflate"),h("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(h,A,t){"use strict";var e=h("./zlib/deflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/messages"),o=h("./zlib/zstream"),a=Object.prototype.toString,r=0,l=-1,c=0,g=8;function p(I){if(!(this instanceof p))return new p(I);this.options=i.assign({level:l,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},I||{});var u=this.options;u.raw&&0<u.windowBits?u.windowBits=-u.windowBits:u.gzip&&0<u.windowBits&&u.windowBits<16&&(u.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new o,this.strm.avail_out=0;var f=e.deflateInit2(this.strm,u.level,u.method,u.windowBits,u.memLevel,u.strategy);if(f!==r)throw new Error(n[f]);if(u.header&&e.deflateSetHeader(this.strm,u.header),u.dictionary){var C;if(C=typeof u.dictionary=="string"?s.string2buf(u.dictionary):a.call(u.dictionary)==="[object ArrayBuffer]"?new Uint8Array(u.dictionary):u.dictionary,(f=e.deflateSetDictionary(this.strm,C))!==r)throw new Error(n[f]);this._dict_set=!0}}function d(I,u){var f=new p(u);if(f.push(I,!0),f.err)throw f.msg||n[f.err];return f.result}p.prototype.push=function(I,u){var f,C,m=this.strm,E=this.options.chunkSize;if(this.ended)return!1;C=u===~~u?u:u===!0?4:0,typeof I=="string"?m.input=s.string2buf(I):a.call(I)==="[object ArrayBuffer]"?m.input=new Uint8Array(I):m.input=I,m.next_in=0,m.avail_in=m.input.length;do{if(m.avail_out===0&&(m.output=new i.Buf8(E),m.next_out=0,m.avail_out=E),(f=e.deflate(m,C))!==1&&f!==r)return this.onEnd(f),!(this.ended=!0);m.avail_out!==0&&(m.avail_in!==0||C!==4&&C!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(i.shrinkBuf(m.output,m.next_out))):this.onData(i.shrinkBuf(m.output,m.next_out)))}while((0<m.avail_in||m.avail_out===0)&&f!==1);return C===4?(f=e.deflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===r):C!==2||(this.onEnd(r),!(m.avail_out=0))},p.prototype.onData=function(I){this.chunks.push(I)},p.prototype.onEnd=function(I){I===r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=I,this.msg=this.strm.msg},t.Deflate=p,t.deflate=d,t.deflateRaw=function(I,u){return(u=u||{}).raw=!0,d(I,u)},t.gzip=function(I,u){return(u=u||{}).gzip=!0,d(I,u)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(h,A,t){"use strict";var e=h("./zlib/inflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/constants"),o=h("./zlib/messages"),a=h("./zlib/zstream"),r=h("./zlib/gzheader"),l=Object.prototype.toString;function c(p){if(!(this instanceof c))return new c(p);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},p||{});var d=this.options;d.raw&&0<=d.windowBits&&d.windowBits<16&&(d.windowBits=-d.windowBits,d.windowBits===0&&(d.windowBits=-15)),!(0<=d.windowBits&&d.windowBits<16)||p&&p.windowBits||(d.windowBits+=32),15<d.windowBits&&d.windowBits<48&&!(15&d.windowBits)&&(d.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var I=e.inflateInit2(this.strm,d.windowBits);if(I!==n.Z_OK)throw new Error(o[I]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,d){var I=new c(d);if(I.push(p,!0),I.err)throw I.msg||o[I.err];return I.result}c.prototype.push=function(p,d){var I,u,f,C,m,E,w=this.strm,y=this.options.chunkSize,v=this.options.dictionary,S=!1;if(this.ended)return!1;u=d===~~d?d:d===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof p=="string"?w.input=s.binstring2buf(p):l.call(p)==="[object ArrayBuffer]"?w.input=new Uint8Array(p):w.input=p,w.next_in=0,w.avail_in=w.input.length;do{if(w.avail_out===0&&(w.output=new i.Buf8(y),w.next_out=0,w.avail_out=y),(I=e.inflate(w,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&v&&(E=typeof v=="string"?s.string2buf(v):l.call(v)==="[object ArrayBuffer]"?new Uint8Array(v):v,I=e.inflateSetDictionary(this.strm,E)),I===n.Z_BUF_ERROR&&S===!0&&(I=n.Z_OK,S=!1),I!==n.Z_STREAM_END&&I!==n.Z_OK)return this.onEnd(I),!(this.ended=!0);w.next_out&&(w.avail_out!==0&&I!==n.Z_STREAM_END&&(w.avail_in!==0||u!==n.Z_FINISH&&u!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(f=s.utf8border(w.output,w.next_out),C=w.next_out-f,m=s.buf2string(w.output,f),w.next_out=C,w.avail_out=y-C,C&&i.arraySet(w.output,w.output,f,C,0),this.onData(m)):this.onData(i.shrinkBuf(w.output,w.next_out)))),w.avail_in===0&&w.avail_out===0&&(S=!0)}while((0<w.avail_in||w.avail_out===0)&&I!==n.Z_STREAM_END);return I===n.Z_STREAM_END&&(u=n.Z_FINISH),u===n.Z_FINISH?(I=e.inflateEnd(this.strm),this.onEnd(I),this.ended=!0,I===n.Z_OK):u!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(w.avail_out=0))},c.prototype.onData=function(p){this.chunks.push(p)},c.prototype.onEnd=function(p){p===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=p,this.msg=this.strm.msg},t.Inflate=c,t.inflate=g,t.inflateRaw=function(p,d){return(d=d||{}).raw=!0,g(p,d)},t.ungzip=g},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var a=o.shift();if(a){if(typeof a!="object")throw new TypeError(a+"must be non-object");for(var r in a)a.hasOwnProperty(r)&&(n[r]=a[r])}}return n},t.shrinkBuf=function(n,o){return n.length===o?n:n.subarray?n.subarray(0,o):(n.length=o,n)};var i={arraySet:function(n,o,a,r,l){if(o.subarray&&n.subarray)n.set(o.subarray(a,a+r),l);else for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){var o,a,r,l,c,g;for(o=r=0,a=n.length;o<a;o++)r+=n[o].length;for(g=new Uint8Array(r),o=l=0,a=n.length;o<a;o++)c=n[o],g.set(c,l),l+=c.length;return g}},s={arraySet:function(n,o,a,r,l){for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){return[].concat.apply([],n)}};t.setTyped=function(n){n?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,i)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,s))},t.setTyped(e)},{}],42:[function(h,A,t){"use strict";var e=h("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch{i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{s=!1}for(var n=new e.Buf8(256),o=0;o<256;o++)n[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;function a(r,l){if(l<65537&&(r.subarray&&s||!r.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(r,l));for(var c="",g=0;g<l;g++)c+=String.fromCharCode(r[g]);return c}n[254]=n[254]=1,t.string2buf=function(r){var l,c,g,p,d,I=r.length,u=0;for(p=0;p<I;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),u+=c<128?1:c<2048?2:c<65536?3:4;for(l=new e.Buf8(u),p=d=0;d<u;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<I&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),c<128?l[d++]=c:(c<2048?l[d++]=192|c>>>6:(c<65536?l[d++]=224|c>>>12:(l[d++]=240|c>>>18,l[d++]=128|c>>>12&63),l[d++]=128|c>>>6&63),l[d++]=128|63&c);return l},t.buf2binstring=function(r){return a(r,r.length)},t.binstring2buf=function(r){for(var l=new e.Buf8(r.length),c=0,g=l.length;c<g;c++)l[c]=r.charCodeAt(c);return l},t.buf2string=function(r,l){var c,g,p,d,I=l||r.length,u=new Array(2*I);for(c=g=0;c<I;)if((p=r[c++])<128)u[g++]=p;else if(4<(d=n[p]))u[g++]=65533,c+=d-1;else{for(p&=d===2?31:d===3?15:7;1<d&&c<I;)p=p<<6|63&r[c++],d--;1<d?u[g++]=65533:p<65536?u[g++]=p:(p-=65536,u[g++]=55296|p>>10&1023,u[g++]=56320|1023&p)}return a(u,g)},t.utf8border=function(r,l){var c;for((l=l||r.length)>r.length&&(l=r.length),c=l-1;0<=c&&(192&r[c])==128;)c--;return c<0||c===0?l:c+n[r[c]]>l?c:l}},{"./common":41}],43:[function(h,A,t){"use strict";A.exports=function(e,i,s,n){for(var o=65535&e|0,a=e>>>16&65535|0,r=0;s!==0;){for(s-=r=2e3<s?2e3:s;a=a+(o=o+i[n++]|0)|0,--r;);o%=65521,a%=65521}return o|a<<16|0}},{}],44:[function(h,A,t){"use strict";A.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(h,A,t){"use strict";var e=function(){for(var i,s=[],n=0;n<256;n++){i=n;for(var o=0;o<8;o++)i=1&i?3988292384^i>>>1:i>>>1;s[n]=i}return s}();A.exports=function(i,s,n,o){var a=e,r=o+n;i^=-1;for(var l=o;l<r;l++)i=i>>>8^a[255&(i^s[l])];return-1^i}},{}],46:[function(h,A,t){"use strict";var e,i=h("../utils/common"),s=h("./trees"),n=h("./adler32"),o=h("./crc32"),a=h("./messages"),r=0,l=4,c=0,g=-2,p=-1,d=4,I=2,u=8,f=9,C=286,m=30,E=19,w=2*C+1,y=15,v=3,S=258,M=S+v+1,F=42,N=113,Q=1,D=2,K=3,x=4;function Y(B,J){return B.msg=a[J],J}function q(B){return(B<<1)-(4<B?9:0)}function _(B){for(var J=B.length;0<=--J;)B[J]=0}function L(B){var J=B.state,G=J.pending;G>B.avail_out&&(G=B.avail_out),G!==0&&(i.arraySet(B.output,J.pending_buf,J.pending_out,G,B.next_out),B.next_out+=G,J.pending_out+=G,B.total_out+=G,B.avail_out-=G,J.pending-=G,J.pending===0&&(J.pending_out=0))}function U(B,J){s._tr_flush_block(B,0<=B.block_start?B.block_start:-1,B.strstart-B.block_start,J),B.block_start=B.strstart,L(B.strm)}function tt(B,J){B.pending_buf[B.pending++]=J}function O(B,J){B.pending_buf[B.pending++]=J>>>8&255,B.pending_buf[B.pending++]=255&J}function V(B,J){var G,b,k=B.max_chain_length,H=B.strstart,z=B.prev_length,W=B.nice_match,R=B.strstart>B.w_size-M?B.strstart-(B.w_size-M):0,X=B.window,et=B.w_mask,Z=B.prev,it=B.strstart+S,ut=X[H+z-1],ht=X[H+z];B.prev_length>=B.good_match&&(k>>=2),W>B.lookahead&&(W=B.lookahead);do if(X[(G=J)+z]===ht&&X[G+z-1]===ut&&X[G]===X[H]&&X[++G]===X[H+1]){H+=2,G++;do;while(X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&X[++H]===X[++G]&&H<it);if(b=S-(it-H),H=it-S,z<b){if(B.match_start=J,W<=(z=b))break;ut=X[H+z-1],ht=X[H+z]}}while((J=Z[J&et])>R&&--k!=0);return z<=B.lookahead?z:B.lookahead}function rt(B){var J,G,b,k,H,z,W,R,X,et,Z=B.w_size;do{if(k=B.window_size-B.lookahead-B.strstart,B.strstart>=Z+(Z-M)){for(i.arraySet(B.window,B.window,Z,Z,0),B.match_start-=Z,B.strstart-=Z,B.block_start-=Z,J=G=B.hash_size;b=B.head[--J],B.head[J]=Z<=b?b-Z:0,--G;);for(J=G=Z;b=B.prev[--J],B.prev[J]=Z<=b?b-Z:0,--G;);k+=Z}if(B.strm.avail_in===0)break;if(z=B.strm,W=B.window,R=B.strstart+B.lookahead,X=k,et=void 0,et=z.avail_in,X<et&&(et=X),G=et===0?0:(z.avail_in-=et,i.arraySet(W,z.input,z.next_in,et,R),z.state.wrap===1?z.adler=n(z.adler,W,et,R):z.state.wrap===2&&(z.adler=o(z.adler,W,et,R)),z.next_in+=et,z.total_in+=et,et),B.lookahead+=G,B.lookahead+B.insert>=v)for(H=B.strstart-B.insert,B.ins_h=B.window[H],B.ins_h=(B.ins_h<<B.hash_shift^B.window[H+1])&B.hash_mask;B.insert&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[H+v-1])&B.hash_mask,B.prev[H&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=H,H++,B.insert--,!(B.lookahead+B.insert<v)););}while(B.lookahead<M&&B.strm.avail_in!==0)}function gt(B,J){for(var G,b;;){if(B.lookahead<M){if(rt(B),B.lookahead<M&&J===r)return Q;if(B.lookahead===0)break}if(G=0,B.lookahead>=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),G!==0&&B.strstart-G<=B.w_size-M&&(B.match_length=V(B,G)),B.match_length>=v)if(b=s._tr_tally(B,B.strstart-B.match_start,B.match_length-v),B.lookahead-=B.match_length,B.match_length<=B.max_lazy_match&&B.lookahead>=v){for(B.match_length--;B.strstart++,B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart,--B.match_length!=0;);B.strstart++}else B.strstart+=B.match_length,B.match_length=0,B.ins_h=B.window[B.strstart],B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+1])&B.hash_mask;else b=s._tr_tally(B,0,B.window[B.strstart]),B.lookahead--,B.strstart++;if(b&&(U(B,!1),B.strm.avail_out===0))return Q}return B.insert=B.strstart<v-1?B.strstart:v-1,J===l?(U(B,!0),B.strm.avail_out===0?K:x):B.last_lit&&(U(B,!1),B.strm.avail_out===0)?Q:D}function nt(B,J){for(var G,b,k;;){if(B.lookahead<M){if(rt(B),B.lookahead<M&&J===r)return Q;if(B.lookahead===0)break}if(G=0,B.lookahead>=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),B.prev_length=B.match_length,B.prev_match=B.match_start,B.match_length=v-1,G!==0&&B.prev_length<B.max_lazy_match&&B.strstart-G<=B.w_size-M&&(B.match_length=V(B,G),B.match_length<=5&&(B.strategy===1||B.match_length===v&&4096<B.strstart-B.match_start)&&(B.match_length=v-1)),B.prev_length>=v&&B.match_length<=B.prev_length){for(k=B.strstart+B.lookahead-v,b=s._tr_tally(B,B.strstart-1-B.prev_match,B.prev_length-v),B.lookahead-=B.prev_length-1,B.prev_length-=2;++B.strstart<=k&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),--B.prev_length!=0;);if(B.match_available=0,B.match_length=v-1,B.strstart++,b&&(U(B,!1),B.strm.avail_out===0))return Q}else if(B.match_available){if((b=s._tr_tally(B,0,B.window[B.strstart-1]))&&U(B,!1),B.strstart++,B.lookahead--,B.strm.avail_out===0)return Q}else B.match_available=1,B.strstart++,B.lookahead--}return B.match_available&&(b=s._tr_tally(B,0,B.window[B.strstart-1]),B.match_available=0),B.insert=B.strstart<v-1?B.strstart:v-1,J===l?(U(B,!0),B.strm.avail_out===0?K:x):B.last_lit&&(U(B,!1),B.strm.avail_out===0)?Q:D}function At(B,J,G,b,k){this.good_length=B,this.max_lazy=J,this.nice_length=G,this.max_chain=b,this.func=k}function lt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=u,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new i.Buf16(2*w),this.dyn_dtree=new i.Buf16(2*(2*m+1)),this.bl_tree=new i.Buf16(2*(2*E+1)),_(this.dyn_ltree),_(this.dyn_dtree),_(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(y+1),this.heap=new i.Buf16(2*C+1),_(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*C+1),_(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function ot(B){var J;return B&&B.state?(B.total_in=B.total_out=0,B.data_type=I,(J=B.state).pending=0,J.pending_out=0,J.wrap<0&&(J.wrap=-J.wrap),J.status=J.wrap?F:N,B.adler=J.wrap===2?0:1,J.last_flush=r,s._tr_init(J),c):Y(B,g)}function Qt(B){var J=ot(B);return J===c&&function(G){G.window_size=2*G.w_size,_(G.head),G.max_lazy_match=e[G.level].max_lazy,G.good_match=e[G.level].good_length,G.nice_match=e[G.level].nice_length,G.max_chain_length=e[G.level].max_chain,G.strstart=0,G.block_start=0,G.lookahead=0,G.insert=0,G.match_length=G.prev_length=v-1,G.match_available=0,G.ins_h=0}(B.state),J}function ft(B,J,G,b,k,H){if(!B)return g;var z=1;if(J===p&&(J=6),b<0?(z=0,b=-b):15<b&&(z=2,b-=16),k<1||f<k||G!==u||b<8||15<b||J<0||9<J||H<0||d<H)return Y(B,g);b===8&&(b=9);var W=new lt;return(B.state=W).strm=B,W.wrap=z,W.gzhead=null,W.w_bits=b,W.w_size=1<<W.w_bits,W.w_mask=W.w_size-1,W.hash_bits=k+7,W.hash_size=1<<W.hash_bits,W.hash_mask=W.hash_size-1,W.hash_shift=~~((W.hash_bits+v-1)/v),W.window=new i.Buf8(2*W.w_size),W.head=new i.Buf16(W.hash_size),W.prev=new i.Buf16(W.w_size),W.lit_bufsize=1<<k+6,W.pending_buf_size=4*W.lit_bufsize,W.pending_buf=new i.Buf8(W.pending_buf_size),W.d_buf=1*W.lit_bufsize,W.l_buf=3*W.lit_bufsize,W.level=J,W.strategy=H,W.method=G,Qt(B)}e=[new At(0,0,0,0,function(B,J){var G=65535;for(G>B.pending_buf_size-5&&(G=B.pending_buf_size-5);;){if(B.lookahead<=1){if(rt(B),B.lookahead===0&&J===r)return Q;if(B.lookahead===0)break}B.strstart+=B.lookahead,B.lookahead=0;var b=B.block_start+G;if((B.strstart===0||B.strstart>=b)&&(B.lookahead=B.strstart-b,B.strstart=b,U(B,!1),B.strm.avail_out===0)||B.strstart-B.block_start>=B.w_size-M&&(U(B,!1),B.strm.avail_out===0))return Q}return B.insert=0,J===l?(U(B,!0),B.strm.avail_out===0?K:x):(B.strstart>B.block_start&&(U(B,!1),B.strm.avail_out),Q)}),new At(4,4,8,4,gt),new At(4,5,16,8,gt),new At(4,6,32,32,gt),new At(4,4,16,16,nt),new At(8,16,32,32,nt),new At(8,16,128,128,nt),new At(8,32,128,256,nt),new At(32,128,258,1024,nt),new At(32,258,258,4096,nt)],t.deflateInit=function(B,J){return ft(B,J,u,15,8,0)},t.deflateInit2=ft,t.deflateReset=Qt,t.deflateResetKeep=ot,t.deflateSetHeader=function(B,J){return B&&B.state?B.state.wrap!==2?g:(B.state.gzhead=J,c):g},t.deflate=function(B,J){var G,b,k,H;if(!B||!B.state||5<J||J<0)return B?Y(B,g):g;if(b=B.state,!B.output||!B.input&&B.avail_in!==0||b.status===666&&J!==l)return Y(B,B.avail_out===0?-5:g);if(b.strm=B,G=b.last_flush,b.last_flush=J,b.status===F)if(b.wrap===2)B.adler=0,tt(b,31),tt(b,139),tt(b,8),b.gzhead?(tt(b,(b.gzhead.text?1:0)+(b.gzhead.hcrc?2:0)+(b.gzhead.extra?4:0)+(b.gzhead.name?8:0)+(b.gzhead.comment?16:0)),tt(b,255&b.gzhead.time),tt(b,b.gzhead.time>>8&255),tt(b,b.gzhead.time>>16&255),tt(b,b.gzhead.time>>24&255),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,255&b.gzhead.os),b.gzhead.extra&&b.gzhead.extra.length&&(tt(b,255&b.gzhead.extra.length),tt(b,b.gzhead.extra.length>>8&255)),b.gzhead.hcrc&&(B.adler=o(B.adler,b.pending_buf,b.pending,0)),b.gzindex=0,b.status=69):(tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,3),b.status=N);else{var z=u+(b.w_bits-8<<4)<<8;z|=(2<=b.strategy||b.level<2?0:b.level<6?1:b.level===6?2:3)<<6,b.strstart!==0&&(z|=32),z+=31-z%31,b.status=N,O(b,z),b.strstart!==0&&(O(b,B.adler>>>16),O(b,65535&B.adler)),B.adler=1}if(b.status===69)if(b.gzhead.extra){for(k=b.pending;b.gzindex<(65535&b.gzhead.extra.length)&&(b.pending!==b.pending_buf_size||(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending!==b.pending_buf_size));)tt(b,255&b.gzhead.extra[b.gzindex]),b.gzindex++;b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),b.gzindex===b.gzhead.extra.length&&(b.gzindex=0,b.status=73)}else b.status=73;if(b.status===73)if(b.gzhead.name){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.name.length?255&b.gzhead.name.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.gzindex=0,b.status=91)}else b.status=91;if(b.status===91)if(b.gzhead.comment){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.comment.length?255&b.gzhead.comment.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.status=103)}else b.status=103;if(b.status===103&&(b.gzhead.hcrc?(b.pending+2>b.pending_buf_size&&L(B),b.pending+2<=b.pending_buf_size&&(tt(b,255&B.adler),tt(b,B.adler>>8&255),B.adler=0,b.status=N)):b.status=N),b.pending!==0){if(L(B),B.avail_out===0)return b.last_flush=-1,c}else if(B.avail_in===0&&q(J)<=q(G)&&J!==l)return Y(B,-5);if(b.status===666&&B.avail_in!==0)return Y(B,-5);if(B.avail_in!==0||b.lookahead!==0||J!==r&&b.status!==666){var W=b.strategy===2?function(R,X){for(var et;;){if(R.lookahead===0&&(rt(R),R.lookahead===0)){if(X===r)return Q;break}if(R.match_length=0,et=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++,et&&(U(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,X===l?(U(R,!0),R.strm.avail_out===0?K:x):R.last_lit&&(U(R,!1),R.strm.avail_out===0)?Q:D}(b,J):b.strategy===3?function(R,X){for(var et,Z,it,ut,ht=R.window;;){if(R.lookahead<=S){if(rt(R),R.lookahead<=S&&X===r)return Q;if(R.lookahead===0)break}if(R.match_length=0,R.lookahead>=v&&0<R.strstart&&(Z=ht[it=R.strstart-1])===ht[++it]&&Z===ht[++it]&&Z===ht[++it]){ut=R.strstart+S;do;while(Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&Z===ht[++it]&&it<ut);R.match_length=S-(ut-it),R.match_length>R.lookahead&&(R.match_length=R.lookahead)}if(R.match_length>=v?(et=s._tr_tally(R,1,R.match_length-v),R.lookahead-=R.match_length,R.strstart+=R.match_length,R.match_length=0):(et=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++),et&&(U(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,X===l?(U(R,!0),R.strm.avail_out===0?K:x):R.last_lit&&(U(R,!1),R.strm.avail_out===0)?Q:D}(b,J):e[b.level].func(b,J);if(W!==K&&W!==x||(b.status=666),W===Q||W===K)return B.avail_out===0&&(b.last_flush=-1),c;if(W===D&&(J===1?s._tr_align(b):J!==5&&(s._tr_stored_block(b,0,0,!1),J===3&&(_(b.head),b.lookahead===0&&(b.strstart=0,b.block_start=0,b.insert=0))),L(B),B.avail_out===0))return b.last_flush=-1,c}return J!==l?c:b.wrap<=0?1:(b.wrap===2?(tt(b,255&B.adler),tt(b,B.adler>>8&255),tt(b,B.adler>>16&255),tt(b,B.adler>>24&255),tt(b,255&B.total_in),tt(b,B.total_in>>8&255),tt(b,B.total_in>>16&255),tt(b,B.total_in>>24&255)):(O(b,B.adler>>>16),O(b,65535&B.adler)),L(B),0<b.wrap&&(b.wrap=-b.wrap),b.pending!==0?c:1)},t.deflateEnd=function(B){var J;return B&&B.state?(J=B.state.status)!==F&&J!==69&&J!==73&&J!==91&&J!==103&&J!==N&&J!==666?Y(B,g):(B.state=null,J===N?Y(B,-3):c):g},t.deflateSetDictionary=function(B,J){var G,b,k,H,z,W,R,X,et=J.length;if(!B||!B.state||(H=(G=B.state).wrap)===2||H===1&&G.status!==F||G.lookahead)return g;for(H===1&&(B.adler=n(B.adler,J,et,0)),G.wrap=0,et>=G.w_size&&(H===0&&(_(G.head),G.strstart=0,G.block_start=0,G.insert=0),X=new i.Buf8(G.w_size),i.arraySet(X,J,et-G.w_size,G.w_size,0),J=X,et=G.w_size),z=B.avail_in,W=B.next_in,R=B.input,B.avail_in=et,B.next_in=0,B.input=J,rt(G);G.lookahead>=v;){for(b=G.strstart,k=G.lookahead-(v-1);G.ins_h=(G.ins_h<<G.hash_shift^G.window[b+v-1])&G.hash_mask,G.prev[b&G.w_mask]=G.head[G.ins_h],G.head[G.ins_h]=b,b++,--k;);G.strstart=b,G.lookahead=v-1,rt(G)}return G.strstart+=G.lookahead,G.block_start=G.strstart,G.insert=G.lookahead,G.lookahead=0,G.match_length=G.prev_length=v-1,G.match_available=0,B.next_in=W,B.input=R,B.avail_in=z,G.wrap=H,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(h,A,t){"use strict";A.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(h,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,l,c,g,p,d,I,u,f,C,m,E,w,y,v,S,M,F,N,Q,D;s=e.state,n=e.next_in,Q=e.input,o=n+(e.avail_in-5),a=e.next_out,D=e.output,r=a-(i-e.avail_out),l=a+(e.avail_out-257),c=s.dmax,g=s.wsize,p=s.whave,d=s.wnext,I=s.window,u=s.hold,f=s.bits,C=s.lencode,m=s.distcode,E=(1<<s.lenbits)-1,w=(1<<s.distbits)-1;t:do{f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=C[u&E];e:for(;;){if(u>>>=v=y>>>24,f-=v,(v=y>>>16&255)===0)D[a++]=65535&y;else{if(!(16&v)){if(!(64&v)){y=C[(65535&y)+(u&(1<<v)-1)];continue e}if(32&v){s.mode=12;break t}e.msg="invalid literal/length code",s.mode=30;break t}S=65535&y,(v&=15)&&(f<v&&(u+=Q[n++]<<f,f+=8),S+=u&(1<<v)-1,u>>>=v,f-=v),f<15&&(u+=Q[n++]<<f,f+=8,u+=Q[n++]<<f,f+=8),y=m[u&w];i:for(;;){if(u>>>=v=y>>>24,f-=v,!(16&(v=y>>>16&255))){if(!(64&v)){y=m[(65535&y)+(u&(1<<v)-1)];continue i}e.msg="invalid distance code",s.mode=30;break t}if(M=65535&y,f<(v&=15)&&(u+=Q[n++]<<f,(f+=8)<v&&(u+=Q[n++]<<f,f+=8)),c<(M+=u&(1<<v)-1)){e.msg="invalid distance too far back",s.mode=30;break t}if(u>>>=v,f-=v,(v=a-r)<M){if(p<(v=M-v)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break t}if(N=I,(F=0)===d){if(F+=g-v,v<S){for(S-=v;D[a++]=I[F++],--v;);F=a-M,N=D}}else if(d<v){if(F+=g+d-v,(v-=d)<S){for(S-=v;D[a++]=I[F++],--v;);if(F=0,d<S){for(S-=v=d;D[a++]=I[F++],--v;);F=a-M,N=D}}}else if(F+=d-v,v<S){for(S-=v;D[a++]=I[F++],--v;);F=a-M,N=D}for(;2<S;)D[a++]=N[F++],D[a++]=N[F++],D[a++]=N[F++],S-=3;S&&(D[a++]=N[F++],1<S&&(D[a++]=N[F++]))}else{for(F=a-M;D[a++]=D[F++],D[a++]=D[F++],D[a++]=D[F++],2<(S-=3););S&&(D[a++]=D[F++],1<S&&(D[a++]=D[F++]))}break}}break}}while(n<o&&a<l);n-=S=f>>3,u&=(1<<(f-=S<<3))-1,e.next_in=n,e.next_out=a,e.avail_in=n<o?o-n+5:5-(n-o),e.avail_out=a<l?l-a+257:257-(a-l),s.hold=u,s.bits=f}},{}],49:[function(h,A,t){"use strict";var e=h("../utils/common"),i=h("./adler32"),s=h("./crc32"),n=h("./inffast"),o=h("./inftrees"),a=1,r=2,l=0,c=-2,g=1,p=852,d=592;function I(F){return(F>>>24&255)+(F>>>8&65280)+((65280&F)<<8)+((255&F)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(F){var N;return F&&F.state?(N=F.state,F.total_in=F.total_out=N.total=0,F.msg="",N.wrap&&(F.adler=1&N.wrap),N.mode=g,N.last=0,N.havedict=0,N.dmax=32768,N.head=null,N.hold=0,N.bits=0,N.lencode=N.lendyn=new e.Buf32(p),N.distcode=N.distdyn=new e.Buf32(d),N.sane=1,N.back=-1,l):c}function C(F){var N;return F&&F.state?((N=F.state).wsize=0,N.whave=0,N.wnext=0,f(F)):c}function m(F,N){var Q,D;return F&&F.state?(D=F.state,N<0?(Q=0,N=-N):(Q=1+(N>>4),N<48&&(N&=15)),N&&(N<8||15<N)?c:(D.window!==null&&D.wbits!==N&&(D.window=null),D.wrap=Q,D.wbits=N,C(F))):c}function E(F,N){var Q,D;return F?(D=new u,(F.state=D).window=null,(Q=m(F,N))!==l&&(F.state=null),Q):c}var w,y,v=!0;function S(F){if(v){var N;for(w=new e.Buf32(512),y=new e.Buf32(32),N=0;N<144;)F.lens[N++]=8;for(;N<256;)F.lens[N++]=9;for(;N<280;)F.lens[N++]=7;for(;N<288;)F.lens[N++]=8;for(o(a,F.lens,0,288,w,0,F.work,{bits:9}),N=0;N<32;)F.lens[N++]=5;o(r,F.lens,0,32,y,0,F.work,{bits:5}),v=!1}F.lencode=w,F.lenbits=9,F.distcode=y,F.distbits=5}function M(F,N,Q,D){var K,x=F.state;return x.window===null&&(x.wsize=1<<x.wbits,x.wnext=0,x.whave=0,x.window=new e.Buf8(x.wsize)),D>=x.wsize?(e.arraySet(x.window,N,Q-x.wsize,x.wsize,0),x.wnext=0,x.whave=x.wsize):(D<(K=x.wsize-x.wnext)&&(K=D),e.arraySet(x.window,N,Q-D,K,x.wnext),(D-=K)?(e.arraySet(x.window,N,Q-D,D,0),x.wnext=D,x.whave=x.wsize):(x.wnext+=K,x.wnext===x.wsize&&(x.wnext=0),x.whave<x.wsize&&(x.whave+=K))),0}t.inflateReset=C,t.inflateReset2=m,t.inflateResetKeep=f,t.inflateInit=function(F){return E(F,15)},t.inflateInit2=E,t.inflate=function(F,N){var Q,D,K,x,Y,q,_,L,U,tt,O,V,rt,gt,nt,At,lt,ot,Qt,ft,B,J,G,b,k=0,H=new e.Buf8(4),z=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!F||!F.state||!F.output||!F.input&&F.avail_in!==0)return c;(Q=F.state).mode===12&&(Q.mode=13),Y=F.next_out,K=F.output,_=F.avail_out,x=F.next_in,D=F.input,q=F.avail_in,L=Q.hold,U=Q.bits,tt=q,O=_,J=l;t:for(;;)switch(Q.mode){case g:if(Q.wrap===0){Q.mode=13;break}for(;U<16;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(2&Q.wrap&&L===35615){H[Q.check=0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0),U=L=0,Q.mode=2;break}if(Q.flags=0,Q.head&&(Q.head.done=!1),!(1&Q.wrap)||(((255&L)<<8)+(L>>8))%31){F.msg="incorrect header check",Q.mode=30;break}if((15&L)!=8){F.msg="unknown compression method",Q.mode=30;break}if(U-=4,B=8+(15&(L>>>=4)),Q.wbits===0)Q.wbits=B;else if(B>Q.wbits){F.msg="invalid window size",Q.mode=30;break}Q.dmax=1<<B,F.adler=Q.check=1,Q.mode=512&L?10:12,U=L=0;break;case 2:for(;U<16;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(Q.flags=L,(255&Q.flags)!=8){F.msg="unknown compression method",Q.mode=30;break}if(57344&Q.flags){F.msg="unknown header flags set",Q.mode=30;break}Q.head&&(Q.head.text=L>>8&1),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0)),U=L=0,Q.mode=3;case 3:for(;U<32;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}Q.head&&(Q.head.time=L),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,H[2]=L>>>16&255,H[3]=L>>>24&255,Q.check=s(Q.check,H,4,0)),U=L=0,Q.mode=4;case 4:for(;U<16;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}Q.head&&(Q.head.xflags=255&L,Q.head.os=L>>8),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0)),U=L=0,Q.mode=5;case 5:if(1024&Q.flags){for(;U<16;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}Q.length=L,Q.head&&(Q.head.extra_len=L),512&Q.flags&&(H[0]=255&L,H[1]=L>>>8&255,Q.check=s(Q.check,H,2,0)),U=L=0}else Q.head&&(Q.head.extra=null);Q.mode=6;case 6:if(1024&Q.flags&&(q<(V=Q.length)&&(V=q),V&&(Q.head&&(B=Q.head.extra_len-Q.length,Q.head.extra||(Q.head.extra=new Array(Q.head.extra_len)),e.arraySet(Q.head.extra,D,x,V,B)),512&Q.flags&&(Q.check=s(Q.check,D,V,x)),q-=V,x+=V,Q.length-=V),Q.length))break t;Q.length=0,Q.mode=7;case 7:if(2048&Q.flags){if(q===0)break t;for(V=0;B=D[x+V++],Q.head&&B&&Q.length<65536&&(Q.head.name+=String.fromCharCode(B)),B&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,x)),q-=V,x+=V,B)break t}else Q.head&&(Q.head.name=null);Q.length=0,Q.mode=8;case 8:if(4096&Q.flags){if(q===0)break t;for(V=0;B=D[x+V++],Q.head&&B&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(B)),B&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,x)),q-=V,x+=V,B)break t}else Q.head&&(Q.head.comment=null);Q.mode=9;case 9:if(512&Q.flags){for(;U<16;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(L!==(65535&Q.check)){F.msg="header crc mismatch",Q.mode=30;break}U=L=0}Q.head&&(Q.head.hcrc=Q.flags>>9&1,Q.head.done=!0),F.adler=Q.check=0,Q.mode=12;break;case 10:for(;U<32;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}F.adler=Q.check=I(L),U=L=0,Q.mode=11;case 11:if(Q.havedict===0)return F.next_out=Y,F.avail_out=_,F.next_in=x,F.avail_in=q,Q.hold=L,Q.bits=U,2;F.adler=Q.check=1,Q.mode=12;case 12:if(N===5||N===6)break t;case 13:if(Q.last){L>>>=7&U,U-=7&U,Q.mode=27;break}for(;U<3;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}switch(Q.last=1&L,U-=1,3&(L>>>=1)){case 0:Q.mode=14;break;case 1:if(S(Q),Q.mode=20,N!==6)break;L>>>=2,U-=2;break t;case 2:Q.mode=17;break;case 3:F.msg="invalid block type",Q.mode=30}L>>>=2,U-=2;break;case 14:for(L>>>=7&U,U-=7&U;U<32;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if((65535&L)!=(L>>>16^65535)){F.msg="invalid stored block lengths",Q.mode=30;break}if(Q.length=65535&L,U=L=0,Q.mode=15,N===6)break t;case 15:Q.mode=16;case 16:if(V=Q.length){if(q<V&&(V=q),_<V&&(V=_),V===0)break t;e.arraySet(K,D,x,V,Y),q-=V,x+=V,_-=V,Y+=V,Q.length-=V;break}Q.mode=12;break;case 17:for(;U<14;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(Q.nlen=257+(31&L),L>>>=5,U-=5,Q.ndist=1+(31&L),L>>>=5,U-=5,Q.ncode=4+(15&L),L>>>=4,U-=4,286<Q.nlen||30<Q.ndist){F.msg="too many length or distance symbols",Q.mode=30;break}Q.have=0,Q.mode=18;case 18:for(;Q.have<Q.ncode;){for(;U<3;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}Q.lens[z[Q.have++]]=7&L,L>>>=3,U-=3}for(;Q.have<19;)Q.lens[z[Q.have++]]=0;if(Q.lencode=Q.lendyn,Q.lenbits=7,G={bits:Q.lenbits},J=o(0,Q.lens,0,19,Q.lencode,0,Q.work,G),Q.lenbits=G.bits,J){F.msg="invalid code lengths set",Q.mode=30;break}Q.have=0,Q.mode=19;case 19:for(;Q.have<Q.nlen+Q.ndist;){for(;At=(k=Q.lencode[L&(1<<Q.lenbits)-1])>>>16&255,lt=65535&k,!((nt=k>>>24)<=U);){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(lt<16)L>>>=nt,U-=nt,Q.lens[Q.have++]=lt;else{if(lt===16){for(b=nt+2;U<b;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(L>>>=nt,U-=nt,Q.have===0){F.msg="invalid bit length repeat",Q.mode=30;break}B=Q.lens[Q.have-1],V=3+(3&L),L>>>=2,U-=2}else if(lt===17){for(b=nt+3;U<b;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}U-=nt,B=0,V=3+(7&(L>>>=nt)),L>>>=3,U-=3}else{for(b=nt+7;U<b;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}U-=nt,B=0,V=11+(127&(L>>>=nt)),L>>>=7,U-=7}if(Q.have+V>Q.nlen+Q.ndist){F.msg="invalid bit length repeat",Q.mode=30;break}for(;V--;)Q.lens[Q.have++]=B}}if(Q.mode===30)break;if(Q.lens[256]===0){F.msg="invalid code -- missing end-of-block",Q.mode=30;break}if(Q.lenbits=9,G={bits:Q.lenbits},J=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,G),Q.lenbits=G.bits,J){F.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,G={bits:Q.distbits},J=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,G),Q.distbits=G.bits,J){F.msg="invalid distances set",Q.mode=30;break}if(Q.mode=20,N===6)break t;case 20:Q.mode=21;case 21:if(6<=q&&258<=_){F.next_out=Y,F.avail_out=_,F.next_in=x,F.avail_in=q,Q.hold=L,Q.bits=U,n(F,O),Y=F.next_out,K=F.output,_=F.avail_out,x=F.next_in,D=F.input,q=F.avail_in,L=Q.hold,U=Q.bits,Q.mode===12&&(Q.back=-1);break}for(Q.back=0;At=(k=Q.lencode[L&(1<<Q.lenbits)-1])>>>16&255,lt=65535&k,!((nt=k>>>24)<=U);){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(At&&!(240&At)){for(ot=nt,Qt=At,ft=lt;At=(k=Q.lencode[ft+((L&(1<<ot+Qt)-1)>>ot)])>>>16&255,lt=65535&k,!(ot+(nt=k>>>24)<=U);){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}L>>>=ot,U-=ot,Q.back+=ot}if(L>>>=nt,U-=nt,Q.back+=nt,Q.length=lt,At===0){Q.mode=26;break}if(32&At){Q.back=-1,Q.mode=12;break}if(64&At){F.msg="invalid literal/length code",Q.mode=30;break}Q.extra=15&At,Q.mode=22;case 22:if(Q.extra){for(b=Q.extra;U<b;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}Q.length+=L&(1<<Q.extra)-1,L>>>=Q.extra,U-=Q.extra,Q.back+=Q.extra}Q.was=Q.length,Q.mode=23;case 23:for(;At=(k=Q.distcode[L&(1<<Q.distbits)-1])>>>16&255,lt=65535&k,!((nt=k>>>24)<=U);){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(!(240&At)){for(ot=nt,Qt=At,ft=lt;At=(k=Q.distcode[ft+((L&(1<<ot+Qt)-1)>>ot)])>>>16&255,lt=65535&k,!(ot+(nt=k>>>24)<=U);){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}L>>>=ot,U-=ot,Q.back+=ot}if(L>>>=nt,U-=nt,Q.back+=nt,64&At){F.msg="invalid distance code",Q.mode=30;break}Q.offset=lt,Q.extra=15&At,Q.mode=24;case 24:if(Q.extra){for(b=Q.extra;U<b;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}Q.offset+=L&(1<<Q.extra)-1,L>>>=Q.extra,U-=Q.extra,Q.back+=Q.extra}if(Q.offset>Q.dmax){F.msg="invalid distance too far back",Q.mode=30;break}Q.mode=25;case 25:if(_===0)break t;if(V=O-_,Q.offset>V){if((V=Q.offset-V)>Q.whave&&Q.sane){F.msg="invalid distance too far back",Q.mode=30;break}rt=V>Q.wnext?(V-=Q.wnext,Q.wsize-V):Q.wnext-V,V>Q.length&&(V=Q.length),gt=Q.window}else gt=K,rt=Y-Q.offset,V=Q.length;for(_<V&&(V=_),_-=V,Q.length-=V;K[Y++]=gt[rt++],--V;);Q.length===0&&(Q.mode=21);break;case 26:if(_===0)break t;K[Y++]=Q.length,_--,Q.mode=21;break;case 27:if(Q.wrap){for(;U<32;){if(q===0)break t;q--,L|=D[x++]<<U,U+=8}if(O-=_,F.total_out+=O,Q.total+=O,O&&(F.adler=Q.check=Q.flags?s(Q.check,K,O,Y-O):i(Q.check,K,O,Y-O)),O=_,(Q.flags?L:I(L))!==Q.check){F.msg="incorrect data check",Q.mode=30;break}U=L=0}Q.mode=28;case 28:if(Q.wrap&&Q.flags){for(;U<32;){if(q===0)break t;q--,L+=D[x++]<<U,U+=8}if(L!==(4294967295&Q.total)){F.msg="incorrect length check",Q.mode=30;break}U=L=0}Q.mode=29;case 29:J=1;break t;case 30:J=-3;break t;case 31:return-4;case 32:default:return c}return F.next_out=Y,F.avail_out=_,F.next_in=x,F.avail_in=q,Q.hold=L,Q.bits=U,(Q.wsize||O!==F.avail_out&&Q.mode<30&&(Q.mode<27||N!==4))&&M(F,F.output,F.next_out,O-F.avail_out)?(Q.mode=31,-4):(tt-=F.avail_in,O-=F.avail_out,F.total_in+=tt,F.total_out+=O,Q.total+=O,Q.wrap&&O&&(F.adler=Q.check=Q.flags?s(Q.check,K,O,F.next_out-O):i(Q.check,K,O,F.next_out-O)),F.data_type=Q.bits+(Q.last?64:0)+(Q.mode===12?128:0)+(Q.mode===20||Q.mode===15?256:0),(tt==0&&O===0||N===4)&&J===l&&(J=-5),J)},t.inflateEnd=function(F){if(!F||!F.state)return c;var N=F.state;return N.window&&(N.window=null),F.state=null,l},t.inflateGetHeader=function(F,N){var Q;return F&&F.state&&2&(Q=F.state).wrap?((Q.head=N).done=!1,l):c},t.inflateSetDictionary=function(F,N){var Q,D=N.length;return F&&F.state?(Q=F.state).wrap!==0&&Q.mode!==11?c:Q.mode===11&&i(1,N,D,0)!==Q.check?-3:M(F,N,D,D)?(Q.mode=31,-4):(Q.havedict=1,l):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(h,A,t){"use strict";var e=h("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],s=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],o=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];A.exports=function(a,r,l,c,g,p,d,I){var u,f,C,m,E,w,y,v,S,M=I.bits,F=0,N=0,Q=0,D=0,K=0,x=0,Y=0,q=0,_=0,L=0,U=null,tt=0,O=new e.Buf16(16),V=new e.Buf16(16),rt=null,gt=0;for(F=0;F<=15;F++)O[F]=0;for(N=0;N<c;N++)O[r[l+N]]++;for(K=M,D=15;1<=D&&O[D]===0;D--);if(D<K&&(K=D),D===0)return g[p++]=20971520,g[p++]=20971520,I.bits=1,0;for(Q=1;Q<D&&O[Q]===0;Q++);for(K<Q&&(K=Q),F=q=1;F<=15;F++)if(q<<=1,(q-=O[F])<0)return-1;if(0<q&&(a===0||D!==1))return-1;for(V[1]=0,F=1;F<15;F++)V[F+1]=V[F]+O[F];for(N=0;N<c;N++)r[l+N]!==0&&(d[V[r[l+N]]++]=N);if(w=a===0?(U=rt=d,19):a===1?(U=i,tt-=257,rt=s,gt-=257,256):(U=n,rt=o,-1),F=Q,E=p,Y=N=L=0,C=-1,m=(_=1<<(x=K))-1,a===1&&852<_||a===2&&592<_)return 1;for(;;){for(y=F-Y,S=d[N]<w?(v=0,d[N]):d[N]>w?(v=rt[gt+d[N]],U[tt+d[N]]):(v=96,0),u=1<<F-Y,Q=f=1<<x;g[E+(L>>Y)+(f-=u)]=y<<24|v<<16|S|0,f!==0;);for(u=1<<F-1;L&u;)u>>=1;if(u!==0?(L&=u-1,L+=u):L=0,N++,--O[F]==0){if(F===D)break;F=r[l+d[N]]}if(K<F&&(L&m)!==C){for(Y===0&&(Y=K),E+=Q,q=1<<(x=F-Y);x+Y<D&&!((q-=O[x+Y])<=0);)x++,q<<=1;if(_+=1<<x,a===1&&852<_||a===2&&592<_)return 1;g[C=L&m]=K<<24|x<<16|E-p|0}}return L!==0&&(g[E+L]=F-Y<<24|64<<16|0),I.bits=K,0}},{"../utils/common":41}],51:[function(h,A,t){"use strict";A.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(h,A,t){"use strict";var e=h("../utils/common"),i=0,s=1;function n(k){for(var H=k.length;0<=--H;)k[H]=0}var o=0,a=29,r=256,l=r+1+a,c=30,g=19,p=2*l+1,d=15,I=16,u=7,f=256,C=16,m=17,E=18,w=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],y=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],v=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],M=new Array(2*(l+2));n(M);var F=new Array(2*c);n(F);var N=new Array(512);n(N);var Q=new Array(256);n(Q);var D=new Array(a);n(D);var K,x,Y,q=new Array(c);function _(k,H,z,W,R){this.static_tree=k,this.extra_bits=H,this.extra_base=z,this.elems=W,this.max_length=R,this.has_stree=k&&k.length}function L(k,H){this.dyn_tree=k,this.max_code=0,this.stat_desc=H}function U(k){return k<256?N[k]:N[256+(k>>>7)]}function tt(k,H){k.pending_buf[k.pending++]=255&H,k.pending_buf[k.pending++]=H>>>8&255}function O(k,H,z){k.bi_valid>I-z?(k.bi_buf|=H<<k.bi_valid&65535,tt(k,k.bi_buf),k.bi_buf=H>>I-k.bi_valid,k.bi_valid+=z-I):(k.bi_buf|=H<<k.bi_valid&65535,k.bi_valid+=z)}function V(k,H,z){O(k,z[2*H],z[2*H+1])}function rt(k,H){for(var z=0;z|=1&k,k>>>=1,z<<=1,0<--H;);return z>>>1}function gt(k,H,z){var W,R,X=new Array(d+1),et=0;for(W=1;W<=d;W++)X[W]=et=et+z[W-1]<<1;for(R=0;R<=H;R++){var Z=k[2*R+1];Z!==0&&(k[2*R]=rt(X[Z]++,Z))}}function nt(k){var H;for(H=0;H<l;H++)k.dyn_ltree[2*H]=0;for(H=0;H<c;H++)k.dyn_dtree[2*H]=0;for(H=0;H<g;H++)k.bl_tree[2*H]=0;k.dyn_ltree[2*f]=1,k.opt_len=k.static_len=0,k.last_lit=k.matches=0}function At(k){8<k.bi_valid?tt(k,k.bi_buf):0<k.bi_valid&&(k.pending_buf[k.pending++]=k.bi_buf),k.bi_buf=0,k.bi_valid=0}function lt(k,H,z,W){var R=2*H,X=2*z;return k[R]<k[X]||k[R]===k[X]&&W[H]<=W[z]}function ot(k,H,z){for(var W=k.heap[z],R=z<<1;R<=k.heap_len&&(R<k.heap_len&<(H,k.heap[R+1],k.heap[R],k.depth)&&R++,!lt(H,W,k.heap[R],k.depth));)k.heap[z]=k.heap[R],z=R,R<<=1;k.heap[z]=W}function Qt(k,H,z){var W,R,X,et,Z=0;if(k.last_lit!==0)for(;W=k.pending_buf[k.d_buf+2*Z]<<8|k.pending_buf[k.d_buf+2*Z+1],R=k.pending_buf[k.l_buf+Z],Z++,W===0?V(k,R,H):(V(k,(X=Q[R])+r+1,H),(et=w[X])!==0&&O(k,R-=D[X],et),V(k,X=U(--W),z),(et=y[X])!==0&&O(k,W-=q[X],et)),Z<k.last_lit;);V(k,f,H)}function ft(k,H){var z,W,R,X=H.dyn_tree,et=H.stat_desc.static_tree,Z=H.stat_desc.has_stree,it=H.stat_desc.elems,ut=-1;for(k.heap_len=0,k.heap_max=p,z=0;z<it;z++)X[2*z]!==0?(k.heap[++k.heap_len]=ut=z,k.depth[z]=0):X[2*z+1]=0;for(;k.heap_len<2;)X[2*(R=k.heap[++k.heap_len]=ut<2?++ut:0)]=1,k.depth[R]=0,k.opt_len--,Z&&(k.static_len-=et[2*R+1]);for(H.max_code=ut,z=k.heap_len>>1;1<=z;z--)ot(k,X,z);for(R=it;z=k.heap[1],k.heap[1]=k.heap[k.heap_len--],ot(k,X,1),W=k.heap[1],k.heap[--k.heap_max]=z,k.heap[--k.heap_max]=W,X[2*R]=X[2*z]+X[2*W],k.depth[R]=(k.depth[z]>=k.depth[W]?k.depth[z]:k.depth[W])+1,X[2*z+1]=X[2*W+1]=R,k.heap[1]=R++,ot(k,X,1),2<=k.heap_len;);k.heap[--k.heap_max]=k.heap[1],function(ht,Ht){var Xe,qt,Ze,Et,Fi,xs,Vt=Ht.dyn_tree,Nn=Ht.max_code,Zo=Ht.stat_desc.static_tree,_o=Ht.stat_desc.has_stree,jo=Ht.stat_desc.extra_bits,xn=Ht.stat_desc.extra_base,_e=Ht.stat_desc.max_length,ki=0;for(Et=0;Et<=d;Et++)ht.bl_count[Et]=0;for(Vt[2*ht.heap[ht.heap_max]+1]=0,Xe=ht.heap_max+1;Xe<p;Xe++)_e<(Et=Vt[2*Vt[2*(qt=ht.heap[Xe])+1]+1]+1)&&(Et=_e,ki++),Vt[2*qt+1]=Et,Nn<qt||(ht.bl_count[Et]++,Fi=0,xn<=qt&&(Fi=jo[qt-xn]),xs=Vt[2*qt],ht.opt_len+=xs*(Et+Fi),_o&&(ht.static_len+=xs*(Zo[2*qt+1]+Fi)));if(ki!==0){do{for(Et=_e-1;ht.bl_count[Et]===0;)Et--;ht.bl_count[Et]--,ht.bl_count[Et+1]+=2,ht.bl_count[_e]--,ki-=2}while(0<ki);for(Et=_e;Et!==0;Et--)for(qt=ht.bl_count[Et];qt!==0;)Nn<(Ze=ht.heap[--Xe])||(Vt[2*Ze+1]!==Et&&(ht.opt_len+=(Et-Vt[2*Ze+1])*Vt[2*Ze],Vt[2*Ze+1]=Et),qt--)}}(k,H),gt(X,ut,k.bl_count)}function B(k,H,z){var W,R,X=-1,et=H[1],Z=0,it=7,ut=4;for(et===0&&(it=138,ut=3),H[2*(z+1)+1]=65535,W=0;W<=z;W++)R=et,et=H[2*(W+1)+1],++Z<it&&R===et||(Z<ut?k.bl_tree[2*R]+=Z:R!==0?(R!==X&&k.bl_tree[2*R]++,k.bl_tree[2*C]++):Z<=10?k.bl_tree[2*m]++:k.bl_tree[2*E]++,X=R,ut=(Z=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4))}function J(k,H,z){var W,R,X=-1,et=H[1],Z=0,it=7,ut=4;for(et===0&&(it=138,ut=3),W=0;W<=z;W++)if(R=et,et=H[2*(W+1)+1],!(++Z<it&&R===et)){if(Z<ut)for(;V(k,R,k.bl_tree),--Z!=0;);else R!==0?(R!==X&&(V(k,R,k.bl_tree),Z--),V(k,C,k.bl_tree),O(k,Z-3,2)):Z<=10?(V(k,m,k.bl_tree),O(k,Z-3,3)):(V(k,E,k.bl_tree),O(k,Z-11,7));X=R,ut=(Z=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4)}}n(q);var G=!1;function b(k,H,z,W){O(k,(o<<1)+(W?1:0),3),function(R,X,et,Z){At(R),Z&&(tt(R,et),tt(R,~et)),e.arraySet(R.pending_buf,R.window,X,et,R.pending),R.pending+=et}(k,H,z,!0)}t._tr_init=function(k){G||(function(){var H,z,W,R,X,et=new Array(d+1);for(R=W=0;R<a-1;R++)for(D[R]=W,H=0;H<1<<w[R];H++)Q[W++]=R;for(Q[W-1]=R,R=X=0;R<16;R++)for(q[R]=X,H=0;H<1<<y[R];H++)N[X++]=R;for(X>>=7;R<c;R++)for(q[R]=X<<7,H=0;H<1<<y[R]-7;H++)N[256+X++]=R;for(z=0;z<=d;z++)et[z]=0;for(H=0;H<=143;)M[2*H+1]=8,H++,et[8]++;for(;H<=255;)M[2*H+1]=9,H++,et[9]++;for(;H<=279;)M[2*H+1]=7,H++,et[7]++;for(;H<=287;)M[2*H+1]=8,H++,et[8]++;for(gt(M,l+1,et),H=0;H<c;H++)F[2*H+1]=5,F[2*H]=rt(H,5);K=new _(M,w,r+1,l,d),x=new _(F,y,0,c,d),Y=new _(new Array(0),v,0,g,u)}(),G=!0),k.l_desc=new L(k.dyn_ltree,K),k.d_desc=new L(k.dyn_dtree,x),k.bl_desc=new L(k.bl_tree,Y),k.bi_buf=0,k.bi_valid=0,nt(k)},t._tr_stored_block=b,t._tr_flush_block=function(k,H,z,W){var R,X,et=0;0<k.level?(k.strm.data_type===2&&(k.strm.data_type=function(Z){var it,ut=4093624447;for(it=0;it<=31;it++,ut>>>=1)if(1&ut&&Z.dyn_ltree[2*it]!==0)return i;if(Z.dyn_ltree[18]!==0||Z.dyn_ltree[20]!==0||Z.dyn_ltree[26]!==0)return s;for(it=32;it<r;it++)if(Z.dyn_ltree[2*it]!==0)return s;return i}(k)),ft(k,k.l_desc),ft(k,k.d_desc),et=function(Z){var it;for(B(Z,Z.dyn_ltree,Z.l_desc.max_code),B(Z,Z.dyn_dtree,Z.d_desc.max_code),ft(Z,Z.bl_desc),it=g-1;3<=it&&Z.bl_tree[2*S[it]+1]===0;it--);return Z.opt_len+=3*(it+1)+5+5+4,it}(k),R=k.opt_len+3+7>>>3,(X=k.static_len+3+7>>>3)<=R&&(R=X)):R=X=z+5,z+4<=R&&H!==-1?b(k,H,z,W):k.strategy===4||X===R?(O(k,2+(W?1:0),3),Qt(k,M,F)):(O(k,4+(W?1:0),3),function(Z,it,ut,ht){var Ht;for(O(Z,it-257,5),O(Z,ut-1,5),O(Z,ht-4,4),Ht=0;Ht<ht;Ht++)O(Z,Z.bl_tree[2*S[Ht]+1],3);J(Z,Z.dyn_ltree,it-1),J(Z,Z.dyn_dtree,ut-1)}(k,k.l_desc.max_code+1,k.d_desc.max_code+1,et+1),Qt(k,k.dyn_ltree,k.dyn_dtree)),nt(k),W&&At(k)},t._tr_tally=function(k,H,z){return k.pending_buf[k.d_buf+2*k.last_lit]=H>>>8&255,k.pending_buf[k.d_buf+2*k.last_lit+1]=255&H,k.pending_buf[k.l_buf+k.last_lit]=255&z,k.last_lit++,H===0?k.dyn_ltree[2*z]++:(k.matches++,H--,k.dyn_ltree[2*(Q[z]+r+1)]++,k.dyn_dtree[2*U(H)]++),k.last_lit===k.lit_bufsize-1},t._tr_align=function(k){O(k,2,3),V(k,f,M),function(H){H.bi_valid===16?(tt(H,H.bi_buf),H.bi_buf=0,H.bi_valid=0):8<=H.bi_valid&&(H.pending_buf[H.pending++]=255&H.bi_buf,H.bi_buf>>=8,H.bi_valid-=8)}(k)}},{"../utils/common":41}],53:[function(h,A,t){"use strict";A.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(h,A,t){(function(e){(function(i,s){"use strict";if(!i.setImmediate){var n,o,a,r,l=1,c={},g=!1,p=i.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(i);d=d&&d.setTimeout?d:i,n={}.toString.call(i.process)==="[object process]"?function(C){process.nextTick(function(){u(C)})}:function(){if(i.postMessage&&!i.importScripts){var C=!0,m=i.onmessage;return i.onmessage=function(){C=!1},i.postMessage("","*"),i.onmessage=m,C}}()?(r="setImmediate$"+Math.random()+"$",i.addEventListener?i.addEventListener("message",f,!1):i.attachEvent("onmessage",f),function(C){i.postMessage(r+C,"*")}):i.MessageChannel?((a=new MessageChannel).port1.onmessage=function(C){u(C.data)},function(C){a.port2.postMessage(C)}):p&&"onreadystatechange"in p.createElement("script")?(o=p.documentElement,function(C){var m=p.createElement("script");m.onreadystatechange=function(){u(C),m.onreadystatechange=null,o.removeChild(m),m=null},o.appendChild(m)}):function(C){setTimeout(u,0,C)},d.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var m=new Array(arguments.length-1),E=0;E<m.length;E++)m[E]=arguments[E+1];var w={callback:C,args:m};return c[l]=w,n(l),l++},d.clearImmediate=I}function I(C){delete c[C]}function u(C){if(g)setTimeout(u,0,C);else{var m=c[C];if(m){g=!0;try{(function(E){var w=E.callback,y=E.args;switch(y.length){case 0:w();break;case 1:w(y[0]);break;case 2:w(y[0],y[1]);break;case 3:w(y[0],y[1],y[2]);break;default:w.apply(s,y)}})(m)}finally{I(C),g=!1}}}}function f(C){C.source===i&&typeof C.data=="string"&&C.data.indexOf(r)===0&&u(+C.data.slice(r.length))}})(typeof self>"u"?e===void 0?this:e:self)}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})});var Qr={};Di(Qr,{default:()=>Ns});module.exports=aa(Qr);var $=require("obsidian");yt();var bt=require("obsidian");var Bt=require("obsidian");yt();function Ni(h){let A=(h.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function Wt(h,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(h))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(h))}}function $t(h,A){let t=Ni(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Gn(h,A,!0);case"us":return Wt(h,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Wt(h,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Wt(h,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Wt(h,{...t,dateStyle:"medium",timeStyle:"short"})}}function Pn(h,A){let t=Ni(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Gn(h,A,!1);case"us":return Wt(h,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Wt(h,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Wt(h,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(h).getFullYear()===e.getFullYear();return Wt(h,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Rn(h,A){let t=Ni(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return Wt(h,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Gn(h,A,t){let e=Ni(A),i=new Intl.DateTimeFormat("en-CA",{...e,year:"numeric",month:"2-digit",day:"2-digit",...t?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:{}}).formatToParts(new Date(h)),s=o=>i.find(a=>a.type===o)?.value??"",n=`${s("year")}-${s("month")}-${s("day")}`;return t?`${n} ${s("hour")}:${s("minute")}`:n}function ye(h,A,t){let e=h.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(A>99?"99+":String(A))}var di={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},Ui=class extends Bt.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 ie}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()===ct&&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,Bt.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,Bt.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,Bt.setIcon)(o.createSpan({cls:"stashpad-panels-global-btn-icon"}),"scroll-text"),o.createSpan({cls:"stashpad-panels-global-btn-text",text:"Log"}),o.onclick=()=>this.openLogFromPanel();let a=n.createEl("button",{cls:"stashpad-panels-global-btn"});(0,Bt.setIcon)(a.createSpan({cls:"stashpad-panels-global-btn-icon"}),"bell"),a.createSpan({cls:"stashpad-panels-global-btn-text",text:"Notifications"}),a.onclick=()=>this.openNotificationsFromPanel();let r=t.createDiv({cls:"stashpad-panels-bar"});for(let c of Object.keys(di)){let g=di[c],p=r.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,Bt.setIcon)(p.createSpan({cls:"stashpad-panels-bar-btn-icon"}),g.icon),p.createSpan({cls:"stashpad-panels-bar-btn-text",text:g.label}),this.activePanel===c&&p.addClass("is-active"),p.onclick=()=>{this.activePanel!==c&&(this.activePanel=c,this.render())}}let l=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(l):this.activePanel==="shared"?this.renderSharedPanel(l):this.activePanel==="tasks"&&this.renderTasksPanel(l)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new Bt.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,Bt.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,Bt.setIcon)(o,"list"),o.setAttr("aria-label","Pinned view options"),o.onclick=p=>{p.stopPropagation(),this.openPinnedOptionsMenu(p)};let a=this.plugin.listPinnedNotes();if(a.length===0){e.createDiv({cls:"stashpad-pinned-empty"}).setText("No pinned notes yet \u2014 right-click a note and choose \u201CPin to sidebar.\u201D");return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"){a.forEach((p,d)=>this.renderPinnedRow(e,p,d));return}let l=new Map;a.forEach((p,d)=>{let I=l.get(p.folder);I||(I=[],l.set(p.folder,I)),I.push({pin:p,idx:d})});let c=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,g=Array.from(l.keys());c&&l.has(c)&&(g.splice(g.indexOf(c),1),g.unshift(c));for(let p of g){let d=p.split("/").pop()||p,I=e.createDiv({cls:"stashpad-pinned-group-header"});p===c&&I.addClass("is-active-folder"),I.createSpan({cls:"stashpad-pinned-group-name",text:d});let u=l.get(p)??[];for(let{pin:f,idx:C}of u)this.renderPinnedRow(e,f,C)}}renderPinnedRow(t,e,i){let s=this.findFileFor(e);if(!s)return;let n=this.app.metadataCache.getFileCache(s)?.frontmatter??{},o=this.titleFromFile(s),a=typeof n.color=="string"?n.color:null,r=n.completed===!0,l=this.childrenOf(e.folder,e.id).length,c=l>0,g=this.expanded.has(`${e.folder}|${e.id}`),p=t.createDiv({cls:"stashpad-pinned-row"});a&&p.addClass("has-color"),r&&p.addClass("is-completed"),p.draggable=!0,p.dataset.pinIdx=String(i),p.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=p.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;p.toggleClass("drop-before",E),p.toggleClass("drop-after",!E)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",C=>{C.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let E=p.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?i:i+1)});let d=p.createSpan({cls:"stashpad-pinned-toggle"});c&&(ye(d,l,g),d.onclick=C=>{C.stopPropagation();let m=`${e.folder}|${e.id}`;this.expanded.has(m)?this.expanded.delete(m):this.expanded.add(m),this.render()});let I=p.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(I,c?"folder-tree":"file-text"),a&&(I.style.color=a);let u=p.createSpan({cls:"stashpad-pinned-label",text:o});u.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(p.createSpan({cls:"stashpad-pinned-folder",text:f}),p.oncontextmenu=C=>{C.preventDefault();let m=new Bt.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},c&&g){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(C,e.folder,e.id,1)}}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],l;!a&&!r?l=Date.now():a?r?l=(a.pinnedAt+r.pinnedAt)/2:l=a.pinnedAt+1e3:l=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=l})}catch(c){console.warn("[Stashpad] pin reorder failed",c)}this.render()}renderPinnedSubtree(t,e,i,s){let n=this.childrenOf(e,i);for(let o of n){let a=this.app.metadataCache.getFileCache(o)?.frontmatter??{},r=typeof a.id=="string"?a.id:null;if(!r)continue;let l=typeof a.color=="string"?a.color:null,c=a.completed===!0,g=this.childrenOf(e,r).length,p=g>0,d=this.expanded.has(`${e}|${r}`),I=t.createDiv({cls:"stashpad-pinned-subrow"});c&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});p&&(ye(u,g,d),u.onclick=m=>{m.stopPropagation();let E=`${e}|${r}`;this.expanded.has(E)?this.expanded.delete(E):this.expanded.add(E),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(f,"file-text"),l&&(f.style.color=l);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:r}),p&&d&&this.renderPinnedSubtree(t,e,r,s+1)}}findFileFor(t){for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==t.folder)continue;if(this.app.metadataCache.getFileCache(e)?.frontmatter?.id===t.id)return e}return null}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===T&&(a==null||a===T)){if(o.id===T)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.created??"",l=a?.created??"";return r.localeCompare(l)}),i}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new Bt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Tt(),ci));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(T)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===ct)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(ct);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()===ct?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let c of s){let g=c.authorId;g&&!n.has(g)&&n.set(g,c.authorDisplay||g)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(c,g,p)=>{let d=o.createEl("button",{cls:"stashpad-shared-chip",text:c});return g&&d.addClass("is-active"),d.onclick=p,d};if(a("All",this.sharedAuthorFilter==="all",()=>{this.sharedAuthorFilter="all",this.render()}),a("Mine",this.sharedAuthorFilter==="mine",()=>{this.sharedAuthorFilter="mine",this.render()}),a("Others",this.sharedAuthorFilter==="others",()=>{this.sharedAuthorFilter="others",this.render()}),n.size>1){let c=o.createEl("select",{cls:"stashpad-shared-author-select"}),g=c.createEl("option",{text:"Any author"});g.value="__any__";for(let[d,I]of n){let u=c.createEl("option",{text:I});u.value=d}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=p,c.onchange=()=>{let d=c.value;d==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=d,this.render()}}let r=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&r.addClass("is-active"),r.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let l=s.filter(c=>{if(this.sharedContribOnly&&c.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return c.authorId===i;case"others":return c.authorId!==i;default:return c.authorId===this.sharedAuthorFilter}});if(l.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let c of l){let g=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),p=g.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(p,"users"),c.color&&(p.style.color=c.color);let d=g.createSpan({cls:"stashpad-pinned-label",text:c.title});d.onclick=()=>this.openSharedFromPanel(c.folder,c.id);let I=c.folder.split("/").pop()||c.folder;g.createSpan({cls:"stashpad-pinned-folder",text:I}),c.authorDisplay&&g.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===i?`you \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:`by ${c.authorDisplay}${c.contributorCount>0?` \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),i=new Set(e),s=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};r.id===T&&s.set(a,this.extractAuthorId(r.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a)||a.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof r.id!="string"||r.id===T)continue;let l=this.extractAuthorId(r.author),c=Array.isArray(r.contributors)?r.contributors.filter(m=>typeof m=="string"):[],g=s.get(a)??null;if(!(c.length>0||g===t&&(l!==null&&l!==t)))continue;let f=this.titleFromFile(o),C=typeof r.color=="string"?r.color:null;n.push({file:o,folder:a,id:r.id,title:f,color:C,authorId:l,authorDisplay:this.extractAuthorDisplay(r.author)||(l??""),contributorCount:c.length})}return n.sort((o,a)=>{let r=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},l=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},c=r.modified??r.created??"";return(l.modified??l.created??"").localeCompare(c)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.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=x=>!!s&&x.assignedTo.some(Y=>Y.id===s),o=x=>{let Y=this.taskAssignFilter;if(Y.startsWith("person:")){let q=Y.slice(7);return x.assignedTo.some(_=>_.id===q)}switch(Y){case"mine":return n(x);case"others":return x.assignedTo.length>0&&!n(x);case"byme":return!!s&&x.assignedBy?.id===s;case"unassigned":return x.assignedTo.length===0;default:return!0}},a=new Map;for(let x of i){for(let Y of x.assignedTo)Y.id!==s&&a.set(Y.id,Y.name);x.assignedBy&&x.assignedBy.id!==s&&a.set(x.assignedBy.id,x.assignedBy.name)}let r=[...a.entries()].map(([x,Y])=>({id:x,name:Y})).sort((x,Y)=>x.name.localeCompare(Y.name)),l=e.createDiv({cls:"stashpad-task-assign-bar"});l.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let c=l.createEl("select",{cls:"stashpad-task-assign-select"}),g=x=>{let Y={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return x.startsWith("person:")?a.get(x.slice(7))??"Person":Y[x]??x},p=x=>{let Y=c.createEl("option",{text:g(x),value:x});this.taskAssignFilter===x&&(Y.selected=!0)};for(let x of["all","mine","others","byme","unassigned"])p(x);if(r.length>0){let x=c.createEl("optgroup");x.setAttr("label","By person");for(let Y of r){let q=x.createEl("option",{text:Y.name,value:`person:${Y.id}`});this.taskAssignFilter===`person:${Y.id}`&&(q.selected=!0)}}c.onchange=()=>{this.taskAssignFilter=c.value,this.render()};let d=[...new Set(i.map(x=>x.folder))].sort((x,Y)=>x.localeCompare(Y));this.taskFolderFilter!=="all"&&!d.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let I=e.createDiv({cls:"stashpad-task-assign-bar"});I.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let u=I.createEl("select",{cls:"stashpad-task-assign-select"}),f=u.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let x of d){let Y=u.createEl("option",{text:x.split("/").pop()||x,value:x});this.taskFolderFilter===x&&(Y.selected=!0)}u.onchange=()=>{this.taskFolderFilter=u.value,this.render()};let C=x=>this.taskFolderFilter==="all"||x.folder===this.taskFolderFilter,m=i.filter(x=>o(x)&&C(x));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let E=new Date;E.setHours(0,0,0,0);let w=E.getTime(),y=w+24*60*60*1e3,v={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let x of m){if(x.completed){v.completed.push(x);continue}if(x.due==null){v.nodate.push(x);continue}x.due<w?v.overdue.push(x):x.due<y?v.today.push(x):v.upcoming.push(x)}let S=(x,Y)=>x.due==null&&Y.due==null?x.title.localeCompare(Y.title):x.due==null?1:Y.due==null?-1:x.due-Y.due,M=[{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"}],F=e.createDiv({cls:"stashpad-task-filters"}),N=m.length,Q=(x,Y,q)=>{let _=F.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===x&&_.addClass("is-active"),_.createSpan({cls:"stashpad-task-filter-label",text:Y}),_.createSpan({cls:"stashpad-task-filter-count",text:String(q)}),_.onclick=()=>{this.taskFilter=x,this.render()}};Q("all","All",N),Q("overdue","Overdue",v.overdue.length),Q("today","Today",v.today.length),Q("upcoming","Upcoming",v.upcoming.length),Q("nodate","No date",v.nodate.length),Q("completed","Done",v.completed.length);let D=this.taskFilter==="all"?M:M.filter(x=>x.key===this.taskFilter),K=!1;for(let x of D){let Y=v[x.key];if(Y.length!==0){if(K=!0,Y.sort(x.key==="completed"?(q,_)=>S(_,q):S),this.taskFilter==="all"){let q=e.createDiv({cls:`stashpad-task-section-header is-${x.key}`});(0,Bt.setIcon)(q.createSpan({cls:"stashpad-task-section-icon"}),x.icon),q.createSpan({cls:"stashpad-task-section-name",text:x.label}),q.createSpan({cls:"stashpad-task-section-count",text:String(Y.length)})}for(let q of Y)this.renderTaskRow(e,q,x.key==="today")}}if(!K&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${D[0]?.label??this.taskFilter}".`);return}K||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,Bt.setIcon)(n,e.completed?"check-square":"square"),e.color&&(n.style.color=e.color),n.title=e.completed?"Mark not done":"Mark done",n.onclick=a=>{a.stopPropagation(),this.toggleTaskCompleted(e)};let o=s.createSpan({cls:"stashpad-pinned-label",text:e.title});if(o.onclick=()=>this.openTaskFromPanel(e.folder,e.id),s.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let a=s.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,i)});e.due<Date.now()&&!e.completed&&a.addClass("is-overdue")}else e.dueRaw&&s.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let a=(this.plugin.settings.authorId??"").trim(),r=s.createSpan({cls:"stashpad-task-assignees"});for(let l of e.assignedTo){let c=r.createSpan({cls:"stashpad-task-assignee"});a&&l.id===a&&c.addClass("is-me"),c.setText(this.initials(l.name)),c.title=a&&l.id===a?`${l.name} (you)`:l.name}}s.oncontextmenu=a=>{a.preventDefault();let r=new Bt.Menu;r.addItem(l=>l.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),r.showAtMouseEvent(a)}}formatDueShort(t,e){return e?Rn(t,this.plugin.settings):Pn(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 Bt.Notice(`Couldn't update task: ${e.message}`);return}this.scheduleRender()}initials(t){let e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}collectTasks(){let t=this.plugin.discoverStashpadFolders(),e=new Set(t),i=[];for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a||a===T)continue;let r=o.completed===!0,l=Ne(o,"task")||o.task===!0||o.completed!==void 0,c=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,g=null;if(c){let p=Date.parse(c);Number.isNaN(p)||(g=p)}!l&&!r&&g==null&&!c||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:l,completed:r,due:g,dueRaw:c,color:typeof o.color=="string"?o.color:null,assignedTo:me(o),assignedBy:ne(o.assignedBy)})}return i}};async function Pi(h){let A=h.workspace.getLeavesOfType(ie);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new Bt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:ie,active:!0}),h.workspace.revealLeaf(t)}var No=require("obsidian");yt();var j=require("obsidian");gi();var Ji=require("obsidian");yt();var Pe=class extends Ji.AbstractInputSuggest{constructor(t,e){super(t,e);this.inputEl=e}getSuggestions(t){let e=t.toLowerCase().split(/\s+/).filter(Boolean),i=o=>e.every(a=>o.toLowerCase().includes(a)),s=[],n=o=>{if(!(o.path!=="/"&&je.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof Ji.TFolder&&n(a)}};return n(this.app.vault.getRoot()),s.slice(0,100)}renderSuggestion(t,e){e.setText(t.path)}selectSuggestion(t){this.setValue(t.path),this.inputEl.dispatchEvent(new Event("input",{bubbles:!0})),this.close()}};yt();Tt();var ve=require("obsidian"),Ys={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."}},ua={info:4e3,success:4e3,warning:6e3,error:1e4},$n=5e3,qi=class{constructor(A){this.app=A;this.history=[];this.nextId=1;this.historyLimit=$n;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??ua[t];return new ve.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:$n,this.history=this.applyLimit(this.history),this.emit()}applyLimit(A){return this.historyLimit<=0||A.length<=this.historyLimit?A:A.slice(A.length-this.historyLimit)}pushHistory(A){this.history.push(A),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let A of this.changeListeners)try{A()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(A,t){let e=document.createDocumentFragment(),i=document.createElement("div");i.className=`stashpad-notice stashpad-notice-${t}`;let s=document.createElement("div");s.className="stashpad-notice-message";let n=A.message.split(/(`[^`\n]+`)/);for(let o of n)if(o.length>1&&o.startsWith("`")&&o.endsWith("`")){let a=document.createElement("code");a.textContent=o.slice(1,-1),s.appendChild(a)}else o.length>0&&s.appendChild(document.createTextNode(o));if(i.appendChild(s),A.actions&&A.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of A.actions){let r=document.createElement("button");r.className="stashpad-notice-action",r.textContent=a.label,r.addEventListener("click",l=>{if(l.stopPropagation(),Promise.resolve().then(()=>a.onClick()).catch(c=>console.warn("[Stashpad] notification action failed",c)),!a.keepOpen){let c=r.closest(".notice");c&&c.parentElement&&c.parentElement.removeChild(c)}}),o.appendChild(r)}i.appendChild(o)}return e.appendChild(i),e}};function Oi(h,A,t){let e=h.vault.getAbstractFileByPath(A);if(!(e instanceof ve.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=h.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;h.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=ve.Platform.isMacOS?"Finder":ve.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=h.vault.adapter?.getFullPath?.(A);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var zs=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function pi(h){if(!h)return"(none)";let A=h.replace(/\bMod\b/g,zs?"Cmd":"Ctrl");return zs&&(A=A.replace(/\bAlt\b/g,"Option")),A}function Xn(h,A,t={allowSingleKey:!0}){let e=h.placeholder,i=h.value;h.placeholder="Press a key\u2026 (Backspace to cancel)",h.value="",h.classList.add("is-recording");let s=!1,n=()=>{h.placeholder=e,h.classList.remove("is-recording"),s||(h.value=i),h.removeEventListener("keydown",o,!0),h.removeEventListener("blur",a)},o=r=>{if(r.key==="Control"||r.key==="Shift"||r.key==="Alt"||r.key==="Meta"||r.key==="OS")return;let l=!!r.code&&(/^Key[A-Z]$/.test(r.code)||/^Digit\d$/.test(r.code));if((r.key==="Dead"||r.key==="Process"||r.key==="Unidentified")&&!l)return;if(r.preventDefault(),r.stopPropagation(),r.key==="Backspace"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.shiftKey){n();return}let c=[];zs?(r.metaKey&&c.push("Mod"),r.ctrlKey&&c.push("Ctrl")):r.ctrlKey&&c.push("Mod"),r.altKey&&c.push("Alt"),r.shiftKey&&c.push("Shift");let g=fa(r.key,r.code);if(!g||c.length===0&&!t.allowSingleKey)return;c.push(g);let p=c.join("+");s=!0,n(),A(p)},a=()=>n();return h.addEventListener("keydown",o,!0),h.addEventListener("blur",a),n}function fa(h,A){if(!h)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return h.length===1?h.toUpperCase():h}He();Kt();function Fe(h,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(l){try{r(e.next(l))}catch(c){n(c)}}function a(l){try{r(e.throw(l))}catch(c){n(c)}}function r(l){l.done?s(l.value):i(l.value).then(o,a)}r((e=e.apply(h,A||[])).next())})}var Ct=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 Fe(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(A())}finally{t()}})}},Vs;function Ca(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var Zs=Ca(),Ws=(Vs=Zs.Buffer)!==null&&Vs!==void 0?Vs:null,ma=Zs.TextEncoder?new Zs.TextEncoder:null;function io(h,A){return(h&15)+(h>>6|h>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function so(h,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;h[e]=io(A.charCodeAt(i),A.charCodeAt(i+1))}}function Ba(h,A){if(h.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==io(h.charCodeAt(e),h.charCodeAt(e+1)))return!1}return!0}var Zn=87,_n=48;function _s(h,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;h[e++]=s>9?s+Zn:s+_n,s=A[i]&15,h[e++]=s>9?s+Zn:s+_n}return String.fromCharCode.apply(null,h)}var _t=Ws!==null?h=>{if(typeof h=="string"){let A=Ws.from(h,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(Ws.isBuffer(h))return new Uint8Array(h.buffer,h.byteOffset,h.length);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")}:h=>{if(typeof h=="string")return ma.encode(h);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")},Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",ui=new Uint8Array(256);for(let h=0;h<Rt.length;h++)ui[Rt.charCodeAt(h)]=h;function jn(h,A=!0){let t=h.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(h[n]<<16&16711680)+(h[n+1]<<8&65280)+(h[n+2]&255),a=Rt.charAt(o>>18&63)+Rt.charAt(o>>12&63)+Rt.charAt(o>>6&63)+Rt.charAt(o&63);i.push(a)}if(e===1){let n=h[t-1],o=Rt.charAt(n>>2),a=Rt.charAt(n<<4&63);i.push(`${o}${a}`),A&&i.push("==")}else if(e===2){let n=(h[t-2]<<8)+h[t-1],o=Rt.charAt(n>>10),a=Rt.charAt(n>>4&63),r=Rt.charAt(n<<2&63);i.push(`${o}${a}${r}`),A&&i.push("=")}return i.join("")}function Qa(h){let A=Math.floor(h.length*.75),t=h.length;return h[t-1]==="="&&(A-=1,h[t-2]==="="&&(A-=1)),A}function Ea(h){let A=Qa(h),t=h.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=ui[h.charCodeAt(s)],o=ui[h.charCodeAt(s+1)],a=ui[h.charCodeAt(s+2)],r=ui[h.charCodeAt(s+3)];e[i]=n<<2|o>>4,i+=1,e[i]=(o&15)<<4|a>>2,i+=1,e[i]=(a&3)<<6|r&63,i+=1}return e}var Ki=16*1024,Ii=4,ya=new Ct,$s=new Map;function no(h,A){return Fe(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,v=0)=>{e.set(y,v)},n=()=>e,o=()=>t.exports,a=y=>{t.exports.Hash_SetMemorySize(y);let v=t.exports.Hash_GetBuffer(),S=t.exports.memory.buffer;e=new Uint8Array(S,v,y)},r=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),l=ya.dispatch(()=>Fe(this,void 0,void 0,function*(){if(!$s.has(h.name)){let v=Ea(h.data),S=WebAssembly.compile(v);$s.set(h.name,S)}let y=yield $s.get(h.name);t=yield WebAssembly.instantiate(y,{})})),c=()=>Fe(this,void 0,void 0,function*(){t||(yield l);let y=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,y,Ki)}),g=(y=null)=>{i=!0,t.exports.Hash_Init(y)},p=y=>{let v=0;for(;v<y.length;){let S=y.subarray(v,v+Ki);v+=S.length,e.set(S),t.exports.Hash_Update(S.length)}},d=y=>{if(!i)throw new Error("update() called before init()");let v=_t(y);p(v)},I=new Uint8Array(A*2),u=(y,v=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(v),y==="binary"?e.slice(0,A):_s(I,e,A)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let y=t.exports.Hash_GetState(),v=r(),S=t.exports.memory.buffer,M=new Uint8Array(S,y,v),F=new Uint8Array(Ii+v);return so(F,h.hash),F.set(M,Ii),F},C=y=>{if(!(y instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let v=t.exports.Hash_GetState(),S=r(),M=Ii+S,F=t.exports.memory.buffer;if(y.length!==M)throw new Error(`Bad state length (expected ${M} bytes, got ${y.length})`);if(!Ba(h.hash,y.subarray(0,Ii)))throw new Error("This state was written by an incompatible hash implementation");let N=y.subarray(Ii);new Uint8Array(F,v,S).set(N),i=!0},m=y=>typeof y=="string"?y.length<Ki/4:y.byteLength<Ki,E=m;switch(h.name){case"argon2":case"scrypt":E=()=>!0;break;case"blake2b":case"blake2s":E=(y,v)=>v<=512&&m(y);break;case"blake3":E=(y,v)=>v===0&&m(y);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":E=()=>!1;break}let w=(y,v=null,S=null)=>{if(!E(y,v))return g(v),d(y),u("hex",S);let M=_t(y);return e.set(M),t.exports.Hash_Calculate(M.length,v,S),_s(I,e,A)};return yield c(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:g,update:d,digest:u,save:f,load:C,calculate:w,hashLength:A}})}var Wr=new Ct;var wa="argon2",va="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",Fa="e4cdc523",ka={name:wa,data:va,hash:Fa},Sa="blake2b",Da="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=",ba="c6f286e6",Na={name:Sa,data:Da,hash:ba},$r=new Ct;function to(h){return!Number.isInteger(h)||h<8||h>512||h%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function xa(h,A){return h|A<<16}function js(h=512,A=null){if(to(h))return Promise.reject(to(h));let t=null,e=h;if(A!==null){if(t=_t(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=xa(h,t.length)}let i=h/8;return no(Na,i).then(s=>{e>512&&s.writeMemory(t),s.init(e);let n={init:e>512?()=>(s.writeMemory(t),s.init(e),n):()=>(s.init(e),n),update:o=>(s.update(o),n),digest:o=>s.digest(o),save:()=>s.save(),load:o=>(s.load(o),n),blockSize:128,digestSize:i};return n})}function Ma(h,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${jn(h,!1)}$${jn(t,!1)}`}var eo=new DataView(new ArrayBuffer(4));function Zt(h){return eo.setInt32(0,h,!0),new Uint8Array(eo.buffer)}function Xs(h,A,t){return Fe(this,void 0,void 0,function*(){if(t<=64){let a=yield js(t*8);return a.update(Zt(t)),a.update(A),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);h.init(),h.update(Zt(t)),h.update(A);let s=h.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)h.init(),h.update(s),s=h.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=h,o.init()):o=yield js(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function Ta(h){switch(h){case"d":return 0;case"i":return 1;default:return 2}}function Ha(h){return Fe(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=h,s=_t(h.password),n=_t(h.salt),o=19,a=Ta(h.hashType),{memorySize:r}=h,l=_t((A=h.secret)!==null&&A!==void 0?A:""),[c,g]=yield Promise.all([no(ka,1024),js(512)]);c.setMemorySize(r*1024+1024);let p=new Uint8Array(24),d=new DataView(p.buffer);d.setInt32(0,t,!0),d.setInt32(4,i,!0),d.setInt32(8,r,!0),d.setInt32(12,e,!0),d.setInt32(16,o,!0),d.setInt32(20,a,!0),c.writeMemory(p,r*1024),g.init(),g.update(p),g.update(Zt(s.length)),g.update(s),g.update(Zt(n.length)),g.update(n),g.update(Zt(l.length)),g.update(l),g.update(Zt(0));let u=Math.floor(r/(t*4))*4,f=new Uint8Array(72),C=g.digest("binary");f.set(C);for(let w=0;w<t;w++){f.set(Zt(0),64),f.set(Zt(w),68);let y=w*u,v=yield Xs(g,f,1024);c.writeMemory(v,y*1024),y+=1,f.set(Zt(1),64),v=yield Xs(g,f,1024),c.writeMemory(v,y*1024)}let m=new Uint8Array(1024);so(m,c.calculate(new Uint8Array([]),r));let E=yield Xs(g,m,i);if(h.outputType==="hex"){let w=new Uint8Array(i*2);return _s(w,E,i)}return h.outputType==="encoded"?Ma(n,h,E):E})}var Ua=h=>{var A;if(!h||typeof h!="object")throw new Error("Invalid options parameter. It requires an object.");if(!h.password)throw new Error("Password must be specified");if(h.password=_t(h.password),h.password.length<1)throw new Error("Password must be specified");if(!h.salt)throw new Error("Salt must be specified");if(h.salt=_t(h.salt),h.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(h.secret=_t((A=h.secret)!==null&&A!==void 0?A:""),!Number.isInteger(h.iterations)||h.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(h.parallelism)||h.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(h.hashLength)||h.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(h.memorySize))throw new Error("Memory size should be specified.");if(h.memorySize<8*h.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(h.outputType===void 0&&(h.outputType="hex"),!["hex","binary","encoded"].includes(h.outputType))throw new Error(`Insupported output type ${h.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function tn(h){return Fe(this,void 0,void 0,function*(){return Ua(h),Ha(Object.assign(Object.assign({},h),{hashType:"id"}))})}var Xr=new Ct;var Zr=new Ct;var _r=new Ct;var jr=new Ct;var tA=new Uint8Array(8);var eA=new Ct;var iA=new Ct;var sA=new Ct;var nA=new Ct;var oA=new Ct;var aA=new Ct;var rA=new Ct;var AA=new Ct;var lA=new Ct;var cA=new Ct;var dA=new Ct;var hA=new Uint8Array(8);var gA=new Ct;var pA=new Uint8Array(8);var IA=new Ct;var uA=new Uint8Array(8);var fA=new Ct;var CA=new Ct;var mA=new Ct;Tt();var Gt=new Uint8Array([83,84,65,83,72,69,78,67]),nn=2,on=1,an=2,ro=3,Pa=32,Re=12,en=32,Ra=6e5,Ga=47104,La=3,Ja=1,wt=h=>h;function Lt(h){if(h.length<Gt.length+1)return!1;for(let A=0;A<Gt.length;A++)if(h[A]!==Gt[A])return!1;return!0}function oo(h,A,t){h[A]=t>>>24&255,h[A+1]=t>>>16&255,h[A+2]=t>>>8&255,h[A+3]=t&255}function ao(h,A){return h[A]*16777216+(h[A+1]<<16)+(h[A+2]<<8)+h[A+3]}async function sn(h,A,t){if(t.id===an)return await tn({password:h,salt:A,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:en,outputType:"binary"});if(t.id===on){let e=await crypto.subtle.importKey("raw",wt(new TextEncoder().encode(h)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:wt(A),iterations:t.a,hash:"SHA-256"},e,en*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function Yi(h){return crypto.subtle.importKey("raw",wt(h),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var Ao={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function Ci(h,A){let t=crypto.getRandomValues(new Uint8Array(Pa)),e=crypto.getRandomValues(new Uint8Array(Re)),i,s,n;try{i={id:an,a:Ga,b:La,c:Ja},n=await sn(A,t,i),s="argon2id"}catch(c){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",c),i={id:on,a:Ra,b:0,c:0},n=await sn(A,t,i),s="pbkdf2"}let o=lo(i,t,e),a=await Yi(n),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(e),additionalData:wt(o)},a,wt(h))),l=new Uint8Array(o.length+r.length);return l.set(o,0),l.set(r,o.length),{data:l,kdf:s}}var fi=null;async function zi(){if(fi!==null)return fi;try{await tn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),fi=!0}catch{fi=!1}return fi}function lo(h,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++]=nn,e[i++]=h.id,oo(e,i,h.a),i+=4,oo(e,i,h.b),i+=4,e[i++]=h.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function Ge(h,A){if(!Lt(h))throw new Error("Not an encrypted Stashpad file.");let t=h[Gt.length];if(t===1)return qa(h,A);if(t!==nn)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Gt.length+1,i={id:h[e++],a:0,b:0,c:0};if(i.a=ao(h,e),e+=4,i.b=ao(h,e),e+=4,i.c=h[e++],i.id===an){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===on&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=h[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=h.slice(e,e+s);e+=s;let o=h.slice(e,e+Re);e+=Re;let a=h.slice(0,e),r=h.slice(e),l=await sn(A,n,i),c=await Yi(l),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(o),additionalData:wt(a)},c,wt(r));return new Uint8Array(g)}async function qa(h,A){let t=Gt.length+1,e=h.slice(t,t+16);t+=16;let i=h.slice(t,t+12);t+=12;let s=h.slice(t),n=await crypto.subtle.importKey("raw",wt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:wt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(i)},o,wt(s));return new Uint8Array(a)}async function mi(h,A){if(A.length!==en)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Re)),i=lo({id:ro,a:0,b:0,c:0},new Uint8Array(0),t),s=await Yi(A),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(t),additionalData:wt(i)},s,wt(h))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function oe(h,A){if(!Lt(h))throw new Error("Not an encrypted Stashpad file.");let t=h[Gt.length];if(t!==nn)throw new Error(`Unsupported encrypted version (${t}).`);let e=Gt.length+1;if(h[e++]!==ro)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=h[e++];e+=s;let n=h.slice(e,e+Re);e+=Re;let o=h.slice(0,e),a=h.slice(e),r=await Yi(A),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(n),additionalData:wt(o)},r,wt(a));return new Uint8Array(l)}async function Le(h,A,t={}){if(!Lt(A))return A;if(t.secretId){let i=h.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Ge(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new ni(h,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Ge(A,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}var Bi="stashpad-vault-encryption";function Qi(){return{wrappedKey:null,kdf:null}}function co(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function rn(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}var Oa=32,Vi=class{constructor(A,t,e,i=()=>0){this.app=A;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.idleTimer=null}argonProbe(){return zi()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}isRemembered(){try{return!!this.secretStore()?.getSecret(Bi)}catch{return!1}}async remember(A){try{await this.secretStore()?.setSecret(Bi,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(Bi):await A.setSecret(Bi,"")}catch(t){console.warn("[Stashpad] couldn't clear keychain",t)}}async tryAutoUnlock(){if(!this.isConfigured()||this.isUnlocked())return this.isUnlocked();let A=null;try{A=this.secretStore()?.getSecret(Bi)??null}catch{A=null}return A?this.unlock(A):!1}isConfigured(){return!!this.load().wrappedKey}isUnlocked(){return this.sessionKey!==null}kdf(){return this.load().kdf}async setup(A,t=!1){if(this.isConfigured())throw new Error("Encryption is already set up.");if(!A)throw new Error("Password required.");let e=crypto.getRandomValues(new Uint8Array(Oa)),i=await Ci(e,A);await this.save({wrappedKey:co(i.data),kdf:i.kdf}),this.sessionKey=e,t?await this.remember(A):await this.forgetKeychain(),this.armIdle()}async unlock(A,t=!1){let e=this.load();if(!e.wrappedKey)throw new Error("Encryption is not set up.");try{let i=await Ge(rn(e.wrappedKey),A);return this.sessionKey=i,t&&await this.remember(A),this.armIdle(),!0}catch{return!1}}async changePassword(A,t,e=!1){let i=this.load();if(!i.wrappedKey)throw new Error("Encryption is not set up.");if(!t)throw new Error("New password required.");let s;try{s=await Ge(rn(i.wrappedKey),A)}catch{return!1}let n=await Ci(s,t);return await this.save({wrappedKey:co(n.data),kdf:n.kdf}),this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=s,e?await this.remember(t):await this.forgetKeychain(),this.armIdle(),!0}async verifyPassword(A){let t=this.load();if(!t.wrappedKey)return!1;try{return(await Ge(rn(t.wrappedKey),A)).fill(0),!0}catch{return!1}}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null,this.clearIdle()}async clear(){this.lock(),await this.forgetKeychain(),await this.save(Qi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}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 cn=Ms(Wi()),$i=require("obsidian");Kt();yt();var ae="stash",Io=1;function go(h){let t=(h.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var ln=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function ke(h,A){let t=new cn.default,e=Ka([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await h.vault.read(o.file),r=a,l=uo(a);for(let c of l){let g=h.metadataCache.getFirstLinkpathDest(c,o.file.path);if(!g){s.push(`Missing attachment "${c}" in ${o.file.path}`);continue}let p=g.name;i.has(p)||i.set(p,await h.vault.readBinary(g)),r=Ya(r,c,p)}r=Wa(r,h,o.file.path),t.file(`notes/${o.file.name}`,r)}for(let[o,a]of i)t.file(`attachments/${o}`,a);let n={stashSchema:Io,exportedAt:new Date().toISOString(),sourceFolder:A.sourceFolder,noteCount:e.length,rootIds:A.rootNotes.map(o=>o.id)};return t.file("manifest.json",JSON.stringify(n,null,2)),s.length&&t.file("warnings.txt",s.join(` +`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function zt(h,A,t,e,i={}){let s=await cn.default.loadAsync(A),n=s.file("manifest.json");if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(await n.async("string"));if(typeof o.stashSchema!="number"||o.stashSchema>Io)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await po(h,t);let a=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("notes/")&&v.name.endsWith(".md")),r=[];for(let v of a){let S=await v.async("string"),{fm:M,body:F}=Dt(S),N=go(v.name.slice(6))||`${M.id||"imported-"+mt(4)}.md`;r.push({originalName:N,fm:M,body:F})}let l=new Map,c=0;for(let v of r){let S=v.fm.id;S&&(i.forceNewIds?l.set(S,mt(6)):e.has(S)||l.has(S)?(l.set(S,`${S}-${mt(4)}-Imported`),c++):l.set(S,S))}let g=new Date().toISOString(),p=[],d=`${t}/_attachments`,I=0,u=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("attachments/")),f=new Map,C=null;if(i.dedupeExisting){C=new Map;for(let v of h.vault.getFiles())C.has(v.name)||C.set(v.name,v.path)}let m=(v,S)=>{if(v.length!==S.length)return!1;for(let M=0;M<v.length;M++)if(v[M]!==S[M])return!1;return!0},E=!1;for(let v of u){let S=go(v.name.slice(12));if(!S)continue;let M=new Uint8Array(await v.async("arraybuffer")),F=[],N=C?.get(S);N&&F.push(N);let Q=`${d}/${S}`;await h.vault.adapter.exists(Q)&&F.push(Q);let D=null;for(let x of F)try{if(m(new Uint8Array(await h.vault.adapter.readBinary(x)),M)){D=x;break}}catch{}if(D){f.set(S,D);continue}let K=Q;for(let x=1;await h.vault.adapter.exists(K);x++)K=`${d}/${za(S,x)}`;f.set(S,K),E||(await po(h,d),E=!0),await h.vault.createBinary(K,M.buffer),I++}let w=0;for(let v of r){let S=v.fm.id;if(!S){p.push(`Skipped ${v.originalName} \u2014 no id in frontmatter`);continue}let M=l.get(S),F=v.fm.parent??null,N=F;!F||F===T?N=i.reparentRootsTo??F??T:l.has(F)?N=l.get(F):N=e.has(F)?F:i.reparentRootsTo??T;let Q=Va(v.body,f,d),D={...v.fm,id:M,parent:N,import_date:g};Array.isArray(D.attachments)&&(D.attachments=D.attachments.map(q=>{let _=fo(Ce(q));return Ot(f.get(_)??`${d}/${_}`)}));let K=re(D,Q),x=M===S?v.originalName:Xa(v.originalName,S,M),Y=`${t}/${x}`;await h.vault.adapter.exists(Y)&&(x=`${x.replace(/\.md$/,"")}-${mt(4)}.md`,Y=`${t}/${x}`),await h.vault.create(Y,K),w++}let y;if(o.colorAliases&&typeof o.colorAliases=="object"){let v={};for(let[S,M]of Object.entries(o.colorAliases)){let F=String(S).trim().toLowerCase(),N=String(M??"").trim();/^#([0-9a-f]{6})$/.test(F)&&N&&(v[F]=N.slice(0,60))}Object.keys(v).length&&(y=v)}return{notesWritten:w,attachmentsWritten:I,collisionsRenamed:c,warnings:p,colorAliases:y,idRemap:Object.fromEntries(l)}}function Ka(h){let A=new Set,t=[];for(let e of h)A.has(e.id)||(A.add(e.id),t.push(e));return t}function uo(h){let A=new Set,t;for(ln.lastIndex=0;(t=ln.exec(h))!==null;)A.add(t[1]);return[...A]}async function Xi(h,A){let t=await h.vault.read(A),e=[],i=new Set;for(let s of uo(t)){let n=h.metadataCache.getFirstLinkpathDest(s,A.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Ya(h,A,t){return h.replace(new RegExp(`!\\[\\[${$a(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function za(h,A){let t=h.lastIndexOf(".");return t>0?`${h.slice(0,t)}-${A}${h.slice(t)}`:`${h}-${A}`}function Va(h,A,t){return h.replace(ln,(e,i,s)=>{if(i.includes("/"))return e;let n=A.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Wa(h,A,t){let e=Dt(h);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return h;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:fo(n)}),s={...e.fm,attachments:i};return re(s,e.body)}function $a(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function fo(h){let A=h.lastIndexOf("/");return A<0?h:h.slice(A+1)}function Xa(h,A,t){return h.includes(A)?h.replace(A,t):h.replace(/\.md$/,`-${t}.md`)}function Dt(h){if(!h.startsWith("---"))return{fm:{},body:h};let A=h.indexOf(` +---`,3);if(A<0)return{fm:{},body:h};let t=h.slice(3,A).replace(/^\n/,""),e=h.slice(A+4),i={};try{i=(0,$i.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` `)?e.slice(1):e;return{fm:i,body:s}}function re(h,A){return`--- -${(0,Wi.stringifyYaml)(h).trimEnd()} +${(0,$i.stringifyYaml)(h).trimEnd()} --- -${A}`}async function ho(h,A){if(!(!A||await h.vault.adapter.exists(A)))try{await h.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}var Ae="stashenc",Za="stashmeta";function le(h){return h.replace(/\.stashenc$/,`.${Za}`)}async function fo(h,A){try{return JSON.parse(await h.vault.adapter.read(le(A)))}catch{return null}}async function Co(h,A,t){let e=A.replace(/\/+$/,""),i=[];for(let l of h.vault.getMarkdownFiles()){if((l.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let c;try{c=Mt(await h.vault.read(l)).fm}catch{continue}typeof c.id=="string"&&i.push({id:c.id,file:l,parent:typeof c.parent=="string"?c.parent:null,created:typeof c.created=="string"?c.created:""})}let s=i.find(l=>l.id===t);if(!s)return null;let n=new Map;for(let l of i){if(!l.parent)continue;let c=n.get(l.parent)??[];c.push(l),n.set(l.parent,c)}let o=[],a=new Set([t]),r=[t];for(;r.length;){let l=[];for(let c of r)for(let g of n.get(c)??[])a.has(g.id)||(a.add(g.id),o.push(g),l.push(g.id));r=l}return{rootNote:s,descendants:o,parentId:s.parent}}function ln(h){if(!h)return null;let A=h.replace(/\/+$/,"");return!A||A.startsWith("/")||A.includes("\\")||/^[a-zA-Z]:/.test(A)||A.split("/").some(t=>t===".."||t===".")?null:A}async function cn(h,A,t){await h.vault.adapter.writeBinary(A,t);let e;try{e=new Uint8Array(await h.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 h.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 $i(h){return h.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||h.basename}function Ge(h){return(h.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function mo(h,A,t){let e=new Set(A.map(a=>a.file.path)),i=new Map;for(let a of A)for(let r of await Io(h,a.file))i.set(r.path,r);let s=new Set,n=h.metadataCache.resolvedLinks??{};for(let a of Object.keys(n))if(!e.has(a))for(let r of Object.keys(n[a]??{}))i.has(r)&&s.add(r);let o=[];for(let a of A){let r=t?.get(a.file.path);if(r!=null)try{let l=await h.vault.adapter.stat(a.file.path);if(l&&l.mtime!==r){console.warn("[Stashpad] note changed since it was bundled \u2014 keeping plaintext",a.file.path),o.push(a.file.path);continue}}catch{}try{await h.vault.delete(a.file)}catch(l){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,l),o.push(a.file.path)}}for(let[a,r]of i)if(!s.has(a))try{await h.vault.delete(r)}catch(l){console.warn("[Stashpad] couldn't delete exclusive attachment",a,l),o.push(a)}return{unpurged:o}}async function Bo(h,A,t,e,i=null,s=!1,n){let o=await Co(h,A,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:r,parentId:l}=o,c=[a,...r],g=new Map;for(let y of c)try{let v=await h.vault.adapter.stat(y.file.path);v&&g.set(y.file.path,v.mtime)}catch{}let p=await Bi(h,{rootNotes:[{id:a.id,file:a.file}],allDescendants:r.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),d=await fi(p,e),I=await oe(d,e);if(I.length!==p.length)throw new Error("Encryption self-check failed (size mismatch).");for(let y=0;y<p.length;y++)if(I[y]!==p[y])throw new Error("Encryption self-check failed (content mismatch).");let u=(n??A).replace(/\/+$/,"");n&&!await h.vault.adapter.exists(u)&&await h.vault.adapter.mkdir(u);let f=Ge(s?t:$i(a.file)),C=`${u}/${f}.${Ae}`;for(let y=1;await h.vault.adapter.exists(C);y++)C=`${u}/${f} (${y}).${Ae}`;await cn(h,C,d);let m=c,E={v:1,parentId:l,title:s?"":$i(a.file),count:m.length,created:a.created,rootId:t,prevSibling:i};try{await h.vault.adapter.write(le(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:w}=await mo(h,m,g);return{blobPath:C,noteCount:m.length,rootId:t,parentId:l,title:E.title,created:a.created,unpurged:w}}async function Qo(h,A,t,e,i){let s=new Uint8Array(await h.vault.adapter.readBinary(A));if(!Lt(s))throw new Error("Not an encrypted bundle.");let n=await oe(s,t),o=ln(i)??A.replace(/\/[^/]*$/,""),a=await _t(h,n,o,e,{dedupeExisting:!0});await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(le(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ut="_deleted";function _a(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function ja(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}async function dn(h,A,t,e){let i=ln(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=ln(new TextDecoder().decode(await oe(ja(t.originalFolderEnc),e)))}catch{i=null}if(i)return await h.vault.adapter.exists(i)||await h.vault.adapter.mkdir(i),i;let s=A.replace(/\/[^/]*$/,"");if(s===Ut||s.startsWith(`${Ut}/`))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 hn(h){let A=[""];for(;A.length;){let t=A.shift(),e;try{e=await h.vault.adapter.list(t||"/")}catch{continue}if(e.files.some(i=>i.endsWith(`.${Ae}`)))return!0;for(let i of e.folders)i===".obsidian"||i.endsWith("/.obsidian")||A.push(i)}return!1}async function Eo(h,A,t,e,i,s=!1){let n=await Co(h,A,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:a,parentId:r}=n,l=[o,...a],c=new Map;for(let y of l)try{let v=await h.vault.adapter.stat(y.file.path);v&&c.set(y.file.path,v.mtime)}catch{}let g=await Bi(h,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),p=await fi(g,e),d=await oe(p,e);if(d.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let y=0;y<g.length;y++)if(d[y]!==g[y])throw new Error("Encryption self-check failed (content).");await h.vault.adapter.exists(Ut)||await h.vault.adapter.mkdir(Ut);let I=A.replace(/\/+$/,""),u=I.split("/").pop()||"vault",f=Ge(s?t:`${u} ${$i(o.file)}`),C=`${Ut}/${f}.${Ae}`;for(let y=1;await h.vault.adapter.exists(C);y++)C=`${Ut}/${f} (${y}).${Ae}`;await cn(h,C,p);let m=l,E={v:1,kind:"deleted",originalFolder:s?"":I,...s?{originalFolderEnc:_a(await fi(new TextEncoder().encode(I),e))}:{},parentId:r,title:s?"":$i(o.file),count:m.length,created:o.created,rootId:t,deletedAt:i};try{await h.vault.adapter.write(le(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write deleted sidecar",y)}let{unpurged:w}=await mo(h,m,c);return{blobPath:C,noteCount:m.length,rootId:t,originalFolder:I,title:E.title,unpurged:w}}async function yo(h,A,t,e){let i=new Uint8Array(await h.vault.adapter.readBinary(A));if(!Lt(i))throw new Error("Not an encrypted bundle.");let s=await Xi(h,A),n=await dn(h,A,s,t),o=await oe(i,t),a=await _t(h,o,n,e,{dedupeExisting:!0});await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(le(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function Xi(h,A){try{return JSON.parse(await h.vault.adapter.read(le(A)))}catch{return null}}var Jt=".trash";async function tr(h,A){let t=[],e=[A];for(;e.length;){let i=e.shift(),s;try{s=await h.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function er(h){let A=h.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 wo(h,A,t,e=!1){if(!await h.vault.adapter.exists(Jt))return null;let i=await tr(h,Jt);if(i.length===0)return null;let{default:s}=await Promise.resolve().then(()=>Ns(Vi())),n=new s,o=new Map;for(let I of i){let u=I.slice(Jt.length+1);n.file(`files/${u}`,await h.vault.adapter.readBinary(I));try{let f=await h.vault.adapter.stat(I);f&&o.set(I,f.mtime)}catch{}}let a=new Uint8Array(await n.generateAsync({type:"arraybuffer"})),r=await fi(a,A),l=await oe(r,A);if(l.length!==a.length)throw new Error("Encryption self-check failed (size).");for(let I=0;I<a.length;I++)if(l[I]!==a[I])throw new Error("Encryption self-check failed (content).");await h.vault.adapter.exists(Ut)||await h.vault.adapter.mkdir(Ut);let c=Ge(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),g=`${Ut}/${c}.${Ae}`;for(let I=1;await h.vault.adapter.exists(g);I++)g=`${Ut}/${c} (${I}).${Ae}`;await cn(h,g,r);let p={v:1,kind:"rawtrash",originalFolder:Jt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await h.vault.adapter.write(le(g),JSON.stringify(p))}catch(I){console.warn("[Stashpad] couldn't write backfill sidecar",I)}let d=[];for(let I of i){let u=o.get(I);try{if(u!=null){let f=await h.vault.adapter.stat(I);if(f&&f.mtime!==u){d.push(I);continue}}await h.vault.adapter.remove(I)}catch(f){console.warn("[Stashpad] couldn't delete trash file",I,f),d.push(I)}}return{blobPath:g,fileCount:i.length,unpurged:d}}async function vo(h,A,t){let e=new Uint8Array(await h.vault.adapter.readBinary(A));if(!Lt(e))throw new Error("Not an encrypted bundle.");let i=await oe(e,t),{default:s}=await Promise.resolve().then(()=>Ns(Vi())),n=await s.loadAsync(i),o=0;for(let[a,r]of Object.entries(n.files)){if(r.dir||!a.startsWith("files/"))continue;let l=er(a.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",a);continue}let c=`${Jt}/${l}`.split("/").slice(0,-1).join("/"),g="";for(let d of c.split("/"))g=g?`${g}/${d}`:d,await h.vault.adapter.exists(g)||await h.vault.adapter.mkdir(g);let p=`${Jt}/${l}`;for(let d=1;await h.vault.adapter.exists(p);d++)p=`${Jt}/${l.replace(/(\.[^./]*)?$/,` (${d})$1`)}`;await h.vault.adapter.writeBinary(p,await r.async("arraybuffer")),o++}await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(le(A))}catch{}return{filesWritten:o}}async function Fo(h){if(!await h.vault.adapter.exists(Ut))return[];try{return(await h.vault.adapter.list(Ut)).files.filter(t=>t.endsWith(`.${Ae}`))}catch{return[]}}var Qi=null,Zi=new Set;function _i(h){if(Qi!==h){Qi=h;for(let A of Zi)A()}}function jt(){return Qi}function ko(h){if(Qi===h){Qi=null;for(let A of Zi)A()}}function So(h){return Zi.add(h),()=>Zi.delete(h)}function ir(){return j.Platform.isMacOS?"Finder":j.Platform.isWin?"File Explorer":"file manager"}var Le=[{id:"move",label:"Move (picker)",desc:"Open a fuzzy picker to choose the new parent.",defaultPrimary:"M"},{id:"pickMove",label:"Move (in-list)",desc:"Highlight a note in the list with arrows; Enter sets it as parent.",defaultPrimary:"O"},{id:"merge",label:"Merge",desc:"Concatenate selected notes into the oldest one.",defaultPrimary:"&"},{id:"copy",label:"Copy",desc:"Copy selected note bodies to clipboard.",defaultPrimary:"C"},{id:"copyTree",label:"Copy tree",desc:"Copy the focused note + all descendants, indented.",defaultPrimary:"Y"},{id:"openEditor",label:"Open in editor",desc:"Open the cursor row (or focused note) in a regular Obsidian markdown tab.",defaultPrimary:"E"},{id:"openTab",label:"Open in new Stashpad tab",desc:"Open the cursor row (or focused note) in a new Stashpad tab focused on it.",defaultPrimary:"T"},{id:"split",label:"Split note",desc:"Split the cursor row (or focused note) into two notes at a chosen line.",defaultPrimary:"S"},{id:"copyOutline",label:"Copy as outline",desc:"Copy selection (or cursor row) as a nested ![[embed]] outline.",defaultPrimary:"L"},{id:"toggleSplit",label:"Toggle split-on-newlines",desc:"Default: Mod+/",defaultPrimary:"Mod+/"},{id:"pickDestination",label:"Pick destination",desc:"Default: Mod+D",defaultPrimary:"Mod+D"},{id:"search",label:"Search notes",desc:"Default: Mod+F",defaultPrimary:"Mod+F"},{id:"searchInParent",label:"Search in current parent",desc:"Default: Mod+Alt+F (Mod+Shift+F is taken by Obsidian's global search).",defaultPrimary:"Mod+Alt+F"},{id:"delete",label:"Delete selection",desc:"Default: Mod+Backspace",defaultPrimary:"Mod+Backspace"},{id:"undo",label:"Undo",desc:"Default: Mod+Z (Stashpad-only \u2014 won't fire while typing in the composer).",defaultPrimary:"Mod+Z"},{id:"redo",label:"Redo",desc:"Default: Mod+Shift+Z",defaultPrimary:"Mod+Shift+Z"},{id:"toggleComplete",label:"Toggle complete (strikethrough)",desc:"Default: Mod+Enter or X \u2014 marks selected/focused notes as complete (both chords active).",defaultPrimary:"Mod+Enter",defaultSecondary:"X",defaultUseBoth:!0},{id:"moveUp",label:"Move note up",desc:"Default: Mod+ArrowUp",defaultPrimary:"Mod+ArrowUp"},{id:"moveDown",label:"Move note down",desc:"Default: Mod+ArrowDown",defaultPrimary:"Mod+ArrowDown"},{id:"moveToTop",label:"Move note to top",desc:"Default: Mod+Shift+ArrowUp",defaultPrimary:"Mod+Shift+ArrowUp"},{id:"moveToBottom",label:"Move note to bottom",desc:"Default: Mod+Shift+ArrowDown",defaultPrimary:"Mod+Shift+ArrowDown"},{id:"outdent",label:"Outdent (move to grandparent)",desc:"Default: Mod+[ \u2014 re-parents the selection one level up.",defaultPrimary:"Mod+["},{id:"setColor",label:"Set note color",desc:"Default: Shift+: or ; \u2014 open the color picker for the selection (both chords active).",defaultPrimary:"Shift+:",defaultSecondary:";",defaultUseBoth:!0},{id:"clone",label:"Clone (duplicate / copy) selection",desc:"Default: Mod+Shift+D \u2014 clone selected notes (with their subtrees) as siblings.",defaultPrimary:"Mod+Shift+D"},{id:"insertTemplate",label:"Insert template (clone an existing note)",desc:"Pick any note in this Stashpad; clone it (with subtree + attachments) into the current view, retimestamped.",defaultPrimary:""},{id:"toggleExpand",label:"Show more / show less (expand toggle)",desc:"Default: Shift+? \u2014 toggle the clamp on the cursor row (or every selected row).",defaultPrimary:"Shift+?"},{id:"exportStash",label:"Export selection to .stash",desc:"Export the selected subtree(s) as a .stash bundle (notes + attachments).",defaultPrimary:""},{id:"importStash",label:"Import .stash file",desc:"Open the .stash bundle picker and import its notes into this Stashpad.",defaultPrimary:""},{id:"pickFolder",label:"Open / switch / create Stashpad folder",desc:"Default: Mod+S \u2014 opens the unified folder picker (reveal, switch, create, convert).",defaultPrimary:"Mod+S"},{id:"cloneStashpadTab",label:"Clone (duplicate / copy) this Stashpad tab",desc:'Open a second tab on the same folder + focus, mirroring the "copy" button in the focused-header actions.',defaultPrimary:""},{id:"selectAll",label:"Select all notes in view",desc:"Default: Mod+A \u2014 adds every visible row to the selection.",defaultPrimary:"Mod+A"},{id:"copyCodeBlock",label:"Copy code from codeblock",desc:"Default: { \u2014 copy the contents of the cursor row's first codeblock (or pick one when multiple exist).",defaultPrimary:"{"},{id:"swapWithParent",label:"Swap with parent (ouroboros)",desc:"Promote the cursor row above its current parent; the parent slides under it (carrying its other children). No default \u2014 bind in this tab.",defaultPrimary:""},{id:"togglePin",label:"Pin / unpin selected note",desc:"Default: P \u2014 toggle the sidebar pin state of the cursor row (or focused note).",defaultPrimary:"P"},{id:"toggleTask",label:"Toggle task (todo)",desc:"Default: H \u2014 mark the selection (or cursor row) as a task / todo, or clear it. Tasks appear in the Tasks panel.",defaultPrimary:"H"},{id:"setDue",label:"Set due date\u2026",desc:"Default: D \u2014 open a date+time picker to set (or clear) the due date on the selection. Setting a due date also marks the note as a task.",defaultPrimary:"D"},{id:"jumpToTop",label:"Jump to top of list",desc:"Default: Home \u2014 move the cursor to the first note in the current list.",defaultPrimary:"Home"},{id:"jumpToBottom",label:"Jump to bottom of list",desc:"Default: End \u2014 move the cursor to the last note in the current list.",defaultPrimary:"End"},{id:"commandPalette",label:"Command palette (Stashpad only)",desc:"Default: Mod+K \u2014 open a command palette listing only Stashpad's commands, with Sift search.",defaultPrimary:"Mod+K"},{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 In(){let h={};for(let A of Le)h[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return h}var ce={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,encryption:mi(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],lockedSubtrees:[],searchOpensInNewTab:!0,pinnedNotes:[],hideMobileToolbarInStashpad:!0,slugStopWords:[],searchIncludedFolders:[],searchExcludedFolders:[],shortcuts:{move:"M",pickMove:"O",merge:"&",copy:"C",copyTree:"Y",openEditor:"E",openTab:"T",split:"S",copyOutline:"L"},mod:{toggleSplit:"Mod+/",pickDestination:"Mod+D",search:"Mod+F",delete:"Mod+Backspace",undo:"Mod+Z",redo:"Mod+Shift+Z",toggleComplete:"Mod+Enter",moveUp:"Mod+ArrowUp",moveDown:"Mod+ArrowDown",moveToTop:"Mod+Shift+ArrowUp",moveToBottom:"Mod+Shift+ArrowDown",outdent:"Mod+[",setColor:"Shift+:"},customPalette:[],colorAliases:{},noteTemplates:{},authorName:"",authorId:"",authorRole:"",authorDepartment:"",showAuthor:!0,showContributors:!0,showLastEdit:!0,viewModes:{},includeAttachmentsInEverything:{},hideChildlessNotes:{},hideCompletedNotes:{},attachmentsOnlyNotes:{},mutedNotificationCategories:[],notificationHistoryLimit:5e3,notifiedDueKeys:[],autoNavOnMoveIn:!1,autoNavOnMoveOut:!1,autoExpandCursorRow:!1,autoOpenDetailPanel:!1,doubleClickToFocus:!0,dateDisplayFormat:"locale",dateDisplayTimezone:"",jdIndexScope:"vault",jdIndexScopeFolder:"",jdIndexStashpadFolder:"",jdIndexFile:"Index",jdIndexIncludeStashpadFolders:!1,jdIndexSort:"natural",jdIndexHasBuilt:!1,drafts:{},lastSubmitted:{},bindings:In()},Do=JSON.parse(JSON.stringify(ce)),pn=new Set;function It(){return Do}function un(h){Do=h;for(let A of pn)A()}function bo(h){return pn.add(h),()=>pn.delete(h)}function es(h){try{let A=h.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var ji=[{id:"general",label:"General"},{id:"encryption",label:"Encryption"},{id:"diagnostics",label:"Diagnostics"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"hotkeys",label:"Hotkeys"}],gn=null;function sr(h,A){return gn||(gn=class extends j.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new gn(h,A)}var ts=class extends j.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if(j.SettingPage){super.display();return}let{containerEl:t}=this;t.empty();for(let e of ji){t.createEl("h2",{text:e.label});let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new j.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 ji.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>sr(t.label,i=>this.renderTabContent(i,t.id))}})}itemsForTab(t){switch(t){case"hotkeys":return this.hotkeyItems();case"diagnostics":return this.diagnosticsItems();case"general":return this.generalItems();case"encryption":return this.encryptionItems();case"authorship":return this.authorshipItems();case"templates":return this.templatesItems();case"jdindex":return this.jdIndexItems();default:return null}}renderTabContent(t,e){switch(e){case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break}}diagnosticsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(Os);return[this.renderDef("Write recovery navigation links","Maintain the redundant parentLink/children frontmatter so you can walk the hierarchy from raw Markdown if the index ever breaks. On a slow / network drive this is a big per-move cost (several round-trips each); turn it off there for snappier moves \u2014 Rebootstrap rebuilds the fields on demand, and your notes' canonical structure (id/parent) is unaffected either way.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async n=>{this.plugin.settings.writeRecoveryLinks=n,await this.plugin.saveSettings()})),["recovery","parentlink","children","frontmatter"]),this.renderDef("Performance profiling","Record timing for list rendering, body reads, and file writes. Turn on, use Stashpad normally (especially the slow operations), then run \u201CDump performance profile\u201D from the command palette and share the result. Off = zero overhead.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.enablePerfProfiling).onChange(async n=>{this.plugin.settings.enablePerfProfiling=n,await this.plugin.saveSettings()})),["perf","profiling","timing","slow"]),this.renderDef("Open log file","Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.",i=>i.addButton(s=>s.setButtonText("Open log").onClick(async()=>{let n=this.app.vault.adapter,o=this.plugin.pluginPrivatePath("log.jsonl");if(!await n.exists(o)){new j.Notice("No log yet \u2014 make some changes first.");return}let a=await n.read(o);new Ne(this.app,a,o).open()})),["log","history","diagnostics"]),this.renderDef("Notification history limit","Maximum number of notifications kept in the persistent history. Set to 0 for unlimited (the file size grows with usage; expect a few hundred KB per ~5000 entries). Default: 5000.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.notificationHistoryLimit??5e3)).setPlaceholder("5000").onChange(async n=>{let o=parseInt(n,10);Number.isFinite(o)&&(this.plugin.settings.notificationHistoryLimit=o,this.plugin.notifications.setHistoryLimit(o),await this.plugin.saveSettings())})),["notification","history","limit"]),{type:"group",heading:"Mute notification categories",items:e.map(i=>{let s=Os[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async a=>{let r=!a;r?t.add(i):t.delete(i),this.plugin.settings.mutedNotificationCategories=Array.from(t),this.plugin.notifications.setMuted(i,r),await this.plugin.saveSettings()})),["notification","mute","toast","category"])})},this.renderDef("Notification history","Browse the last 200 toasts. Filter by category. Live-updates as new notifications arrive. Muted categories still appear here so you can review what was suppressed.",i=>i.addButton(s=>s.setButtonText("View notification history").onClick(()=>{new ai(this.app,this.plugin.notifications,async n=>{let o=this.app.vault.adapter,a=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(a)){new j.Notice("No log yet \u2014 make some changes first.");return}let r=await o.read(a);new Ne(this.app,r,a).open()},this.plugin.settings.authorId||null,n=>this.plugin.lookupNoteAuthorIds(n)).open()})),["notification","history","panel"])]}renderTemplatesTab(t){this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t)}renderDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{n.setName(t).setDesc(e),i(n)}}}sectionDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{let o=n.settingEl;o.empty(),o.removeClass("setting-item"),o.addClass("stashpad-settings-section"),i(o)}}}generalItems(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,r)=>this.renderDef(s,n,l=>l.addToggle(c=>c.setValue(o()).onChange(async g=>{a(g),await t()})),r),i=[];i.push(this.renderDef("Stashpad notes folder","Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.",s=>{s.addText(n=>{new Te(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||ce.folder,r=a.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(c=>(c??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(r)){new j.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.push(e("Auto-import dropped files","When on, any file you drop directly into a Stashpad folder is imported automatically: markdown becomes a note (the original is archived to .archive); other files move to _attachments with a note that links to them. Large drops ask for confirmation first.",()=>this.plugin.settings.autoImport,s=>{this.plugin.settings.autoImport=s},["import","drop","auto"])),i.push(e("Inherit Obsidian's excluded files","Also hide files matching Obsidian's \u201CExcluded files\u201D list (Settings \u2192 Files & Links) from Stashpad's link autocomplete and file surfaces \u2014 so you manage exclusions in one place. Plugin-internal formats like .edtz are always excluded regardless.",()=>this.plugin.settings.inheritObsidianExclusions,s=>{this.plugin.settings.inheritObsidianExclusions=s},["excluded","ignore","files"])),i.push(this.renderDef("Dedicated import subfolder (optional)","Optional. A subfolder (relative to each Stashpad folder) where dropped .stash files auto-import. Leave blank to just drop files into the Stashpad folder itself (recommended). Suggested name: _imports.",s=>s.addText(n=>n.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async o=>{this.plugin.settings.importDropFolder=(o||"").trim().replace(/^\/+|\/+$/g,""),await t()})),["import","subfolder"])),i.push(this.renderDef("Stash export subfolder","Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.",s=>s.addText(n=>n.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async o=>{this.plugin.settings.exportFolder=(o||"").trim().replace(/^\/+|\/+$/g,"")||ce.exportFolder,await t()})),["export","stash","subfolder"])),i.push(this.renderDef("Rebootstrap existing Stashpad folders","Walk every folder that has a home note: ensure infrastructure (_imports, _exports, drafts file), backfill the redundant parentLink + children frontmatter fields, AND rename any note whose filename slug no longer matches its body's first line. Safe to run anytime; skip-if-equal means already-synced notes are no-op writes.",s=>s.addButton(n=>n.setButtonText("Rebootstrap now").onClick(async()=>{n.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:o,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:c,imported:g,attachmentsLinked:p}=await this.plugin.rebootstrapAllFolders(),d=[];d.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),g>0&&d.push(`imported ${g} loose file${g===1?"":"s"}`),p>0&&d.push(`linked attachments on ${p} note${p===1?"":"s"}`),r>0?d.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&d.push(`frontmatter already in sync (${a} notes checked)`),l>0&&d.push(`renamed ${l} note${l===1?"":"s"} to match body`),c>0&&d.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new j.Notice(`Stashpad: ${d.join("; ")}.`)}catch(o){new j.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.push(this.renderDef("Use Templates plugin date/time formats","When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.",s=>{s.addToggle(o=>o.setValue(this.plugin.settings.useTemplatesFormat).onChange(async a=>{this.plugin.settings.useTemplatesFormat=a,await t()}));let n=es(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: ${Wt(Date.now(),this.plugin.settings)}`)};i.push(this.renderDef("Date display format","How due dates and created/modified times are shown in the Tasks and detail panels.",o=>{o.addDropdown(a=>{a.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),a.addOption("long","Locale, long (Thursday, March 5\u2026)"),a.addOption("iso","ISO (2026-03-05 09:00)"),a.addOption("us","US (3/5/2026, 9:00 AM)"),a.addOption("eu","EU (5/3/2026, 09:00)"),a.setValue(this.plugin.settings.dateDisplayFormat??"locale"),a.onChange(async r=>{this.plugin.settings.dateDisplayFormat=r,await t(),n()})})},["date","format","display"])),i.push(this.renderDef("Display timezone","IANA timezone name (e.g. America/New_York, Europe/London, Asia/Kolkata). Leave blank to use your system timezone.",o=>{o.addText(a=>{a.setPlaceholder("(system timezone)"),a.setValue(this.plugin.settings.dateDisplayTimezone??""),a.onChange(async r=>{this.plugin.settings.dateDisplayTimezone=(r||"").trim(),await t(),n()})})},["timezone","tz","date","iana"])),i.push({name:"Date sample",searchable:!1,render:o=>{let a=o.settingEl;a.empty(),a.removeClass("setting-item"),s=a.createDiv({cls:"setting-item-description stashpad-settings-note"}),n()}})}return i.push(e("Navigate into parent after moving a note IN","When you move a note onto another note via the in-list move picker (drag-onto-sibling), automatically drill into the new parent so you can see the moved note in its new home. Off = stay focused where you were.",()=>this.plugin.settings.autoNavOnMoveIn,s=>{this.plugin.settings.autoNavOnMoveIn=s},["navigate","move","in"])),i.push(e("Navigate to destination after moving a note OUT","When you outdent a note, move it via the cross-parent picker, or send it to Home, automatically drill into the destination parent. Off = stay focused where you were.",()=>this.plugin.settings.autoNavOnMoveOut,s=>{this.plugin.settings.autoNavOnMoveOut=s},["navigate","move","out"])),i.push(e("Double-click a note to open it","Double-click (or double-tap on mobile) a note in the list to focus/open it \u2014 the same as pressing \u2192 or clicking the enter arrow. Single click still just selects. On by default.",()=>this.plugin.settings.doubleClickToFocus,s=>{this.plugin.settings.doubleClickToFocus=s},["double","click","open","focus"])),i.push(e("Auto-open the detail panel","Open the right-sidebar Stashpad detail panel automatically whenever a Stashpad view becomes active. The panel shows the cursored note's body, metadata, and children. Off = open manually via ribbon or command palette.",()=>this.plugin.settings.autoOpenDetailPanel,s=>{this.plugin.settings.autoOpenDetailPanel=s},["detail","panel","sidebar"])),i.push(e("Expand the cursor row's body automatically","As you arrow-key through the list, the row under the cursor temporarily un-clamps to show its full body. Moving away re-collapses it. Doesn't affect the persistent 'Show more' state \u2014 this is a transient view-only effect.",()=>this.plugin.settings.autoExpandCursorRow,s=>{this.plugin.settings.autoExpandCursorRow=s},["expand","cursor","body"])),i.push(e("Confirm cross-parent drag-and-drop","When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).",()=>this.plugin.settings.confirmCrossParentDrag,s=>{this.plugin.settings.confirmCrossParentDrag=s},["confirm","drag","drop","reparent"])),i.push(e("Confirm bulk deletes","Warn before deletes that affect more than one note \u2014 multi-selection delete OR deleting a note that has descendants. A single childless note with no attachments never prompts. Off = those deletes apply immediately (undo still recovers everything).",()=>this.plugin.settings.confirmBulkDelete,s=>{this.plugin.settings.confirmBulkDelete=s},["confirm","delete","bulk"])),i.push(e("Offer to delete attachments with note",`When a note references attachments, the delete modal includes an "Also delete attachments" checkbox so orphaned files don't pile up in your vault. Attachments are detected from both ![[\u2026]] embeds in the body and the frontmatter attachments: list. Off = attachments are always preserved on delete (no checkbox shown), and a single childless note with attachments deletes silently.`,()=>this.plugin.settings.confirmAttachmentDelete,s=>{this.plugin.settings.confirmAttachmentDelete=s},["delete","attachment","orphan"])),i.push(this.renderDef("Slug stop-words","Words removed from auto-generated note titles (filenames). One per line.",s=>{let n=null,o=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:Yt).join(` +${A}`}async function po(h,A){if(!(!A||await h.vault.adapter.exists(A)))try{await h.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}var Ae="stashenc",Za="stashmeta";function le(h){return h.replace(/\.stashenc$/,`.${Za}`)}async function Co(h,A){try{return JSON.parse(await h.vault.adapter.read(le(A)))}catch{return null}}async function Se(h,A,t){let e=A.replace(/\/+$/,""),i=[];for(let l of h.vault.getMarkdownFiles()){if((l.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let c;try{c=Dt(await h.vault.read(l)).fm}catch{continue}typeof c.id=="string"&&i.push({id:c.id,file:l,parent:typeof c.parent=="string"?c.parent:null,created:typeof c.created=="string"?c.created:""})}let s=i.find(l=>l.id===t);if(!s)return null;let n=new Map;for(let l of i){if(!l.parent)continue;let c=n.get(l.parent)??[];c.push(l),n.set(l.parent,c)}let o=[],a=new Set([t]),r=[t];for(;r.length;){let l=[];for(let c of r)for(let g of n.get(c)??[])a.has(g.id)||(a.add(g.id),o.push(g),l.push(g.id));r=l}return{rootNote:s,descendants:o,parentId:s.parent}}function dn(h){if(!h)return null;let A=h.replace(/\/+$/,"");return!A||A.startsWith("/")||A.includes("\\")||/^[a-zA-Z]:/.test(A)||A.split("/").some(t=>t===".."||t===".")?null:A}async function hn(h,A,t){await h.vault.adapter.writeBinary(A,t);let e;try{e=new Uint8Array(await h.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 h.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 Zi(h){return h.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||h.basename}function Je(h){return(h.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function mo(h,A,t){let e=new Set(A.map(a=>a.file.path)),i=new Map;for(let a of A)for(let r of await Xi(h,a.file))i.set(r.path,r);let s=new Set,n=h.metadataCache.resolvedLinks??{};for(let a of Object.keys(n))if(!e.has(a))for(let r of Object.keys(n[a]??{}))i.has(r)&&s.add(r);let o=[];for(let a of A){let r=t?.get(a.file.path);if(r!=null)try{let l=await h.vault.adapter.stat(a.file.path);if(l&&l.mtime!==r){console.warn("[Stashpad] note changed since it was bundled \u2014 keeping plaintext",a.file.path),o.push(a.file.path);continue}}catch{}try{await h.vault.delete(a.file)}catch(l){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,l),o.push(a.file.path)}}for(let[a,r]of i)if(!s.has(a))try{await h.vault.delete(r)}catch(l){console.warn("[Stashpad] couldn't delete exclusive attachment",a,l),o.push(a)}return{unpurged:o}}async function Bo(h,A,t,e,i=null,s=!1,n){let o=await Se(h,A,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:r,parentId:l}=o,c=[a,...r],g=new Map;for(let y of c)try{let v=await h.vault.adapter.stat(y.file.path);v&&g.set(y.file.path,v.mtime)}catch{}let p=await ke(h,{rootNotes:[{id:a.id,file:a.file}],allDescendants:r.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),d=await mi(p,e),I=await oe(d,e);if(I.length!==p.length)throw new Error("Encryption self-check failed (size mismatch).");for(let y=0;y<p.length;y++)if(I[y]!==p[y])throw new Error("Encryption self-check failed (content mismatch).");let u=(n??A).replace(/\/+$/,"");n&&!await h.vault.adapter.exists(u)&&await h.vault.adapter.mkdir(u);let f=Je(s?t:Zi(a.file)),C=`${u}/${f}.${Ae}`;for(let y=1;await h.vault.adapter.exists(C);y++)C=`${u}/${f} (${y}).${Ae}`;await hn(h,C,d);let m=c,E={v:1,parentId:l,title:s?"":Zi(a.file),count:m.length,created:a.created,rootId:t,prevSibling:i};try{await h.vault.adapter.write(le(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:w}=await mo(h,m,g);return{blobPath:C,noteCount:m.length,rootId:t,parentId:l,title:E.title,created:a.created,unpurged:w}}async function Qo(h,A,t,e,i){let s=new Uint8Array(await h.vault.adapter.readBinary(A));if(!Lt(s))throw new Error("Not an encrypted bundle.");let n=await oe(s,t),o=dn(i)??A.replace(/\/[^/]*$/,""),a=await zt(h,n,o,e,{dedupeExisting:!0});await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(le(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ut="_deleted";function _a(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function ja(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}async function gn(h,A,t,e){let i=dn(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=dn(new TextDecoder().decode(await oe(ja(t.originalFolderEnc),e)))}catch{i=null}if(i)return await h.vault.adapter.exists(i)||await h.vault.adapter.mkdir(i),i;let s=A.replace(/\/[^/]*$/,"");if(s===Ut||s.startsWith(`${Ut}/`))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 pn(h){let A=[""];for(;A.length;){let t=A.shift(),e;try{e=await h.vault.adapter.list(t||"/")}catch{continue}if(e.files.some(i=>i.endsWith(`.${Ae}`)))return!0;for(let i of e.folders)i===".obsidian"||i.endsWith("/.obsidian")||A.push(i)}return!1}async function Eo(h,A,t,e,i,s=!1){let n=await Se(h,A,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:a,parentId:r}=n,l=[o,...a],c=new Map;for(let y of l)try{let v=await h.vault.adapter.stat(y.file.path);v&&c.set(y.file.path,v.mtime)}catch{}let g=await ke(h,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),p=await mi(g,e),d=await oe(p,e);if(d.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let y=0;y<g.length;y++)if(d[y]!==g[y])throw new Error("Encryption self-check failed (content).");await h.vault.adapter.exists(Ut)||await h.vault.adapter.mkdir(Ut);let I=A.replace(/\/+$/,""),u=I.split("/").pop()||"vault",f=Je(s?t:`${u} ${Zi(o.file)}`),C=`${Ut}/${f}.${Ae}`;for(let y=1;await h.vault.adapter.exists(C);y++)C=`${Ut}/${f} (${y}).${Ae}`;await hn(h,C,p);let m=l,E={v:1,kind:"deleted",originalFolder:s?"":I,...s?{originalFolderEnc:_a(await mi(new TextEncoder().encode(I),e))}:{},parentId:r,title:s?"":Zi(o.file),count:m.length,created:o.created,rootId:t,deletedAt:i};try{await h.vault.adapter.write(le(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write deleted sidecar",y)}let{unpurged:w}=await mo(h,m,c);return{blobPath:C,noteCount:m.length,rootId:t,originalFolder:I,title:E.title,unpurged:w}}async function yo(h,A,t,e){let i=new Uint8Array(await h.vault.adapter.readBinary(A));if(!Lt(i))throw new Error("Not an encrypted bundle.");let s=await _i(h,A),n=await gn(h,A,s,t),o=await oe(i,t),a=await zt(h,o,n,e,{dedupeExisting:!0});await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(le(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function _i(h,A){try{return JSON.parse(await h.vault.adapter.read(le(A)))}catch{return null}}var Jt=".trash";async function tr(h,A){let t=[],e=[A];for(;e.length;){let i=e.shift(),s;try{s=await h.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function er(h){let A=h.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 wo(h,A,t,e=!1){if(!await h.vault.adapter.exists(Jt))return null;let i=await tr(h,Jt);if(i.length===0)return null;let{default:s}=await Promise.resolve().then(()=>Ms(Wi())),n=new s,o=new Map;for(let I of i){let u=I.slice(Jt.length+1);n.file(`files/${u}`,await h.vault.adapter.readBinary(I));try{let f=await h.vault.adapter.stat(I);f&&o.set(I,f.mtime)}catch{}}let a=new Uint8Array(await n.generateAsync({type:"arraybuffer"})),r=await mi(a,A),l=await oe(r,A);if(l.length!==a.length)throw new Error("Encryption self-check failed (size).");for(let I=0;I<a.length;I++)if(l[I]!==a[I])throw new Error("Encryption self-check failed (content).");await h.vault.adapter.exists(Ut)||await h.vault.adapter.mkdir(Ut);let c=Je(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),g=`${Ut}/${c}.${Ae}`;for(let I=1;await h.vault.adapter.exists(g);I++)g=`${Ut}/${c} (${I}).${Ae}`;await hn(h,g,r);let p={v:1,kind:"rawtrash",originalFolder:Jt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await h.vault.adapter.write(le(g),JSON.stringify(p))}catch(I){console.warn("[Stashpad] couldn't write backfill sidecar",I)}let d=[];for(let I of i){let u=o.get(I);try{if(u!=null){let f=await h.vault.adapter.stat(I);if(f&&f.mtime!==u){d.push(I);continue}}await h.vault.adapter.remove(I)}catch(f){console.warn("[Stashpad] couldn't delete trash file",I,f),d.push(I)}}return{blobPath:g,fileCount:i.length,unpurged:d}}async function vo(h,A,t){let e=new Uint8Array(await h.vault.adapter.readBinary(A));if(!Lt(e))throw new Error("Not an encrypted bundle.");let i=await oe(e,t),{default:s}=await Promise.resolve().then(()=>Ms(Wi())),n=await s.loadAsync(i),o=0;for(let[a,r]of Object.entries(n.files)){if(r.dir||!a.startsWith("files/"))continue;let l=er(a.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",a);continue}let c=`${Jt}/${l}`.split("/").slice(0,-1).join("/"),g="";for(let d of c.split("/"))g=g?`${g}/${d}`:d,await h.vault.adapter.exists(g)||await h.vault.adapter.mkdir(g);let p=`${Jt}/${l}`;for(let d=1;await h.vault.adapter.exists(p);d++)p=`${Jt}/${l.replace(/(\.[^./]*)?$/,` (${d})$1`)}`;await h.vault.adapter.writeBinary(p,await r.async("arraybuffer")),o++}await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(le(A))}catch{}return{filesWritten:o}}async function Fo(h){if(!await h.vault.adapter.exists(Ut))return[];try{return(await h.vault.adapter.list(Ut)).files.filter(t=>t.endsWith(`.${Ae}`))}catch{return[]}}var Ei=null,ji=new Set;function ts(h){if(Ei!==h){Ei=h;for(let A of ji)A()}}function jt(){return Ei}function ko(h){if(Ei===h){Ei=null;for(let A of ji)A()}}function So(h){return ji.add(h),()=>ji.delete(h)}function ir(){return j.Platform.isMacOS?"Finder":j.Platform.isWin?"File Explorer":"file manager"}var qe=[{id:"move",label:"Move (picker)",desc:"Open a fuzzy picker to choose the new parent.",defaultPrimary:"M"},{id:"pickMove",label:"Move (in-list)",desc:"Highlight a note in the list with arrows; Enter sets it as parent.",defaultPrimary:"O"},{id:"merge",label:"Merge",desc:"Concatenate selected notes into the oldest one.",defaultPrimary:"&"},{id:"copy",label:"Copy",desc:"Copy selected note bodies to clipboard.",defaultPrimary:"C"},{id:"copyTree",label:"Copy tree",desc:"Copy the focused note + all descendants, indented.",defaultPrimary:"Y"},{id:"openEditor",label:"Open in editor",desc:"Open the cursor row (or focused note) in a regular Obsidian markdown tab.",defaultPrimary:"E"},{id:"openTab",label:"Open in new Stashpad tab",desc:"Open the cursor row (or focused note) in a new Stashpad tab focused on it.",defaultPrimary:"T"},{id:"split",label:"Split note",desc:"Split the cursor row (or focused note) into two notes at a chosen line.",defaultPrimary:"S"},{id:"copyOutline",label:"Copy as outline",desc:"Copy selection (or cursor row) as a nested ![[embed]] outline.",defaultPrimary:"L"},{id:"toggleSplit",label:"Toggle split-on-newlines",desc:"Default: Mod+/",defaultPrimary:"Mod+/"},{id:"pickDestination",label:"Pick destination",desc:"Default: Mod+D",defaultPrimary:"Mod+D"},{id:"search",label:"Search notes",desc:"Default: Mod+F",defaultPrimary:"Mod+F"},{id:"searchInParent",label:"Search in current parent",desc:"Default: Mod+Alt+F (Mod+Shift+F is taken by Obsidian's global search).",defaultPrimary:"Mod+Alt+F"},{id:"delete",label:"Delete selection",desc:"Default: Mod+Backspace",defaultPrimary:"Mod+Backspace"},{id:"undo",label:"Undo",desc:"Default: Mod+Z (Stashpad-only \u2014 won't fire while typing in the composer).",defaultPrimary:"Mod+Z"},{id:"redo",label:"Redo",desc:"Default: Mod+Shift+Z",defaultPrimary:"Mod+Shift+Z"},{id:"toggleComplete",label:"Toggle complete (strikethrough)",desc:"Default: Mod+Enter or X \u2014 marks selected/focused notes as complete (both chords active).",defaultPrimary:"Mod+Enter",defaultSecondary:"X",defaultUseBoth:!0},{id:"moveUp",label:"Move note up",desc:"Default: Mod+ArrowUp",defaultPrimary:"Mod+ArrowUp"},{id:"moveDown",label:"Move note down",desc:"Default: Mod+ArrowDown",defaultPrimary:"Mod+ArrowDown"},{id:"moveToTop",label:"Move note to top",desc:"Default: Mod+Shift+ArrowUp",defaultPrimary:"Mod+Shift+ArrowUp"},{id:"moveToBottom",label:"Move note to bottom",desc:"Default: Mod+Shift+ArrowDown",defaultPrimary:"Mod+Shift+ArrowDown"},{id:"outdent",label:"Outdent (move to grandparent)",desc:"Default: Mod+[ \u2014 re-parents the selection one level up.",defaultPrimary:"Mod+["},{id:"setColor",label:"Set note color",desc:"Default: Shift+: or ; \u2014 open the color picker for the selection (both chords active).",defaultPrimary:"Shift+:",defaultSecondary:";",defaultUseBoth:!0},{id:"clone",label:"Clone (duplicate / copy) selection",desc:"Default: Mod+Shift+D \u2014 clone selected notes (with their subtrees) as siblings.",defaultPrimary:"Mod+Shift+D"},{id:"insertTemplate",label:"Insert template (clone an existing note)",desc:"Pick any note in this Stashpad; clone it (with subtree + attachments) into the current view, retimestamped.",defaultPrimary:""},{id:"toggleExpand",label:"Show more / show less (expand toggle)",desc:"Default: Shift+? \u2014 toggle the clamp on the cursor row (or every selected row).",defaultPrimary:"Shift+?"},{id:"exportStash",label:"Export selection to .stash",desc:"Export the selected subtree(s) as a .stash bundle (notes + attachments).",defaultPrimary:""},{id:"importStash",label:"Import .stash file",desc:"Open the .stash bundle picker and import its notes into this Stashpad.",defaultPrimary:""},{id:"pickFolder",label:"Open / switch / create Stashpad folder",desc:"Default: Mod+S \u2014 opens the unified folder picker (reveal, switch, create, convert).",defaultPrimary:"Mod+S"},{id:"cloneStashpadTab",label:"Clone (duplicate / copy) this Stashpad tab",desc:'Open a second tab on the same folder + focus, mirroring the "copy" button in the focused-header actions.',defaultPrimary:""},{id:"selectAll",label:"Select all notes in view",desc:"Default: Mod+A \u2014 adds every visible row to the selection.",defaultPrimary:"Mod+A"},{id:"copyCodeBlock",label:"Copy code from codeblock",desc:"Default: { \u2014 copy the contents of the cursor row's first codeblock (or pick one when multiple exist).",defaultPrimary:"{"},{id:"swapWithParent",label:"Swap with parent (ouroboros)",desc:"Promote the cursor row above its current parent; the parent slides under it (carrying its other children). No default \u2014 bind in this tab.",defaultPrimary:""},{id:"togglePin",label:"Pin / unpin selected note",desc:"Default: P \u2014 toggle the sidebar pin state of the cursor row (or focused note).",defaultPrimary:"P"},{id:"toggleTask",label:"Toggle task (todo)",desc:"Default: H \u2014 mark the selection (or cursor row) as a task / todo, or clear it. Tasks appear in the Tasks panel.",defaultPrimary:"H"},{id:"setDue",label:"Set due date\u2026",desc:"Default: D \u2014 open a date+time picker to set (or clear) the due date on the selection. Setting a due date also marks the note as a task.",defaultPrimary:"D"},{id:"jumpToTop",label:"Jump to top of list",desc:"Default: Home \u2014 move the cursor to the first note in the current list.",defaultPrimary:"Home"},{id:"jumpToBottom",label:"Jump to bottom of list",desc:"Default: End \u2014 move the cursor to the last note in the current list.",defaultPrimary:"End"},{id:"commandPalette",label:"Command palette (Stashpad only)",desc:"Default: Mod+K \u2014 open a command palette listing only Stashpad's commands, with Sift search.",defaultPrimary:"Mod+K"},{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 fn(){let h={};for(let A of qe)h[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return h}var ce={folder:"Stashpad",importDropFolder:"",exportFolder:"_exports",autoImport:!1,inheritObsidianExclusions:!0,folderPanelPinnedFraction:.5,folderPanelPinned:[],folderPanelDownranked:[],folderPanelHidden:[],folderPanelPinnedGrouping:"pin-order",enablePerfProfiling:!1,writeRecoveryLinks:!0,useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,popoutDuplicates:!0,encryption:Qi(),encryptTrash:!1,encryptTrashFilenames:!1,encryptionIdleLockMinutes:0,hideLockedTitles:!1,archiveFolders:[],lockedSubtrees:[],searchOpensInNewTab:!0,pinnedNotes:[],hideMobileToolbarInStashpad:!0,slugStopWords:[],searchIncludedFolders:[],searchExcludedFolders:[],shortcuts:{move:"M",pickMove:"O",merge:"&",copy:"C",copyTree:"Y",openEditor:"E",openTab:"T",split:"S",copyOutline:"L"},mod:{toggleSplit:"Mod+/",pickDestination:"Mod+D",search:"Mod+F",delete:"Mod+Backspace",undo:"Mod+Z",redo:"Mod+Shift+Z",toggleComplete:"Mod+Enter",moveUp:"Mod+ArrowUp",moveDown:"Mod+ArrowDown",moveToTop:"Mod+Shift+ArrowUp",moveToBottom:"Mod+Shift+ArrowDown",outdent:"Mod+[",setColor:"Shift+:"},customPalette:[],colorAliases:{},noteTemplates:{},authorName:"",authorId:"",authorRole:"",authorDepartment:"",showAuthor:!0,showContributors:!0,showLastEdit:!0,viewModes:{},includeAttachmentsInEverything:{},hideChildlessNotes:{},hideCompletedNotes:{},attachmentsOnlyNotes:{},mutedNotificationCategories:[],notificationHistoryLimit:5e3,notifiedDueKeys:[],autoNavOnMoveIn:!1,autoNavOnMoveOut:!1,autoExpandCursorRow:!1,autoOpenDetailPanel:!1,doubleClickToFocus:!0,dateDisplayFormat:"locale",dateDisplayTimezone:"",jdIndexScope:"vault",jdIndexScopeFolder:"",jdIndexStashpadFolder:"",jdIndexFile:"Index",jdIndexIncludeStashpadFolders:!1,jdIndexSort:"natural",jdIndexHasBuilt:!1,drafts:{},lastSubmitted:{},bindings:fn()},Do=JSON.parse(JSON.stringify(ce)),un=new Set;function pt(){return Do}function Cn(h){Do=h;for(let A of un)A()}function bo(h){return un.add(h),()=>un.delete(h)}function ss(h){try{let A=h.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var es=[{id:"general",label:"General"},{id:"encryption",label:"Encryption"},{id:"diagnostics",label:"Diagnostics"},{id:"authorship",label:"Authorship"},{id:"templates",label:"Templates"},{id:"jdindex",label:"JD Index"},{id:"hotkeys",label:"Hotkeys"}],In=null;function sr(h,A){return In||(In=class extends j.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new In(h,A)}var is=class extends j.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if(j.SettingPage){super.display();return}let{containerEl:t}=this;t.empty();for(let e of es){t.createEl("h2",{text:e.label});let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new j.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 es.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>sr(t.label,i=>this.renderTabContent(i,t.id))}})}itemsForTab(t){switch(t){case"hotkeys":return this.hotkeyItems();case"diagnostics":return this.diagnosticsItems();case"general":return this.generalItems();case"encryption":return this.encryptionItems();case"authorship":return this.authorshipItems();case"templates":return this.templatesItems();case"jdindex":return this.jdIndexItems();default:return null}}renderTabContent(t,e){switch(e){case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break}}diagnosticsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(Ys);return[this.renderDef("Write recovery navigation links","Maintain the redundant parentLink/children frontmatter so you can walk the hierarchy from raw Markdown if the index ever breaks. On a slow / network drive this is a big per-move cost (several round-trips each); turn it off there for snappier moves \u2014 Rebootstrap rebuilds the fields on demand, and your notes' canonical structure (id/parent) is unaffected either way.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.writeRecoveryLinks).onChange(async n=>{this.plugin.settings.writeRecoveryLinks=n,await this.plugin.saveSettings()})),["recovery","parentlink","children","frontmatter"]),this.renderDef("Performance profiling","Record timing for list rendering, body reads, and file writes. Turn on, use Stashpad normally (especially the slow operations), then run \u201CDump performance profile\u201D from the command palette and share the result. Off = zero overhead.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.enablePerfProfiling).onChange(async n=>{this.plugin.settings.enablePerfProfiling=n,await this.plugin.saveSettings()})),["perf","profiling","timing","slow"]),this.renderDef("Open log file","Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.",i=>i.addButton(s=>s.setButtonText("Open log").onClick(async()=>{let n=this.app.vault.adapter,o=this.plugin.pluginPrivatePath("log.jsonl");if(!await n.exists(o)){new j.Notice("No log yet \u2014 make some changes first.");return}let a=await n.read(o);new Me(this.app,a,o).open()})),["log","history","diagnostics"]),this.renderDef("Notification history limit","Maximum number of notifications kept in the persistent history. Set to 0 for unlimited (the file size grows with usage; expect a few hundred KB per ~5000 entries). Default: 5000.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.notificationHistoryLimit??5e3)).setPlaceholder("5000").onChange(async n=>{let o=parseInt(n,10);Number.isFinite(o)&&(this.plugin.settings.notificationHistoryLimit=o,this.plugin.notifications.setHistoryLimit(o),await this.plugin.saveSettings())})),["notification","history","limit"]),{type:"group",heading:"Mute notification categories",items:e.map(i=>{let s=Ys[i];return this.renderDef(s.label,s.desc,n=>n.addToggle(o=>o.setValue(!t.has(i)).onChange(async a=>{let r=!a;r?t.add(i):t.delete(i),this.plugin.settings.mutedNotificationCategories=Array.from(t),this.plugin.notifications.setMuted(i,r),await this.plugin.saveSettings()})),["notification","mute","toast","category"])})},this.renderDef("Notification history","Browse the last 200 toasts. Filter by category. Live-updates as new notifications arrive. Muted categories still appear here so you can review what was suppressed.",i=>i.addButton(s=>s.setButtonText("View notification history").onClick(()=>{new Ai(this.app,this.plugin.notifications,async n=>{let o=this.app.vault.adapter,a=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(a)){new j.Notice("No log yet \u2014 make some changes first.");return}let r=await o.read(a);new Me(this.app,r,a).open()},this.plugin.settings.authorId||null,n=>this.plugin.lookupNoteAuthorIds(n)).open()})),["notification","history","panel"])]}renderTemplatesTab(t){this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t)}renderDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{n.setName(t).setDesc(e),i(n)}}}sectionDef(t,e,i,s){return{name:t,desc:e,aliases:s,render:n=>{let o=n.settingEl;o.empty(),o.removeClass("setting-item"),o.addClass("stashpad-settings-section"),i(o)}}}generalItems(){let t=async()=>this.plugin.saveSettings(),e=(s,n,o,a,r)=>this.renderDef(s,n,l=>l.addToggle(c=>c.setValue(o()).onChange(async g=>{a(g),await t()})),r),i=[];i.push(this.renderDef("Stashpad notes folder","Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.",s=>{s.addText(n=>{new Pe(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||ce.folder,r=a.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(c=>(c??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(r)){new j.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.push(e("Auto-import dropped files","When on, any file you drop directly into a Stashpad folder is imported automatically: markdown becomes a note (the original is archived to .archive); other files move to _attachments with a note that links to them. Large drops ask for confirmation first.",()=>this.plugin.settings.autoImport,s=>{this.plugin.settings.autoImport=s},["import","drop","auto"])),i.push(e("Inherit Obsidian's excluded files","Also hide files matching Obsidian's \u201CExcluded files\u201D list (Settings \u2192 Files & Links) from Stashpad's link autocomplete and file surfaces \u2014 so you manage exclusions in one place. Plugin-internal formats like .edtz are always excluded regardless.",()=>this.plugin.settings.inheritObsidianExclusions,s=>{this.plugin.settings.inheritObsidianExclusions=s},["excluded","ignore","files"])),i.push(this.renderDef("Dedicated import subfolder (optional)","Optional. A subfolder (relative to each Stashpad folder) where dropped .stash files auto-import. Leave blank to just drop files into the Stashpad folder itself (recommended). Suggested name: _imports.",s=>s.addText(n=>n.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports (leave blank to use the folder root)").onChange(async o=>{this.plugin.settings.importDropFolder=(o||"").trim().replace(/^\/+|\/+$/g,""),await t()})),["import","subfolder"])),i.push(this.renderDef("Stash export subfolder","Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.",s=>s.addText(n=>n.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async o=>{this.plugin.settings.exportFolder=(o||"").trim().replace(/^\/+|\/+$/g,"")||ce.exportFolder,await t()})),["export","stash","subfolder"])),i.push(this.renderDef("Rebootstrap existing Stashpad folders","Walk every folder that has a home note: ensure infrastructure (_imports, _exports, drafts file), backfill the redundant parentLink + children frontmatter fields, AND rename any note whose filename slug no longer matches its body's first line. Safe to run anytime; skip-if-equal means already-synced notes are no-op writes.",s=>s.addButton(n=>n.setButtonText("Rebootstrap now").onClick(async()=>{n.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:o,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:c,imported:g,attachmentsLinked:p}=await this.plugin.rebootstrapAllFolders(),d=[];d.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),g>0&&d.push(`imported ${g} loose file${g===1?"":"s"}`),p>0&&d.push(`linked attachments on ${p} note${p===1?"":"s"}`),r>0?d.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&d.push(`frontmatter already in sync (${a} notes checked)`),l>0&&d.push(`renamed ${l} note${l===1?"":"s"} to match body`),c>0&&d.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new j.Notice(`Stashpad: ${d.join("; ")}.`)}catch(o){new j.Notice(`Stashpad: rebootstrap failed (${o.message})`)}finally{n.setDisabled(!1).setButtonText("Rebootstrap now")}})),["rebootstrap","rebuild","repair","backfill","slug"])),i.push(this.renderDef("Use Templates plugin date/time formats","When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.",s=>{s.addToggle(o=>o.setValue(this.plugin.settings.useTemplatesFormat).onChange(async a=>{this.plugin.settings.useTemplatesFormat=a,await t()}));let n=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: ${$t(Date.now(),this.plugin.settings)}`)};i.push(this.renderDef("Date display format","How due dates and created/modified times are shown in the Tasks and detail panels.",o=>{o.addDropdown(a=>{a.addOption("locale","Locale, short (Mar 5, 9:00 AM)"),a.addOption("long","Locale, long (Thursday, March 5\u2026)"),a.addOption("iso","ISO (2026-03-05 09:00)"),a.addOption("us","US (3/5/2026, 9:00 AM)"),a.addOption("eu","EU (5/3/2026, 09:00)"),a.setValue(this.plugin.settings.dateDisplayFormat??"locale"),a.onChange(async r=>{this.plugin.settings.dateDisplayFormat=r,await t(),n()})})},["date","format","display"])),i.push(this.renderDef("Display timezone","IANA timezone name (e.g. America/New_York, Europe/London, Asia/Kolkata). Leave blank to use your system timezone.",o=>{o.addText(a=>{a.setPlaceholder("(system timezone)"),a.setValue(this.plugin.settings.dateDisplayTimezone??""),a.onChange(async r=>{this.plugin.settings.dateDisplayTimezone=(r||"").trim(),await t(),n()})})},["timezone","tz","date","iana"])),i.push({name:"Date sample",searchable:!1,render:o=>{let a=o.settingEl;a.empty(),a.removeClass("setting-item"),s=a.createDiv({cls:"setting-item-description stashpad-settings-note"}),n()}})}return i.push(e("Navigate into parent after moving a note IN","When you move a note onto another note via the in-list move picker (drag-onto-sibling), automatically drill into the new parent so you can see the moved note in its new home. Off = stay focused where you were.",()=>this.plugin.settings.autoNavOnMoveIn,s=>{this.plugin.settings.autoNavOnMoveIn=s},["navigate","move","in"])),i.push(e("Navigate to destination after moving a note OUT","When you outdent a note, move it via the cross-parent picker, or send it to Home, automatically drill into the destination parent. Off = stay focused where you were.",()=>this.plugin.settings.autoNavOnMoveOut,s=>{this.plugin.settings.autoNavOnMoveOut=s},["navigate","move","out"])),i.push(e("Double-click a note to open it","Double-click (or double-tap on mobile) a note in the list to focus/open it \u2014 the same as pressing \u2192 or clicking the enter arrow. Single click still just selects. On by default.",()=>this.plugin.settings.doubleClickToFocus,s=>{this.plugin.settings.doubleClickToFocus=s},["double","click","open","focus"])),i.push(e("Auto-open the detail panel","Open the right-sidebar Stashpad detail panel automatically whenever a Stashpad view becomes active. The panel shows the cursored note's body, metadata, and children. Off = open manually via ribbon or command palette.",()=>this.plugin.settings.autoOpenDetailPanel,s=>{this.plugin.settings.autoOpenDetailPanel=s},["detail","panel","sidebar"])),i.push(e("Expand the cursor row's body automatically","As you arrow-key through the list, the row under the cursor temporarily un-clamps to show its full body. Moving away re-collapses it. Doesn't affect the persistent 'Show more' state \u2014 this is a transient view-only effect.",()=>this.plugin.settings.autoExpandCursorRow,s=>{this.plugin.settings.autoExpandCursorRow=s},["expand","cursor","body"])),i.push(e("Confirm cross-parent drag-and-drop","When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).",()=>this.plugin.settings.confirmCrossParentDrag,s=>{this.plugin.settings.confirmCrossParentDrag=s},["confirm","drag","drop","reparent"])),i.push(e("Confirm bulk deletes","Warn before deletes that affect more than one note \u2014 multi-selection delete OR deleting a note that has descendants. A single childless note with no attachments never prompts. Off = those deletes apply immediately (undo still recovers everything).",()=>this.plugin.settings.confirmBulkDelete,s=>{this.plugin.settings.confirmBulkDelete=s},["confirm","delete","bulk"])),i.push(e("Offer to delete attachments with note",`When a note references attachments, the delete modal includes an "Also delete attachments" checkbox so orphaned files don't pile up in your vault. Attachments are detected from both ![[\u2026]] embeds in the body and the frontmatter attachments: list. Off = attachments are always preserved on delete (no checkbox shown), and a single childless note with attachments deletes silently.`,()=>this.plugin.settings.confirmAttachmentDelete,s=>{this.plugin.settings.confirmAttachmentDelete=s},["delete","attachment","orphan"])),i.push(this.renderDef("Slug stop-words","Words removed from auto-generated note titles (filenames). One per line.",s=>{let n=null,o=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:Yt).join(` `);s.addTextArea(a=>{a.setValue(o),n=a.inputEl,n.rows=6,n.style.fontFamily="var(--font-monospace)",a.onChange(async r=>{this.plugin.settings.slugStopWords=(r||"").split(/\r?\n/).map(l=>l.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(a=>a.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Yt],n&&(n.value=Yt.join(` -`)),await t()}))},["slug","stopwords","filename","title"])),i.push(this.sectionDef("Cross-Stashpad search scope","Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations. Also: create a new Stashpad.",s=>{let n=this.plugin.discoverStashpadFolders();if(new j.Setting(s).setName("Cross-Stashpad search scope").setDesc("Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations \u2014 their notes just don't appear in search results from elsewhere."),n.length===0)s.createEl("p",{cls:"setting-item-description"}).setText('No Stashpads found in this vault yet. A Stashpad is just a folder that contains a Stashpad-shaped note (frontmatter has both `id` and `parent`). Easiest way: open Stashpad (ribbon icon or command "Reveal or open Stashpad") \u2014 it auto-creates the default folder on first use. Or create one below.');else{let a=s.createDiv({cls:"stashpad-folder-list"});for(let r of n)this.renderFolderScopeRow(a,r)}let o=null;new j.Setting(s).setName("Create a new Stashpad").setDesc("Type a vault-relative folder path. The folder is created (with intermediates) and seeded with a Home note so Stashpad recognizes it.").addText(a=>{a.setPlaceholder("my-stashpad"),o=a.inputEl}).addButton(a=>a.setButtonText("Create").setCta().onClick(async()=>{let r=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!r){new j.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(r),new j.Notice(`Created Stashpad "${r}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(r,2e3),this.update?.()}catch(l){new j.Notice(`Couldn't create: ${l.message}`)}}))},["search","scope","exclude","include","create","new","stashpad","folder"])),i.push(this.sectionDef("Folder panel placement","Pin, downrank, or hide folders in the Stashpad folder panel. Restore hidden folders here or from the panel's \u201CHidden\u201D section.",s=>{new j.Setting(s).setName("Folder panel placement").setDesc("Folders you've pinned, downranked, or hidden in the Stashpad folder panel. Pin/downrank from a folder's right-click menu in the panel; restore here or from the panel's \u201CHidden\u201D section."),this.renderFolderPlacementList(s)},["folder","panel","pin","pinned","downrank","hide","hidden","restore","placement"])),i.push(e("Autofocus composer after sending","After Enter-submitting a note, return focus to the composer so you can keep typing. Off keeps focus in the list \u2014 useful if you want arrow keys to work without an extra click.",()=>this.plugin.settings.autofocusComposerAfterSend,s=>{this.plugin.settings.autofocusComposerAfterSend=s},["composer","focus","send"])),i.push(e("Open in new window \u2014 duplicate tab","ON: the new-window button (in the time-filter row) duplicates the current Stashpad tab \u2014 original stays open in the main window. OFF: the leaf is MOVED to the new window, closing the original tab.",()=>this.plugin.settings.popoutDuplicates,s=>{this.plugin.settings.popoutDuplicates=s},["popout","window","duplicate"])),i.push(e("Search results open in a new tab","When you pick a result in the Search modal, open it in a new Stashpad tab instead of navigating the current tab. Applies to same-folder and cross-Stashpad results alike. On by default.",()=>this.plugin.settings.searchOpensInNewTab,s=>{this.plugin.settings.searchOpensInNewTab=s},["search","new tab","results","open"])),i.push(e("Prefix timestamps when copying","Include each note's timestamp before its body when copying with C or Y.",()=>this.plugin.settings.prefixTimestampsOnCopy,s=>{this.plugin.settings.prefixTimestampsOnCopy=s},["copy","timestamp","prefix"])),i}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"),i.createEl("p",{cls:"setting-item-description"}).setText("\u26A0\uFE0F One password protects everything you encrypt in this vault, and it's stored ONLY on this device \u2014 if you forget it, anything encrypted with it is gone for good. While encrypting, don't run a sync/cloud service over the vault and avoid working in Stashpad mid-operation \u2014 either can corrupt files. (File-encryption actions aren't enabled in this version yet \u2014 this screen sets up the key.)");let s=()=>t.argonProbe();if(!t.isConfigured()){new j.Setting(i).setName("Encryption").setDesc("Not set up yet.").addButton(a=>a.setButtonText("Set up password\u2026").setCta().onClick(()=>{new $t(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:s,onSubmit:async({next:r,remember:l})=>{if(!r)return"Enter a password.";try{await t.setup(r,l)}catch(c){return c.message}return new j.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}let n=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",o=t.isRemembered()?" \xB7 remembered on this device":"";new j.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${n?` \xB7 ${n}`:""}${o}`),t.isUnlocked()?new j.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(a=>a.setButtonText("Lock now").onClick(()=>{t.lock(),new j.Notice("Encryption locked."),this.update?.()})):new j.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(a=>a.setButtonText("Unlock\u2026").setCta().onClick(()=>{new $t(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:r,remember:l})=>await t.unlock(r,l)?(new j.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),t.keychainAvailable()&&t.isRemembered()&&new j.Setting(i).setName("Forget remembered password").setDesc("Remove the saved password from this device's keychain (you'll re-type it next session).").addButton(a=>a.setButtonText("Forget").onClick(async()=>{await t.forgetKeychain(),new j.Notice("Removed from keychain."),this.update?.()})),new j.Setting(i).setName("Change password").setDesc("Re-wraps the same key under a new password \u2014 does not re-encrypt your files.").addButton(a=>a.setButtonText("Change\u2026").onClick(()=>{new $t(this.app,{mode:"change",offerKeychain:!0,kdfProbe:s,onSubmit:async({current:r,next:l,remember:c})=>await t.changePassword(r,l,c)?(new j.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),new j.Setting(i).setName("Remove encryption").setDesc("Erases the key from this vault. Refused while any locked notes exist \u2014 decrypt everything first (locked notes have NO plaintext copy; losing the key loses them forever).").addButton(a=>{a.setButtonText("Remove\u2026").onClick(async()=>{if(await hn(this.app)){new j.Notice(`Can't remove encryption: locked/encrypted-deleted notes still exist and would be lost forever. Run "Decrypt (unlock) ALL locked notes in the vault" and empty the encrypted trash first.`,1e4);return}new si(this.app,{title:"Remove encryption?",body:"This erases the encryption key for this vault. Nothing is currently encrypted (locked notes are checked), so no content is lost \u2014 but you'll need to set a new password to encrypt later, and anything you had exported encrypted with this key stays locked to its passphrase.",phrase:"REMOVE ENCRYPTION",confirmText:"Remove encryption",requirePassword:r=>t.verifyPassword(r),onConfirm:async()=>{if(await hn(this.app)){new j.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}await t.clear(),new j.Notice("Encryption removed."),this.update?.()}}).open()}),a.setWarning?.(!0)})},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{this.plugin.settings.encryptTrash=n,await this.plugin.saveSettings()})),["trash","delete","encrypt"])),e.push(this.renderDef("Encrypt trash filenames","Hide the filename + origin folder of encrypted-trashed items (opaque names on disk; shown under \u201CHidden\u201D in the trash tab). Default OFF so you can still tell what to restore when working outside the app.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFilenames).onChange(async n=>{this.plugin.settings.encryptTrashFilenames=n,await this.plugin.saveSettings()})),["trash","filename","encrypt"])),e.push(this.renderDef("Follow Obsidian's trash setting instead","OFF (recommended): encrypted-deleted notes go to Stashpad's own \u201C_deleted/\u201D store \u2014 the only trash location Stashpad fully controls, so it can encrypt, list, and restore them. ON: deletes follow Obsidian's \u201CDeleted files\u201D setting instead (system/OS trash or permanent). \u26A0\uFE0F Stashpad CANNOT encrypt or recover notes that go to the system trash \u2014 so the encrypted trash + recoverable trash view won't apply. Only turn this on if you specifically want Obsidian's native trash behavior.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFollowObsidian??!1).onChange(async n=>{this.plugin.settings.encryptTrashFollowObsidian=n||void 0,await this.plugin.saveSettings()})),["trash","obsidian","system","delete","encrypt"])),e.push(this.renderDef("Auto-lock after idle minutes","Forget the password from memory after this many idle minutes (0 = never). Re-prompts on the next encryption action.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.encryptionIdleLockMinutes??0)).onChange(async n=>{let o=Math.max(0,Math.floor(Number(n)||0));this.plugin.settings.encryptionIdleLockMinutes=o,await this.plugin.saveSettings()})),["auto-lock","idle","timeout","lock"])),e.push(this.renderDef("Hide titles of locked notes","Show a generic label on \u{1F512} locked placeholders instead of the note's title, so a glance at the vault doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.renderDef("Default archive folder",`Where the "Move selection to archive" command sends notes (they're auto-encrypted on arrival). Leaving this blank is fine \u2014 the command will just show you a list of your archive folders to pick from each time (or use the only one if you have a single archive). Mark a folder as an archive via the folder panel \u2192 right-click \u2192 "Mark as archive".`,i=>{let s=this.plugin.settings.archiveFolders??[];i.addDropdown(n=>{n.addOption("",s.length?"\u2014 pick from list each time \u2014":"\u2014 no archive folders yet \u2014");for(let a of s)n.addOption(a,a);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async a=>{this.plugin.settings.defaultArchiveFolder=a||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e}hotkeyItems(){let t={name:"Hotkeys",desc:"Each command has up to two slots. Click a slot and press a key (or chord) to bind it; press Backspace (delete on Mac) to cancel without binding; or click \u2715 to clear an existing binding. A \u21BA icon appears on any slot that differs from its shipped default \u2014 click it to revert that slot. When both slots are set, the pill on the right decides which one is active.",searchable:!1},e=Le.map(i=>({name:i.label,desc:i.desc,aliases:["hotkey","shortcut","keybind","binding","key"],render:s=>this.renderBindingRow(s,i)}));return[t,...e]}renderJdIndexSection(t){let e=t.createEl("h3",{text:"JD Index Builder"});e.id="stashpad-jd-index-section";let i=t.createEl("p",{cls:"setting-item-description"});i.innerHTML="Builds a Johnny-Decimal-style index inside a designated Stashpad folder. Two commands:<br/><strong>Preview</strong> overwrites the designated folder’s HOME note body with the would-be hierarchy + everything that didn’t match. Frontmatter is preserved; everything below it is replaced.<br/><strong>Build</strong> creates an actual hierarchy of Stashpad notes (one per prefix), with child\u2192parent relationships matching the dotted segments.<br/>Matches strict prefixes only: all-digits (<code>10 Life</code>) or alphanumeric-with-dots (<code>1.2 Family</code>, <code>animal.duck.yellow Eggs</code>). Mixed schemes sort numbers first, then alphabetically.";let s=this.plugin.discoverStashpadFolders();new j.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(r=>{r.addOption("vault","Entire vault"),r.addOption("folder","Single folder"),r.setValue(this.plugin.settings.jdIndexScope??"vault"),r.onChange(async l=>{this.plugin.settings.jdIndexScope=l==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new j.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(r=>{new Te(this.app,r.inputEl),r.setPlaceholder("Path/To/Folder"),r.setValue(this.plugin.settings.jdIndexScopeFolder??""),r.onChange(async l=>{this.plugin.settings.jdIndexScopeFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new j.Setting(t).setName("Include Stashpad folders in scan").setDesc("By default, notes inside any known Stashpad folder are excluded \u2014 the index destination shouldn't index itself, and other Stashpad folders are usually already organized. Toggle on if you want them included anyway.").addToggle(r=>{r.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),r.onChange(async l=>{this.plugin.settings.jdIndexIncludeStashpadFolders=l,await this.plugin.saveSettings(),this.display()})}),new j.Setting(t).setName("Designated Stashpad folder for Index").setDesc("Required. Must be a Stashpad folder. The index hierarchy is built here. New notes are created; nothing is deleted.").addText(r=>{new Te(this.app,r.inputEl),r.setPlaceholder(s[0]??"(pick a Stashpad folder)"),r.setValue(this.plugin.settings.jdIndexStashpadFolder??""),r.onChange(async l=>{this.plugin.settings.jdIndexStashpadFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new j.Setting(t).setName("Sort").setDesc("Order of entries within the same depth. Natural: numbers first then alphabetical (recommended). Created: by source file's creation time \u2014 handy when prefixes are word-only and don't carry ordering.").addDropdown(r=>{r.addOption("natural","Natural (numeric \u2192 alphabetical)"),r.addOption("created","By creation time"),r.setValue(this.plugin.settings.jdIndexSort??"natural"),r.onChange(async l=>{this.plugin.settings.jdIndexSort=l==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=He(this.app,this.plugin,this.plugin.settings),o=t.createEl("p",{cls:"setting-item-description"}),a=n.skippedStashpadNotes.length>0?` (${n.skippedStashpadNotes.length} Stashpad-folder note${n.skippedStashpadNotes.length===1?"":"s"} excluded by default)`:"";o.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${a}.`),new j.Setting(t).setName("Actions").setDesc("Preview aggressively overwrites the designated folder's HOME note body (frontmatter preserved). Build creates Stashpad notes (existing notes with the same jdPrefix are updated, not duplicated).").addButton(r=>{r.setButtonText("Preview"),r.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),r.onClick(async()=>{try{let l=await Pi(this.app,this.plugin,this.plugin.settings);if(l.error==="no-dest"){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(l.error==="no-home"){new j.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}Ri(this.app,l),this.display()}catch(l){console.error("[stashpad] preview failed",l),new j.Notice(`Preview failed: ${l?.message??l}`,8e3)}})}).addButton(r=>{r.setButtonText("Build Stashpad notes"),r.setCta(),r.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),r.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new ci(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let g=await Js(this.app,this.plugin,this.plugin.settings);if(g.error==="no-dest"){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(g.error==="dest-not-stashpad"){new j.Notice(`"${g.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder (or create one first).`,7e3);return}this.plugin.settings.jdIndexHasBuilt=!0,await this.plugin.saveSettings(),new j.Notice(`Built: ${g.created} created, ${g.updated} updated, ${g.skipped} skipped \u2192 ${g.destFolder}`,6e3),this.display()}catch(g){console.error("[stashpad] build failed",g),new j.Notice(`Build failed: ${g?.message??g}`,8e3)}}).open()})}).addButton(r=>{r.setButtonText(`Reveal in ${ir()}`),r.setTooltip("Open the designated Stashpad folder in your OS file browser."),r.onClick(async()=>{let l=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(l)){new j.Notice(`Folder "${l}" doesn't exist yet.`,5e3);return}try{let g=this.app.vault.adapter.basePath;if(g){let{shell:p}=window.require?.("electron")??{},d=`${g}/${l}`;p?.openPath?.(d)}else new j.Notice("Reveal in file system not supported on this platform.",4e3)}catch(g){new j.Notice(`Couldn't open folder: ${g?.message??g}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new j.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=jt()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new j.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(o=>{for(let a of e)o.addOption(a,a);o.setValue(i),o.onChange(a=>{i=a,n()})}),t.createEl("p",{cls:"setting-item-description",text:"Give each per-note color a friendly name. Filters and pickers display the alias instead of the hex code; the underlying color stays the same. The same hex in two Stashpads can have different aliases."});let s=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{s.empty();let o=this.plugin.collectColorsInFolder(i),a=new Map(o.map(g=>[g.hex,g.count])),r=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},l=new Set([...a.keys(),...Object.keys(r)]);if(l.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...l].map(g=>({hex:g,count:a.get(g)??0}));c.sort((g,p)=>p.count-g.count||g.hex.localeCompare(p.hex));for(let g of c)this.renderColorAliasRow(s,i,g.hex,g.count,n)};n()}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=Bt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["author","name","identity","stamp"])),t.push(this.renderDef("Author id (auto-assigned)","Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. To reset it, clear and retype your author name.",i=>i.addText(s=>s.setValue(this.plugin.settings.authorId).setDisabled(!0)),["author","id"])),t.push(this.renderDef("Title / role",'Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorRole).onChange(async n=>{this.plugin.settings.authorRole=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["role","title","job"])),t.push(this.renderDef("Department / team",'Optional. Shown on your author page (e.g. "Engineering", "Growth").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorDepartment).onChange(async n=>{this.plugin.settings.authorDepartment=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["department","team"]));let e=(i,s,n,o)=>this.renderDef(i,"",a=>a.addToggle(r=>r.setValue(s()).onChange(async l=>{n(l),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=r=>{r.preventDefault(),this.plugin.activateViewForFolder(s.folder)};let a=[];s.authored>0&&a.push(`authored ${s.authored}`),s.contributed>0&&a.push(`contributed to ${s.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}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"])]}renderAuthorshipSection(t){t.createEl("h3",{text:"Authorship"}),t.createEl("p",{cls:"setting-item-description",text:"Stamp each new note with your name. If the vault is later shared (e.g. a coworker opens it with --config pointing at their own settings folder), every modification automatically tracks contributors on top of the original author. Names link to per-user pages in <stashpad>/_authors/."}),new j.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=Bt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new j.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 j.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 j.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 j.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 j.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 j.Setting(t).setName("Show last edit time in note footer").addToggle(i=>i.setValue(this.plugin.settings.showLastEdit).onChange(async s=>{this.plugin.settings.showLastEdit=s,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let i=t.createDiv({cls:"stashpad-authored-folders-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-authored-folder-row"}),o=n.createEl("a",{cls:"stashpad-authored-folder-link",text:s.folder});o.onclick=r=>{r.preventDefault(),this.plugin.activateViewForFolder(s.folder)};let a=[];s.authored>0&&a.push(`authored ${s.authored}`),s.contributed>0&&a.push(`contributed to ${s.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}this.renderKnownAuthorsSection(t)}renderKnownAuthorsSection(t){t.createEl("h4",{text:"Known authors (registry)"}),t.createEl("div",{cls:"setting-item-description",text:"A rebuildable cache of every author Stashpad has seen, with rename history. Not a source of truth \u2014 the author id stored in each note is authoritative. Use it to recover deleted author pages or audit name changes."}),new j.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 j.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new j.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 j.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new j.Notice(`Restore failed: ${n.message}`)}s.setDisabled(!1).setButtonText("Restore missing pages")}));let e=this.plugin.authorRegistry.all();if(e.length===0){t.createEl("div",{cls:"setting-item-description",text:"No authors recorded yet. Rebuild to scan the vault."});return}let i=t.createDiv({cls:"stashpad-known-authors-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-known-author-row"}),o=n.createDiv({cls:"stashpad-known-author-main"});o.createSpan({cls:"stashpad-known-author-name",text:s.name||"(unnamed)"});let a=[];if(s.role&&a.push(s.role),s.department&&a.push(s.department),a.push(`id ${s.id}`),o.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${a.join(" \xB7 ")}`}),s.renames&&s.renames.length>0){let r=n.createDiv({cls:"stashpad-known-author-history"}),l=s.renames.map(c=>`${c.from} \u2192 ${c.to}`).join(", ");r.setText(`Renamed: ${l}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new j.Setting(t).setName("Note templates per Stashpad").setDesc("Pick a markdown file to use as the default template for new notes in each Stashpad. The template's frontmatter becomes the new note's frontmatter (id/parent/created/attachments are always set by Stashpad). If the body contains {{body}}, that's where the user-typed body goes; otherwise the user body is followed by the template body.");let i=t.createDiv({cls:"stashpad-note-templates-list"}),s=n=>{let o=n.replace(/\/+$/,""),a=i.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let l=a.createDiv({cls:"stashpad-note-template-input-wrap"}),c=l.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});c.value=(this.plugin.settings.noteTemplates??{})[o]??"";let g=l.createDiv({cls:"stashpad-note-template-suggest"});g.style.display="none";let p=a.createDiv({cls:"stashpad-note-template-warn"});p.style.display="none";let d=()=>this.app.vault.getMarkdownFiles().map(C=>C.path).filter(C=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(C)).sort(),I=()=>{g.empty();let C=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),m=w=>{let y=w.toLowerCase();return C.every(v=>y.includes(v))},E=d().filter(w=>m(w)).slice(0,12);if(E.length===0){g.style.display="none";return}g.style.display="";for(let w of E)g.createDiv({cls:"stashpad-note-template-suggest-item",text:w}).addEventListener("mousedown",async v=>{v.preventDefault(),c.value=w,await u(),g.style.display="none"})},u=async()=>{let C=c.value.trim(),m={...this.plugin.settings.noteTemplates??{}};C?m[o]=C:delete m[o],this.plugin.settings.noteTemplates=m,await this.plugin.saveSettings(),f()},f=()=>{p.empty(),p.style.display="none";let C=c.value.trim();if(!C)return;let m=this.app.vault.getAbstractFileByPath(C);if(!m||m.extension!=="md"){p.style.display="",p.setText(`\u26A0 "${C}" is not a markdown file in this vault.`);return}let E=this.app.metadataCache.getFileCache(m)?.frontmatter??{},y=se.filter(v=>{let S=E[v];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.length===0)});y.length!==0&&(p.style.display="",p.setText(`\u26A0 Template defines ${y.join(", ")} \u2014 Stashpad always sets ${y.length===1?"this":"these"} on new notes, so the template value${y.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",I),c.addEventListener("input",I),c.addEventListener("blur",()=>{setTimeout(()=>{g.style.display="none"},150)}),c.addEventListener("change",()=>{u()}),f()};for(let n of e)s(n)}renderColorAliasRow(t,e,i,s,n){let o=t.createDiv({cls:"stashpad-color-alias-row"});s===0&&o.addClass("is-unused");let a=o.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=i,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let g=this.plugin.settings.customPalette??[];new Ee(this.app,i,g,async p=>{if((p??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(p&&p.toLowerCase()===i){n();return}let d=await this.plugin.recolorAllInFolder(e,i,p??null);if(d>0)new j.Notice(`Recolored ${d} note${d===1?"":"s"}.`);else if(s===0){let I=this.plugin.getColorAlias(e,i);I&&(await this.plugin.setColorAlias(e,i,""),p&&await this.plugin.setColorAlias(e,p,I))}n()},async p=>{let d=(this.plugin.settings.customPalette??[]).filter(I=>I.toLowerCase()!==p.toLowerCase());return this.plugin.settings.customPalette=d,await this.plugin.saveSettings(),d}).open()};let r=o.createDiv({cls:"stashpad-color-alias-meta"});r.createSpan({cls:"stashpad-color-alias-hex",text:i}),r.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let l=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,i)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,i,l.value),!l.value.trim()&&s===0&&n()};let c=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});l.value||(c.style.visibility="hidden"),c.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let i=t.createDiv({cls:"stashpad-folder-row"});i.createSpan({cls:"stashpad-folder-row-label",text:e});let s=i.createSpan({cls:"stashpad-folder-row-state"}),n=i.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let o=n.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),r=()=>{let c=a();n.toggleClass("is-right",c),n.setAttribute("aria-checked",String(c)),o.setText(c?"X":"\u2713"),s.setText(c?"Excluded":"Included"),s.toggleClass("is-excluded",c),n.title=c?"Excluded \u2014 notes here won't appear in cross-Stashpad search. Click to include.":"Included \u2014 notes here appear in cross-Stashpad search. Click to exclude."},l=async()=>{let c=new Set(this.plugin.settings.searchExcludedFolders??[]);c.has(e)?c.delete(e):c.add(e),this.plugin.settings.searchExcludedFolders=[...c].sort(),r(),await this.plugin.saveSettings()};n.onclick=()=>void l(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},r()}renderFolderPlacementList(t){let e=this.plugin.settings,i=[{key:"folderPanelPinned",label:"Pinned",action:"Unpin"},{key:"folderPanelDownranked",label:"Downranked",action:"Reset"},{key:"folderPanelHidden",label:"Hidden",action:"Unhide"}];if(!i.some(o=>(e[o.key]??[]).length>0)){t.createEl("p",{cls:"setting-item-description"}).setText("No folders customized yet. Right-click a folder in the Stashpad folder panel to pin, downrank, or hide it.");return}let n=async o=>{e.folderPanelPinned=(e.folderPanelPinned??[]).filter(a=>a!==o),e.folderPanelDownranked=(e.folderPanelDownranked??[]).filter(a=>a!==o),e.folderPanelHidden=(e.folderPanelHidden??[]).filter(a=>a!==o),await this.plugin.saveSettings(),this.update?.()};for(let o of i){let a=[...e[o.key]??[]].sort();if(a.length===0)continue;t.createEl("div",{cls:"stashpad-folder-placement-group",text:`${o.label} (${a.length})`});let r=t.createDiv({cls:"stashpad-folder-list"});for(let l of a){let c=r.createDiv({cls:"stashpad-folder-row"});c.createSpan({cls:"stashpad-folder-row-label",text:l});let g=c.createEl("button",{text:o.action});g.onclick=()=>void n(l)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=d=>{let I=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=I.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=hi(i()[d]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=d==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{Wn(u,async y=>{this.plugin.settings.bindings[e.id][d]=y,u.value=hi(y),f(),await this.plugin.saveSettings(),o(),w()})};let m=I.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][d]="",u.value="",f(),await this.plugin.saveSettings(),o(),w()};let E=I.createEl("button",{cls:"stashpad-binding-revert"});(0,j.setIcon)(E,"rotate-ccw");let w=()=>{let v=i()[d]!==C;E.toggleClass("is-hidden",!v),E.title=C?`Revert to default (${hi(C)})`:"Revert to default (no binding)"};return E.onclick=async()=>{this.plugin.settings.bindings[e.id][d]=C,u.value=hi(C),f(),await this.plugin.saveSettings(),o(),w()},w(),u};s=a("primary"),n=a("secondary");let r=t.controlEl.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let l=r.createDiv({cls:"stashpad-binding-pill-knob"}),c=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),g=c.createEl("input",{type:"checkbox"});g.title="Use both bindings simultaneously (overrides the L/R toggle)",c.createSpan({text:"Use both"}),g.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=g.checked,await this.plugin.saveSettings(),o()},o=()=>{let d=i(),I=!!(d.primary&&d.secondary);g.checked=!!d.useBoth,g.disabled=!I,c.toggleClass("is-disabled",!I);let u=!!d.useBoth&&I;r.toggleClass("is-disabled",!I||u),r.toggleClass("is-right",d.preferRight),r.setAttribute("aria-checked",String(d.preferRight)),r.setAttribute("aria-disabled",String(!I||u)),l.setText(d.preferRight?"R":"L"),r.title=I?u?'Overridden by "Use both"':d.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let p=async()=>{let d=i();!d.primary||!d.secondary||(this.plugin.settings.bindings[e.id].preferRight=!d.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void p(),r.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),p())},o()}};var Je=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=It().inheritObsidianExclusions,t=A?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!xn(i.path)&&!Mn(i.path)&&!(A&&Hn(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 No.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()}};yt();var is=class extends Dt.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 fe}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?.()===ct&&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?.()===ct&&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 I=t.createDiv({cls:"stashpad-detail-empty"});(0,Dt.setIcon)(I.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),I.createSpan({cls:"stashpad-detail-empty-text",text:"No Stashpad note selected. Cursor or click a note in a Stashpad list to inspect it here."});return}let n=s.file;this.displayedPath=n.path;let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=t.createDiv({cls:"stashpad-detail-scroll"}),r=a.createDiv({cls:"stashpad-detail-header"}),l=r.createDiv({cls:"stashpad-detail-titlerow"});l.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let c=l.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,Dt.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(s.folder,s.id)};let g=r.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&g.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let I=g.createSpan({cls:"stashpad-detail-meta-color"});I.style.background=o.color,I.title=o.color}if(o.completed===!0&&g.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let I=Date.parse(String(o.due)),u=Number.isNaN(I)?String(o.due):Wt(I,this.plugin.settings);g.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${u}`})}if(Array.isArray(o.tags))for(let I of o.tags.filter(u=>typeof u=="string"))g.createSpan({cls:"stashpad-detail-meta-tag",text:`#${I.replace(/^#/,"")}`});let p=a.createDiv({cls:"stashpad-detail-body"});try{let I=await this.app.vault.cachedRead(n),u=this.stripFrontmatter(I);await Dt.MarkdownRenderer.render(this.app,u,p,n.path,this)}catch(I){p.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${I.message}`})}this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s);let d=this.composerInputEl;if(e&&d&&(d.focus(),i!=null)){let I=Math.min(i,d.value.length);try{d.setSelectionRange(I,I)}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,Dt.setIcon)(n.createSpan({cls:"stashpad-detail-composer-send-icon"}),"plus"),n.createSpan({cls:"stashpad-detail-composer-send-text",text:"Add child note"}),n.title="Add child note (Enter)",n.onclick=()=>void this.submitComposer(e),this.composerAutocomplete=new Je(this.app,s),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==ct||typeof i.createNoteUnder!="function"){new Dt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new Dt.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?.()!==ct)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let r=a.createDiv({cls:"stashpad-detail-children-list"});for(let l of o)l.file&&this.renderDetailChildRow(r,s,n,e,l,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},r=typeof a.color=="string"?a.color:null,l=a.completed===!0,c=i.getChildren(n.id),g=c.length>0,p=`${s}|${n.id}`,d=this.expanded.has(p),I=t.createDiv({cls:"stashpad-detail-child-row"});l&&I.addClass("is-completed"),o>0&&(I.style.paddingLeft=`${o*16}px`),I.draggable=!0,I.dataset.id=n.id,I.addEventListener("dragstart",E=>{E.dataTransfer?.setData("text/plain",n.id),E.dataTransfer&&(E.dataTransfer.effectAllowed="move"),I.addClass("is-dragging")}),I.addEventListener("dragend",()=>I.removeClass("is-dragging")),I.addEventListener("dragover",E=>{E.preventDefault(),E.dataTransfer&&(E.dataTransfer.dropEffect="move");let w=I.getBoundingClientRect(),y=E.clientY-w.top<w.height/2;I.toggleClass("drop-before",y),I.toggleClass("drop-after",!y)}),I.addEventListener("dragleave",()=>{I.removeClass("drop-before"),I.removeClass("drop-after")}),I.addEventListener("drop",E=>{E.preventDefault(),I.removeClass("drop-before"),I.removeClass("drop-after");let w=E.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let y=I.getBoundingClientRect(),v=E.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,v?"before":"after")}),I.oncontextmenu=E=>{E.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(E,w)};let u=I.createSpan({cls:"stashpad-detail-child-toggle"});if(g&&(ye(u,c.length,d),u.onclick=E=>{E.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),De(a,"task")||a.task===!0||a.completed!==void 0){let E=I.createSpan({cls:"stashpad-detail-child-checkbox"});(0,Dt.setIcon)(E,l?"check-square":"square"),E.title=l?"Mark not done":"Mark done",E.addEventListener("mousedown",w=>w.stopPropagation()),E.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),E.onclick=w=>{w.preventDefault(),w.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let C=I.createSpan({cls:"stashpad-detail-child-icon"});(0,Dt.setIcon)(C,g?"folder-tree":"file-text"),r&&(C.style.color=r);let m=I.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},g&&d)for(let E of c)this.renderDetailChildRow(t,e,i,s,E,o+1)}renderFooterMeta(t,e,i,s){let n=t.createDiv({cls:"stashpad-detail-footer-meta"}),o=[];if(typeof i.author=="string"&&i.author&&o.push({label:"Author",value:this.stripWikiLink(i.author)}),Array.isArray(i.contributors)){let a=i.contributors.filter(r=>typeof r=="string").map(r=>this.stripWikiLink(r));a.length>0&&o.push({label:"Contributors",value:a.join(", ")})}if(typeof i.modified=="string"&&o.push({label:"Modified",value:this.formatTime(i.modified)}),typeof i.created=="string"&&o.push({label:"Created",value:this.formatTime(i.created)}),o.push({label:"Path",value:e.path}),o.push({label:"ID",value:s.id}),o.length===0){n.remove();return}for(let a of o){let r=n.createDiv({cls:"stashpad-detail-meta-line"});r.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),r.createSpan({cls:"stashpad-detail-meta-val",text:a.value})}}titleFor(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")}stripFrontmatter(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` ----`,3);return e<0?t:t.slice(e+4).replace(/^\n+/,"")}stripWikiLink(t){let e=t.match(/^\[\[(.+?)(?:\|(.+))?\]\]$/);return e?e[2]??(e[1].split("/").pop()??e[1]).replace(/\.md$/,""):t}formatTime(t){let e=Date.parse(t);return Number.isFinite(e)?Wt(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==M&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new Dt.Notice(`Couldn't open: ${i.message}`)}}};async function ss(h){let A=h.workspace.getLeavesOfType(fe);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getRightLeaf(!1);if(!t){new Dt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:fe,active:!0}),h.workspace.revealLeaf(t)}var P=require("obsidian");yt();var de=require("obsidian");yt();function nr(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof de.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof de.TFile?n.extension==="md"&&e.push(n):n instanceof de.TFolder&&(Ze.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(M,{id:M,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(M,{id:M,parent:null,children:[],file:null,created:""});let s=t?nr(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=o?.id;if(!a){let l=e.get(n.path),c=l?i.get(l):void 0,g=this.synthetic.get(n.path),p=c??g;p&&(this.nodes.set(p.id,{...p,children:[],file:n}),this.byPath.set(n.path,p.id));continue}if(this.synthetic.delete(n.path),a===M){let l=this.nodes.get(M);l.file=n,l.created=o?.created??"",this.byPath.set(n.path,M);continue}let r=o?.parent??null;r===a&&(r=null),this.nodes.set(a,{id:a,parent:r??M,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===M)continue;let o=n.parent??M;(this.nodes.get(o)??this.nodes.get(M)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let r=this.nodes.get(o),l=this.nodes.get(a);return(r.created||"").localeCompare(l.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((r,l)=>a.set(r,l)),n.children.sort((r,l)=>{let c=a.has(r)?a.get(r):1/0,g=a.has(l)?a.get(l):1/0;return c===g?0:c-g})}}this.emit()}insertSynthetic(A){if(!A.file)return;let t=A.file.path;this.synthetic.set(t,A),this.nodes.set(A.id,A),this.byPath.set(t,A.id);let e=A.parent??M,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(M)}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!==M&&!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===M||!t.file||(A[t.id]={parent:t.parent===M?null:t.parent,path:t.file.path});return A}hookMetadataCache(A){let t=r=>{let l=this.currentFolder;return l?typeof r!="string"?!1:r===l||r.startsWith(l+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),A())},16))},s=r=>{r instanceof de.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof de.TFile&&t(r.path)&&r.extension==="md"&&this.applyChange(r)&&i()},o=r=>{let l=r?.path;typeof l=="string"&&t(l)&&this.applyDelete(l)&&i()},a=(r,l)=>{if(!(r instanceof de.TFile))return;let c=typeof l=="string"?l:null;!t(r.path)&&!t(c)||this.applyRename(r,c??"")&&i()};return this.app.metadataCache.on("changed",s),this.app.vault.on("create",n),this.app.vault.on("delete",o),this.app.vault.on("rename",a),()=>{this.app.metadataCache.off("changed",s),this.app.vault.off("create",n),this.app.vault.off("delete",o),this.app.vault.off("rename",a),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(A){if(be(A.path))return this.byPath.has(A.path)?this.applyDelete(A.path):!1;let t=this.app.metadataCache.getFileCache(A)?.frontmatter,e=t?.id,i=this.byPath.get(A.path);if(!e){if(i){let l=this.nodes.get(i);if(l&&l.file!==A)return l.file=A,!0}return!1}if(this.synthetic.delete(A.path),e===M){let l=this.nodes.get(M),c=t?.created??"",g=!1;return l.file!==A&&(l.file=A,g=!0),l.created!==c&&(l.created=c,g=!0),this.byPath.get(A.path)!==M&&(this.byPath.set(A.path,M),g=!0),g}let s=t?.parent??M,n=t?.created??"";if(!(s===M||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let l={id:e,parent:s,children:[],file:A,created:n};return this.nodes.set(e,l),this.byPath.set(A.path,e),this.attachToParent(l),this.resortChildrenOf(s),!0}let r=!1;if(a.file!==A&&(a.file=A,r=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??M),r=!0),a.parent!==s){let l=a.parent??M;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(l),this.resortChildrenOf(s),r=!0}return r}applyDelete(A){let t=this.byPath.get(A);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(A),this.synthetic.delete(A),!0;this.detachFromParent(e);let i=this.nodes.get(M);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=M,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(M),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(be(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??M);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??M);t||(t=this.nodes.get(M)),t.children.includes(A.id)||t.children.push(A.id)}resortChildrenOf(A){let t=this.nodes.get(A);if(t&&(t.children.sort((e,i)=>{let s=this.nodes.get(e),n=this.nodes.get(i);return(s.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(A);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,a=i.has(n)?i.get(n):1/0;return o===a?0:o-a})}}}};var fn=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(` -`)}},bt=new fn;var xo=".stashpad-order.json",qe=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}/${xo}`,e=this.app.vault.adapter,i={};try{if(await e.exists(t)){let s=await e.read(t),n=JSON.parse(s);if(n&&typeof n=="object"&&!Array.isArray(n))for(let[o,a]of Object.entries(n))Array.isArray(a)&&a.every(r=>typeof r=="string")&&(i[o]=a)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(A,i),i}async save(A){this.scheduleWrite(A)}async flush(A){let t=this.pendingTimers.get(A);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(A)),await this.writeNow(A)}scheduleWrite(A){let t=this.pendingTimers.get(A);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(A),this.writeNow(A)},150);this.pendingTimers.set(A,e)}async writeNow(A){let e=(this.writeInFlight.get(A)??Promise.resolve()).then(()=>this.doWrite(A));this.writeInFlight.set(A,e);try{await e}finally{this.writeInFlight.get(A)===e&&this.writeInFlight.delete(A)}}async doWrite(A){let t=this.cache.get(A)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(A,e);let i=`${A}/${xo}`,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 Ei={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"},Cn=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],or=new Set(Cn),Mo=".stashpad-sort.json",os=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}/${Mo}`,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"&&or.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}/${Mo}`,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)}};yt();var he="parentLink",Oe="children";var As=class As{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||!It().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(),As.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[he]=="string"?n[he]:null,a=n?.[Oe],r=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];if((o??null)!==(i??null)||r.length!==s.length)return!0;for(let l=0;l<r.length;l++)if(r[l]!==s[l])return!0;return!1}async syncOne(A){let e=this.getTree().get(A);if(!e||!e.file||!this.wouldWrite(A))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await bt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[he]=i:delete n[he],s.length>0?n[Oe]=s:delete n[Oe]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(A){if(A.id===M)return null;let t=this.getTree();if(!A.parent||A.parent===M){let i=t.getRoot();return i&&i.id!==A.id&&i.file?as(i.file.path):null}let e=t.get(A.parent);return e?.file?as(e.file.path):null}computeChildrenLinks(A){return this.getTree().getChildren(A.id).filter(e=>!!e.file).map(e=>as(e.file.path))}};As.PACING_MS=100;var rs=As;async function Ke(h,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let l of h.vault.getMarkdownFiles()){if(l.path!==A&&!l.path.startsWith(t))continue;let c=h.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id:null;if(!g)continue;let p=typeof c?.parent=="string"?c.parent:M;e.set(g,{file:l,id:g,parent:p});let d=i.get(p)??[];d.push(g),i.set(p,d)}let s=l=>as(l.file.path),n=l=>{if(l.id===M)return null;if(l.parent===M||!l.parent){let g=e.get(M);return g?s(g):null}let c=e.get(l.parent);return c?s(c):null},o=l=>{let c=i.get(l.id)??[],g=[];for(let p of c){let d=e.get(p);d&&g.push(s(d))}return g},a=0,r=0;for(let l of e.values()){a+=1;let c=n(l),g=o(l),p=h.metadataCache.getFileCache(l.file)?.frontmatter,d=p&&typeof p[he]=="string"?p[he]:null,I=p?.[Oe],u=Array.isArray(I)?I.filter(m=>typeof m=="string"):[],f=(d??null)===(c??null),C=u.length===g.length&&u.every((m,E)=>m===g[E]);if(!(f&&C))try{await h.fileManager.processFrontMatter(l.file,m=>{c?m[he]=c:delete m[he],g.length>0?m[Oe]=g:delete m[Oe]}),r+=1,await new Promise(m=>setTimeout(m,50))}catch(m){console.warn("[Stashpad] rebootstrap fm sync failed",l.file.path,m)}}return{checked:a,written:r}}function as(h){return`[[${h.replace(/\.md$/i,"")}]]`}Kt();Me();var ls=class{constructor(A,t){this.tree=A;this.log=t}async sweep(A){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!A)return!0;let o=A.replace(/\/+$/,"");return n===o||n.startsWith(o+"/")};for(let[n,o]of Object.entries(e)){let a=t[n];a?a.parent!==o.parent?await this.log.append({type:"parent_change",id:n,payload:{from:a.parent,to:o.parent}}):a.path!==o.path&&await this.log.append({type:"rename",id:n,payload:{from:a.path,to:o.path}}):await this.log.append({type:"create",id:n,payload:{path:o.path,parent:o.parent}})}for(let[n,o]of Object.entries(t))!e[n]&&i(o.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:o.path}});let s={};for(let[n,o]of Object.entries(t))i(o.path)||(s[n]=o);for(let[n,o]of Object.entries(e))s[n]=o;await this.log.writeState(s)}};var vt=require("obsidian");yt();Ts();var St=vt.moment;function mn(h){let A=h.trim().toLowerCase();if(!A)return null;let t=Date.now(),e=I=>St(I).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=A,a=i.exec(A);if(a&&(a[3]||a[2])){let I=parseInt(a[1],10),u=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&I<12&&(I+=12),f==="am"&&I===12&&(I=0),I>=0&&I<24&&u>=0&&u<60&&(s=(I*3600+u*60)*1e3,n=!0,o=A.replace(a[0]," ").replace(/\s+/g," ").trim())}let r=I=>n?I+s:I;if(o===""||o==="today")return r(e(t));if(o==="yesterday")return r(e(t)-864e5);if(o==="tomorrow")return r(e(t)+864e5);let l=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],c=["sun","mon","tue","wed","thu","fri","sat"],g=l.indexOf(o)>=0?l.indexOf(o):c.indexOf(o);if(g>=0){let I=St().startOf("day"),f=(I.day()-g+7)%7;return r(I.subtract(f,"days").valueOf())}let p=/^(\d+)\s*([dwmy])$/.exec(o);if(p){let I=parseInt(p[1],10),u={d:"days",w:"weeks",m:"months",y:"years"}[p[2]];return r(St().subtract(I,u).startOf("day").valueOf())}let d=St(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return d.isValid()?r(d.startOf("day").valueOf()):null}function Ho(h){let A={text:[],filters:{}},t=(h||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let a=mn(o);a!=null&&(A.filters.before=a)}else if(n==="after"){let a=mn(o);a!=null&&(A.filters.after=a)}else if(n==="on"){let a=mn(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))A.filters.on={start:a-6e4,end:a+6e4};else{let l=St(a).startOf("day").valueOf();A.filters.on={start:l,end:l+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&A.text.push(n.toLowerCase());return A}var te=class h extends vt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==M?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===M&&this.notes.push({node:a,title:i,body:""});for(let r of this.tree.getChildren(n))s(r.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(M))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(a=>{o.body=this.stripFm(a)})}}createdMsFor(t){if(t.node?.created){let e=Date.parse(t.node.created);if(!Number.isNaN(e))return e}return t.cross?.file?.stat?.ctime!=null?t.cross.file.stat.ctime:null}stripFm(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` ----`,3);return e===-1?t:t.slice(e+4).replace(/^\r?\n/,"")}getSuggestions(t){let e=t.trim().toLowerCase(),i=Ho(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=C=>{if(!s.length)return!0;for(let m of s)if(!C.includes(m))return!1;return!0},o=null,a=null;if(i.filters.in){let C=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,a=new Map;let m=y=>C.every(v=>y.toLowerCase().includes(v)),E=y=>{if(!o.has(y)){o.add(y);for(let v of this.tree.getChildren(y))E(v.id)}};for(let y of this.notes)!y.node||y.cross||m(y.title)&&E(y.node.id);let w=new Map;for(let y of this.notes){if(!y.cross)continue;let v=w.get(y.cross.folder)??[];v.push(y),w.set(y.cross.folder,v)}for(let[y,v]of w){let S=new Map;for(let x of v){let Q=x.cross?.parentId??null;if(!Q)continue;let D=S.get(Q)??[];D.push(x.cross.id),S.set(Q,D)}let U=new Set;a.set(y,U);let F=x=>{if(!U.has(x)){U.add(x);for(let Q of S.get(x)??[])F(Q)}};for(let x of v)m(x.title)&&F(x.cross.id)}}let r=C=>{let m=i.filters;if(o||a)if(C.cross){let E=a?.get(C.cross.folder);if(!E||!E.has(C.cross.id))return!1}else if(C.node){if(!o||!o.has(C.node.id))return!1}else return!1;if(m.before||m.after||m.on){let E=this.createdMsFor(C);if(E==null||m.before!=null&&E>=m.before||m.after!=null&&E<=m.after||m.on&&(E<m.on.start||E>=m.on.end))return!1}return!0},l=C=>n(C.toLowerCase()),c=this.notes.filter(C=>!C.cross),g=this.notes.filter(C=>C.cross),p=(C,m)=>({id:C.cross?`cross:${C.cross.folder}:${C.cross.id}`:C.node.id,label:C.title,node:C.node,kind:"note",bodyPreview:this.previewFromBody(C.body,m),matchLine:m,crossFolder:C.cross?.folder,crossFile:C.cross?.file,crossId:C.cross?.id}),d=C=>{let m=[];for(let E of C)if(r(E))if(this.opts.mode==="search"){if(!e){m.push(p(E,-1));continue}let w=n(E.title.toLowerCase()),y=E.body.split(/\r?\n/),v=[];for(let U=0;U<y.length;U++)l(y[U])&&v.push(U);let S=v.length>0||n(E.body.toLowerCase());if(!w&&!S)continue;if(v.length===0)m.push(p(E,-1));else{let U=[],F=-100;for(let Q of v)Q-F>5&&U.push(Q),F=Q;let x=5;for(let Q of U.slice(0,x))m.push(p(E,Q))}}else{if(e&&!n(E.title.toLowerCase())&&!n(E.body.toLowerCase()))continue;m.push(p(E,-1))}return m},I=d(c),u=[...I];if(this.opts.mode==="search"?e?!0:I.length<10:!!e){let C=d(g);this.opts.mode==="search"&&!e&&(u.length=Math.min(u.length,50)),u.push(...C)}if(this.opts.folderResults){let C=this.opts.folderResults(),m={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};C.length>0&&(e?C.some(E=>{let w=E.split("/").pop()??E;return n(`${E.toLowerCase()} ${w.toLowerCase()}`)})&&u.push(m):u.unshift(m))}if(this.opts.allowCreate&&e&&!u.some(C=>C.label.trim().toLowerCase()===e)&&u.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let C=E=>E.kind==="note"&&(E.id===M||E.crossId===M)&&n(E.label.toLowerCase()),m=u.filter(C);if(m.length>0){let E=u.filter(w=>!C(w));u.splice(0,u.length,...m,...E)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&u.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),u}loadExcludedNotes(){if(this.includeExcluded||!this.opts.excludedFolderNotes)return;this.includeExcluded=!0;for(let e of this.opts.excludedFolderNotes())this.notes.push({node:null,title:e.title,body:e.body,cross:e});for(let e of this.notes)!e.cross||e.body||!e.cross.file||this.app.vault.cachedRead(e.cross.file).then(i=>{e.body=this.stripFm(i)});let t=this.inputEl;t&&(t.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(()=>t.dispatchEvent(new Event("input",{bubbles:!0})),250))}previewFromBody(t,e){let i=t.split(/\r?\n/);if(e<0)return i.filter(a=>a.trim().length>0).slice(0,3).join(` +`)),await t()}))},["slug","stopwords","filename","title"])),i.push(this.sectionDef("Cross-Stashpad search scope","Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations. Also: create a new Stashpad.",s=>{let n=this.plugin.discoverStashpadFolders();if(new j.Setting(s).setName("Cross-Stashpad search scope").setDesc("Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations \u2014 their notes just don't appear in search results from elsewhere."),n.length===0)s.createEl("p",{cls:"setting-item-description"}).setText('No Stashpads found in this vault yet. A Stashpad is just a folder that contains a Stashpad-shaped note (frontmatter has both `id` and `parent`). Easiest way: open Stashpad (ribbon icon or command "Reveal or open Stashpad") \u2014 it auto-creates the default folder on first use. Or create one below.');else{let a=s.createDiv({cls:"stashpad-folder-list"});for(let r of n)this.renderFolderScopeRow(a,r)}let o=null;new j.Setting(s).setName("Create a new Stashpad").setDesc("Type a vault-relative folder path. The folder is created (with intermediates) and seeded with a Home note so Stashpad recognizes it.").addText(a=>{a.setPlaceholder("my-stashpad"),o=a.inputEl}).addButton(a=>a.setButtonText("Create").setCta().onClick(async()=>{let r=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!r){new j.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(r),new j.Notice(`Created Stashpad "${r}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(r,2e3),this.update?.()}catch(l){new j.Notice(`Couldn't create: ${l.message}`)}}))},["search","scope","exclude","include","create","new","stashpad","folder"])),i.push(this.sectionDef("Folder panel placement","Pin, downrank, or hide folders in the Stashpad folder panel. Restore hidden folders here or from the panel's \u201CHidden\u201D section.",s=>{new j.Setting(s).setName("Folder panel placement").setDesc("Folders you've pinned, downranked, or hidden in the Stashpad folder panel. Pin/downrank from a folder's right-click menu in the panel; restore here or from the panel's \u201CHidden\u201D section."),this.renderFolderPlacementList(s)},["folder","panel","pin","pinned","downrank","hide","hidden","restore","placement"])),i.push(e("Autofocus composer after sending","After Enter-submitting a note, return focus to the composer so you can keep typing. Off keeps focus in the list \u2014 useful if you want arrow keys to work without an extra click.",()=>this.plugin.settings.autofocusComposerAfterSend,s=>{this.plugin.settings.autofocusComposerAfterSend=s},["composer","focus","send"])),i.push(e("Open in new window \u2014 duplicate tab","ON: the new-window button (in the time-filter row) duplicates the current Stashpad tab \u2014 original stays open in the main window. OFF: the leaf is MOVED to the new window, closing the original tab.",()=>this.plugin.settings.popoutDuplicates,s=>{this.plugin.settings.popoutDuplicates=s},["popout","window","duplicate"])),i.push(e("Search results open in a new tab","When you pick a result in the Search modal, open it in a new Stashpad tab instead of navigating the current tab. Applies to same-folder and cross-Stashpad results alike. On by default.",()=>this.plugin.settings.searchOpensInNewTab,s=>{this.plugin.settings.searchOpensInNewTab=s},["search","new tab","results","open"])),i.push(e("Prefix timestamps when copying","Include each note's timestamp before its body when copying with C or Y.",()=>this.plugin.settings.prefixTimestampsOnCopy,s=>{this.plugin.settings.prefixTimestampsOnCopy=s},["copy","timestamp","prefix"])),i}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"),i.createEl("p",{cls:"setting-item-description"}).setText("\u26A0\uFE0F One password protects everything you encrypt in this vault, and it's stored ONLY on this device \u2014 if you forget it, anything encrypted with it is gone for good. While encrypting, don't run a sync/cloud service over the vault and avoid working in Stashpad mid-operation \u2014 either can corrupt files. (File-encryption actions aren't enabled in this version yet \u2014 this screen sets up the key.)");let s=()=>t.argonProbe();if(!t.isConfigured()){new j.Setting(i).setName("Encryption").setDesc("Not set up yet.").addButton(a=>a.setButtonText("Set up password\u2026").setCta().onClick(()=>{new Xt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:s,onSubmit:async({next:r,remember:l})=>{if(!r)return"Enter a password.";try{await t.setup(r,l)}catch(c){return c.message}return new j.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}let n=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",o=t.isRemembered()?" \xB7 remembered on this device":"";new j.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${n?` \xB7 ${n}`:""}${o}`),t.isUnlocked()?new j.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(a=>a.setButtonText("Lock now").onClick(()=>{t.lock(),new j.Notice("Encryption locked."),this.update?.()})):new j.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(a=>a.setButtonText("Unlock\u2026").setCta().onClick(()=>{new Xt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:r,remember:l})=>await t.unlock(r,l)?(new j.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),t.keychainAvailable()&&t.isRemembered()&&new j.Setting(i).setName("Forget remembered password").setDesc("Remove the saved password from this device's keychain (you'll re-type it next session).").addButton(a=>a.setButtonText("Forget").onClick(async()=>{await t.forgetKeychain(),new j.Notice("Removed from keychain."),this.update?.()})),new j.Setting(i).setName("Change password").setDesc("Re-wraps the same key under a new password \u2014 does not re-encrypt your files.").addButton(a=>a.setButtonText("Change\u2026").onClick(()=>{new Xt(this.app,{mode:"change",offerKeychain:!0,kdfProbe:s,onSubmit:async({current:r,next:l,remember:c})=>await t.changePassword(r,l,c)?(new j.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),new j.Setting(i).setName("Remove encryption").setDesc("Erases the key from this vault. Refused while any locked notes exist \u2014 decrypt everything first (locked notes have NO plaintext copy; losing the key loses them forever).").addButton(a=>{a.setButtonText("Remove\u2026").onClick(async()=>{if(await pn(this.app)){new j.Notice(`Can't remove encryption: locked/encrypted-deleted notes still exist and would be lost forever. Run "Decrypt (unlock) ALL locked notes in the vault" and empty the encrypted trash first.`,1e4);return}new oi(this.app,{title:"Remove encryption?",body:"This erases the encryption key for this vault. Nothing is currently encrypted (locked notes are checked), so no content is lost \u2014 but you'll need to set a new password to encrypt later, and anything you had exported encrypted with this key stays locked to its passphrase.",phrase:"REMOVE ENCRYPTION",confirmText:"Remove encryption",requirePassword:r=>t.verifyPassword(r),onConfirm:async()=>{if(await pn(this.app)){new j.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}await t.clear(),new j.Notice("Encryption removed."),this.update?.()}}).open()}),a.setWarning?.(!0)})},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{this.plugin.settings.encryptTrash=n,await this.plugin.saveSettings()})),["trash","delete","encrypt"])),e.push(this.renderDef("Encrypt trash filenames","Hide the filename + origin folder of encrypted-trashed items (opaque names on disk; shown under \u201CHidden\u201D in the trash tab). Default OFF so you can still tell what to restore when working outside the app.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFilenames).onChange(async n=>{this.plugin.settings.encryptTrashFilenames=n,await this.plugin.saveSettings()})),["trash","filename","encrypt"])),e.push(this.renderDef("Follow Obsidian's trash setting instead","OFF (recommended): encrypted-deleted notes go to Stashpad's own \u201C_deleted/\u201D store \u2014 the only trash location Stashpad fully controls, so it can encrypt, list, and restore them. ON: deletes follow Obsidian's \u201CDeleted files\u201D setting instead (system/OS trash or permanent). \u26A0\uFE0F Stashpad CANNOT encrypt or recover notes that go to the system trash \u2014 so the encrypted trash + recoverable trash view won't apply. Only turn this on if you specifically want Obsidian's native trash behavior.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFollowObsidian??!1).onChange(async n=>{this.plugin.settings.encryptTrashFollowObsidian=n||void 0,await this.plugin.saveSettings()})),["trash","obsidian","system","delete","encrypt"])),e.push(this.renderDef("Auto-lock after idle minutes","Forget the password from memory after this many idle minutes (0 = never). Re-prompts on the next encryption action.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.encryptionIdleLockMinutes??0)).onChange(async n=>{let o=Math.max(0,Math.floor(Number(n)||0));this.plugin.settings.encryptionIdleLockMinutes=o,await this.plugin.saveSettings()})),["auto-lock","idle","timeout","lock"])),e.push(this.renderDef("Hide titles of locked notes","Show a generic label on \u{1F512} locked placeholders instead of the note's title, so a glance at the vault doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.renderDef("Default archive folder",`Where the "Move selection to archive" command sends notes (they're auto-encrypted on arrival). Leaving this blank is fine \u2014 the command will just show you a list of your archive folders to pick from each time (or use the only one if you have a single archive). Mark a folder as an archive via the folder panel \u2192 right-click \u2192 "Mark as archive".`,i=>{let s=this.plugin.settings.archiveFolders??[];i.addDropdown(n=>{n.addOption("",s.length?"\u2014 pick from list each time \u2014":"\u2014 no archive folders yet \u2014");for(let a of s)n.addOption(a,a);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async a=>{this.plugin.settings.defaultArchiveFolder=a||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e}hotkeyItems(){let t={name:"Hotkeys",desc:"Each command has up to two slots. Click a slot and press a key (or chord) to bind it; press Backspace (delete on Mac) to cancel without binding; or click \u2715 to clear an existing binding. A \u21BA icon appears on any slot that differs from its shipped default \u2014 click it to revert that slot. When both slots are set, the pill on the right decides which one is active.",searchable:!1},e=qe.map(i=>({name:i.label,desc:i.desc,aliases:["hotkey","shortcut","keybind","binding","key"],render:s=>this.renderBindingRow(s,i)}));return[t,...e]}renderJdIndexSection(t){let e=t.createEl("h3",{text:"JD Index Builder"});e.id="stashpad-jd-index-section";let i=t.createEl("p",{cls:"setting-item-description"});i.innerHTML="Builds a Johnny-Decimal-style index inside a designated Stashpad folder. Two commands:<br/><strong>Preview</strong> overwrites the designated folder’s HOME note body with the would-be hierarchy + everything that didn’t match. Frontmatter is preserved; everything below it is replaced.<br/><strong>Build</strong> creates an actual hierarchy of Stashpad notes (one per prefix), with child\u2192parent relationships matching the dotted segments.<br/>Matches strict prefixes only: all-digits (<code>10 Life</code>) or alphanumeric-with-dots (<code>1.2 Family</code>, <code>animal.duck.yellow Eggs</code>). Mixed schemes sort numbers first, then alphabetically.";let s=this.plugin.discoverStashpadFolders();new j.Setting(t).setName("Scope").setDesc("Scan the whole vault, or restrict to a single folder + its descendants.").addDropdown(r=>{r.addOption("vault","Entire vault"),r.addOption("folder","Single folder"),r.setValue(this.plugin.settings.jdIndexScope??"vault"),r.onChange(async l=>{this.plugin.settings.jdIndexScope=l==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new j.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(r=>{new Pe(this.app,r.inputEl),r.setPlaceholder("Path/To/Folder"),r.setValue(this.plugin.settings.jdIndexScopeFolder??""),r.onChange(async l=>{this.plugin.settings.jdIndexScopeFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new j.Setting(t).setName("Include Stashpad folders in scan").setDesc("By default, notes inside any known Stashpad folder are excluded \u2014 the index destination shouldn't index itself, and other Stashpad folders are usually already organized. Toggle on if you want them included anyway.").addToggle(r=>{r.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),r.onChange(async l=>{this.plugin.settings.jdIndexIncludeStashpadFolders=l,await this.plugin.saveSettings(),this.display()})}),new j.Setting(t).setName("Designated Stashpad folder for Index").setDesc("Required. Must be a Stashpad folder. The index hierarchy is built here. New notes are created; nothing is deleted.").addText(r=>{new Pe(this.app,r.inputEl),r.setPlaceholder(s[0]??"(pick a Stashpad folder)"),r.setValue(this.plugin.settings.jdIndexStashpadFolder??""),r.onChange(async l=>{this.plugin.settings.jdIndexStashpadFolder=(l||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new j.Setting(t).setName("Sort").setDesc("Order of entries within the same depth. Natural: numbers first then alphabetical (recommended). Created: by source file's creation time \u2014 handy when prefixes are word-only and don't carry ordering.").addDropdown(r=>{r.addOption("natural","Natural (numeric \u2192 alphabetical)"),r.addOption("created","By creation time"),r.setValue(this.plugin.settings.jdIndexSort??"natural"),r.onChange(async l=>{this.plugin.settings.jdIndexSort=l==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=Ue(this.app,this.plugin,this.plugin.settings),o=t.createEl("p",{cls:"setting-item-description"}),a=n.skippedStashpadNotes.length>0?` (${n.skippedStashpadNotes.length} Stashpad-folder note${n.skippedStashpadNotes.length===1?"":"s"} excluded by default)`:"";o.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${a}.`),new j.Setting(t).setName("Actions").setDesc("Preview aggressively overwrites the designated folder's HOME note body (frontmatter preserved). Build creates Stashpad notes (existing notes with the same jdPrefix are updated, not duplicated).").addButton(r=>{r.setButtonText("Preview"),r.setTooltip("Overwrites the designated Stashpad folder's HOME note body with the preview."),r.onClick(async()=>{try{let l=await Ri(this.app,this.plugin,this.plugin.settings);if(l.error==="no-dest"){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(l.error==="no-home"){new j.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}Gi(this.app,l),this.display()}catch(l){console.error("[stashpad] preview failed",l),new j.Notice(`Preview failed: ${l?.message??l}`,8e3)}})}).addButton(r=>{r.setButtonText("Build Stashpad notes"),r.setCta(),r.setTooltip("Create the Stashpad-note hierarchy. Existing notes with matching jdPrefix are updated."),r.onClick(()=>{if(!(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new hi(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let g=await Os(this.app,this.plugin,this.plugin.settings);if(g.error==="no-dest"){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(g.error==="dest-not-stashpad"){new j.Notice(`"${g.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder (or create one first).`,7e3);return}this.plugin.settings.jdIndexHasBuilt=!0,await this.plugin.saveSettings(),new j.Notice(`Built: ${g.created} created, ${g.updated} updated, ${g.skipped} skipped \u2192 ${g.destFolder}`,6e3),this.display()}catch(g){console.error("[stashpad] build failed",g),new j.Notice(`Build failed: ${g?.message??g}`,8e3)}}).open()})}).addButton(r=>{r.setButtonText(`Reveal in ${ir()}`),r.setTooltip("Open the designated Stashpad folder in your OS file browser."),r.onClick(async()=>{let l=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!l){new j.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(l)){new j.Notice(`Folder "${l}" doesn't exist yet.`,5e3);return}try{let g=this.app.vault.adapter.basePath;if(g){let{shell:p}=window.require?.("electron")??{},d=`${g}/${l}`;p?.openPath?.(d)}else new j.Notice("Reveal in file system not supported on this platform.",4e3)}catch(g){new j.Notice(`Couldn't open folder: ${g?.message??g}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new j.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=jt()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new j.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(o=>{for(let a of e)o.addOption(a,a);o.setValue(i),o.onChange(a=>{i=a,n()})}),t.createEl("p",{cls:"setting-item-description",text:"Give each per-note color a friendly name. Filters and pickers display the alias instead of the hex code; the underlying color stays the same. The same hex in two Stashpads can have different aliases."});let s=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{s.empty();let o=this.plugin.collectColorsInFolder(i),a=new Map(o.map(g=>[g.hex,g.count])),r=this.plugin.settings.colorAliases?.[i.replace(/\/+$/,"")]??{},l=new Set([...a.keys(),...Object.keys(r)]);if(l.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...l].map(g=>({hex:g,count:a.get(g)??0}));c.sort((g,p)=>p.count-g.count||g.hex.localeCompare(p.hex));for(let g of c)this.renderColorAliasRow(s,i,g.hex,g.count,n)};n()}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=mt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["author","name","identity","stamp"])),t.push(this.renderDef("Author id (auto-assigned)","Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. To reset it, clear and retype your author name.",i=>i.addText(s=>s.setValue(this.plugin.settings.authorId).setDisabled(!0)),["author","id"])),t.push(this.renderDef("Title / role",'Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorRole).onChange(async n=>{this.plugin.settings.authorRole=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["role","title","job"])),t.push(this.renderDef("Department / team",'Optional. Shown on your author page (e.g. "Engineering", "Growth").',i=>i.addText(s=>s.setValue(this.plugin.settings.authorDepartment).onChange(async n=>{this.plugin.settings.authorDepartment=n.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})),["department","team"]));let e=(i,s,n,o)=>this.renderDef(i,"",a=>a.addToggle(r=>r.setValue(s()).onChange(async l=>{n(l),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=r=>{r.preventDefault(),this.plugin.activateViewForFolder(s.folder)};let a=[];s.authored>0&&a.push(`authored ${s.authored}`),s.contributed>0&&a.push(`contributed to ${s.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}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"])]}renderAuthorshipSection(t){t.createEl("h3",{text:"Authorship"}),t.createEl("p",{cls:"setting-item-description",text:"Stamp each new note with your name. If the vault is later shared (e.g. a coworker opens it with --config pointing at their own settings folder), every modification automatically tracks contributors on top of the original author. Names link to per-user pages in <stashpad>/_authors/."}),new j.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=mt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new j.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 j.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 j.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 j.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 j.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 j.Setting(t).setName("Show last edit time in note footer").addToggle(i=>i.setValue(this.plugin.settings.showLastEdit).onChange(async s=>{this.plugin.settings.showLastEdit=s,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let i=t.createDiv({cls:"stashpad-authored-folders-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-authored-folder-row"}),o=n.createEl("a",{cls:"stashpad-authored-folder-link",text:s.folder});o.onclick=r=>{r.preventDefault(),this.plugin.activateViewForFolder(s.folder)};let a=[];s.authored>0&&a.push(`authored ${s.authored}`),s.contributed>0&&a.push(`contributed to ${s.contributed}`),n.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}this.renderKnownAuthorsSection(t)}renderKnownAuthorsSection(t){t.createEl("h4",{text:"Known authors (registry)"}),t.createEl("div",{cls:"setting-item-description",text:"A rebuildable cache of every author Stashpad has seen, with rename history. Not a source of truth \u2014 the author id stored in each note is authoritative. Use it to recover deleted author pages or audit name changes."}),new j.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 j.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new j.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 j.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new j.Notice(`Restore failed: ${n.message}`)}s.setDisabled(!1).setButtonText("Restore missing pages")}));let e=this.plugin.authorRegistry.all();if(e.length===0){t.createEl("div",{cls:"setting-item-description",text:"No authors recorded yet. Rebuild to scan the vault."});return}let i=t.createDiv({cls:"stashpad-known-authors-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-known-author-row"}),o=n.createDiv({cls:"stashpad-known-author-main"});o.createSpan({cls:"stashpad-known-author-name",text:s.name||"(unnamed)"});let a=[];if(s.role&&a.push(s.role),s.department&&a.push(s.department),a.push(`id ${s.id}`),o.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${a.join(" \xB7 ")}`}),s.renames&&s.renames.length>0){let r=n.createDiv({cls:"stashpad-known-author-history"}),l=s.renames.map(c=>`${c.from} \u2192 ${c.to}`).join(", ");r.setText(`Renamed: ${l}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new j.Setting(t).setName("Note templates per Stashpad").setDesc("Pick a markdown file to use as the default template for new notes in each Stashpad. The template's frontmatter becomes the new note's frontmatter (id/parent/created/attachments are always set by Stashpad). If the body contains {{body}}, that's where the user-typed body goes; otherwise the user body is followed by the template body.");let i=t.createDiv({cls:"stashpad-note-templates-list"}),s=n=>{let o=n.replace(/\/+$/,""),a=i.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let l=a.createDiv({cls:"stashpad-note-template-input-wrap"}),c=l.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});c.value=(this.plugin.settings.noteTemplates??{})[o]??"";let g=l.createDiv({cls:"stashpad-note-template-suggest"});g.style.display="none";let p=a.createDiv({cls:"stashpad-note-template-warn"});p.style.display="none";let d=()=>this.app.vault.getMarkdownFiles().map(C=>C.path).filter(C=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(C)).sort(),I=()=>{g.empty();let C=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),m=w=>{let y=w.toLowerCase();return C.every(v=>y.includes(v))},E=d().filter(w=>m(w)).slice(0,12);if(E.length===0){g.style.display="none";return}g.style.display="";for(let w of E)g.createDiv({cls:"stashpad-note-template-suggest-item",text:w}).addEventListener("mousedown",async v=>{v.preventDefault(),c.value=w,await u(),g.style.display="none"})},u=async()=>{let C=c.value.trim(),m={...this.plugin.settings.noteTemplates??{}};C?m[o]=C:delete m[o],this.plugin.settings.noteTemplates=m,await this.plugin.saveSettings(),f()},f=()=>{p.empty(),p.style.display="none";let C=c.value.trim();if(!C)return;let m=this.app.vault.getAbstractFileByPath(C);if(!m||m.extension!=="md"){p.style.display="",p.setText(`\u26A0 "${C}" is not a markdown file in this vault.`);return}let E=this.app.metadataCache.getFileCache(m)?.frontmatter??{},y=se.filter(v=>{let S=E[v];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.length===0)});y.length!==0&&(p.style.display="",p.setText(`\u26A0 Template defines ${y.join(", ")} \u2014 Stashpad always sets ${y.length===1?"this":"these"} on new notes, so the template value${y.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",I),c.addEventListener("input",I),c.addEventListener("blur",()=>{setTimeout(()=>{g.style.display="none"},150)}),c.addEventListener("change",()=>{u()}),f()};for(let n of e)s(n)}renderColorAliasRow(t,e,i,s,n){let o=t.createDiv({cls:"stashpad-color-alias-row"});s===0&&o.addClass("is-unused");let a=o.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=i,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let g=this.plugin.settings.customPalette??[];new Ee(this.app,i,g,async p=>{if((p??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(p&&p.toLowerCase()===i){n();return}let d=await this.plugin.recolorAllInFolder(e,i,p??null);if(d>0)new j.Notice(`Recolored ${d} note${d===1?"":"s"}.`);else if(s===0){let I=this.plugin.getColorAlias(e,i);I&&(await this.plugin.setColorAlias(e,i,""),p&&await this.plugin.setColorAlias(e,p,I))}n()},async p=>{let d=(this.plugin.settings.customPalette??[]).filter(I=>I.toLowerCase()!==p.toLowerCase());return this.plugin.settings.customPalette=d,await this.plugin.saveSettings(),d}).open()};let r=o.createDiv({cls:"stashpad-color-alias-meta"});r.createSpan({cls:"stashpad-color-alias-hex",text:i}),r.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let l=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,i)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,i,l.value),!l.value.trim()&&s===0&&n()};let c=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});l.value||(c.style.visibility="hidden"),c.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let i=t.createDiv({cls:"stashpad-folder-row"});i.createSpan({cls:"stashpad-folder-row-label",text:e});let s=i.createSpan({cls:"stashpad-folder-row-state"}),n=i.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let o=n.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),r=()=>{let c=a();n.toggleClass("is-right",c),n.setAttribute("aria-checked",String(c)),o.setText(c?"X":"\u2713"),s.setText(c?"Excluded":"Included"),s.toggleClass("is-excluded",c),n.title=c?"Excluded \u2014 notes here won't appear in cross-Stashpad search. Click to include.":"Included \u2014 notes here appear in cross-Stashpad search. Click to exclude."},l=async()=>{let c=new Set(this.plugin.settings.searchExcludedFolders??[]);c.has(e)?c.delete(e):c.add(e),this.plugin.settings.searchExcludedFolders=[...c].sort(),r(),await this.plugin.saveSettings()};n.onclick=()=>void l(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},r()}renderFolderPlacementList(t){let e=this.plugin.settings,i=[{key:"folderPanelPinned",label:"Pinned",action:"Unpin"},{key:"folderPanelDownranked",label:"Downranked",action:"Reset"},{key:"folderPanelHidden",label:"Hidden",action:"Unhide"}];if(!i.some(o=>(e[o.key]??[]).length>0)){t.createEl("p",{cls:"setting-item-description"}).setText("No folders customized yet. Right-click a folder in the Stashpad folder panel to pin, downrank, or hide it.");return}let n=async o=>{e.folderPanelPinned=(e.folderPanelPinned??[]).filter(a=>a!==o),e.folderPanelDownranked=(e.folderPanelDownranked??[]).filter(a=>a!==o),e.folderPanelHidden=(e.folderPanelHidden??[]).filter(a=>a!==o),await this.plugin.saveSettings(),this.update?.()};for(let o of i){let a=[...e[o.key]??[]].sort();if(a.length===0)continue;t.createEl("div",{cls:"stashpad-folder-placement-group",text:`${o.label} (${a.length})`});let r=t.createDiv({cls:"stashpad-folder-list"});for(let l of a){let c=r.createDiv({cls:"stashpad-folder-row"});c.createSpan({cls:"stashpad-folder-row-label",text:l});let g=c.createEl("button",{text:o.action});g.onclick=()=>void n(l)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=d=>{let I=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=I.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=pi(i()[d]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=d==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{Xn(u,async y=>{this.plugin.settings.bindings[e.id][d]=y,u.value=pi(y),f(),await this.plugin.saveSettings(),o(),w()})};let m=I.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][d]="",u.value="",f(),await this.plugin.saveSettings(),o(),w()};let E=I.createEl("button",{cls:"stashpad-binding-revert"});(0,j.setIcon)(E,"rotate-ccw");let w=()=>{let v=i()[d]!==C;E.toggleClass("is-hidden",!v),E.title=C?`Revert to default (${pi(C)})`:"Revert to default (no binding)"};return E.onclick=async()=>{this.plugin.settings.bindings[e.id][d]=C,u.value=pi(C),f(),await this.plugin.saveSettings(),o(),w()},w(),u};s=a("primary"),n=a("secondary");let r=t.controlEl.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let l=r.createDiv({cls:"stashpad-binding-pill-knob"}),c=t.controlEl.createDiv({cls:"stashpad-binding-useboth"}),g=c.createEl("input",{type:"checkbox"});g.title="Use both bindings simultaneously (overrides the L/R toggle)",c.createSpan({text:"Use both"}),g.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=g.checked,await this.plugin.saveSettings(),o()},o=()=>{let d=i(),I=!!(d.primary&&d.secondary);g.checked=!!d.useBoth,g.disabled=!I,c.toggleClass("is-disabled",!I);let u=!!d.useBoth&&I;r.toggleClass("is-disabled",!I||u),r.toggleClass("is-right",d.preferRight),r.setAttribute("aria-checked",String(d.preferRight)),r.setAttribute("aria-disabled",String(!I||u)),l.setText(d.preferRight?"R":"L"),r.title=I?u?'Overridden by "Use both"':d.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let p=async()=>{let d=i();!d.primary||!d.secondary||(this.plugin.settings.bindings[e.id].preferRight=!d.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void p(),r.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),p())},o()}};var Oe=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=pt().inheritObsidianExclusions,t=A?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!Tn(i.path)&&!Hn(i.path)&&!(A&&Un(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 No.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()}};yt();var ns=class extends bt.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 fe}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?.()===ct&&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?.()===ct&&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 I=t.createDiv({cls:"stashpad-detail-empty"});(0,bt.setIcon)(I.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),I.createSpan({cls:"stashpad-detail-empty-text",text:"No Stashpad note selected. Cursor or click a note in a Stashpad list to inspect it here."});return}let n=s.file;this.displayedPath=n.path;let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=t.createDiv({cls:"stashpad-detail-scroll"}),r=a.createDiv({cls:"stashpad-detail-header"}),l=r.createDiv({cls:"stashpad-detail-titlerow"});l.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let c=l.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,bt.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(s.folder,s.id)};let g=r.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&g.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let I=g.createSpan({cls:"stashpad-detail-meta-color"});I.style.background=o.color,I.title=o.color}if(o.completed===!0&&g.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let I=Date.parse(String(o.due)),u=Number.isNaN(I)?String(o.due):$t(I,this.plugin.settings);g.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${u}`})}if(Array.isArray(o.tags))for(let I of o.tags.filter(u=>typeof u=="string"))g.createSpan({cls:"stashpad-detail-meta-tag",text:`#${I.replace(/^#/,"")}`});let p=a.createDiv({cls:"stashpad-detail-body"});try{let I=await this.app.vault.cachedRead(n),u=this.stripFrontmatter(I);await bt.MarkdownRenderer.render(this.app,u,p,n.path,this)}catch(I){p.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${I.message}`})}this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s);let d=this.composerInputEl;if(e&&d&&(d.focus(),i!=null)){let I=Math.min(i,d.value.length);try{d.setSelectionRange(I,I)}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,bt.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 Oe(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?.()!==ct||typeof i.createNoteUnder!="function"){new bt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new bt.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?.()!==ct)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let r=a.createDiv({cls:"stashpad-detail-children-list"});for(let l of o)l.file&&this.renderDetailChildRow(r,s,n,e,l,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},r=typeof a.color=="string"?a.color:null,l=a.completed===!0,c=i.getChildren(n.id),g=c.length>0,p=`${s}|${n.id}`,d=this.expanded.has(p),I=t.createDiv({cls:"stashpad-detail-child-row"});l&&I.addClass("is-completed"),o>0&&(I.style.paddingLeft=`${o*16}px`),I.draggable=!0,I.dataset.id=n.id,I.addEventListener("dragstart",E=>{E.dataTransfer?.setData("text/plain",n.id),E.dataTransfer&&(E.dataTransfer.effectAllowed="move"),I.addClass("is-dragging")}),I.addEventListener("dragend",()=>I.removeClass("is-dragging")),I.addEventListener("dragover",E=>{E.preventDefault(),E.dataTransfer&&(E.dataTransfer.dropEffect="move");let w=I.getBoundingClientRect(),y=E.clientY-w.top<w.height/2;I.toggleClass("drop-before",y),I.toggleClass("drop-after",!y)}),I.addEventListener("dragleave",()=>{I.removeClass("drop-before"),I.removeClass("drop-after")}),I.addEventListener("drop",E=>{E.preventDefault(),I.removeClass("drop-before"),I.removeClass("drop-after");let w=E.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let y=I.getBoundingClientRect(),v=E.clientY-y.top<y.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,v?"before":"after")}),I.oncontextmenu=E=>{E.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(E,w)};let u=I.createSpan({cls:"stashpad-detail-child-toggle"});if(g&&(ye(u,c.length,d),u.onclick=E=>{E.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Ne(a,"task")||a.task===!0||a.completed!==void 0){let E=I.createSpan({cls:"stashpad-detail-child-checkbox"});(0,bt.setIcon)(E,l?"check-square":"square"),E.title=l?"Mark not done":"Mark done",E.addEventListener("mousedown",w=>w.stopPropagation()),E.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),E.onclick=w=>{w.preventDefault(),w.stopPropagation();let y=i.get(n.id);y&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(y)}}let C=I.createSpan({cls:"stashpad-detail-child-icon"});(0,bt.setIcon)(C,g?"folder-tree":"file-text"),r&&(C.style.color=r);let m=I.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},g&&d)for(let E of c)this.renderDetailChildRow(t,e,i,s,E,o+1)}renderFooterMeta(t,e,i,s){let n=t.createDiv({cls:"stashpad-detail-footer-meta"}),o=[];if(typeof i.author=="string"&&i.author&&o.push({label:"Author",value:this.stripWikiLink(i.author)}),Array.isArray(i.contributors)){let a=i.contributors.filter(r=>typeof r=="string").map(r=>this.stripWikiLink(r));a.length>0&&o.push({label:"Contributors",value:a.join(", ")})}if(typeof i.modified=="string"&&o.push({label:"Modified",value:this.formatTime(i.modified)}),typeof i.created=="string"&&o.push({label:"Created",value:this.formatTime(i.created)}),o.push({label:"Path",value:e.path}),o.push({label:"ID",value:s.id}),o.length===0){n.remove();return}for(let a of o){let r=n.createDiv({cls:"stashpad-detail-meta-line"});r.createSpan({cls:"stashpad-detail-meta-key",text:a.label}),r.createSpan({cls:"stashpad-detail-meta-val",text:a.value})}}titleFor(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")}stripFrontmatter(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` +---`,3);return e<0?t:t.slice(e+4).replace(/^\n+/,"")}stripWikiLink(t){let e=t.match(/^\[\[(.+?)(?:\|(.+))?\]\]$/);return e?e[2]??(e[1].split("/").pop()??e[1]).replace(/\.md$/,""):t}formatTime(t){let e=Date.parse(t);return Number.isFinite(e)?$t(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==T&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new bt.Notice(`Couldn't open: ${i.message}`)}}};async function os(h){let A=h.workspace.getLeavesOfType(fe);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getRightLeaf(!1);if(!t){new bt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:fe,active:!0}),h.workspace.revealLeaf(t)}var P=require("obsidian");yt();var de=require("obsidian");yt();function nr(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof de.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof de.TFile?n.extension==="md"&&e.push(n):n instanceof de.TFolder&&(je.has(n.name)||i.push(n))}return e}var as=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(T,{id:T,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(T,{id:T,parent:null,children:[],file:null,created:""});let s=t?nr(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=o?.id;if(!a){let l=e.get(n.path),c=l?i.get(l):void 0,g=this.synthetic.get(n.path),p=c??g;p&&(this.nodes.set(p.id,{...p,children:[],file:n}),this.byPath.set(n.path,p.id));continue}if(this.synthetic.delete(n.path),a===T){let l=this.nodes.get(T);l.file=n,l.created=o?.created??"",this.byPath.set(n.path,T);continue}let r=o?.parent??null;r===a&&(r=null),this.nodes.set(a,{id:a,parent:r??T,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===T)continue;let o=n.parent??T;(this.nodes.get(o)??this.nodes.get(T)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let r=this.nodes.get(o),l=this.nodes.get(a);return(r.created||"").localeCompare(l.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((r,l)=>a.set(r,l)),n.children.sort((r,l)=>{let c=a.has(r)?a.get(r):1/0,g=a.has(l)?a.get(l):1/0;return c===g?0:c-g})}}this.emit()}insertSynthetic(A){if(!A.file)return;let t=A.file.path;this.synthetic.set(t,A),this.nodes.set(A.id,A),this.byPath.set(t,A.id);let e=A.parent??T,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(T)}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!==T&&!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===T||!t.file||(A[t.id]={parent:t.parent===T?null:t.parent,path:t.file.path});return A}hookMetadataCache(A){let t=r=>{let l=this.currentFolder;return l?typeof r!="string"?!1:r===l||r.startsWith(l+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),A())},16))},s=r=>{r instanceof de.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof de.TFile&&t(r.path)&&r.extension==="md"&&this.applyChange(r)&&i()},o=r=>{let l=r?.path;typeof l=="string"&&t(l)&&this.applyDelete(l)&&i()},a=(r,l)=>{if(!(r instanceof de.TFile))return;let c=typeof l=="string"?l:null;!t(r.path)&&!t(c)||this.applyRename(r,c??"")&&i()};return this.app.metadataCache.on("changed",s),this.app.vault.on("create",n),this.app.vault.on("delete",o),this.app.vault.on("rename",a),()=>{this.app.metadataCache.off("changed",s),this.app.vault.off("create",n),this.app.vault.off("delete",o),this.app.vault.off("rename",a),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(A){if(xe(A.path))return this.byPath.has(A.path)?this.applyDelete(A.path):!1;let t=this.app.metadataCache.getFileCache(A)?.frontmatter,e=t?.id,i=this.byPath.get(A.path);if(!e){if(i){let l=this.nodes.get(i);if(l&&l.file!==A)return l.file=A,!0}return!1}if(this.synthetic.delete(A.path),e===T){let l=this.nodes.get(T),c=t?.created??"",g=!1;return l.file!==A&&(l.file=A,g=!0),l.created!==c&&(l.created=c,g=!0),this.byPath.get(A.path)!==T&&(this.byPath.set(A.path,T),g=!0),g}let s=t?.parent??T,n=t?.created??"";if(!(s===T||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let l={id:e,parent:s,children:[],file:A,created:n};return this.nodes.set(e,l),this.byPath.set(A.path,e),this.attachToParent(l),this.resortChildrenOf(s),!0}let r=!1;if(a.file!==A&&(a.file=A,r=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??T),r=!0),a.parent!==s){let l=a.parent??T;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(l),this.resortChildrenOf(s),r=!0}return r}applyDelete(A){let t=this.byPath.get(A);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(A),this.synthetic.delete(A),!0;this.detachFromParent(e);let i=this.nodes.get(T);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=T,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(T),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(xe(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??T);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??T);t||(t=this.nodes.get(T)),t.children.includes(A.id)||t.children.push(A.id)}resortChildrenOf(A){let t=this.nodes.get(A);if(t&&(t.children.sort((e,i)=>{let s=this.nodes.get(e),n=this.nodes.get(i);return(s.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(A);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,a=i.has(n)?i.get(n):1/0;return o===a?0:o-a})}}}};var mn=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(` +`)}},Nt=new mn;var xo=".stashpad-order.json",Ke=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}/${xo}`,e=this.app.vault.adapter,i={};try{if(await e.exists(t)){let s=await e.read(t),n=JSON.parse(s);if(n&&typeof n=="object"&&!Array.isArray(n))for(let[o,a]of Object.entries(n))Array.isArray(a)&&a.every(r=>typeof r=="string")&&(i[o]=a)}}catch(s){console.warn("Stashpad: order load failed",s)}return this.cache.set(A,i),i}async save(A){this.scheduleWrite(A)}async flush(A){let t=this.pendingTimers.get(A);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(A)),await this.writeNow(A)}scheduleWrite(A){let t=this.pendingTimers.get(A);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(A),this.writeNow(A)},150);this.pendingTimers.set(A,e)}async writeNow(A){let e=(this.writeInFlight.get(A)??Promise.resolve()).then(()=>this.doWrite(A));this.writeInFlight.set(A,e);try{await e}finally{this.writeInFlight.get(A)===e&&this.writeInFlight.delete(A)}}async doWrite(A){let t=this.cache.get(A)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(A,e);let i=`${A}/${xo}`,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 yi={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"},Bn=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],or=new Set(Bn),Mo=".stashpad-sort.json",rs=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}/${Mo}`,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"&&or.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}/${Mo}`,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)}};yt();var he="parentLink",Ye="children";var cs=class cs{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||!pt().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(),cs.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[he]=="string"?n[he]:null,a=n?.[Ye],r=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];if((o??null)!==(i??null)||r.length!==s.length)return!0;for(let l=0;l<r.length;l++)if(r[l]!==s[l])return!0;return!1}async syncOne(A){let e=this.getTree().get(A);if(!e||!e.file||!this.wouldWrite(A))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await Nt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[he]=i:delete n[he],s.length>0?n[Ye]=s:delete n[Ye]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(A){if(A.id===T)return null;let t=this.getTree();if(!A.parent||A.parent===T){let i=t.getRoot();return i&&i.id!==A.id&&i.file?As(i.file.path):null}let e=t.get(A.parent);return e?.file?As(e.file.path):null}computeChildrenLinks(A){return this.getTree().getChildren(A.id).filter(e=>!!e.file).map(e=>As(e.file.path))}};cs.PACING_MS=100;var ls=cs;async function ze(h,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let l of h.vault.getMarkdownFiles()){if(l.path!==A&&!l.path.startsWith(t))continue;let c=h.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id:null;if(!g)continue;let p=typeof c?.parent=="string"?c.parent:T;e.set(g,{file:l,id:g,parent:p});let d=i.get(p)??[];d.push(g),i.set(p,d)}let s=l=>As(l.file.path),n=l=>{if(l.id===T)return null;if(l.parent===T||!l.parent){let g=e.get(T);return g?s(g):null}let c=e.get(l.parent);return c?s(c):null},o=l=>{let c=i.get(l.id)??[],g=[];for(let p of c){let d=e.get(p);d&&g.push(s(d))}return g},a=0,r=0;for(let l of e.values()){a+=1;let c=n(l),g=o(l),p=h.metadataCache.getFileCache(l.file)?.frontmatter,d=p&&typeof p[he]=="string"?p[he]:null,I=p?.[Ye],u=Array.isArray(I)?I.filter(m=>typeof m=="string"):[],f=(d??null)===(c??null),C=u.length===g.length&&u.every((m,E)=>m===g[E]);if(!(f&&C))try{await h.fileManager.processFrontMatter(l.file,m=>{c?m[he]=c:delete m[he],g.length>0?m[Ye]=g:delete m[Ye]}),r+=1,await new Promise(m=>setTimeout(m,50))}catch(m){console.warn("[Stashpad] rebootstrap fm sync failed",l.file.path,m)}}return{checked:a,written:r}}function As(h){return`[[${h.replace(/\.md$/i,"")}]]`}Kt();He();var ds=class{constructor(A,t){this.tree=A;this.log=t}async sweep(A){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!A)return!0;let o=A.replace(/\/+$/,"");return n===o||n.startsWith(o+"/")};for(let[n,o]of Object.entries(e)){let a=t[n];a?a.parent!==o.parent?await this.log.append({type:"parent_change",id:n,payload:{from:a.parent,to:o.parent}}):a.path!==o.path&&await this.log.append({type:"rename",id:n,payload:{from:a.path,to:o.path}}):await this.log.append({type:"create",id:n,payload:{path:o.path,parent:o.parent}})}for(let[n,o]of Object.entries(t))!e[n]&&i(o.path)&&await this.log.append({type:"missing",id:n,payload:{lastPath:o.path}});let s={};for(let[n,o]of Object.entries(t))i(o.path)||(s[n]=o);for(let[n,o]of Object.entries(e))s[n]=o;await this.log.writeState(s)}};var vt=require("obsidian");yt();Ps();var St=vt.moment;function Qn(h){let A=h.trim().toLowerCase();if(!A)return null;let t=Date.now(),e=I=>St(I).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=A,a=i.exec(A);if(a&&(a[3]||a[2])){let I=parseInt(a[1],10),u=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&I<12&&(I+=12),f==="am"&&I===12&&(I=0),I>=0&&I<24&&u>=0&&u<60&&(s=(I*3600+u*60)*1e3,n=!0,o=A.replace(a[0]," ").replace(/\s+/g," ").trim())}let r=I=>n?I+s:I;if(o===""||o==="today")return r(e(t));if(o==="yesterday")return r(e(t)-864e5);if(o==="tomorrow")return r(e(t)+864e5);let l=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],c=["sun","mon","tue","wed","thu","fri","sat"],g=l.indexOf(o)>=0?l.indexOf(o):c.indexOf(o);if(g>=0){let I=St().startOf("day"),f=(I.day()-g+7)%7;return r(I.subtract(f,"days").valueOf())}let p=/^(\d+)\s*([dwmy])$/.exec(o);if(p){let I=parseInt(p[1],10),u={d:"days",w:"weeks",m:"months",y:"years"}[p[2]];return r(St().subtract(I,u).startOf("day").valueOf())}let d=St(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return d.isValid()?r(d.startOf("day").valueOf()):null}function To(h){let A={text:[],filters:{}},t=(h||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let a=Qn(o);a!=null&&(A.filters.before=a)}else if(n==="after"){let a=Qn(o);a!=null&&(A.filters.after=a)}else if(n==="on"){let a=Qn(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))A.filters.on={start:a-6e4,end:a+6e4};else{let l=St(a).startOf("day").valueOf();A.filters.on={start:l,end:l+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&A.text.push(n.toLowerCase());return A}var te=class h extends vt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==T?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===T&&this.notes.push({node:a,title:i,body:""});for(let r of this.tree.getChildren(n))s(r.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(T))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(a=>{o.body=this.stripFm(a)})}}createdMsFor(t){if(t.node?.created){let e=Date.parse(t.node.created);if(!Number.isNaN(e))return e}return t.cross?.file?.stat?.ctime!=null?t.cross.file.stat.ctime:null}stripFm(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` +---`,3);return e===-1?t:t.slice(e+4).replace(/^\r?\n/,"")}getSuggestions(t){let e=t.trim().toLowerCase(),i=To(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=C=>{if(!s.length)return!0;for(let m of s)if(!C.includes(m))return!1;return!0},o=null,a=null;if(i.filters.in){let C=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,a=new Map;let m=y=>C.every(v=>y.toLowerCase().includes(v)),E=y=>{if(!o.has(y)){o.add(y);for(let v of this.tree.getChildren(y))E(v.id)}};for(let y of this.notes)!y.node||y.cross||m(y.title)&&E(y.node.id);let w=new Map;for(let y of this.notes){if(!y.cross)continue;let v=w.get(y.cross.folder)??[];v.push(y),w.set(y.cross.folder,v)}for(let[y,v]of w){let S=new Map;for(let N of v){let Q=N.cross?.parentId??null;if(!Q)continue;let D=S.get(Q)??[];D.push(N.cross.id),S.set(Q,D)}let M=new Set;a.set(y,M);let F=N=>{if(!M.has(N)){M.add(N);for(let Q of S.get(N)??[])F(Q)}};for(let N of v)m(N.title)&&F(N.cross.id)}}let r=C=>{let m=i.filters;if(o||a)if(C.cross){let E=a?.get(C.cross.folder);if(!E||!E.has(C.cross.id))return!1}else if(C.node){if(!o||!o.has(C.node.id))return!1}else return!1;if(m.before||m.after||m.on){let E=this.createdMsFor(C);if(E==null||m.before!=null&&E>=m.before||m.after!=null&&E<=m.after||m.on&&(E<m.on.start||E>=m.on.end))return!1}return!0},l=C=>n(C.toLowerCase()),c=this.notes.filter(C=>!C.cross),g=this.notes.filter(C=>C.cross),p=(C,m)=>({id:C.cross?`cross:${C.cross.folder}:${C.cross.id}`:C.node.id,label:C.title,node:C.node,kind:"note",bodyPreview:this.previewFromBody(C.body,m),matchLine:m,crossFolder:C.cross?.folder,crossFile:C.cross?.file,crossId:C.cross?.id}),d=C=>{let m=[];for(let E of C)if(r(E))if(this.opts.mode==="search"){if(!e){m.push(p(E,-1));continue}let w=n(E.title.toLowerCase()),y=E.body.split(/\r?\n/),v=[];for(let M=0;M<y.length;M++)l(y[M])&&v.push(M);let S=v.length>0||n(E.body.toLowerCase());if(!w&&!S)continue;if(v.length===0)m.push(p(E,-1));else{let M=[],F=-100;for(let Q of v)Q-F>5&&M.push(Q),F=Q;let N=5;for(let Q of M.slice(0,N))m.push(p(E,Q))}}else{if(e&&!n(E.title.toLowerCase())&&!n(E.body.toLowerCase()))continue;m.push(p(E,-1))}return m},I=d(c),u=[...I];if(this.opts.mode==="search"?e?!0:I.length<10:!!e){let C=d(g);this.opts.mode==="search"&&!e&&(u.length=Math.min(u.length,50)),u.push(...C)}if(this.opts.folderResults){let C=this.opts.folderResults(),m={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};C.length>0&&(e?C.some(E=>{let w=E.split("/").pop()??E;return n(`${E.toLowerCase()} ${w.toLowerCase()}`)})&&u.push(m):u.unshift(m))}if(this.opts.allowCreate&&e&&!u.some(C=>C.label.trim().toLowerCase()===e)&&u.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let C=E=>E.kind==="note"&&(E.id===T||E.crossId===T)&&n(E.label.toLowerCase()),m=u.filter(C);if(m.length>0){let E=u.filter(w=>!C(w));u.splice(0,u.length,...m,...E)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&u.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),u}loadExcludedNotes(){if(this.includeExcluded||!this.opts.excludedFolderNotes)return;this.includeExcluded=!0;for(let e of this.opts.excludedFolderNotes())this.notes.push({node:null,title:e.title,body:e.body,cross:e});for(let e of this.notes)!e.cross||e.body||!e.cross.file||this.app.vault.cachedRead(e.cross.file).then(i=>{e.body=this.stripFm(i)});let t=this.inputEl;t&&(t.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(()=>t.dispatchEvent(new Event("input",{bubbles:!0})),250))}previewFromBody(t,e){let i=t.split(/\r?\n/);if(e<0)return i.filter(a=>a.trim().length>0).slice(0,3).join(` `);let s=Math.max(0,e-2),n=Math.min(i.length,e+3);return i.slice(s,n).filter(o=>o.trim().length>0).join(` -`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let d=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),I=d.createSpan({cls:"stashpad-search-excluded-icon"});(0,vt.setIcon)(I,"folder-search"),d.createSpan({text:t.label}),e.createDiv({cls:"stashpad-suggest-preview",text:"Include folders you've excluded from search (e.g. to move a note there)."});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let i=e.createDiv({cls:"stashpad-suggest-body"}),s=this.notes.find(d=>t.crossFolder?d.cross?.folder===t.crossFolder&&d.cross?.id===t.crossId:d.node?.id===t.id),n=Ho(this.inputEl?.value??"").text,o=this.firstLineOfBody(s?.body??"")||t.label.trim(),a=i.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(a,o,n);let r=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let d=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(d,t.bodyPreview,n)}let l="";if(t.crossFolder?l=s?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let d=i.createDiv({cls:"stashpad-suggest-preview"});d.appendText("Parent: "),this.highlightInto(d,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),g=t.crossFolder??this.opts.localFolder??null;if(g||c){let d=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[g?g.split("/").pop()||g:"",c].filter(f=>f&&f.length>0).join(" \u203A ");u&&d.setText(u)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let d=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let I=d.createDiv({cls:"stashpad-suggest-time"});I.setText(this.formatRelativeTime(p)),I.title=St(p).format("YYYY-MM-DD HH:mm")}r&&d.createDiv({cls:"stashpad-suggest-folder-badge",text:r.split("/").pop()||r})}}formatRelativeTime(t){let e=St(t),i=St().startOf("day").diff(St(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(l=>l&&l.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let l of s){let c=0;for(;(c=n.indexOf(l,c))!==-1;)o.push([c,c+l.length]),c+=l.length}if(!o.length){t.appendText(e);return}o.sort((l,c)=>l[0]-c[0]);let a=[];for(let l of o){let c=a[a.length-1];c&&l[0]<=c[1]?c[1]=Math.max(c[1],l[1]):a.push([l[0],l[1]])}let r=0;for(let[l,c]of a)l>r&&t.appendText(e.slice(r,l)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(l,c)}),r=c;r<e.length&&t.appendText(e.slice(r))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===M)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==M&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==M?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 r of this.notes){if(!r.cross)continue;let l=this.crossFolderIndex.get(r.cross.folder);l||(l=new Map,this.crossFolderIndex.set(r.cross.folder,l)),l.set(r.cross.id,r.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.crossId??t.id.replace(/^cross:/,""),s=e.get(i);if(!s)return"";let n=[],o=new Set([s.id]),a=s.parentId?e.get(s.parentId):null;for(;a&&!o.has(a.id);)o.add(a.id),n.unshift(a.title),a=a.parentId?e.get(a.parentId):null;return n.join(" \u203A ")}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let i of e){let s=i.trim();if(s)return s}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===M)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&&!vt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(vt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",l=>{if(l.key==="["){l.preventDefault();let c=t.selectionStart??t.value.length,g=t.selectionEnd??c,p=t.value.slice(0,c),d=t.value.slice(c,g),I=t.value.slice(g);t.value=`${p}[${d}]${I}`;let u=c+1+d.length;t.setSelectionRange(u,u),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(l.key==="]"){let c=t.selectionStart??-1;c>=0&&t.value[c]==="]"&&(l.preventDefault(),t.setSelectionRange(c+1,c+1));return}if(l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&t.selectionStart===t.selectionEnd){let c=t.selectionStart??-1;if(c>0&&t.value[c-1]==="["&&t.value[c]==="]"){l.preventDefault();let g=t.value.slice(0,c-1),p=t.value.slice(c+1);t.value=`${g}${p}`,t.setSelectionRange(c-1,c-1),t.dispatchEvent(new Event("input",{bubbles:!0}))}}});let i=document.createElement("div");i.className="stashpad-search-filter-row";let s=document.createElement("span");s.className="stashpad-search-filter-label",s.textContent="Filters:",i.appendChild(s);let n=document.createElement("button");n.className="stashpad-search-filter-chip",n.type="button",n.textContent="in:[parent note]",n.title='Insert "in:" \u2014 filter by parent note.',n.addEventListener("mousedown",l=>{l.preventDefault()}),n.addEventListener("click",l=>{l.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),n.click())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",l=>{l.preventDefault()}),o.addEventListener("click",l=>{l.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new vt.Scope(this.scope),r=l=>{let c=document.activeElement;return c?.classList?.contains("stashpad-search-filter-chip")?(l.preventDefault(),c.click(),!1):l.key==="Enter"&&!l.isComposing?(l.preventDefault(),this.selectActiveSuggestion?.(l),!1):!0};a.register([],"Enter",r),a.register([]," ",r),a.register(["Mod"],"f",l=>{l.preventDefault();let c=this.inputEl;return c&&(c.focus(),c.select()),!1}),a.register([],"Tab",l=>{let c=this.modalEl,g=this.inputEl;if(!c)return!0;let p=Array.from(c.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1&&u.offsetParent!==null);if(p.length===0)return!0;let d=document.activeElement,I=d?p.indexOf(d):-1;if(l.shiftKey){if(I<=0)return l.preventDefault(),p[p.length-1].focus(),!1}else if(I===p.length-1)return l.preventDefault(),(g??p[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(a),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(a)}catch{}})}appendFilterToInput(t,e,i){let s=t.value,o=`${s.length>0&&!/\s$/.test(s)?" ":""}${e}: [`,a="]",r=i;t.value=`${s}${o}${r}${a}`;let l=s.length+o.length+r.length;if(t.setSelectionRange(l,l+0),!r){let c=s.length+o.length;t.setSelectionRange(c,c)}t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}toggleWhenBuilder(t,e){let i=this.modalEl;if(this.whenBuilderEl){this.whenBuilderEl.remove(),this.whenBuilderEl=null,i?.removeClass("is-when-builder-open");return}i?.addClass("is-when-builder-open");let s=document.createElement("div");s.className="stashpad-when-builder";let n=document.createElement("div");n.className="stashpad-when-tabs";let o=[{id:"before",label:"Before"},{id:"on",label:"On"},{id:"after",label:"After"},{id:"between",label:"Between"}],a={};for(let u of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=u.label,this.whenMode===u.id&&f.addClass("is-active"),f.addEventListener("mousedown",C=>C.preventDefault()),f.addEventListener("click",C=>{if(C.preventDefault(),this.whenMode===u.id)return;let m=this.whenMode;m!=="between"&&u.id==="between"?this.whenBetweenEndText="":m==="between"&&u.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=u.id;for(let E in a)a[E].toggleClass("is-active",E===u.id);I()}),a[u.id]=f,n.appendChild(f)}s.appendChild(n);let r=document.createElement("div");r.className="stashpad-when-body",s.appendChild(r);let l=(u,f,C="single")=>{let m=St().format("YYYY-MM-DD"),E=!f||f===m;if(C==="betweenStart")return"00:00";if(C==="betweenEnd")return"23:59";switch(u){case"after":return"00:00";case"on":return E?St().format("HH:mm"):"23:59";case"before":return E?St().format("HH:mm"):"23:59";default:return"23:59"}},c=(u,f)=>{u.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},g=(u,f)=>{let C=u.selectionStart??u.value.length,m=u.selectionEnd??u.value.length,w=`${C>0&&!/\s$/.test(u.value.slice(0,C))?" ":""}${f}`,y=u.value.slice(0,C)+w+u.value.slice(m);u.value=y;let v=C+w.length;u.setSelectionRange(v,v),u.focus(),u.dispatchEvent(new Event("input",{bubbles:!0}))},p=(u,f)=>{let m=u.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return m?m[1]:null},d=(u,f,C,m)=>{let E=r.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=E.createDiv({cls:"stashpad-when-icon-slot"}),y=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,vt.setIcon)(y,"calendar-days");let v=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});v.tabIndex=-1;let S=E.createDiv({cls:"stashpad-when-icon-slot"}),U=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});U.type="button",U.title="Pick time",(0,vt.setIcon)(U,"clock");let F=E.createDiv({cls:"stashpad-when-icon-slot"}),x=F.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});x.type="button",x.title="Pick day",(0,vt.setIcon)(x,"calendar");let Q=E.createDiv({cls:"stashpad-when-icon-slot"}),D=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});D.type="button",D.title="Pick timeframe",(0,vt.setIcon)(D,"history");let K=E.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:u}});K.value=f(),K.addEventListener("input",()=>C(K.value));let N=E.createEl("button",{cls:"stashpad-when-clear"});N.type="button",N.textContent="\xD7",N.title="Clear";for(let T of[y,U,x,D,N])T.addEventListener("mousedown",tt=>tt.preventDefault());let Y=null,q=(T,tt)=>{Y&&Y();let O=T.createDiv({cls:"stashpad-when-popover"}),V=new vt.Scope(this.scope),rt=null,gt=ot=>{rt=ot},nt=!1,At=ot=>{!O.contains(ot.target)&&ot.target!==T&&!T.contains(ot.target)&<()},lt=()=>{if(!nt){nt=!0,O.remove(),document.removeEventListener("mousedown",At,!0);try{this.app.keymap?.popScope(V)}catch{}Y===lt&&(Y=null)}};Y=lt,V.register([],"Escape",ot=>(ot.preventDefault(),lt(),!1)),V.register([],"Enter",ot=>(ot.preventDefault(),rt&&rt(),!1));try{tt(O,lt,gt)}catch(ot){console.error("[stashpad] popover fill threw:",ot),O.remove(),Y=null;return}this.app.keymap?.pushScope(V),this.pendingCleanups.push(lt),setTimeout(()=>document.addEventListener("mousedown",At,!0),0)};D.addEventListener("click",T=>{T.preventDefault(),q(Q,(tt,O,V)=>{let rt=this.whenMode==="on",gt=(J,G)=>{if(!rt)return`${J}${G}`;let b={d:"days",w:"weeks",m:"months",y:"years"}[G];return St().subtract(J,b).format("YYYY-MM-DD")},nt=tt.createDiv({cls:"stashpad-when-pop-row"}),At=[{label:"Last 7d",n:7,unit:"d"},{label:"Last 30d",n:30,unit:"d"},{label:"This week",n:1,unit:"w"},{label:"This month",n:1,unit:"m"}];for(let J of At){let G=nt.createEl("button",{cls:"stashpad-when-pop-chip",text:J.label});G.type="button",G.addEventListener("mousedown",b=>b.preventDefault()),G.addEventListener("click",b=>{b.preventDefault(),g(K,gt(J.n,J.unit)),O()})}let lt=tt.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});lt.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let ot=lt.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),Qt=lt.createEl("select",{cls:"stashpad-when-pop-unit"});for(let J of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let G=Qt.createEl("option",{text:J.label});G.value=J.v}let ft=lt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ft.type="button";let B=()=>{let J=parseInt(ot.value,10);!Number.isFinite(J)||J<1||(g(K,gt(J,Qt.value)),O())};ft.addEventListener("mousedown",J=>J.preventDefault()),ft.addEventListener("click",J=>{J.preventDefault(),B()}),V(B),ot.focus(),ot.select()})});let _=(T,tt,O,V,rt)=>{q(tt,(gt,nt,At)=>{Ni(gt,{seedH:O,seedM:V,seedPeriod:rt,close:nt,setOnEnter:At,onFinalize:lt=>g(T,Gn(lt))})})};x.addEventListener("click",T=>{T.preventDefault(),q(F,(tt,O,V)=>{let rt=tt.createDiv({cls:"stashpad-when-pop-row"});for(let ot of["Today","Yesterday"]){let Qt=rt.createEl("button",{cls:"stashpad-when-pop-chip",text:ot});Qt.type="button",Qt.addEventListener("mousedown",ft=>ft.preventDefault()),Qt.addEventListener("click",ft=>{ft.preventDefault(),g(K,ot),O()})}let gt=tt.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),nt=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],lt=(St().day()+6)%7;for(let ot=0;ot<nt.length;ot++){let Qt=nt[ot],ft=gt.createEl("button",{cls:"stashpad-when-pop-chip",text:Qt.slice(0,3)});ft.type="button",ft.title=Qt,ot===lt&&ft.addClass("is-today"),ft.addEventListener("mousedown",B=>B.preventDefault()),ft.addEventListener("click",B=>{if(B.preventDefault(),m==="betweenEnd"){let J=ot,G=St().startOf("day"),b=(G.day()+6)%7,k=(J-b+7)%7;k===0&&(k=7);let H=G.clone().add(k,"days").format("YYYY-MM-DD");g(K,H)}else g(K,Qt);O()})}})});let L=(T,tt)=>{T.value||(T.value=tt);let O=T;if(typeof O.showPicker=="function")try{O.showPicker();return}catch{}T.focus(),T.click()};return y.addEventListener("click",T=>{T.preventDefault(),L(v,St().format("YYYY-MM-DD"))}),v.addEventListener("change",()=>{v.value&&g(K,v.value)}),U.addEventListener("click",T=>{T.preventDefault();let tt=K.selectionStart??K.value.length,O=p(K.value,tt),V=l(this.whenMode,O,m),[rt,gt]=V.split(":"),nt=parseInt(rt,10),At=parseInt(gt,10),lt=nt%12;lt===0&&(lt=12);let ot=nt>=12?"pm":"am";_(K,S,lt,At,ot)}),N.addEventListener("click",T=>{T.preventDefault(),K.value="",C(""),K.focus()}),K},I=()=>{if(r.empty(),this.whenMode==="between"){let u=d("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=d("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),C=r.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",y=>y.preventDefault());let E=()=>{let y=u.value.trim(),v=f.value.trim();y&&this.appendFilterToInput(t,"after",y),v&&this.appendFilterToInput(t,"before",v),this.closeWhenBuilder()};m.addEventListener("click",y=>{y.preventDefault(),E()});let w=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),c(u,E),c(f,E),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}else{let u=d("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),f=r.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",w=>w.preventDefault());let m=()=>{let w=u.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};C.addEventListener("click",w=>{w.preventDefault(),m()});let E=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});E.type="button",E.addEventListener("mousedown",w=>w.preventDefault()),E.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),c(u,m),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}};I(),e.parentElement?.insertBefore(s,e.nextSibling),this.whenBuilderEl=s}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}selectSuggestion(t,e){if(t&&t.kind==="search-excluded"){this.loadExcludedNotes();return}super.selectSuggestion(t,e)}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}if(t.kind==="folder-open"&&t.id==="__folder_picker__"){let e=this.opts.folderResults?.()??[];if(!e.length)return;let i=this.inputEl?.value??"",s=!1,n=p=>{s=!0;let d=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${d}\u201D in a new tab`,node:null,kind:"folder-open",folder:p})},o=new Bn(this.app,e,n),a=o.onClose.bind(o),r=this.tree,l=this.titleFn,c=this.opts,g=this.app;o.onClose=()=>{if(a(),!s){let p=new h(g,r,l,c);p.open(),setTimeout(()=>{let d=p.inputEl;d&&(i&&(d.value=i,d.dispatchEvent(new Event("input",{bubbles:!0}))),d.focus(),d.setSelectionRange(d.value.length,d.value.length))},0)}},o.open();return}this.opts.onPick(t)}},Bn=class extends vt.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 To=require("obsidian");yt();var cs=class extends To.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:ar(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(A){return this.commands.filter(t=>Di(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 ar(h){return h.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||h}Ht();var Qn=require("obsidian");function rr(h,A){return!A||h.metaKey||h.ctrlKey||h.altKey?!1:h.key.toLowerCase()===A.toLowerCase()}function Ye(h,A){return A?A.includes("+")?Ar(h,A):rr(h,A):!1}function st(h,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?Ye(h,t)||Ye(h,e):i?Ye(h,e):Ye(h,t):Ye(h,t)||Ye(h,e)}function yi(h){if(!h)return"";let A=Qn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return h.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function Ar(h,A){if(!A)return!1;let t=A.split("+").map(g=>g.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(g=>g.toLowerCase())),s=i.has("mod"),n=i.has("ctrl")||i.has("control"),o=i.has("cmd")||i.has("meta")||i.has("command"),a=i.has("alt")||i.has("option"),r=i.has("shift"),c=Qn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?h.metaKey:h.ctrlKey;return s&&!c||n&&!h.ctrlKey||o&&!h.metaKey||a!==h.altKey||r!==h.shiftKey||!s&&(!n&&h.ctrlKey||!o&&h.metaKey)?!1:h.key.toLowerCase()===e}var ke=require("obsidian");Ht();var Pt=class Pt{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 ke.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 ke.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 ke.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let d=this.host.app.metadataCache.getFileCache(p)?.frontmatter,I=typeof d?.author=="string"?d.author:"";if(!I.trim()){s.push(p.path);continue}if(I.includes(e)||!A.contributorMode)continue;(Array.isArray(d?.contributors)?d.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(p.path)}let o=s.length+n.length;if(o===0){new ke.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(A.scope==="folder"){let p=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&p.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(I=>{new Ft(this.host.app,"Claim authorship",`${p.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",I).open()}))return}let a=this.host.noteFolder,r=t.link,l=new Set,c=async()=>{await this.pacedFrontmatter(s,(p,d)=>{typeof p.author=="string"&&p.author.trim()||(p.author=r),Array.isArray(p.contributors)&&p.contributors.some(I=>typeof I=="string"&&I.includes(e))&&(p.contributors=p.contributors.filter(I=>!(typeof I=="string"&&I.includes(e))),l.add(d))}),await this.pacedFrontmatter(n,p=>{let d=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];d.some(I=>I.includes(e))||d.push(r),p.contributors=d})};this.ensureAuthorFile(t),await c(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(p,d)=>{if(typeof p.author=="string"&&p.author.includes(e)&&delete p.author,l.has(d)){let I=Array.isArray(p.contributors)?p.contributors.filter(u=>typeof u=="string"):[];I.some(u=>u.includes(e))||I.push(r),p.contributors=I}}),await this.pacedFrontmatter(n,p=>{Array.isArray(p.contributors)&&(p.contributors=p.contributors.filter(d=>!(typeof d=="string"&&d.includes(e))))}),this.host.debouncedRender()},redo:async()=>{l.clear(),await c(),this.host.debouncedRender()}});let g=[];s.length&&g.push(`authored ${s.length}`),n.length&&g.push(`contributing to ${n.length}`),new ke.Notice(`Claimed authorship: ${g.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(A){try{A.id&&this.host.plugin.authorRegistry.record({id:A.id,name:A.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(A.path))return;let e=A.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:A.id,name:A.name,role:e?this.host.plugin.settings.authorRole:void 0,department:e?this.host.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.host.app.vault.create(A.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(A){let t=new Set,e=i=>{if(typeof i!="string")return null;let s=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return s?s[1]:null};for(let i of A){if(!i.file)continue;let s=this.host.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!s)continue;let n=e(s.author);if(n&&t.add(n),Array.isArray(s.contributors))for(let o of s.contributors){let a=e(o);a&&t.add(a)}}return Array.from(t)}pruneContribMaps(){let A=Date.now(),t=Pt.EXTERNAL_WRITE_GRACE_MS*20,e=Pt.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<Pt.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=Pt.CONTRIB_DEBOUNCE_MS+(e?Pt.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<Pt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(A);return}this.maybeRecordContribution(A)},i);this.contribTimers.set(A.path,s)}isFileActivelyEdited(A){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==A.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(A){let t="";try{t=await this.host.app.vault.cachedRead(A)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(A.path);if(this.knownBodies.set(A.path,e),i===void 0||i===e||this.host.plugin.rebootstrapInProgress)return;let s=this.currentAuthorLink();if(!s)return;this.ensureAuthorFile(s);let n=new Date().toISOString();this.recentSelfWrites.set(A.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(A,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],l=`-${s.id}`,c=a.includes(l),g=r.some(p=>p.includes(l));!c&&!g&&r.push(s.link),o.contributors=r})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Pt.CONTRIB_DEBOUNCE_MS=4e3,Pt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Pt.EXTERNAL_WRITE_GRACE_MS=1500,Pt.EXTERNAL_QUIESCENCE_MS=5e3;var ds=Pt;var hs=class{constructor(A){this.host=A;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(A,t,e){A.addEventListener("dragstart",i=>{let s=this.host.selection.has(t.id)&&this.host.selection.size>1?[...this.host.selection]:[t.id];if(this.dragSourceIds=s,this.dragRowHeight=A.offsetHeight,A.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.style.height="0px",this.dragPlaceholder.addEventListener("dragover",n=>{this.dragSourceIds&&(n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect="move"))}),this.dragPlaceholder.addEventListener("drop",n=>{if(!this.dragSourceIds||!this.dragPlaceholder)return;n.preventDefault(),n.stopPropagation();let o=this.dragSourceIds.slice();this.dragSourceIds=null;let a=this.dragPlaceholder.nextElementSibling,r=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let l,c="before";a&&a.classList.contains("stashpad-note")?(l=a.dataset.id,c="before"):r&&r.classList.contains("stashpad-note")&&(l=r.dataset.id,c="after"),l&&this.host.reorderToTarget(o,l,c)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(A,12,12)}catch{}}}),A.addEventListener("dragend",()=>{A.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),A.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,A);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),A.addClass("drop-into")):(A.removeClass("drop-into"),this.placePlaceholder(A,s==="drop-above"?"before":"after"))}),A.addEventListener("dragleave",i=>{let s=A.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&A.removeClass("drop-into")}),A.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,A);this.clearDropIndicators(),this.removeDragPlaceholder(),A.removeClass("is-dragging"),n==="drop-into"?this.host.reorderToTarget(s,t.id,"into"):this.host.reorderToTarget(s,t.id,n==="drop-above"?"before":"after")})}attachListDnD(A){A.addEventListener("dragover",t=>{if(!this.dragSourceIds)return;let e=t.target;if(e&&e.closest&&e.closest(".stashpad-note"))return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move");let i=Array.from(A.querySelectorAll(".stashpad-note"));if(i.length!==0){for(let s of i){let n=s.getBoundingClientRect();if(t.clientY<n.top+n.height/2){this.placePlaceholder(s,"before");return}}this.placePlaceholder(i[i.length-1],"after")}}),A.addEventListener("drop",t=>{if(!this.dragSourceIds)return;t.preventDefault();let e=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let i=this.dragPlaceholder.nextElementSibling,s=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),i&&i.classList.contains("stashpad-note")){let n=i.dataset.id;n&&this.host.reorderToTarget(e,n,"before")}else if(s&&s.classList.contains("stashpad-note")){let n=s.dataset.id;n&&this.host.reorderToTarget(e,n,"after")}})}placePlaceholder(A,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?A:A.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===A||t==="after"&&this.dragPlaceholder.previousSibling===A)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),this.dragPlaceholder.style.opacity="1",i?this.dragPlaceholder.style.height=`${this.dragRowHeight}px`:(this.dragPlaceholder.style.height="0px",this.dragPlaceholder.offsetHeight,this.dragPlaceholder.style.height=`${this.dragRowHeight}px`)}removeDragPlaceholder(){if(!this.dragPlaceholder?.parentElement)return;let A=this.dragPlaceholder;A.style.height="0px",A.style.opacity="0",setTimeout(()=>{A.parentElement&&A.remove()},150)}dropZone(A,t){let e=t.getBoundingClientRect(),i=A.clientY-e.top;return i<e.height*.3?"drop-above":i>e.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.host.listEl)for(let A of Array.from(this.host.listEl.querySelectorAll(".drop-into")))A.removeClass("drop-into")}};var Uo=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 bt.record("render.row.cacheHit",0),t;let e=await bt.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 bt.timeAsync("render.row.markdown",()=>Uo.MarkdownRenderer.render(this.host.app,s,o,A.path,this.component));let a=o.innerHTML,r={mtime:A.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(A.path,r),r}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(A=>{for(let t of A){if(!t.isIntersecting)continue;let e=t.target,i=this.lazyBodies.get(e);this.bodyObserver?.unobserve(e),this.lazyBodies.delete(e),i&&i()}},{root:this.host.contentEl,rootMargin:"1400px 0px"})}dispose(){this.bodyObserver?.disconnect(),this.bodyObserver=null}isArmed(){return!!this.bodyObserver}hasFreshRenderCache(A){let t=this.renderCache.get(A.path);return!!t&&t.mtime===A.stat.mtime}defer(A,t){this.lazyBodies.set(A,t),this.bodyObserver?.observe(A)}splitAttachments(A){let t=[];return{text:A.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` +`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let d=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),I=d.createSpan({cls:"stashpad-search-excluded-icon"});(0,vt.setIcon)(I,"folder-search"),d.createSpan({text:t.label}),e.createDiv({cls:"stashpad-suggest-preview",text:"Include folders you've excluded from search (e.g. to move a note there)."});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let i=e.createDiv({cls:"stashpad-suggest-body"}),s=this.notes.find(d=>t.crossFolder?d.cross?.folder===t.crossFolder&&d.cross?.id===t.crossId:d.node?.id===t.id),n=To(this.inputEl?.value??"").text,o=this.firstLineOfBody(s?.body??"")||t.label.trim(),a=i.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(a,o,n);let r=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let d=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(d,t.bodyPreview,n)}let l="";if(t.crossFolder?l=s?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let d=i.createDiv({cls:"stashpad-suggest-preview"});d.appendText("Parent: "),this.highlightInto(d,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),g=t.crossFolder??this.opts.localFolder??null;if(g||c){let d=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[g?g.split("/").pop()||g:"",c].filter(f=>f&&f.length>0).join(" \u203A ");u&&d.setText(u)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let d=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let I=d.createDiv({cls:"stashpad-suggest-time"});I.setText(this.formatRelativeTime(p)),I.title=St(p).format("YYYY-MM-DD HH:mm")}r&&d.createDiv({cls:"stashpad-suggest-folder-badge",text:r.split("/").pop()||r})}}formatRelativeTime(t){let e=St(t),i=St().startOf("day").diff(St(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(l=>l&&l.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let l of s){let c=0;for(;(c=n.indexOf(l,c))!==-1;)o.push([c,c+l.length]),c+=l.length}if(!o.length){t.appendText(e);return}o.sort((l,c)=>l[0]-c[0]);let a=[];for(let l of o){let c=a[a.length-1];c&&l[0]<=c[1]?c[1]=Math.max(c[1],l[1]):a.push([l[0],l[1]])}let r=0;for(let[l,c]of a)l>r&&t.appendText(e.slice(r,l)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(l,c)}),r=c;r<e.length&&t.appendText(e.slice(r))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===T)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==T&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==T?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 r of this.notes){if(!r.cross)continue;let l=this.crossFolderIndex.get(r.cross.folder);l||(l=new Map,this.crossFolderIndex.set(r.cross.folder,l)),l.set(r.cross.id,r.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.crossId??t.id.replace(/^cross:/,""),s=e.get(i);if(!s)return"";let n=[],o=new Set([s.id]),a=s.parentId?e.get(s.parentId):null;for(;a&&!o.has(a.id);)o.add(a.id),n.unshift(a.title),a=a.parentId?e.get(a.parentId):null;return n.join(" \u203A ")}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let i of e){let s=i.trim();if(s)return s}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===T)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&&!vt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(vt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",l=>{if(l.key==="["){l.preventDefault();let c=t.selectionStart??t.value.length,g=t.selectionEnd??c,p=t.value.slice(0,c),d=t.value.slice(c,g),I=t.value.slice(g);t.value=`${p}[${d}]${I}`;let u=c+1+d.length;t.setSelectionRange(u,u),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(l.key==="]"){let c=t.selectionStart??-1;c>=0&&t.value[c]==="]"&&(l.preventDefault(),t.setSelectionRange(c+1,c+1));return}if(l.key==="Backspace"&&!l.metaKey&&!l.ctrlKey&&!l.altKey&&t.selectionStart===t.selectionEnd){let c=t.selectionStart??-1;if(c>0&&t.value[c-1]==="["&&t.value[c]==="]"){l.preventDefault();let g=t.value.slice(0,c-1),p=t.value.slice(c+1);t.value=`${g}${p}`,t.setSelectionRange(c-1,c-1),t.dispatchEvent(new Event("input",{bubbles:!0}))}}});let i=document.createElement("div");i.className="stashpad-search-filter-row";let s=document.createElement("span");s.className="stashpad-search-filter-label",s.textContent="Filters:",i.appendChild(s);let n=document.createElement("button");n.className="stashpad-search-filter-chip",n.type="button",n.textContent="in:[parent note]",n.title='Insert "in:" \u2014 filter by parent note.',n.addEventListener("mousedown",l=>{l.preventDefault()}),n.addEventListener("click",l=>{l.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),n.click())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",l=>{l.preventDefault()}),o.addEventListener("click",l=>{l.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",l=>{(l.key==="Enter"||l.key===" ")&&(l.preventDefault(),l.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new vt.Scope(this.scope),r=l=>{let c=document.activeElement;return c?.classList?.contains("stashpad-search-filter-chip")?(l.preventDefault(),c.click(),!1):l.key==="Enter"&&!l.isComposing?(l.preventDefault(),this.selectActiveSuggestion?.(l),!1):!0};a.register([],"Enter",r),a.register([]," ",r),a.register(["Mod"],"f",l=>{l.preventDefault();let c=this.inputEl;return c&&(c.focus(),c.select()),!1}),a.register([],"Tab",l=>{let c=this.modalEl,g=this.inputEl;if(!c)return!0;let p=Array.from(c.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(u=>!u.hasAttribute("disabled")&&u.tabIndex!==-1&&u.offsetParent!==null);if(p.length===0)return!0;let d=document.activeElement,I=d?p.indexOf(d):-1;if(l.shiftKey){if(I<=0)return l.preventDefault(),p[p.length-1].focus(),!1}else if(I===p.length-1)return l.preventDefault(),(g??p[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(a),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(a)}catch{}})}appendFilterToInput(t,e,i){let s=t.value,o=`${s.length>0&&!/\s$/.test(s)?" ":""}${e}: [`,a="]",r=i;t.value=`${s}${o}${r}${a}`;let l=s.length+o.length+r.length;if(t.setSelectionRange(l,l+0),!r){let c=s.length+o.length;t.setSelectionRange(c,c)}t.focus(),t.dispatchEvent(new Event("input",{bubbles:!0}))}toggleWhenBuilder(t,e){let i=this.modalEl;if(this.whenBuilderEl){this.whenBuilderEl.remove(),this.whenBuilderEl=null,i?.removeClass("is-when-builder-open");return}i?.addClass("is-when-builder-open");let s=document.createElement("div");s.className="stashpad-when-builder";let n=document.createElement("div");n.className="stashpad-when-tabs";let o=[{id:"before",label:"Before"},{id:"on",label:"On"},{id:"after",label:"After"},{id:"between",label:"Between"}],a={};for(let u of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=u.label,this.whenMode===u.id&&f.addClass("is-active"),f.addEventListener("mousedown",C=>C.preventDefault()),f.addEventListener("click",C=>{if(C.preventDefault(),this.whenMode===u.id)return;let m=this.whenMode;m!=="between"&&u.id==="between"?this.whenBetweenEndText="":m==="between"&&u.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=u.id;for(let E in a)a[E].toggleClass("is-active",E===u.id);I()}),a[u.id]=f,n.appendChild(f)}s.appendChild(n);let r=document.createElement("div");r.className="stashpad-when-body",s.appendChild(r);let l=(u,f,C="single")=>{let m=St().format("YYYY-MM-DD"),E=!f||f===m;if(C==="betweenStart")return"00:00";if(C==="betweenEnd")return"23:59";switch(u){case"after":return"00:00";case"on":return E?St().format("HH:mm"):"23:59";case"before":return E?St().format("HH:mm"):"23:59";default:return"23:59"}},c=(u,f)=>{u.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},g=(u,f)=>{let C=u.selectionStart??u.value.length,m=u.selectionEnd??u.value.length,w=`${C>0&&!/\s$/.test(u.value.slice(0,C))?" ":""}${f}`,y=u.value.slice(0,C)+w+u.value.slice(m);u.value=y;let v=C+w.length;u.setSelectionRange(v,v),u.focus(),u.dispatchEvent(new Event("input",{bubbles:!0}))},p=(u,f)=>{let m=u.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return m?m[1]:null},d=(u,f,C,m)=>{let E=r.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=E.createDiv({cls:"stashpad-when-icon-slot"}),y=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});y.type="button",y.title="Pick date",(0,vt.setIcon)(y,"calendar-days");let v=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});v.tabIndex=-1;let S=E.createDiv({cls:"stashpad-when-icon-slot"}),M=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});M.type="button",M.title="Pick time",(0,vt.setIcon)(M,"clock");let F=E.createDiv({cls:"stashpad-when-icon-slot"}),N=F.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});N.type="button",N.title="Pick day",(0,vt.setIcon)(N,"calendar");let Q=E.createDiv({cls:"stashpad-when-icon-slot"}),D=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});D.type="button",D.title="Pick timeframe",(0,vt.setIcon)(D,"history");let K=E.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:u}});K.value=f(),K.addEventListener("input",()=>C(K.value));let x=E.createEl("button",{cls:"stashpad-when-clear"});x.type="button",x.textContent="\xD7",x.title="Clear";for(let U of[y,M,N,D,x])U.addEventListener("mousedown",tt=>tt.preventDefault());let Y=null,q=(U,tt)=>{Y&&Y();let O=U.createDiv({cls:"stashpad-when-popover"}),V=new vt.Scope(this.scope),rt=null,gt=ot=>{rt=ot},nt=!1,At=ot=>{!O.contains(ot.target)&&ot.target!==U&&!U.contains(ot.target)&<()},lt=()=>{if(!nt){nt=!0,O.remove(),document.removeEventListener("mousedown",At,!0);try{this.app.keymap?.popScope(V)}catch{}Y===lt&&(Y=null)}};Y=lt,V.register([],"Escape",ot=>(ot.preventDefault(),lt(),!1)),V.register([],"Enter",ot=>(ot.preventDefault(),rt&&rt(),!1));try{tt(O,lt,gt)}catch(ot){console.error("[stashpad] popover fill threw:",ot),O.remove(),Y=null;return}this.app.keymap?.pushScope(V),this.pendingCleanups.push(lt),setTimeout(()=>document.addEventListener("mousedown",At,!0),0)};D.addEventListener("click",U=>{U.preventDefault(),q(Q,(tt,O,V)=>{let rt=this.whenMode==="on",gt=(J,G)=>{if(!rt)return`${J}${G}`;let b={d:"days",w:"weeks",m:"months",y:"years"}[G];return St().subtract(J,b).format("YYYY-MM-DD")},nt=tt.createDiv({cls:"stashpad-when-pop-row"}),At=[{label:"Last 7d",n:7,unit:"d"},{label:"Last 30d",n:30,unit:"d"},{label:"This week",n:1,unit:"w"},{label:"This month",n:1,unit:"m"}];for(let J of At){let G=nt.createEl("button",{cls:"stashpad-when-pop-chip",text:J.label});G.type="button",G.addEventListener("mousedown",b=>b.preventDefault()),G.addEventListener("click",b=>{b.preventDefault(),g(K,gt(J.n,J.unit)),O()})}let lt=tt.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});lt.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let ot=lt.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),Qt=lt.createEl("select",{cls:"stashpad-when-pop-unit"});for(let J of[{v:"d",label:"days"},{v:"w",label:"weeks"},{v:"m",label:"months"},{v:"y",label:"years"}]){let G=Qt.createEl("option",{text:J.label});G.value=J.v}let ft=lt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ft.type="button";let B=()=>{let J=parseInt(ot.value,10);!Number.isFinite(J)||J<1||(g(K,gt(J,Qt.value)),O())};ft.addEventListener("mousedown",J=>J.preventDefault()),ft.addEventListener("click",J=>{J.preventDefault(),B()}),V(B),ot.focus(),ot.select()})});let _=(U,tt,O,V,rt)=>{q(tt,(gt,nt,At)=>{xi(gt,{seedH:O,seedM:V,seedPeriod:rt,close:nt,setOnEnter:At,onFinalize:lt=>g(U,Jn(lt))})})};N.addEventListener("click",U=>{U.preventDefault(),q(F,(tt,O,V)=>{let rt=tt.createDiv({cls:"stashpad-when-pop-row"});for(let ot of["Today","Yesterday"]){let Qt=rt.createEl("button",{cls:"stashpad-when-pop-chip",text:ot});Qt.type="button",Qt.addEventListener("mousedown",ft=>ft.preventDefault()),Qt.addEventListener("click",ft=>{ft.preventDefault(),g(K,ot),O()})}let gt=tt.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),nt=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],lt=(St().day()+6)%7;for(let ot=0;ot<nt.length;ot++){let Qt=nt[ot],ft=gt.createEl("button",{cls:"stashpad-when-pop-chip",text:Qt.slice(0,3)});ft.type="button",ft.title=Qt,ot===lt&&ft.addClass("is-today"),ft.addEventListener("mousedown",B=>B.preventDefault()),ft.addEventListener("click",B=>{if(B.preventDefault(),m==="betweenEnd"){let J=ot,G=St().startOf("day"),b=(G.day()+6)%7,k=(J-b+7)%7;k===0&&(k=7);let H=G.clone().add(k,"days").format("YYYY-MM-DD");g(K,H)}else g(K,Qt);O()})}})});let L=(U,tt)=>{U.value||(U.value=tt);let O=U;if(typeof O.showPicker=="function")try{O.showPicker();return}catch{}U.focus(),U.click()};return y.addEventListener("click",U=>{U.preventDefault(),L(v,St().format("YYYY-MM-DD"))}),v.addEventListener("change",()=>{v.value&&g(K,v.value)}),M.addEventListener("click",U=>{U.preventDefault();let tt=K.selectionStart??K.value.length,O=p(K.value,tt),V=l(this.whenMode,O,m),[rt,gt]=V.split(":"),nt=parseInt(rt,10),At=parseInt(gt,10),lt=nt%12;lt===0&&(lt=12);let ot=nt>=12?"pm":"am";_(K,S,lt,At,ot)}),x.addEventListener("click",U=>{U.preventDefault(),K.value="",C(""),K.focus()}),K},I=()=>{if(r.empty(),this.whenMode==="between"){let u=d("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=d("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),C=r.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",y=>y.preventDefault());let E=()=>{let y=u.value.trim(),v=f.value.trim();y&&this.appendFilterToInput(t,"after",y),v&&this.appendFilterToInput(t,"before",v),this.closeWhenBuilder()};m.addEventListener("click",y=>{y.preventDefault(),E()});let w=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",y=>y.preventDefault()),w.addEventListener("click",y=>{y.preventDefault(),this.closeWhenBuilder()}),c(u,E),c(f,E),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}else{let u=d("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),f=r.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",w=>w.preventDefault());let m=()=>{let w=u.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};C.addEventListener("click",w=>{w.preventDefault(),m()});let E=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});E.type="button",E.addEventListener("mousedown",w=>w.preventDefault()),E.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),c(u,m),u.focus(),u.setSelectionRange(u.value.length,u.value.length)}};I(),e.parentElement?.insertBefore(s,e.nextSibling),this.whenBuilderEl=s}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}selectSuggestion(t,e){if(t&&t.kind==="search-excluded"){this.loadExcludedNotes();return}super.selectSuggestion(t,e)}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}if(t.kind==="folder-open"&&t.id==="__folder_picker__"){let e=this.opts.folderResults?.()??[];if(!e.length)return;let i=this.inputEl?.value??"",s=!1,n=p=>{s=!0;let d=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${d}\u201D in a new tab`,node:null,kind:"folder-open",folder:p})},o=new En(this.app,e,n),a=o.onClose.bind(o),r=this.tree,l=this.titleFn,c=this.opts,g=this.app;o.onClose=()=>{if(a(),!s){let p=new h(g,r,l,c);p.open(),setTimeout(()=>{let d=p.inputEl;d&&(i&&(d.value=i,d.dispatchEvent(new Event("input",{bubbles:!0}))),d.focus(),d.setSelectionRange(d.value.length,d.value.length))},0)}},o.open();return}this.opts.onPick(t)}},En=class extends vt.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 Ho=require("obsidian");yt();var hs=class extends Ho.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:ar(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(A){return this.commands.filter(t=>bi(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 ar(h){return h.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||h}Tt();var yn=require("obsidian");function rr(h,A){return!A||h.metaKey||h.ctrlKey||h.altKey?!1:h.key.toLowerCase()===A.toLowerCase()}function Ve(h,A){return A?A.includes("+")?Ar(h,A):rr(h,A):!1}function st(h,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?Ve(h,t)||Ve(h,e):i?Ve(h,e):Ve(h,t):Ve(h,t)||Ve(h,e)}function wi(h){if(!h)return"";let A=yn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return h.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function Ar(h,A){if(!A)return!1;let t=A.split("+").map(g=>g.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(g=>g.toLowerCase())),s=i.has("mod"),n=i.has("ctrl")||i.has("control"),o=i.has("cmd")||i.has("meta")||i.has("command"),a=i.has("alt")||i.has("option"),r=i.has("shift"),c=yn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?h.metaKey:h.ctrlKey;return s&&!c||n&&!h.ctrlKey||o&&!h.metaKey||a!==h.altKey||r!==h.shiftKey||!s&&(!n&&h.ctrlKey||!o&&h.metaKey)?!1:h.key.toLowerCase()===e}var De=require("obsidian");Tt();var Pt=class Pt{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 De.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 De.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 De.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let d=this.host.app.metadataCache.getFileCache(p)?.frontmatter,I=typeof d?.author=="string"?d.author:"";if(!I.trim()){s.push(p.path);continue}if(I.includes(e)||!A.contributorMode)continue;(Array.isArray(d?.contributors)?d.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(p.path)}let o=s.length+n.length;if(o===0){new De.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(A.scope==="folder"){let p=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&p.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(I=>{new Ft(this.host.app,"Claim authorship",`${p.join(" ")}? +Existing authors are never overwritten. This can be undone.`,"Claim",I).open()}))return}let a=this.host.noteFolder,r=t.link,l=new Set,c=async()=>{await this.pacedFrontmatter(s,(p,d)=>{typeof p.author=="string"&&p.author.trim()||(p.author=r),Array.isArray(p.contributors)&&p.contributors.some(I=>typeof I=="string"&&I.includes(e))&&(p.contributors=p.contributors.filter(I=>!(typeof I=="string"&&I.includes(e))),l.add(d))}),await this.pacedFrontmatter(n,p=>{let d=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];d.some(I=>I.includes(e))||d.push(r),p.contributors=d})};this.ensureAuthorFile(t),await c(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(p,d)=>{if(typeof p.author=="string"&&p.author.includes(e)&&delete p.author,l.has(d)){let I=Array.isArray(p.contributors)?p.contributors.filter(u=>typeof u=="string"):[];I.some(u=>u.includes(e))||I.push(r),p.contributors=I}}),await this.pacedFrontmatter(n,p=>{Array.isArray(p.contributors)&&(p.contributors=p.contributors.filter(d=>!(typeof d=="string"&&d.includes(e))))}),this.host.debouncedRender()},redo:async()=>{l.clear(),await c(),this.host.debouncedRender()}});let g=[];s.length&&g.push(`authored ${s.length}`),n.length&&g.push(`contributing to ${n.length}`),new De.Notice(`Claimed authorship: ${g.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(A){try{A.id&&this.host.plugin.authorRegistry.record({id:A.id,name:A.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(A.path))return;let e=A.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:A.id,name:A.name,role:e?this.host.plugin.settings.authorRole:void 0,department:e?this.host.plugin.settings.authorDepartment:void 0},new Date().toISOString());await this.host.app.vault.create(A.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(A){let t=new Set,e=i=>{if(typeof i!="string")return null;let s=i.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return s?s[1]:null};for(let i of A){if(!i.file)continue;let s=this.host.app.metadataCache.getFileCache(i.file)?.frontmatter;if(!s)continue;let n=e(s.author);if(n&&t.add(n),Array.isArray(s.contributors))for(let o of s.contributors){let a=e(o);a&&t.add(a)}}return Array.from(t)}pruneContribMaps(){let A=Date.now(),t=Pt.EXTERNAL_WRITE_GRACE_MS*20,e=Pt.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<Pt.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=Pt.CONTRIB_DEBOUNCE_MS+(e?Pt.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<Pt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(A);return}this.maybeRecordContribution(A)},i);this.contribTimers.set(A.path,s)}isFileActivelyEdited(A){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==A.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(A){let t="";try{t=await this.host.app.vault.cachedRead(A)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(A.path);if(this.knownBodies.set(A.path,e),i===void 0||i===e||this.host.plugin.rebootstrapInProgress)return;let s=this.currentAuthorLink();if(!s)return;this.ensureAuthorFile(s);let n=new Date().toISOString();this.recentSelfWrites.set(A.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(A,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],l=`-${s.id}`,c=a.includes(l),g=r.some(p=>p.includes(l));!c&&!g&&r.push(s.link),o.contributors=r})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Pt.CONTRIB_DEBOUNCE_MS=4e3,Pt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Pt.EXTERNAL_WRITE_GRACE_MS=1500,Pt.EXTERNAL_QUIESCENCE_MS=5e3;var gs=Pt;var ps=class{constructor(A){this.host=A;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(A,t,e){A.addEventListener("dragstart",i=>{let s=this.host.selection.has(t.id)&&this.host.selection.size>1?[...this.host.selection]:[t.id];if(this.dragSourceIds=s,this.dragRowHeight=A.offsetHeight,A.addClass("is-dragging"),this.host.listEl&&(this.dragPlaceholder=this.host.listEl.createDiv({cls:"stashpad-drop-placeholder"}),this.dragPlaceholder.style.height="0px",this.dragPlaceholder.addEventListener("dragover",n=>{this.dragSourceIds&&(n.preventDefault(),n.dataTransfer&&(n.dataTransfer.dropEffect="move"))}),this.dragPlaceholder.addEventListener("drop",n=>{if(!this.dragSourceIds||!this.dragPlaceholder)return;n.preventDefault(),n.stopPropagation();let o=this.dragSourceIds.slice();this.dragSourceIds=null;let a=this.dragPlaceholder.nextElementSibling,r=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let l,c="before";a&&a.classList.contains("stashpad-note")?(l=a.dataset.id,c="before"):r&&r.classList.contains("stashpad-note")&&(l=r.dataset.id,c="after"),l&&this.host.reorderToTarget(o,l,c)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(A,12,12)}catch{}}}),A.addEventListener("dragend",()=>{A.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),A.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,A);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),A.addClass("drop-into")):(A.removeClass("drop-into"),this.placePlaceholder(A,s==="drop-above"?"before":"after"))}),A.addEventListener("dragleave",i=>{let s=A.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&A.removeClass("drop-into")}),A.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,A);this.clearDropIndicators(),this.removeDragPlaceholder(),A.removeClass("is-dragging"),n==="drop-into"?this.host.reorderToTarget(s,t.id,"into"):this.host.reorderToTarget(s,t.id,n==="drop-above"?"before":"after")})}attachListDnD(A){A.addEventListener("dragover",t=>{if(!this.dragSourceIds)return;let e=t.target;if(e&&e.closest&&e.closest(".stashpad-note"))return;t.preventDefault(),t.dataTransfer&&(t.dataTransfer.dropEffect="move");let i=Array.from(A.querySelectorAll(".stashpad-note"));if(i.length!==0){for(let s of i){let n=s.getBoundingClientRect();if(t.clientY<n.top+n.height/2){this.placePlaceholder(s,"before");return}}this.placePlaceholder(i[i.length-1],"after")}}),A.addEventListener("drop",t=>{if(!this.dragSourceIds)return;t.preventDefault();let e=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let i=this.dragPlaceholder.nextElementSibling,s=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),i&&i.classList.contains("stashpad-note")){let n=i.dataset.id;n&&this.host.reorderToTarget(e,n,"before")}else if(s&&s.classList.contains("stashpad-note")){let n=s.dataset.id;n&&this.host.reorderToTarget(e,n,"after")}})}placePlaceholder(A,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?A:A.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===A||t==="after"&&this.dragPlaceholder.previousSibling===A)return;let i=!!this.dragPlaceholder.parentElement;this.host.listEl.insertBefore(this.dragPlaceholder,e),this.dragPlaceholder.style.opacity="1",i?this.dragPlaceholder.style.height=`${this.dragRowHeight}px`:(this.dragPlaceholder.style.height="0px",this.dragPlaceholder.offsetHeight,this.dragPlaceholder.style.height=`${this.dragRowHeight}px`)}removeDragPlaceholder(){if(!this.dragPlaceholder?.parentElement)return;let A=this.dragPlaceholder;A.style.height="0px",A.style.opacity="0",setTimeout(()=>{A.parentElement&&A.remove()},150)}dropZone(A,t){let e=t.getBoundingClientRect(),i=A.clientY-e.top;return i<e.height*.3?"drop-above":i>e.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.host.listEl)for(let A of Array.from(this.host.listEl.querySelectorAll(".drop-into")))A.removeClass("drop-into")}};var Uo=require("obsidian");var Is=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 Nt.record("render.row.cacheHit",0),t;let e=await Nt.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 Nt.timeAsync("render.row.markdown",()=>Uo.MarkdownRenderer.render(this.host.app,s,o,A.path,this.component));let a=o.innerHTML,r={mtime:A.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(A.path,r),r}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(A=>{for(let t of A){if(!t.isIntersecting)continue;let e=t.target,i=this.lazyBodies.get(e);this.bodyObserver?.unobserve(e),this.lazyBodies.delete(e),i&&i()}},{root:this.host.contentEl,rootMargin:"1400px 0px"})}dispose(){this.bodyObserver?.disconnect(),this.bodyObserver=null}isArmed(){return!!this.bodyObserver}hasFreshRenderCache(A){let t=this.renderCache.get(A.path);return!!t&&t.mtime===A.stat.mtime}defer(A,t){this.lazyBodies.set(A,t),this.bodyObserver?.observe(A)}splitAttachments(A){let t=[];return{text:A.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` -`).trim(),attachments:t}}};function Ro(h,A,t){return h.tree.getChildren(A).slice().sort((i,s)=>lr(h,i,s,t)).map(i=>i.id)}function lr(h,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=Po(h,A)||A.created||"",s=Po(h,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=h.titleForNode(A),s=h.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function Po(h,A){if(!A.file)return"";let t=h.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var ze=require("obsidian");var Go=require("obsidian");function ge(h,A,t){h.empty();try{(0,Go.setIcon)(h,A)}catch{}let e=h.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(h.empty(),h.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Lo(h){if(h instanceof Element&&h.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);h instanceof Element&&h.ownerDocument&&A.add(h.ownerDocument);for(let t of A)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}function Jo(h){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(h))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function wi(h){return h.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function qo(h,A,t){let e=new Set(A),i=h.filter(n=>!e.has(n)),s=h.findIndex(n=>e.has(n));if(s<0)return h.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let l=-1;return h.forEach((c,g)=>{e.has(c)&&(l=g)}),l})(),o=0;for(let l=0;l<Math.min(h.length,n+2);l++)e.has(h[l])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function En(h,A){if(h.length!==A.length)return!1;for(let t=0;t<h.length;t++)if(h[t]!==A[t])return!1;return!0}async function yn(h){let A=h.getActionTargets();if(!A.length)return;let t=It().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await h.app.vault.cachedRead(i.file),n=h.stripFrontmatter(s).trim();e.push(t?`${h.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function Ro(h,A,t){return h.tree.getChildren(A).slice().sort((i,s)=>lr(h,i,s,t)).map(i=>i.id)}function lr(h,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=Po(h,A)||A.created||"",s=Po(h,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=h.titleForNode(A),s=h.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function Po(h,A){if(!A.file)return"";let t=h.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var We=require("obsidian");var Go=require("obsidian");function ge(h,A,t){h.empty();try{(0,Go.setIcon)(h,A)}catch{}let e=h.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(h.empty(),h.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Lo(h){if(h instanceof Element&&h.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);h instanceof Element&&h.ownerDocument&&A.add(h.ownerDocument);for(let t of A)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}function Jo(h){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(h))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function vi(h){return h.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function qo(h,A,t){let e=new Set(A),i=h.filter(n=>!e.has(n)),s=h.findIndex(n=>e.has(n));if(s<0)return h.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let l=-1;return h.forEach((c,g)=>{e.has(c)&&(l=g)}),l})(),o=0;for(let l=0;l<Math.min(h.length,n+2);l++)e.has(h[l])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function wn(h,A){if(h.length!==A.length)return!1;for(let t=0;t<h.length;t++)if(h[t]!==A[t])return!1;return!0}async function vn(h){let A=h.getActionTargets();if(!A.length)return;let t=pt().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await h.app.vault.cachedRead(i.file),n=h.stripFrontmatter(s).trim();e.push(t?`${h.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` -`)),h.plugin.notifications.show({message:`Copied ${h.titleList(A)} to clipboard`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}async function Oo(h){let A=h.getActionTargets();if(!A.length||!A[0].file){new ze.Notice("Nothing to copy from.");return}let t=A[0],e=await h.app.vault.cachedRead(t.file),i=h.stripFrontmatter(e),s=Jo(i);if(s.length===0){h.plugin.notifications.show({message:`No codeblock found in "${h.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),h.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}let n=s.map((a,r)=>({kind:"one",idx:r,label:`${r+1}. ${a.lang||"(no language)"} \u2014 ${a.code.split(` +`)),h.plugin.notifications.show({message:`Copied ${h.titleList(A)} to clipboard`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}async function Oo(h){let A=h.getActionTargets();if(!A.length||!A[0].file){new We.Notice("Nothing to copy from.");return}let t=A[0],e=await h.app.vault.cachedRead(t.file),i=h.stripFrontmatter(e),s=Jo(i);if(s.length===0){h.plugin.notifications.show({message:`No codeblock found in "${h.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),h.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}let n=s.map((a,r)=>({kind:"one",idx:r,label:`${r+1}. ${a.lang||"(no language)"} \u2014 ${a.code.split(` `)[0].slice(0,60)}${a.code.includes(` -`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends ze.SuggestModal{getSuggestions(a){let r=a.trim().toLowerCase();if(!r)return n;let l=r.split(/\s+/).filter(Boolean);return n.filter(c=>{let g=c.label.toLowerCase();return l.every(p=>g.includes(p))})}renderSuggestion(a,r){r.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let r=a.kind==="all"?s.map(l=>l.code).join(` +`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends We.SuggestModal{getSuggestions(a){let r=a.trim().toLowerCase();if(!r)return n;let l=r.split(/\s+/).filter(Boolean);return n.filter(c=>{let g=c.label.toLowerCase();return l.every(p=>g.includes(p))})}renderSuggestion(a,r){r.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let r=a.kind==="all"?s.map(l=>l.code).join(` -`):s[a.idx].code;await navigator.clipboard.writeText(r),h.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${h.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder})}}(h.app);o.setPlaceholder(`${s.length} codeblocks in "${h.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function Ko(h){let A=h.getActionTargets();if(A.length===0){let n=h.tree.get(h.focusId);n?.file&&(A=[n])}if(A.length===0){new ze.Notice("Nothing to copy.");return}let t=It().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await h.app.vault.cachedRead(n.file),r=h.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),l=t?`${h.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${l}${r}`)}for(let a of h.tree.getChildren(n.id))await i(a,o+1)};for(let n of A)await i(n,0);let s=e.join(` -`);await navigator.clipboard.writeText(s),h.plugin.clearNoteClipboard(),h.plugin.noteClipboard={mode:"copy",folder:h.noteFolder,ids:A.map(n=>n.id),text:s},h.render(),h.plugin.notifications.show({message:`Copied tree of ${h.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:h.noteFolder})}async function Yo(h){let A=h.getActionTargets();if(A.length===0){let i=h.tree.get(h.focusId);i?.file&&(A=[i])}if(A.length===0){new ze.Notice("Nothing to copy.");return}let t=[],e=(i,s)=>{if(!i.file)return;let n=" ".repeat(s);t.push(`${n}- ![[${i.file.basename}]]`);for(let o of h.tree.getChildren(i.id))e(o,s+1)};for(let i of A)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),h.plugin.notifications.show({message:`Copied outline of ${h.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}var pe=require("obsidian");yt();xi();Ht();function dr(h){return h.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function zo(h,A){let t=gr(h,A);if(t.length===0){new pe.Notice("Nothing to export.");return}let e=pr(h,t);if(e.length===0){new pe.Notice("No exportable notes (no files attached).");return}let i=(h.noteFolder.split("/").pop()||h.noteFolder).trim(),s=t.length===1?h.titleForNode(t[0]):`${i}-${t.length}notes`;new ei(h.app,s,e.length,(n,o,a)=>{hr(h,t,e,n,o,a)},Yi).open()}async function hr(h,A,t,e,i,s=!1){try{let n=await Bi(h.app,{rootNotes:A.filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),allDescendants:t.filter(d=>!A.some(I=>I.id===d.id)).filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),sourceFolder:h.noteFolder}),o="";if(i){let d=await ui(n,i);n=d.data;let I=ao[d.kdf];o=I.strong?` (encrypted \xB7 ${I.label})`:` (encrypted \xB7 ${I.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,pe.moment)().format("YYYYMMDD-HHmmss"),r=dr(e),l=(h.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${h.noteFolder}/${l}`;await h.ensureFolder(c);let g=`${r}-${a}`,p=`${c}/${g}.${ae}`;if(await h.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let d=h.app.secretStorage;try{d?.setSecret(_e(g),i)}catch(I){console.warn("[Stashpad] couldn't save export passphrase to secret storage",I)}}await h.log.append({type:"stash_export",id:A[0].id,payload:{path:p,noteCount:t.length,rootIds:A.map(d=>d.id)}}),h.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:h.noteFolder,actions:h.actionsForFile(p),duration:0})}catch(n){h.plugin.notifications.show({message:`Stashpad: export failed +`):s[a.idx].code;await navigator.clipboard.writeText(r),h.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${h.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder})}}(h.app);o.setPlaceholder(`${s.length} codeblocks in "${h.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function Ko(h){let A=h.getActionTargets();if(A.length===0){let n=h.tree.get(h.focusId);n?.file&&(A=[n])}if(A.length===0){new We.Notice("Nothing to copy.");return}let t=pt().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await h.app.vault.cachedRead(n.file),r=h.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),l=t?`${h.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${l}${r}`)}for(let a of h.tree.getChildren(n.id))await i(a,o+1)};for(let n of A)await i(n,0);let s=e.join(` +`);await navigator.clipboard.writeText(s),h.plugin.clearNoteClipboard(),h.plugin.noteClipboard={mode:"copy",folder:h.noteFolder,ids:A.map(n=>n.id),text:s},h.render(),h.plugin.notifications.show({message:`Copied tree of ${h.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:h.noteFolder})}async function Yo(h){let A=h.getActionTargets();if(A.length===0){let i=h.tree.get(h.focusId);i?.file&&(A=[i])}if(A.length===0){new We.Notice("Nothing to copy.");return}let t=[],e=(i,s)=>{if(!i.file)return;let n=" ".repeat(s);t.push(`${n}- ![[${i.file.basename}]]`);for(let o of h.tree.getChildren(i.id))e(o,s+1)};for(let i of A)e(i,0);await navigator.clipboard.writeText(t.join(` +`)),h.plugin.notifications.show({message:`Copied outline of ${h.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}var pe=require("obsidian");yt();Mi();Tt();function dr(h){return h.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function zo(h,A){let t=gr(h,A);if(t.length===0){new pe.Notice("Nothing to export.");return}let e=pr(h,t);if(e.length===0){new pe.Notice("No exportable notes (no files attached).");return}let i=(h.noteFolder.split("/").pop()||h.noteFolder).trim(),s=t.length===1?h.titleForNode(t[0]):`${i}-${t.length}notes`;new si(h.app,s,e.length,(n,o,a)=>{hr(h,t,e,n,o,a)},zi).open()}async function hr(h,A,t,e,i,s=!1){try{let n=await ke(h.app,{rootNotes:A.filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),allDescendants:t.filter(d=>!A.some(I=>I.id===d.id)).filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),sourceFolder:h.noteFolder}),o="";if(i){let d=await Ci(n,i);n=d.data;let I=Ao[d.kdf];o=I.strong?` (encrypted \xB7 ${I.label})`:` (encrypted \xB7 ${I.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,pe.moment)().format("YYYYMMDD-HHmmss"),r=dr(e),l=(h.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${h.noteFolder}/${l}`;await h.ensureFolder(c);let g=`${r}-${a}`,p=`${c}/${g}.${ae}`;if(await h.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let d=h.app.secretStorage;try{d?.setSecret(ti(g),i)}catch(I){console.warn("[Stashpad] couldn't save export passphrase to secret storage",I)}}await h.log.append({type:"stash_export",id:A[0].id,payload:{path:p,noteCount:t.length,rootIds:A.map(d=>d.id)}}),h.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:h.noteFolder,actions:h.actionsForFile(p),duration:0})}catch(n){h.plugin.notifications.show({message:`Stashpad: export failed Error: ${n.message} -Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function gr(h,A){if(A?.file)return[A];if(h.selection.size>0)return[...h.selection].map(e=>h.tree.get(e)).filter(e=>!!e?.file);if(h.cursorIdx>=0&&h.currentChildren[h.cursorIdx])return[h.currentChildren[h.cursorIdx]];let t=h.tree.get(h.focusId);return t?.file?[t]:[]}function pr(h,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of h.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function Vo(h){let A=h.app.vault.getFiles().filter(e=>e.extension===ae);if(A.length===0){new pe.Notice("No .stash files found in this vault.");return}let t=new class extends pe.FuzzySuggestModal{getItems(){return A}getItemText(e){return e.path}onChooseItem(e){wn(h,e)}}(h.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function wn(h,A){try{let t=new Uint8Array(await h.app.vault.readBinary(A)),e=await Re(h.app,t,{secretId:_e(A.basename)});if(!e)return;let i=await _t(h.app,e,h.noteFolder,Ir(h));h.tree.rebuild(h.noteFolder),h.render(),await h.log.append({type:"stash_import",id:M,payload:{from:A.path,into:h.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await h.app.fileManager.trashFile(A)}catch{}h.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),h.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:h.noteFolder})}catch(t){h.plugin.notifications.show({message:`Stashpad: import failed +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function gr(h,A){if(A?.file)return[A];if(h.selection.size>0)return[...h.selection].map(e=>h.tree.get(e)).filter(e=>!!e?.file);if(h.cursorIdx>=0&&h.currentChildren[h.cursorIdx])return[h.currentChildren[h.cursorIdx]];let t=h.tree.get(h.focusId);return t?.file?[t]:[]}function pr(h,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of h.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function Vo(h){let A=h.app.vault.getFiles().filter(e=>e.extension===ae);if(A.length===0){new pe.Notice("No .stash files found in this vault.");return}let t=new class extends pe.FuzzySuggestModal{getItems(){return A}getItemText(e){return e.path}onChooseItem(e){Fn(h,e)}}(h.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Fn(h,A){try{let t=new Uint8Array(await h.app.vault.readBinary(A)),e=await Le(h.app,t,{secretId:ti(A.basename)});if(!e)return;let i=await zt(h.app,e,h.noteFolder,Ir(h));h.tree.rebuild(h.noteFolder),h.render(),await h.log.append({type:"stash_import",id:T,payload:{from:A.path,into:h.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await h.app.fileManager.trashFile(A)}catch{}h.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),h.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:h.noteFolder})}catch(t){h.plugin.notifications.show({message:`Stashpad: import failed File: \`${A.name}\` Error: ${t.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[A.path],actions:h.actionsForFile(A.path)}),console.error(t)}}function Ir(h){let A=new Set,t=e=>{if(A.add(e),!!h.tree.get(e))for(let s of h.tree.getChildren(e))t(s.id)};return t(M),A}var fr=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),ps={nested:"Nested",flat:"Flat",everything:"Everything"},Is=[{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"}],us=class extends P.ItemView{constructor(t,e){super(t);this.focusId=M;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.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.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||Lo(t.target))return;let e=It().bindings;if(st(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(st(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(st(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(st(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(st(t,e.lockSelection)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdLockSelection();return}if(st(t,e.unlockAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUnlockAll();return}if(st(t,e.moveToArchive)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToArchive();return}if(st(t,e.encryptDelete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdEncryptDelete();return}if(st(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(st(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(st(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(st(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(st(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let i=t.target,s=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!s){let r=this.composerInputEl;if(r){t.preventDefault(),t.stopPropagation(),r.focus();let l=r.value.length;r.setSelectionRange(l,l);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let r=this.listEl,l=!!r&&r.scrollTop+r.clientHeight>=r.scrollHeight-2,c=r?.scrollTop??0;if(this.render(),r){let g=l?r.scrollHeight:c;r.scrollTop=g,requestAnimationFrame(()=>{r.scrollTop=l?r.scrollHeight:c}),setTimeout(()=>{r.scrollTop=l?r.scrollHeight:c},60),this.revealCursorRow()}return}if(this.inListPicker&&!n){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,-1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}if(st(t,It().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(st(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(st(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(st(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(st(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(st(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(st(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(st(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(st(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(st(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(st(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(st(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(st(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let r=this.composerInputEl;if(r){r.focus();let l=r.value.length;r.setSelectionRange(l,l)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let r=this.currentChildren[this.cursorIdx];r&&(t.preventDefault(),this.navigateTo(r.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return;if(this.plugin.noteClipboard&&this.plugin.noteClipboard.folder===this.noteFolder){this.plugin.clearNoteClipboard(),this.render();return}let r=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,r){let l=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,l>=0&&(this.cursorIdx=l)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=It().bindings;if(st(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(st(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(st(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(st(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(st(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(st(t,o.copyNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyNotes();return}if(st(t,o.cutNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCutNotes();return}if(st(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(st(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(st(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(st(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let r=this.tree.get(this.focusId);r?.file&&this.cmdOpenInEditor(r)}else this.cmdOpenInEditor();return}if(st(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(st(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(st(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(st(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(st(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(st(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(st(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(st(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(st(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(st(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(st(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(st(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.openSearchInstance=null;this.fmSyncUnsubscribe=null;this.completedState=new Map;this.taskTaggedState=new Map;this.pendingFocusIds=null;this.onFileModify=t=>{!(t instanceof P.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 P.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 ls(this.tree,this.log),this.order=new qe(this.app),this.sortStore=new os(this.app),this.fmSync=new rs(this.app,()=>this.tree),this.tree.setOrderProvider(i=>{let s=this.noteFolder,n=this.sortStore.getMode(s,i);return n==="manual"?this.order.getOrder(s,i):Ro(this,i,n)}),this.debouncedRender=(0,P.debounce)(()=>this.render(),80),this.authorship=new ds(this),this.dnd=new hs(this),this.bodyRenderer=new gs(this,this,this.plugin.renderCacheStore)}getViewType(){return ct}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==M){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",()=>_i(this)),this.viewRoot.addEventListener("click",()=>_i(this)),this.viewRoot.addEventListener("mouseup",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),_i(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new P.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.inListPicker)return this.inListPicker=null,this.pickerEscapeAt=Date.now(),this.repaintSelectionClasses(),!1;if(Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return!1;if(this.selection.size>1){let r=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,r){let l=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,l>=0&&(this.cursorIdx=l)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",r=>{let l=r.relatedTarget;l&&this.viewRoot&&this.viewRoot.contains(l)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",r=>{if(r.extension!=="md")return;let l=this.app.metadataCache.getFileCache(r)?.frontmatter;this.completedState.set(r.path,!!l?.completed),this.taskTaggedState.set(r.path,this.taggedFromFm(l))})),this.registerEvent(this.app.vault.on("rename",(r,l)=>{for(let c of[this.completedState,this.taskTaggedState])c.has(l)&&(c.set(r.path,c.get(l)),c.delete(l))})),this.registerEvent(this.app.vault.on("delete",r=>{this.completedState.delete(r.path),this.taskTaggedState.delete(r.path)})),this.detachSettings=bo(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",l=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&l===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&l!==""&&(this.composerDraft=l),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(r){let l=r?.message??"";/already exists/i.test(l)||console.warn("[Stashpad] bootstrapFolder failed:",r)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let r=this.plugin.loadLastCursor(this.noteFolder);for(let[l,c]of r)this.lastCursorByFocus.set(l,c);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let n=this.lastCursorByFocus.get(this.focusId),o;n&&this.tree.get(n)?(o={kind:"scroll-to-id",id:n,align:"start"},this.pendingFocusIds=[n]):(this.scrollToBottomOnNextRender=!0,o={kind:"pin-bottom",until:"next-user-input"});let a=this.foldRestoredSelection(n);a&&(this.pendingFocusIds=a),this.render(o),this.scheduleSelectionRestore(),this.tinyMode&&(setTimeout(()=>this.applyTinyWindow(),1e3),setTimeout(()=>this.applyTinyWindow(),1500)),this.registerDomEvent(window,"beforeunload",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.registerDomEvent(window,"blur",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.focusComposer(),this.registerEvent(this.app.workspace.on("active-leaf-change",r=>{r===this.leaf?this.focusComposer():this.stickToListBottom=!1}))}scheduleTreeReconcile(){this.treeReconcileTimer==null&&(this.treeReconcileTimer=window.setTimeout(()=>{if(this.treeReconcileTimer=null,!this.viewRoot?.isConnected)return;let t=this.noteFolder,e=t+"/",i=0;for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!(n===t||t!==""&&n.startsWith(e)))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.id;typeof o=="string"&&o&&i++}i!==this.tree.fileBackedCount()&&(this.tree.rebuild(t),this.debouncedRender())},400))}focusView(){requestAnimationFrame(()=>{this.viewRoot?.isConnected&&(document.activeElement instanceof HTMLElement&&(document.activeElement.tagName==="INPUT"||document.activeElement.tagName==="TEXTAREA")||this.viewRoot.focus({preventScroll:!0}))})}focusComposer(){if(!It().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(){ko(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.bodyRenderer.dispose(),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();this.authorship.dispose();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear(),this.lastSelectionByFocus.clear();try{let l=this.plugin.loadLastCursor(this.noteFolder);for(let[c,g]of l)this.lastCursorByFocus.set(c,g);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let o=this.lastCursorByFocus.get(this.focusId),a;o&&this.tree.get(o)?(this.pendingFocusIds=[o],a={kind:"scroll-to-id",id:o,align:"start"}):a={kind:"pin-bottom",until:"next-user-input"};let r=this.foldRestoredSelection(o);r&&(this.pendingFocusIds=r),this.render(a),this.scheduleSelectionRestore()}}focus(){this.viewRoot?.focus({preventScroll:!0})}foldRestoredSelection(t){let e=this.lastSelectionByFocus.get(this.focusId)??null;if(!e||!e.length)return null;let i=e.filter(s=>!!this.tree.get(s));return i.length?t&&i.includes(t)?[t,...i.filter(s=>s!==t)]:i:null}stampSelection(t=!1){let e=[...this.selection],i=()=>{try{this.plugin.saveLastSelection(this.noteFolder,this.focusId,e)}catch{}};if(this.stampSelectionTimer!=null&&(window.clearTimeout(this.stampSelectionTimer),this.stampSelectionTimer=null),t){i();return}this.stampSelectionTimer=window.setTimeout(()=>{this.stampSelectionTimer=null,i()},400)}scheduleSelectionRestore(){let t=this.lastSelectionByFocus.get(this.focusId);if(!t||!t.length)return;let e=()=>{let i=t.filter(a=>this.currentChildren.some(r=>r.id===a));if(!i.length)return;let s=[...this.selection],n=new Set(i);if(s.length<i.length&&s.every(a=>n.has(a))){this.selection.clear();for(let a of i)this.selection.add(a);this.firstSelectedId=i[0],this.lastSelected=i[i.length-1],this.repaintSelectionClasses()}};for(let i of[120,400,900,1600])window.setTimeout(e,i)}loadConfig(){let t=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),i=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"Stashpad";i!==this.noteFolder?(this.noteFolder=i,this.tree.rebuild(this.noteFolder)):this.noteFolder=i}captureNavSnapshot(){return{folder:this.noteFolder,focusId:this.focusId}}recordNavState(t={}){let e=this.captureNavSnapshot(),i=this.navBackStack[this.navBackStack.length-1];i&&i.folder===e.folder&&i.focusId===e.focusId||(this.navBackStack.push(e),t.keepForward||(this.navForwardSnapshots=[]))}async setFolderOverride(t,e={}){let i=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(i&&this.isReservedFolder(i)){new P.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=M,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 P.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 P.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 P.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Redo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let i=[],s=new Set;for(let r of t)!r.file||s.has(r.file.path)||(s.add(r.file.path),i.push(r.file));let n=await Promise.all(i.map(r=>this.app.vault.read(r))),o=i.map((r,l)=>({path:r.path,content:n[l]})),a=[];if(e){let r=new Set,l=[];for(let g of n)for(let p of this.extractAttachments(this.stripFrontmatter(g))){let d=this.app.metadataCache.getFirstLinkpathDest(p,"");d&&!r.has(d.path)&&(r.add(d.path),l.push(d))}let c=await Promise.all(l.map(g=>this.app.vault.readBinary(g)));for(let g=0;g<l.length;g++)a.push({path:l[g].path,data:c[g]})}return{notes:o,attachments:a}}async restoreSnapshots(t,e){for(let s of t.attachments)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.createBinary(s.path,s.data)}catch{}for(let s of t.notes)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.create(s.path,s.content)}catch{}let i=()=>{e&&e.some(n=>this.tree.get(n))&&(this.pendingFocusIds=e.slice())};i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"}),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},100),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},400),setTimeout(()=>{for(let s of t.notes){let n=this.tree.idForPath(s.path);n&&this.fmSync.schedule(n)}},500)}async trashNotesAndAttachments(t){let e=new Set;for(let i of t.notes){let s=this.tree.idForPath(i.path);if(!s)continue;let n=this.tree.get(s);n?.parent&&e.add(n.parent)}for(let i of t.notes){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}for(let i of t.attachments){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}this.tree.rebuild(this.noteFolder),this.render();for(let i of e)this.fmSync.scheduleParentOfDeleted(i)}async loadDraftsForFolder(){if(this.draftsLoadedFor===this.noteFolder)return;this.draftsLoadedFor=this.noteFolder;let t=this.plugin.settings.drafts??{};this.composerDraft=t[this.noteFolder]??"",console.debug("[Stashpad] loadDrafts",{folder:this.noteFolder,has:!!t[this.noteFolder],available:Object.keys(t)})}async saveDraft(t){try{let e=this.noteFolder;if((this.plugin.settings.drafts?.[e]??"")===t)return;let s={...this.plugin.settings.drafts??{}};t.length===0?delete s[e]:s[e]=t,this.plugin.settings.drafts=s,t.length===0?await this.plugin.saveSettings():await this.plugin.persistSettingsQuiet()}catch(e){console.warn("Stashpad: drafts save failed",e)}}async recordLastSubmitted(t){try{let e={...this.plugin.settings.lastSubmitted??{}};e[this.noteFolder]=t,this.plugin.settings.lastSubmitted=e,await this.plugin.persistSettingsQuiet()}catch{}}hasRestorableDraft(){let t=this.plugin.settings.drafts?.[this.noteFolder];if(!t||!t.trim())return!1;let e=this.plugin.settings.lastSubmitted?.[this.noteFolder];return!(e&&e===t)}syncComposerDraftForFocus(){}async flushDrafts(){this.composerInputEl?await this.saveDraft(this.composerInputEl.value):await this.saveDraft(this.composerDraft)}timeFilterCutoff(){if(this.timeFilter==="all")return null;if(this.timeFilterCalendar){let e=(0,P.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 P.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof P.TFolder){s.push(o);continue}if(!(o instanceof P.TFile)||o.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let r of a.attachments){if(typeof r!="string")continue;let l=Ce(r),c=this.app.metadataCache.getFirstLinkpathDest(l,o.path);c?t.add(c.path):t.add(l)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof P.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],r=[i];for(;r.length;){let l=r.pop();for(let c of l.children){if(c instanceof P.TFolder){let g=c.name;if(l===i&&o.has(g)||l===i&&g==="_attachments"&&!s)continue;r.push(c);continue}c instanceof P.TFile&&c.extension!=="md"&&(c.name===".stashpad-order.json"||c.name===".stashpad-sort.json"||!s&&n.has(c.path)||a.push(c))}}return a}populateListBody(t,e){if(this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),this.pendingCursorId){let c=this.currentChildren.findIndex(g=>g.id===this.pendingCursorId);c>=0&&(this.cursorIdx=c,this.selection.clear(),this.selection.add(this.pendingCursorId),this.lastSelected=this.pendingCursorId,this.pendingCursorId=null)}e.file&&P.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode(),s=i==="everything"?this.collectFileItems(e.id):[],n=c=>c.created&&Number.isFinite(Date.parse(c.created))?Date.parse(c.created):Number.POSITIVE_INFINITY,o=this.currentEncryptionFilter(),a;if(o==="unlocked")a=[];else if(i==="nested")a=this.plugin.lockedSubtreesFor(this.noteFolder,e.id);else{let c=new Set([e.id,...this.currentChildren.map(p=>p.id)]),g=new Set;a=[];for(let p of c)for(let d of this.plugin.lockedSubtreesFor(this.noteFolder,p))g.has(d.blob)||(g.add(d.blob),a.push(d))}let r=a.map(c=>({lk:c,ts:n(c)})).sort((c,g)=>c.ts-g.ts),l=i==="nested"&&this.sortStore.getMode(this.noteFolder,e.id)==="manual";if(this.currentChildren.length===0&&s.length===0&&r.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(l&&r.length>0){let c=new Map(this.currentChildren.map((u,f)=>[u.id,f])),g=new Map;for(let{lk:u}of r)u.rootId&&g.set(u.rootId,u);let p=this.currentChildren.map(u=>u.id),d=r.map(({lk:u})=>u).filter(u=>u.rootId).sort((u,f)=>n(f)-n(u)),I=!0;for(;d.length&&I;){I=!1;for(let u=0;u<d.length;u++){let f=d[u],C=f.prevSibling??null,m;if(C==null)m=0;else{let E=p.indexOf(C);if(E<0)continue;m=E+1}p.splice(m,0,f.rootId),d.splice(u,1),u--,I=!0}}for(let u of d)p.push(u.rootId);for(let u of p){let f=c.get(u);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let C=g.get(u);C&&this.renderLockedPlaceholder(t,C)}}for(let u of s.slice().sort((f,C)=>f.stat.ctime-C.stat.ctime))this.renderFileRow(t,u)}else if(s.length===0){let c=0;for(let g=0;g<this.currentChildren.length;g++){let p=Number.isFinite(Date.parse(this.currentChildren[g].created))?Date.parse(this.currentChildren[g].created):0;for(;c<r.length&&r[c].ts<=p;)this.renderLockedPlaceholder(t,r[c].lk),c++;this.renderNote(t,this.currentChildren[g],g)}for(;c<r.length;)this.renderLockedPlaceholder(t,r[c].lk),c++}else{let c=[...this.currentChildren.map((g,p)=>({kind:"note",ts:Number.isFinite(Date.parse(g.created))?Date.parse(g.created):0,idx:p})),...s.map(g=>({kind:"file",ts:g.stat.ctime,file:g})),...r.map(g=>({kind:"lock",ts:g.ts,lk:g.lk}))];c.sort((g,p)=>g.ts-p.ts);for(let g of c)g.kind==="note"?this.renderNote(t,this.currentChildren[g.idx],g.idx):g.kind==="file"?this.renderFileRow(t,g.file):this.renderLockedPlaceholder(t,g.lk)}e.file&&P.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,P.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,P.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async l=>{l.preventDefault(),l.stopPropagation();let c=(this.plugin.settings.lockedSubtrees??[]).find(u=>u.blob===e.blob),g=e.rootId??c?.rootId??null,p=e.parentId??c?.parentId??M,d=e.prevSibling??c?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,g){let u=this.order.getOrder(this.noteFolder,p),f=this.sortStore.getMode(this.noteFolder,p)==="manual";if(u.length===0&&f&&(u=this.tree.getChildren(p).map(C=>C.id)),u.length>0){let C=u.filter(E=>E!==g),m=d&&C.includes(d)?C.indexOf(d)+1:0;C.splice(Math.max(0,m),0,g),this.order.setOrder(this.noteFolder,p,C),this.order.flush(this.noteFolder)}this.pendingCursorId=g}this.render()}};o.onclick=a;let r=l=>{l.preventDefault(),l.stopPropagation();let c=new P.Menu;if(c.addItem(g=>g.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(l))),!P.Platform.isMobile){let g=P.Platform.isMacOS?"Finder":P.Platform.isWin?"File Explorer":"file manager";c.addItem(p=>p.setTitle(`Show in ${g}`).setIcon("folder-search").onClick(()=>{try{let d=window.require?.("electron")?.shell,I=this.app.vault.adapter?.getFullPath?.(e.blob);I&&d?.showItemInFolder&&d.showItemInFolder(I)}catch(d){console.warn("[Stashpad] showItemInFolder failed",d)}}))}c.addItem(g=>g.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let p=e.blob;if(!P.Platform.isMobile)try{p=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(p),new P.Notice("Path copied.")})),c.showAtMouseEvent(l)};if(i.oncontextmenu=r,P.Platform.isMobile){let l=i.createEl("button",{cls:"stashpad-locked-menu"});(0,P.setIcon)(l,"more-vertical"),l.setAttr("aria-label","Locked note menu"),l.onclick=c=>r(c)}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(r=>r.children.length>0):s;if(e==="nested")return n;let o=[],a=r=>{o.push(r);for(let l of this.tree.getChildren(r.id))a(l)};for(let r of n)a(r);return o}filterChildren(t){let e=this.timeFilterCutoff(),i=this.tagFilter?.toLowerCase(),s=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),o=this.currentAttachmentsOnly(),a=this.importedOnly,r=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!a&&!r?t:t.filter(l=>{if(a&&(!l.file||this.app.metadataCache.getFileCache(l.file)?.frontmatter?.imported!==!0))return!1;if(r){if(!l.file)return!1;let c=ne(this.app.metadataCache.getFileCache(l.file)?.frontmatter?.author);if(!c||c.id!==r)return!1}if(e&&l.created){let c=Date.parse(l.created);if(!Number.isNaN(c)&&c<e)return!1}return!(i&&(!l.file||!this.nodeHasTag(l,i))||s&&(this.colorForNode(l)?.toLowerCase()??null)!==s||n&&this.isCompleted(l)&&!this.hasIncompleteDescendant(l)||o&&!this.hasAttachmentInSubtree(l))})}nodeHasTag(t,e){if(!t.file)return!1;let i=this.app.metadataCache.getFileCache(t.file);if(!i)return!1;if(i.tags){for(let n of i.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let s=i.frontmatter?.tags;if(s){let n=Array.isArray(s)?s:[s];for(let o of n)if(typeof o=="string"&&o.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){if(!s.file)continue;let n=this.app.metadataCache.getFileCache(s.file);if(n?.tags)for(let a of n.tags){let r=(a.tag||"").replace(/^#/,"");r&&t.set(r,(t.get(r)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let r of a){if(typeof r!="string")continue;let l=r.replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){bt.enabled&&(this._renderT0=performance.now()),this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,i=this.listEl?.scrollTop??0,n=(t??{kind:"preserve"}).kind==="preserve"?this.captureScrollAnchor():null;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let a=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);e.empty(),e.toggleClass("is-mobile",P.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let r=this.containerEl.closest(".workspace-leaf");r&&(r.classList.toggle("stashpad-is-tiny",this.tinyMode),r.classList.toggle("stashpad-is-compact",this.compactMode));let l=this.containerEl.closest(".workspace-tabs");l&&l.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let c=this.tree.get(this.focusId)??this.tree.getRoot();c.file&&!P.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,c),this.currentChildren=this.filterChildren(this.collectViewItems(c.id));let g=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let I=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(I.id),this.lastSelected=I.id,this.autoSelectNewest=!1,g=!0}else if(this.pendingFocusIds){let I=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let u=-1;for(let f of I){let C=this.currentChildren.findIndex(m=>m.id===f);C>=0&&(this.selection.add(f),u<0&&(u=C))}this.cursorIdx=u,u>=0&&(this.lastSelected=I.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let p=e.createDiv({cls:"stashpad-list"});if(this.listEl=p,this.dnd.attachListDnD(p),this.populateListBody(p,c),this.renderComposer(e),P.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(bt.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),g&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let I=this.pendingComposerCaret;this.pendingComposerCaret=null;let u=this.composerInputEl;if(u&&u.isConnected){if(u.focus({preventScroll:!0}),I!=null){let f=Math.min(I,u.value.length);try{u.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),I!=null)){let C=Math.min(I,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let d=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,d&&this.listEl){let I=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,d.kind){case"preserve":I?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=d.scrollTop,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let m=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(u,m),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let u=d.id,f=d.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let E=C.querySelector(`[data-id="${u}"]`);E&&E.scrollIntoView({block:f,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&a?this.scrollListToBottom():this.listEl&&i>0&&(this.listEl.scrollTop=i);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let I=this.listEl,u=I.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){I.scrollTop=I.scrollHeight,u=I.scrollTop;return}let m=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop<u&&u<=m?I.scrollTop=u:u=I.scrollTop});f.observe(I),this.listResizeObserver=f,I.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;I.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),I.addEventListener("touchmove",m=>{let E=m.touches[0]?.clientY??C;E>C&&(this.stickToListBottom=!1),C=E},{passive:!0}),I.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),I.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),i=e.createEl("button",{cls:"stashpad-folder-btn"}),s=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,P.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[A.path],actions:h.actionsForFile(A.path)}),console.error(t)}}function Ir(h){let A=new Set,t=e=>{if(A.add(e),!!h.tree.get(e))for(let s of h.tree.getChildren(e))t(s.id)};return t(T),A}var fr=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),us={nested:"Nested",flat:"Flat",everything:"Everything"},fs=[{key:"day",calShort:"Today",rollShort:"24h",calLong:"Since midnight today",rollLong:"Last 24 hours"},{key:"week",calShort:"Week",rollShort:"7d",calLong:"Since Monday this week",rollLong:"Last 7 days"},{key:"month",calShort:"Month",rollShort:"30d",calLong:"Since the 1st of this month",rollLong:"Last 30 days"},{key:"year",calShort:"Year",rollShort:"365d",calLong:"Since January 1 this year",rollLong:"Last 365 days"},{key:"all",calShort:"All",rollShort:"ad infinitum",calLong:"All time",rollLong:"All time"}],Cs=class extends P.ItemView{constructor(t,e){super(t);this.focusId=T;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.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.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||Lo(t.target))return;let e=pt().bindings;if(st(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(st(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(st(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(st(t,e.commandPalette)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openStashpadCommandPalette();return}if(st(t,e.lockSelection)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdLockSelection();return}if(st(t,e.unlockAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUnlockAll();return}if(st(t,e.moveToArchive)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToArchive();return}if(st(t,e.encryptDelete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdEncryptDelete();return}if(st(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(st(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(st(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(st(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(st(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let i=t.target,s=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!s){let r=this.composerInputEl;if(r){t.preventDefault(),t.stopPropagation(),r.focus();let l=r.value.length;r.setSelectionRange(l,l);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let r=this.listEl,l=!!r&&r.scrollTop+r.clientHeight>=r.scrollHeight-2,c=r?.scrollTop??0;if(this.render(),r){let g=l?r.scrollHeight:c;r.scrollTop=g,requestAnimationFrame(()=>{r.scrollTop=l?r.scrollHeight:c}),setTimeout(()=>{r.scrollTop=l?r.scrollHeight:c},60),this.revealCursorRow()}return}if(this.inListPicker&&!n){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=this.nextPickableIdx(this.inListPicker.activeIdx,-1),this.repaintSelectionClasses(),this.revealRowAt(this.inListPicker.activeIdx);return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}if(st(t,pt().bindings.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.inListPicker=null,this.repaintSelectionClasses(),this.cmdMovePicker();return}return}if(n)return;if(st(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(st(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(st(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(st(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(st(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(st(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(st(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(st(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(st(t,e.selectAll)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSelectAll();return}if(st(t,e.swapWithParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSwapWithParent();return}if(st(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(st(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let r=this.composerInputEl;if(r){r.focus();let l=r.value.length;r.setSelectionRange(l,l)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let r=this.currentChildren[this.cursorIdx];r&&(t.preventDefault(),this.navigateTo(r.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return;if(this.plugin.noteClipboard&&this.plugin.noteClipboard.folder===this.noteFolder){this.plugin.clearNoteClipboard(),this.render();return}let r=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,r){let l=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,l>=0&&(this.cursorIdx=l)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=pt().bindings;if(st(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(st(t,o.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(st(t,o.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(st(t,o.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(st(t,o.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(st(t,o.copyNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyNotes();return}if(st(t,o.cutNotes)&&!window.getSelection()?.toString()){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCutNotes();return}if(st(t,o.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(st(t,o.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(st(t,o.copyCodeBlock)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyCodeBlock();return}if(st(t,o.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let r=this.tree.get(this.focusId);r?.file&&this.cmdOpenInEditor(r)}else this.cmdOpenInEditor();return}if(st(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(st(t,o.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(st(t,o.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(st(t,o.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(st(t,o.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}if(st(t,o.togglePin)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdTogglePin();return}if(st(t,o.toggleTask)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleTask();return}if(st(t,o.setDue)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetDue();return}}if(this.currentChildren.length>0){if(st(t,o.jumpToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToTop();return}if(st(t,o.jumpToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.jumpToBottom();return}}let a=this.tree.get(this.focusId);if(a?.file){if(st(t,o.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(st(t,o.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.openSearchInstance=null;this.fmSyncUnsubscribe=null;this.completedState=new Map;this.taskTaggedState=new Map;this.pendingFocusIds=null;this.onFileModify=t=>{!(t instanceof P.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 P.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new as(this.app),this.log=e.newLog(),this.integrity=new ds(this.tree,this.log),this.order=new Ke(this.app),this.sortStore=new rs(this.app),this.fmSync=new ls(this.app,()=>this.tree),this.tree.setOrderProvider(i=>{let s=this.noteFolder,n=this.sortStore.getMode(s,i);return n==="manual"?this.order.getOrder(s,i):Ro(this,i,n)}),this.debouncedRender=(0,P.debounce)(()=>this.render(),80),this.authorship=new gs(this),this.dnd=new ps(this),this.bodyRenderer=new Is(this,this,this.plugin.renderCacheStore)}getViewType(){return ct}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==T){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",()=>ts(this)),this.viewRoot.addEventListener("click",()=>ts(this)),this.viewRoot.addEventListener("mouseup",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),this.viewRoot.addEventListener("auxclick",r=>{r.button===3?(r.preventDefault(),this.navigateBack()):r.button===4&&(r.preventDefault(),this.navigateForward())}),ts(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new P.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.inListPicker)return this.inListPicker=null,this.pickerEscapeAt=Date.now(),this.repaintSelectionClasses(),!1;if(Date.now()-this.pickerEscapeAt<350||Date.now()-this.composerExitAt<400)return!1;if(this.selection.size>1){let r=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,r){let l=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,l>=0&&(this.cursorIdx=l)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",r=>{let l=r.relatedTarget;l&&this.viewRoot&&this.viewRoot.contains(l)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",r=>{if(r.extension!=="md")return;let l=this.app.metadataCache.getFileCache(r)?.frontmatter;this.completedState.set(r.path,!!l?.completed),this.taskTaggedState.set(r.path,this.taggedFromFm(l))})),this.registerEvent(this.app.vault.on("rename",(r,l)=>{for(let c of[this.completedState,this.taskTaggedState])c.has(l)&&(c.set(r.path,c.get(l)),c.delete(l))})),this.registerEvent(this.app.vault.on("delete",r=>{this.completedState.delete(r.path),this.taskTaggedState.delete(r.path)})),this.detachSettings=bo(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",l=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&l===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&l!==""&&(this.composerDraft=l),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(r){let l=r?.message??"";/already exists/i.test(l)||console.warn("[Stashpad] bootstrapFolder failed:",r)}this.tree.rebuild(this.noteFolder),this.installFmSyncActivityNotice(),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder();try{let r=this.plugin.loadLastCursor(this.noteFolder);for(let[l,c]of r)this.lastCursorByFocus.set(l,c);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let n=this.lastCursorByFocus.get(this.focusId),o;n&&this.tree.get(n)?(o={kind:"scroll-to-id",id:n,align:"start"},this.pendingFocusIds=[n]):(this.scrollToBottomOnNextRender=!0,o={kind:"pin-bottom",until:"next-user-input"});let a=this.foldRestoredSelection(n);a&&(this.pendingFocusIds=a),this.render(o),this.scheduleSelectionRestore(),this.tinyMode&&(setTimeout(()=>this.applyTinyWindow(),1e3),setTimeout(()=>this.applyTinyWindow(),1500)),this.registerDomEvent(window,"beforeunload",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.registerDomEvent(window,"blur",()=>{this.flushDrafts(),this.stampSelectedCursor(!0)}),this.focusComposer(),this.registerEvent(this.app.workspace.on("active-leaf-change",r=>{r===this.leaf?this.focusComposer():this.stickToListBottom=!1}))}scheduleTreeReconcile(){this.treeReconcileTimer==null&&(this.treeReconcileTimer=window.setTimeout(()=>{if(this.treeReconcileTimer=null,!this.viewRoot?.isConnected)return;let t=this.noteFolder,e=t+"/",i=0;for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!(n===t||t!==""&&n.startsWith(e)))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.id;typeof o=="string"&&o&&i++}i!==this.tree.fileBackedCount()&&(this.tree.rebuild(t),this.debouncedRender())},400))}focusView(){requestAnimationFrame(()=>{this.viewRoot?.isConnected&&(document.activeElement instanceof HTMLElement&&(document.activeElement.tagName==="INPUT"||document.activeElement.tagName==="TEXTAREA")||this.viewRoot.focus({preventScroll:!0}))})}focusComposer(){if(!pt().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(){ko(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.bodyRenderer.dispose(),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();this.authorship.dispose();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear(),this.lastSelectionByFocus.clear();try{let l=this.plugin.loadLastCursor(this.noteFolder);for(let[c,g]of l)this.lastCursorByFocus.set(c,g);this.lastSelectionByFocus=this.plugin.loadLastSelection(this.noteFolder)}catch{}let o=this.lastCursorByFocus.get(this.focusId),a;o&&this.tree.get(o)?(this.pendingFocusIds=[o],a={kind:"scroll-to-id",id:o,align:"start"}):a={kind:"pin-bottom",until:"next-user-input"};let r=this.foldRestoredSelection(o);r&&(this.pendingFocusIds=r),this.render(a),this.scheduleSelectionRestore()}}focus(){this.viewRoot?.focus({preventScroll:!0})}foldRestoredSelection(t){let e=this.lastSelectionByFocus.get(this.focusId)??null;if(!e||!e.length)return null;let i=e.filter(s=>!!this.tree.get(s));return i.length?t&&i.includes(t)?[t,...i.filter(s=>s!==t)]:i:null}stampSelection(t=!1){let e=[...this.selection],i=()=>{try{this.plugin.saveLastSelection(this.noteFolder,this.focusId,e)}catch{}};if(this.stampSelectionTimer!=null&&(window.clearTimeout(this.stampSelectionTimer),this.stampSelectionTimer=null),t){i();return}this.stampSelectionTimer=window.setTimeout(()=>{this.stampSelectionTimer=null,i()},400)}scheduleSelectionRestore(){let t=this.lastSelectionByFocus.get(this.focusId);if(!t||!t.length)return;let e=()=>{let i=t.filter(a=>this.currentChildren.some(r=>r.id===a));if(!i.length)return;let s=[...this.selection],n=new Set(i);if(s.length<i.length&&s.every(a=>n.has(a))){this.selection.clear();for(let a of i)this.selection.add(a);this.firstSelectedId=i[0],this.lastSelected=i[i.length-1],this.repaintSelectionClasses()}};for(let i of[120,400,900,1600])window.setTimeout(e,i)}loadConfig(){let t=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),i=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"Stashpad";i!==this.noteFolder?(this.noteFolder=i,this.tree.rebuild(this.noteFolder)):this.noteFolder=i}captureNavSnapshot(){return{folder:this.noteFolder,focusId:this.focusId}}recordNavState(t={}){let e=this.captureNavSnapshot(),i=this.navBackStack[this.navBackStack.length-1];i&&i.folder===e.folder&&i.focusId===e.focusId||(this.navBackStack.push(e),t.keepForward||(this.navForwardSnapshots=[]))}async setFolderOverride(t,e={}){let i=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(i&&this.isReservedFolder(i)){new P.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=T,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 P.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 P.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 P.Notice("Nothing to redo.");return}let e=t.peekRedoLabel(),i=this.plugin.notifications.recent()[0]?.category??"system";t.redo().then(()=>this.plugin.notifications.show({message:`Redid: ${e}`,kind:"info",category:i,folder:this.noteFolder})).catch(s=>this.plugin.notifications.show({message:`Redo failed: ${s.message}`,kind:"error",category:"system",folder:this.noteFolder}))}async snapshotNotes(t,e){let i=[],s=new Set;for(let r of t)!r.file||s.has(r.file.path)||(s.add(r.file.path),i.push(r.file));let n=await Promise.all(i.map(r=>this.app.vault.read(r))),o=i.map((r,l)=>({path:r.path,content:n[l]})),a=[];if(e){let r=new Set,l=[];for(let g of n)for(let p of this.extractAttachments(this.stripFrontmatter(g))){let d=this.app.metadataCache.getFirstLinkpathDest(p,"");d&&!r.has(d.path)&&(r.add(d.path),l.push(d))}let c=await Promise.all(l.map(g=>this.app.vault.readBinary(g)));for(let g=0;g<l.length;g++)a.push({path:l[g].path,data:c[g]})}return{notes:o,attachments:a}}async restoreSnapshots(t,e){for(let s of t.attachments)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.createBinary(s.path,s.data)}catch{}for(let s of t.notes)try{await this.app.vault.adapter.exists(s.path)||await this.app.vault.create(s.path,s.content)}catch{}let i=()=>{e&&e.some(n=>this.tree.get(n))&&(this.pendingFocusIds=e.slice())};i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"}),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},100),setTimeout(()=>{i(),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"})},400),setTimeout(()=>{for(let s of t.notes){let n=this.tree.idForPath(s.path);n&&this.fmSync.schedule(n)}},500)}async trashNotesAndAttachments(t){let e=new Set;for(let i of t.notes){let s=this.tree.idForPath(i.path);if(!s)continue;let n=this.tree.get(s);n?.parent&&e.add(n.parent)}for(let i of t.notes){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}for(let i of t.attachments){let s=this.app.vault.getAbstractFileByPath(i.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}this.tree.rebuild(this.noteFolder),this.render();for(let i of e)this.fmSync.scheduleParentOfDeleted(i)}async loadDraftsForFolder(){if(this.draftsLoadedFor===this.noteFolder)return;this.draftsLoadedFor=this.noteFolder;let t=this.plugin.settings.drafts??{};this.composerDraft=t[this.noteFolder]??"",console.debug("[Stashpad] loadDrafts",{folder:this.noteFolder,has:!!t[this.noteFolder],available:Object.keys(t)})}async saveDraft(t){try{let e=this.noteFolder;if((this.plugin.settings.drafts?.[e]??"")===t)return;let s={...this.plugin.settings.drafts??{}};t.length===0?delete s[e]:s[e]=t,this.plugin.settings.drafts=s,t.length===0?await this.plugin.saveSettings():await this.plugin.persistSettingsQuiet()}catch(e){console.warn("Stashpad: drafts save failed",e)}}async recordLastSubmitted(t){try{let e={...this.plugin.settings.lastSubmitted??{}};e[this.noteFolder]=t,this.plugin.settings.lastSubmitted=e,await this.plugin.persistSettingsQuiet()}catch{}}hasRestorableDraft(){let t=this.plugin.settings.drafts?.[this.noteFolder];if(!t||!t.trim())return!1;let e=this.plugin.settings.lastSubmitted?.[this.noteFolder];return!(e&&e===t)}syncComposerDraftForFocus(){}async flushDrafts(){this.composerInputEl?await this.saveDraft(this.composerInputEl.value):await this.saveDraft(this.composerDraft)}timeFilterCutoff(){if(this.timeFilter==="all")return null;if(this.timeFilterCalendar){let e=(0,P.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 P.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof P.TFolder){s.push(o);continue}if(!(o instanceof P.TFile)||o.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let r of a.attachments){if(typeof r!="string")continue;let l=Ce(r),c=this.app.metadataCache.getFirstLinkpathDest(l,o.path);c?t.add(c.path):t.add(l)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof P.TFolder))return[];let s=this.currentIncludeAttachments(),n=s?new Set:this.collectEmbeddedAttachmentPaths(),o=new Set(["_authors","_imports","_exports","_processed","_attachments","_archive",".archive"]),a=[],r=[i];for(;r.length;){let l=r.pop();for(let c of l.children){if(c instanceof P.TFolder){let g=c.name;if(l===i&&o.has(g)||l===i&&g==="_attachments"&&!s)continue;r.push(c);continue}c instanceof P.TFile&&c.extension!=="md"&&(c.name===".stashpad-order.json"||c.name===".stashpad-sort.json"||!s&&n.has(c.path)||a.push(c))}}return a}populateListBody(t,e){if(this.lastListWidth=t.clientWidth||this.lastListWidth,this.bodyRenderer.arm(),this.pendingCursorId){let c=this.currentChildren.findIndex(g=>g.id===this.pendingCursorId);c>=0&&(this.cursorIdx=c,this.selection.clear(),this.selection.add(this.pendingCursorId),this.lastSelected=this.pendingCursorId,this.pendingCursorId=null)}e.file&&P.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode(),s=i==="everything"?this.collectFileItems(e.id):[],n=c=>c.created&&Number.isFinite(Date.parse(c.created))?Date.parse(c.created):Number.POSITIVE_INFINITY,o=this.currentEncryptionFilter(),a;if(o==="unlocked")a=[];else if(i==="nested")a=this.plugin.lockedSubtreesFor(this.noteFolder,e.id);else{let c=new Set([e.id,...this.currentChildren.map(p=>p.id)]),g=new Set;a=[];for(let p of c)for(let d of this.plugin.lockedSubtreesFor(this.noteFolder,p))g.has(d.blob)||(g.add(d.blob),a.push(d))}let r=a.map(c=>({lk:c,ts:n(c)})).sort((c,g)=>c.ts-g.ts),l=i==="nested"&&this.sortStore.getMode(this.noteFolder,e.id)==="manual";if(this.currentChildren.length===0&&s.length===0&&r.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(l&&r.length>0){let c=new Map(this.currentChildren.map((u,f)=>[u.id,f])),g=new Map;for(let{lk:u}of r)u.rootId&&g.set(u.rootId,u);let p=this.currentChildren.map(u=>u.id),d=r.map(({lk:u})=>u).filter(u=>u.rootId).sort((u,f)=>n(f)-n(u)),I=!0;for(;d.length&&I;){I=!1;for(let u=0;u<d.length;u++){let f=d[u],C=f.prevSibling??null,m;if(C==null)m=0;else{let E=p.indexOf(C);if(E<0)continue;m=E+1}p.splice(m,0,f.rootId),d.splice(u,1),u--,I=!0}}for(let u of d)p.push(u.rootId);for(let u of p){let f=c.get(u);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let C=g.get(u);C&&this.renderLockedPlaceholder(t,C)}}for(let u of s.slice().sort((f,C)=>f.stat.ctime-C.stat.ctime))this.renderFileRow(t,u)}else if(s.length===0){let c=0;for(let g=0;g<this.currentChildren.length;g++){let p=Number.isFinite(Date.parse(this.currentChildren[g].created))?Date.parse(this.currentChildren[g].created):0;for(;c<r.length&&r[c].ts<=p;)this.renderLockedPlaceholder(t,r[c].lk),c++;this.renderNote(t,this.currentChildren[g],g)}for(;c<r.length;)this.renderLockedPlaceholder(t,r[c].lk),c++}else{let c=[...this.currentChildren.map((g,p)=>({kind:"note",ts:Number.isFinite(Date.parse(g.created))?Date.parse(g.created):0,idx:p})),...s.map(g=>({kind:"file",ts:g.stat.ctime,file:g})),...r.map(g=>({kind:"lock",ts:g.ts,lk:g.lk}))];c.sort((g,p)=>g.ts-p.ts);for(let g of c)g.kind==="note"?this.renderNote(t,this.currentChildren[g.idx],g.idx):g.kind==="file"?this.renderFileRow(t,g.file):this.renderLockedPlaceholder(t,g.lk)}e.file&&P.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,P.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,P.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async l=>{l.preventDefault(),l.stopPropagation();let c=(this.plugin.settings.lockedSubtrees??[]).find(u=>u.blob===e.blob),g=e.rootId??c?.rootId??null,p=e.parentId??c?.parentId??T,d=e.prevSibling??c?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,g){let u=this.order.getOrder(this.noteFolder,p),f=this.sortStore.getMode(this.noteFolder,p)==="manual";if(u.length===0&&f&&(u=this.tree.getChildren(p).map(C=>C.id)),u.length>0){let C=u.filter(E=>E!==g),m=d&&C.includes(d)?C.indexOf(d)+1:0;C.splice(Math.max(0,m),0,g),this.order.setOrder(this.noteFolder,p,C),this.order.flush(this.noteFolder)}this.pendingCursorId=g}this.render()}};o.onclick=a;let r=l=>{l.preventDefault(),l.stopPropagation();let c=new P.Menu;if(c.addItem(g=>g.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(l))),!P.Platform.isMobile){let g=P.Platform.isMacOS?"Finder":P.Platform.isWin?"File Explorer":"file manager";c.addItem(p=>p.setTitle(`Show in ${g}`).setIcon("folder-search").onClick(()=>{try{let d=window.require?.("electron")?.shell,I=this.app.vault.adapter?.getFullPath?.(e.blob);I&&d?.showItemInFolder&&d.showItemInFolder(I)}catch(d){console.warn("[Stashpad] showItemInFolder failed",d)}}))}c.addItem(g=>g.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let p=e.blob;if(!P.Platform.isMobile)try{p=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(p),new P.Notice("Path copied.")})),c.showAtMouseEvent(l)};if(i.oncontextmenu=r,P.Platform.isMobile){let l=i.createEl("button",{cls:"stashpad-locked-menu"});(0,P.setIcon)(l,"more-vertical"),l.setAttr("aria-label","Locked note menu"),l.onclick=c=>r(c)}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(r=>r.children.length>0):s;if(e==="nested")return n;let o=[],a=r=>{o.push(r);for(let l of this.tree.getChildren(r.id))a(l)};for(let r of n)a(r);return o}filterChildren(t){let e=this.timeFilterCutoff(),i=this.tagFilter?.toLowerCase(),s=this.colorFilter?.toLowerCase()??null,n=this.currentHideCompleted(),o=this.currentAttachmentsOnly(),a=this.importedOnly,r=this.authorFilter;return!e&&!i&&!s&&!n&&!o&&!a&&!r?t:t.filter(l=>{if(a&&(!l.file||this.app.metadataCache.getFileCache(l.file)?.frontmatter?.imported!==!0))return!1;if(r){if(!l.file)return!1;let c=ne(this.app.metadataCache.getFileCache(l.file)?.frontmatter?.author);if(!c||c.id!==r)return!1}if(e&&l.created){let c=Date.parse(l.created);if(!Number.isNaN(c)&&c<e)return!1}return!(i&&(!l.file||!this.nodeHasTag(l,i))||s&&(this.colorForNode(l)?.toLowerCase()??null)!==s||n&&this.isCompleted(l)&&!this.hasIncompleteDescendant(l)||o&&!this.hasAttachmentInSubtree(l))})}nodeHasTag(t,e){if(!t.file)return!1;let i=this.app.metadataCache.getFileCache(t.file);if(!i)return!1;if(i.tags){for(let n of i.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let s=i.frontmatter?.tags;if(s){let n=Array.isArray(s)?s:[s];for(let o of n)if(typeof o=="string"&&o.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){if(!s.file)continue;let n=this.app.metadataCache.getFileCache(s.file);if(n?.tags)for(let a of n.tags){let r=(a.tag||"").replace(/^#/,"");r&&t.set(r,(t.get(r)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let r of a){if(typeof r!="string")continue;let l=r.replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){Nt.enabled&&(this._renderT0=performance.now()),this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,i=this.listEl?.scrollTop??0,n=(t??{kind:"preserve"}).kind==="preserve"?this.captureScrollAnchor():null;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let a=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);e.empty(),e.toggleClass("is-mobile",P.Platform.isMobile),e.toggleClass("is-tiny",this.tinyMode),e.toggleClass("is-compact",this.compactMode);let r=this.containerEl.closest(".workspace-leaf");r&&(r.classList.toggle("stashpad-is-tiny",this.tinyMode),r.classList.toggle("stashpad-is-compact",this.compactMode));let l=this.containerEl.closest(".workspace-tabs");l&&l.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let c=this.tree.get(this.focusId)??this.tree.getRoot();c.file&&!P.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,c),this.currentChildren=this.filterChildren(this.collectViewItems(c.id));let g=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let I=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(I.id),this.lastSelected=I.id,this.autoSelectNewest=!1,g=!0}else if(this.pendingFocusIds){let I=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let u=-1;for(let f of I){let C=this.currentChildren.findIndex(m=>m.id===f);C>=0&&(this.selection.add(f),u<0&&(u=C))}this.cursorIdx=u,u>=0&&(this.lastSelected=I.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let p=e.createDiv({cls:"stashpad-list"});if(this.listEl=p,this.dnd.attachListDnD(p),this.populateListBody(p,c),this.renderComposer(e),P.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(Nt.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),g&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let I=this.pendingComposerCaret;this.pendingComposerCaret=null;let u=this.composerInputEl;if(u&&u.isConnected){if(u.focus({preventScroll:!0}),I!=null){let f=Math.min(I,u.value.length);try{u.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),I!=null)){let C=Math.min(I,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let d=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,d&&this.listEl){let I=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,d.kind){case"preserve":I?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=d.scrollTop,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let m=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(u,m),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let u=d.id,f=d.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let E=C.querySelector(`[data-id="${u}"]`);E&&E.scrollIntoView({block:f,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&a?this.scrollListToBottom():this.listEl&&i>0&&(this.listEl.scrollTop=i);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let I=this.listEl,u=I.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){I.scrollTop=I.scrollHeight,u=I.scrollTop;return}let m=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop<u&&u<=m?I.scrollTop=u:u=I.scrollTop});f.observe(I),this.listResizeObserver=f,I.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;I.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),I.addEventListener("touchmove",m=>{let E=m.touches[0]?.clientY??C;E>C&&(this.stickToListBottom=!1),C=E},{passive:!0}),I.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),I.addEventListener("keydown",()=>{this.stickToListBottom=!1})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),i=e.createEl("button",{cls:"stashpad-folder-btn"}),s=!!this.folderOverride,n=this.noteFolder.split("/").pop()||this.noteFolder||"Stashpad";(0,P.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=d=>{d.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});ge(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=d=>{d.preventDefault(),this.openSearchModal()},P.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let a=e.createDiv({cls:"stashpad-time-filter-btns"}),r=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,P.setIcon)(r,this.timeFilterCalendar?"calendar":"history"),r.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&r.addClass("is-active"),r.onclick=d=>{d.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let d of Is){let I=this.timeFilterCalendar?d.calShort:d.rollShort,u=this.timeFilterCalendar?d.calLong:d.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:I});f.title=u,this.timeFilter===d.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(d.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let d of Is){let I=this.timeFilterCalendar?d.calLong:d.rollLong,u=l.createEl("option",{text:I});u.value=d.key,this.timeFilter===d.key&&(u.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!P.Platform.isMobile){let d=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,P.setIcon)(d,"minimize-2"),d.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",d.onclick=I=>{I.preventDefault(),this.plugin.openTinyWindow()}}let g=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,P.setIcon)(g,this.compactMode?"panel-top":"rows-2"),g.title=this.compactMode?"Compact mode is ON \u2014 click to restore full chrome.":"Compact mode \u2014 hide the filter row + focused header; keep breadcrumb + list + composer.",this.compactMode&&g.addClass("is-active"),g.onclick=d=>{d.preventDefault(),this.toggleCompactMode()},P.Platform.isMobile)return;let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,P.setIcon)(p,"external-link"),p.title=It().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",p.onclick=d=>{d.preventDefault();let I=It().popoutDuplicates;try{let u=this.app.workspace;if(I){let f=this.leaf.getViewState(),C=u.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new P.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else u.moveLeafToPopout?.(this.leaf)}catch(u){new P.Notice(`Stashpad: open-in-new-window failed (${u.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),i=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ge(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==M;i.title=this.navBackStack.length>0?"Back":this.focusId!==M?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ge(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=c=>{c.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),r=this.mobileSelectMode;ge(a,r?"check-square":"square",r?"\u2611":"\u2610"),a.title=r?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",r&&a.addClass("is-active"),a.onclick=c=>{if(c.preventDefault(),this.mobileSelectMode){let g=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),g){let p=this.currentChildren.findIndex(d=>d.id===g);this.selection.add(g),this.lastSelected=g,p>=0&&(this.cursorIdx=p)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let g=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),g&&(this.selection.add(g.id),this.lastSelected=g.id,this.firstSelectedId=g.id),this.render(),new P.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let l=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ge(l,"zap","\u26A1"),l.title="Actions (move, delete, undo, \u2026)",l.onclick=c=>{c.preventDefault(),this.openMobileActionsMenu(l)}}openMobileActionsMenu(t){let e=new P.Menu,i=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],s=this.selection.size<=1;e.addItem(o=>o.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(o=>o.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(o=>o.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addSeparator(),e.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!i).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(o=>o.setTitle("Open in editor").setIcon("pencil").setDisabled(!i).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(o=>o.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!i).onClick(()=>this.cmdMovePicker())),e.addItem(o=>o.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!i).onClick(()=>this.cmdInListPicker())),e.addItem(o=>o.setTitle("Outdent").setIcon("outdent").setDisabled(!i).onClick(()=>void this.cmdOutdent())),e.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").setDisabled(!i).onClick(()=>this.cmdSetColor())),e.addItem(o=>o.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!i).onClick(()=>void this.cmdToggleComplete())),e.addItem(o=>o.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!i).onClick(()=>void this.cmdToggleTask())),e.addItem(o=>o.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!i).onClick(()=>this.cmdSetDue())),e.addItem(o=>o.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!i).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(o=>o.setTitle("Copy").setIcon("copy").setDisabled(!i).onClick(()=>void this.cmdCopy())),e.addItem(o=>o.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!i).onClick(()=>void this.cmdCopyTree())),e.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!i).onClick(()=>void this.cmdClone())),e.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(o=>o.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(o=>o.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!i||!s).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(o=>o.setTitle("Delete").setIcon("trash-2").setDisabled(!i).onClick(()=>void this.cmdDelete())),e.addSeparator(),e.addItem(o=>o.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}openCommandPalette(){this.app.commands?.executeCommandById?.("command-palette:open")}openStashpadCommandPalette(){new cs(this.app).open()}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),i=e.createEl("option",{text:"All tags"});i.value="",this.tagFilter||(i.selected=!0);let s=this.collectFolderTags();if(s.length===0)e.disabled=!0,i.text="No tags";else for(let n of s){let o=e.createEl("option",{text:`${n.label} (${n.count})`});o.value=n.raw,this.tagFilter&&this.tagFilter.toLowerCase()===n.raw.toLowerCase()&&(o.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),i=t.createDiv({cls:"stashpad-color-filter-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0"),(()=>{i.empty();let o=i.createSpan({cls:"stashpad-color-filter-swatch"}),a=i.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let r=this.colorFilter.toLowerCase();o.style.background=r;let l=this.plugin.getColorAlias(this.noteFolder,r);a.setText(l??r)}else e.length===0?(o.addClass("is-empty"),a.setText("No colors"),i.addClass("is-disabled")):(o.addClass("is-empty"),a.setText("All colors"))})();let n=o=>{o.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(i,e)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openColorFilterMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.style.left=`${Math.max(8,n.left)}px`,s.style.top=`${n.bottom+4}px`,s.style.minWidth=`${n.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let o=new P.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=l=>{!s.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&a()};o.register([],"Escape",l=>(l.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",r,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,i=this.focusId,s=this.sortStore.getMode(e,i),n=this.currentViewMode(),o=n!=="nested",a=t.createDiv({cls:"stashpad-sort-btn"});a.setAttribute("role","button"),a.setAttribute("tabindex",o?"-1":"0"),o&&a.addClass("is-disabled");let r=a.createSpan({cls:"stashpad-sort-icon"});(0,P.setIcon)(r,"arrow-up-down");let l=a.createSpan({cls:"stashpad-sort-label"});o?(l.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${ps[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(Ei[s]),s!=="manual"&&a.addClass("is-active"),a.title=s==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${Ei[s]}. Drag-reorder will revert this parent to Manual.`);let c=g=>{o||(g.preventDefault(),this.openSortMenu(a))};a.onclick=c,a.onkeydown=g=>{o||(g.key==="Enter"||g.key===" ")&&c(g)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-sort-popover"}),s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateSortMenuBody(i,n);let a=new P.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let i=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,P.setIcon)(i,"sliders-horizontal"),e.title="Filters / view options";let s=!!this.tagFilter,n=!!this.colorFilter,o=this.timeFilter!=="all",a=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",r=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||a||r)&&e.addClass("is-active");let l=c=>{c.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=l,e.onkeydown=c=>{(c.key==="Enter"||c.key===" ")&&l(c)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(p=>p.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.style.right=`${Math.max(8,n.innerWidth-s.right)}px`,i.style.left="auto",i.style.top=`${s.bottom+4}px`,i.style.maxWidth="min(360px, calc(100vw - 16px))",i.style.width="max-content",i.style.minWidth="260px";let o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(g)}catch{}},a=p=>{!i.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&o()},r=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let p=Is.find(d=>d.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":Ei[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:()=>ps[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,o)}],l="",c=()=>{i.empty();for(let p of r){let d=i.createDiv({cls:"stashpad-mobile-filters-section"}),I=d.createDiv({cls:"stashpad-mobile-filters-header"}),u=I.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,P.setIcon)(u,l===p.key?"chevron-down":"chevron-right"),I.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),I.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),I.onclick=f=>{f.preventDefault(),f.stopPropagation(),l=l===p.key?"":p.key,c()},l===p.key){let f=d.createDiv({cls:"stashpad-mobile-filters-body"});p.populate(f)}}};c();let g=new P.Scope(this.app.scope);g.register([],"Escape",p=>(p.preventDefault(),o(),!1)),this.app.keymap?.pushScope(g),setTimeout(()=>{e.addEventListener("mousedown",a,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),i=t.createDiv({cls:"stashpad-view-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-view-icon"});(0,P.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(ps[e]),(e!=="nested"||this.currentEncryptionFilter()!=="all")&&i.addClass("is-active"),i.title=e==="nested"?"View: Nested (the default). Click to switch to Flat or Everything.":e==="flat"?"View: Flat \u2014 all descendants of the current focus, flat by sort order. Drag-reorder is disabled in this mode. Click to change.":"View: Everything \u2014 all descendants of the current focus PLUS non-Stashpad files in the folder, flat by created/ctime. Click to change.";let o=a=>{a.preventDefault(),this.openViewMenu(i)};i.onclick=o,i.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&o(a)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-view-popover"});P.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(320px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateViewMenuBody(i,n);let a=new P.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(y,v)=>{let S=t.createDiv({cls:"stashpad-view-popover-row"});y===i&&S.addClass("is-active"),S.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:ps[y]}),S.createDiv({cls:"stashpad-view-popover-desc",text:v}),S.onclick=async F=>{F.preventDefault(),F.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(),v=(S,U,F)=>{let x=t.createDiv({cls:"stashpad-view-popover-row"});S===y&&x.addClass("is-active"),x.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:U}),x.createDiv({cls:"stashpad-view-popover-desc",text:F}),x.onclick=async Q=>{Q.preventDefault(),Q.stopPropagation(),S!==y&&(await this.setEncryptionFilter(S),this.refreshList()),e()}};v("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),v("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),v("unlocked","Encryption: decrypted only","Hide locked \u{1F512} stubs."),t.createDiv({cls:"stashpad-view-popover-divider"})}let n=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),o=n.createEl("input",{type:"checkbox"});o.checked=this.currentHideChildless(),n.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),n.createDiv({cls:"stashpad-view-popover-desc",text:i==="nested"?"Show only notes that have children. Applied at this level.":"Hide top-level notes without children; keep every parent's full subtree so no task is overlooked."}),n.onclick=async y=>{y.target!==o&&(y.preventDefault(),o.checked=!o.checked),await this.setHideChildless(o.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),r=a.createEl("input",{type:"checkbox"});r.checked=this.currentHideCompleted(),a.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide completed notes"}),a.createDiv({cls:"stashpad-view-popover-desc",text:"Hide notes marked complete. A completed parent stays visible while any descendant is still incomplete."}),a.onclick=async y=>{y.target!==r&&(y.preventDefault(),r.checked=!r.checked),await this.setHideCompleted(r.checked),this.refreshList()};let l=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),c=l.createEl("input",{type:"checkbox"});c.checked=this.currentAttachmentsOnly(),l.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),l.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),l.onclick=async y=>{y.target!==c&&(y.preventDefault(),c.checked=!c.checked),await this.setAttachmentsOnly(c.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let g=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&g.addClass("is-disabled");let p=g.createEl("input",{type:"checkbox"});p.checked=this.currentIncludeAttachments(),p.disabled=i!=="everything",g.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),g.createDiv({cls:"stashpad-view-popover-desc",text:i==="everything"?"Show attachments referenced by notes as their own rows in the file list. Off by default \u2014 they already appear inline on the notes that embed them.":"Only applies in Everything mode."}),g.onclick=async y=>{i==="everything"&&(y.target!==p&&(y.preventDefault(),p.checked=!p.checked),await this.setIncludeAttachments(p.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let d=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),I=d.createEl("input",{type:"checkbox"});I.checked=this.importedOnly,d.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),d.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),d.onclick=y=>{y.target!==I&&(y.preventDefault(),I.checked=!I.checked),this.importedOnly=I.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let u=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let v=ne(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);v&&u.set(v.id,v.name)}let C=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),m=C.createDiv({cls:"stashpad-view-popover-main"});m.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let E=m.createEl("select",{cls:"stashpad-view-author-select"}),w=E.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[y,v]of[...u.entries()].sort((S,U)=>S[1].localeCompare(U[1]))){let S=E.createEl("option",{text:v,value:y});this.authorFilter===y&&(S.selected=!0)}E.onclick=y=>y.stopPropagation(),E.onchange=()=>{this.authorFilter=E.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},C.createDiv({cls:"stashpad-view-popover-desc",text:u.size?"Show only notes by the chosen author.":"No authored notes in this folder yet."})}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let i=this.noteFolder,s=this.focusId,n=this.sortStore.getMode(i,s);for(let o of Cn){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:Ei[o]}),a.onclick=async r=>{r.preventDefault(),r.stopPropagation(),e(),o!==n&&(this.sortStore.setMode(i,s,o),await this.sortStore.save(i),this.tree.rebuild(i),this.render())}}}populateTimeMenuBody(t,e){let i=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),s=i.createEl("input",{type:"checkbox"});s.checked=this.timeFilterCalendar,i.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),i.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),i.onclick=n=>{n.target!==s&&(n.preventDefault(),s.checked=!s.checked),this.timeFilterCalendar=s.checked,this.persistFocus(),this.refreshList()};for(let n of Is){let o=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&o.addClass("is-active");let a=this.timeFilterCalendar?n.calLong:n.rollLong;o.createSpan({cls:"stashpad-sort-popover-label",text:a}),o.onclick=r=>{r.preventDefault(),r.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,a)=>{let r=t.createDiv({cls:"stashpad-color-filter-popover-row"}),l=r.createSpan({cls:"stashpad-color-filter-swatch"});o?l.style.background=o:l.addClass("is-empty");let c=r.createSpan({cls:"stashpad-color-filter-popover-label"});c.setText(n),o&&(c.style.color=o),r.onclick=g=>{g.preventDefault(),g.stopPropagation(),a(),i()}};s("All colors",null,()=>this.setColorFilter(null));for(let n of e){let o=this.plugin.getColorAlias(this.noteFolder,n.hex),a=o?`${o} (${n.count})`:`${n.hex} (${n.count})`;s(a,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let i=this.collectFolderTags(),s=(n,o)=>{let a=t.createDiv({cls:"stashpad-color-filter-popover-row"});a.createSpan({cls:"stashpad-color-filter-swatch is-empty"}),a.createSpan({cls:"stashpad-color-filter-popover-label"}).setText(n),(this.tagFilter??"")===(o??"")&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),c.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null);for(let n of i)s(`${n.label} (${n.count})`,n.raw)}setColorFilter(t){let e=t?t.toLowerCase():null;(this.colorFilter??null)!==e&&(this.colorFilter=e,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}setTimeFilter(t){this.timeFilter!==t&&(this.timeFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}reconcileSelectionAfterFilter(){let t=this.filterChildren(this.collectViewItems(this.focusId)),e=new Set(t.map(i=>i.id));for(let i of[...this.selection])e.has(i)||this.selection.delete(i);if(this.firstSelectedId&&!e.has(this.firstSelectedId)&&(this.firstSelectedId=null),this.lastSelected&&!e.has(this.lastSelected)&&(this.lastSelected=null),this.selection.size>0){let i=t.findIndex(s=>this.selection.has(s.id));this.cursorIdx=i>=0?i:Math.min(this.cursorIdx,t.length-1)}else this.cursorIdx>=t.length&&(this.cursorIdx=t.length-1)}renderTinyHeader(t){let e=t.createDiv({cls:"stashpad-tiny-header"}),i=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});ge(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==M||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==M?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});ge(n,"arrow-right","\u203A"),n.title=this.navForwardSnapshots.length>0?"Forward":"No forward history",this.navForwardSnapshots.length===0&&n.addClass("is-disabled"),n.onclick=()=>this.navigateForward();let o=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),r=this.focusId===M?a:`${a} / ${this.titleForNode(o).trim()}`,l=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=l.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,P.setIcon)(c,"folder"),l.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:r}),l.title=`${this.noteFolder}${this.focusId!==M?` / ${this.titleForNode(o).trim()}`:""} -Click to switch / create folder.`,l.onclick=u=>{u.preventDefault(),this.plugin.openFolderPicker()};let g=e.createDiv({cls:"stashpad-tiny-sticky"}),p=g.createEl("input",{type:"checkbox"});if(p.checked=this.tinyAlwaysOnTop,g.createSpan({text:"Sticky"}),p.onchange=()=>{this.tinyAlwaysOnTop=p.checked,this.applyTinyAlwaysOnTop()},!P.Platform.isMobile){let u=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,P.setIcon)(u,"contrast"),u.title="Window transparency",this.tinyOpacity<1&&u.addClass("is-active"),u.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(u)}}let d=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,P.setIcon)(d,this.compactMode?"panel-top":"rows-2"),d.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&d.addClass("is-active"),d.onclick=()=>{this.toggleCompactMode()};let I=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,P.setIcon)(I,"maximize-2"),I.title="Exit tiny mode",I.onclick=()=>{this.exitTinyMode()}}toggleTinyOpacityPopover(t){if(this.tinyOpacityPopover){this.tinyOpacityPopover.remove(),this.tinyOpacityPopover=null;return}let e=document.createElement("div");e.className="stashpad-tiny-opacity-popover",e.createSpan({cls:"stashpad-tiny-opacity-label",text:"Transparency"});let i=e.createEl("input",{type:"range"});i.min="30",i.max="100",i.step="1",i.value=String(Math.round(this.tinyOpacity*100));let s=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${i.value}%`});i.addEventListener("input",()=>{let c=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=c/100,s.setText(`${c}%`),this.applyTinyOpacity(),t.toggleClass("is-active",this.tinyOpacity<1)}),i.addEventListener("change",()=>{this.app.workspace.requestSaveLayout()}),this.viewRoot.appendChild(e);let n=t.getBoundingClientRect(),o=this.viewRoot.getBoundingClientRect();e.style.top=`${n.bottom-o.top+4}px`,e.style.left=`${Math.max(4,Math.min(n.left-o.left,o.width-180))}px`;let a=c=>{e.contains(c.target)||c.target===t||t.contains(c.target)||l()},r=c=>{c.key==="Escape"&&l()},l=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",r,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",r,!0)},0),this.tinyOpacityPopover=e,i.focus()}getOwnElectronWindow(){try{let t=this.containerEl?.ownerDocument?.defaultView??window,s=((t?.require?.("electron")??window.require?.("electron"))?.remote??t?.electron?.remote??t?.["@electron/remote"])?.getCurrentWindow?.()??t?.electronWindow??null;if(!s)try{let n=window.require?.("electron"),o=n?.remote??n?.["@electron/remote"],r=(o?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];r.length===1?s=r[0]:r.length>1&&(s=o?.getFocusedWindow?.()??null??r[r.length-1])}catch(n){console.debug("[Stashpad] BrowserWindow.getAllWindows fallback failed",n)}return s||console.debug("[Stashpad] couldn't resolve own electron window"),s??null}catch(t){return console.debug("[Stashpad] resolve own electron window failed",t),null}}applyTinyAlwaysOnTop(){let t=this.getOwnElectronWindow();if(t)try{t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop)}catch(e){console.debug("[Stashpad] setAlwaysOnTop failed",e)}}applyTinyOpacity(){let t=this.getOwnElectronWindow();if(!t)return;let e=Math.min(1,Math.max(.3,this.tinyOpacity));try{t.setOpacity?.(e)}catch(i){console.debug("[Stashpad] setOpacity failed",i)}}applyTinyWindow(){let t=this.getOwnElectronWindow();if(t)try{if(this.tinyMode){t.setMinimumSize?.(220,260);let s=100,n=100;try{let o=t.getBounds?.();o&&typeof o.x=="number"&&(s=o.x,n=o.y)}catch{}try{t.setBounds?.({x:s,y:n,width:280,height:360})}catch{}try{t.setSize?.(280,360)}catch{}t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop);try{t.setOpacity?.(Math.min(1,Math.max(.3,this.tinyOpacity)))}catch{}}else t.setAlwaysOnTop?.(!1)}catch(e){console.debug("[Stashpad] tiny window apply failed",e)}}async exitTinyMode(){this.tinyMode=!1,this.tinyAlwaysOnTop=!1,this.tinyOpacity=1;try{this.getOwnElectronWindow()?.setOpacity?.(1)}catch{}this.compactMode=!1,this.applyTinyWindow();let t=this.getOwnElectronWindow();try{if(t?.setMinimumSize?.(400,300),P.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(P.Platform.isMobile?((0,P.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(M),this.focusId===M){let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,P.setIcon)(g,"panel-top"),g.title="Exit compact mode",g.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(c=>{let g=this.titleForNode(c),p=g.length>s?g.slice(0,s-1)+"\u2026":g;return{id:c.id,label:p}}),r=c=>c.reduce((g,p)=>g+p.label.length+3,0);if(r(a)>n&&a.length>2){let c=!1;for(;r(a)>n&&a.length>2;)a.splice(1,1),c||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),c=!0)}for(let c of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),c.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:c.label}).title=o.map(g=>this.titleForNode(g)).join(" / ");else{let g=c.id,p=e.createSpan({cls:"stashpad-crumb",text:c.label});p.title=c.label,p.onclick=()=>this.navigateTo(g),p.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,g)},P.Platform.isMobile&&this.attachLongPress(p,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,M)}),P.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,M))}let l=this.tree.getChildren(this.focusId).length;if(l>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${l}`}).title=`${l} direct child${l===1?"":"ren"}`),this.compactMode){let c=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,P.setIcon)(c,"panel-top"),c.title="Exit compact mode",c.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",a=>{let r=a.touches[0];s=r?.clientX??0,n=r?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let r=a.touches[0];r&&(Math.abs(r.clientX-s)>10||Math.abs(r.clientY-n)>10)&&o()},{passive:!0}),t.addEventListener("touchend",o),t.addEventListener("touchcancel",o)}openCrumbMenu(t,e){let i=this.tree.get(e);if(!i)return;let s=new P.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,P.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(i)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),i=t.querySelector(".stashpad-focused-mini");!e||!i||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(s=>{for(let n of s)i.toggleClass("is-visible",!n.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused"}),o=s.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});o.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),o.createDiv({cls:"stashpad-focused-grip-spacer"});let a=s.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",g=>this.handleRenderedClick(g,e));let r=s.createDiv({cls:"stashpad-focused-actions"}),l=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,P.setIcon)(l,"pencil"),l.title="Edit in new tab",l.onclick=()=>void this.openFileAtEnd(i);let c=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,P.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:P.Platform.isMobile,toggleHost:r,toggleAnchor:l})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(a=>a.id===this.focusId),n=i.slice(s+1,i.length-1);if(n.length===0)return;let o=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,r)=>{let l=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});l.title=`Focus into "${this.titleForNode(a)}"`,l.onclick=c=>{c.stopPropagation(),this.navigateTo(a.id)},r<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return qi(this.app,t,P.Platform.isMobile)}bulkActionMessage(t){let e=t.nodes.map(a=>`"${this.titleForNode(a).trim()||"(untitled)"}"`),i=t.suffix?` ${t.suffix}`:"",s=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${i}${s}`;if(e.length===1)return`${t.verb} ${e[0]}${i}${s}`;let n=t.bulletMax??10,o=e.length<=n?e.map(a=>`\u2022 ${a}`).join(` +Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=d=>{d.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});ge(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=d=>{d.preventDefault(),this.openSearchModal()},P.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let a=e.createDiv({cls:"stashpad-time-filter-btns"}),r=a.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,P.setIcon)(r,this.timeFilterCalendar?"calendar":"history"),r.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&r.addClass("is-active"),r.onclick=d=>{d.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let d of fs){let I=this.timeFilterCalendar?d.calShort:d.rollShort,u=this.timeFilterCalendar?d.calLong:d.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:I});f.title=u,this.timeFilter===d.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(d.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let d of fs){let I=this.timeFilterCalendar?d.calLong:d.rollLong,u=l.createEl("option",{text:I});u.value=d.key,this.timeFilter===d.key&&(u.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!P.Platform.isMobile){let d=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,P.setIcon)(d,"minimize-2"),d.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",d.onclick=I=>{I.preventDefault(),this.plugin.openTinyWindow()}}let g=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,P.setIcon)(g,this.compactMode?"panel-top":"rows-2"),g.title=this.compactMode?"Compact mode is ON \u2014 click to restore full chrome.":"Compact mode \u2014 hide the filter row + focused header; keep breadcrumb + list + composer.",this.compactMode&&g.addClass("is-active"),g.onclick=d=>{d.preventDefault(),this.toggleCompactMode()},P.Platform.isMobile)return;let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,P.setIcon)(p,"external-link"),p.title=pt().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",p.onclick=d=>{d.preventDefault();let I=pt().popoutDuplicates;try{let u=this.app.workspace;if(I){let f=this.leaf.getViewState(),C=u.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new P.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else u.moveLeafToPopout?.(this.leaf)}catch(u){new P.Notice(`Stashpad: open-in-new-window failed (${u.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),i=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ge(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==T;i.title=this.navBackStack.length>0?"Back":this.focusId!==T?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ge(n,"arrow-right","\u203A");let o=this.navForwardSnapshots.length>0;n.title=o?"Forward":"No forward history",o||n.addClass("is-disabled"),n.onclick=c=>{c.preventDefault(),this.navigateForward()};let a=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),r=this.mobileSelectMode;ge(a,r?"check-square":"square",r?"\u2611":"\u2610"),a.title=r?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",r&&a.addClass("is-active"),a.onclick=c=>{if(c.preventDefault(),this.mobileSelectMode){let g=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),g){let p=this.currentChildren.findIndex(d=>d.id===g);this.selection.add(g),this.lastSelected=g,p>=0&&(this.cursorIdx=p)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let g=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),g&&(this.selection.add(g.id),this.lastSelected=g.id,this.firstSelectedId=g.id),this.render(),new P.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let l=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ge(l,"zap","\u26A1"),l.title="Actions (move, delete, undo, \u2026)",l.onclick=c=>{c.preventDefault(),this.openMobileActionsMenu(l)}}openMobileActionsMenu(t){let e=new P.Menu,i=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],s=this.selection.size<=1;e.addItem(o=>o.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(o=>o.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(o=>o.setTitle("Notification history\u2026").setIcon("bell").onClick(()=>{this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")})),e.addSeparator(),e.addItem(o=>o.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!i).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(o=>o.setTitle("Open in editor").setIcon("pencil").setDisabled(!i).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(o=>o.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!i).onClick(()=>this.cmdMovePicker())),e.addItem(o=>o.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!i).onClick(()=>this.cmdInListPicker())),e.addItem(o=>o.setTitle("Outdent").setIcon("outdent").setDisabled(!i).onClick(()=>void this.cmdOutdent())),e.addItem(o=>o.setTitle("Set color\u2026").setIcon("palette").setDisabled(!i).onClick(()=>this.cmdSetColor())),e.addItem(o=>o.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!i).onClick(()=>void this.cmdToggleComplete())),e.addItem(o=>o.setTitle("Toggle task (todo)").setIcon("check-square").setDisabled(!i).onClick(()=>void this.cmdToggleTask())),e.addItem(o=>o.setTitle("Set due date\u2026").setIcon("calendar-clock").setDisabled(!i).onClick(()=>this.cmdSetDue())),e.addItem(o=>o.setTitle("Assign to\u2026").setIcon("user-plus").setDisabled(!i).onClick(()=>this.cmdAssign())),e.addSeparator(),e.addItem(o=>o.setTitle("Copy").setIcon("copy").setDisabled(!i).onClick(()=>void this.cmdCopy())),e.addItem(o=>o.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!i).onClick(()=>void this.cmdCopyTree())),e.addItem(o=>o.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!i).onClick(()=>void this.cmdClone())),e.addItem(o=>o.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(o=>o.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(o=>o.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!i||!s).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(o=>o.setTitle("Delete").setIcon("trash-2").setDisabled(!i).onClick(()=>void this.cmdDelete())),e.addSeparator(),e.addItem(o=>o.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette()));let n=t.getBoundingClientRect();e.showAtPosition({x:n.left,y:n.bottom+4})}openCommandPalette(){this.app.commands?.executeCommandById?.("command-palette:open")}openStashpadCommandPalette(){new hs(this.app).open()}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),i=e.createEl("option",{text:"All tags"});i.value="",this.tagFilter||(i.selected=!0);let s=this.collectFolderTags();if(s.length===0)e.disabled=!0,i.text="No tags";else for(let n of s){let o=e.createEl("option",{text:`${n.label} (${n.count})`});o.value=n.raw,this.tagFilter&&this.tagFilter.toLowerCase()===n.raw.toLowerCase()&&(o.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),i=t.createDiv({cls:"stashpad-color-filter-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0"),(()=>{i.empty();let o=i.createSpan({cls:"stashpad-color-filter-swatch"}),a=i.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let r=this.colorFilter.toLowerCase();o.style.background=r;let l=this.plugin.getColorAlias(this.noteFolder,r);a.setText(l??r)}else e.length===0?(o.addClass("is-empty"),a.setText("No colors"),i.addClass("is-disabled")):(o.addClass("is-empty"),a.setText("All colors"))})();let n=o=>{o.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(i,e)};i.onclick=n,i.onkeydown=o=>{(o.key==="Enter"||o.key===" ")&&n(o)}}openColorFilterMenu(t,e){let i=t.ownerDocument??document;i.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let s=i.body.createDiv({cls:"stashpad-color-filter-popover"}),n=t.getBoundingClientRect();s.style.left=`${Math.max(8,n.left)}px`,s.style.top=`${n.bottom+4}px`,s.style.minWidth=`${n.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let o=new P.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=l=>{!s.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&a()};o.register([],"Escape",l=>(l.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",r,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,i=this.focusId,s=this.sortStore.getMode(e,i),n=this.currentViewMode(),o=n!=="nested",a=t.createDiv({cls:"stashpad-sort-btn"});a.setAttribute("role","button"),a.setAttribute("tabindex",o?"-1":"0"),o&&a.addClass("is-disabled");let r=a.createSpan({cls:"stashpad-sort-icon"});(0,P.setIcon)(r,"arrow-up-down");let l=a.createSpan({cls:"stashpad-sort-label"});o?(l.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${us[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(yi[s]),s!=="manual"&&a.addClass("is-active"),a.title=s==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${yi[s]}. Drag-reorder will revert this parent to Manual.`);let c=g=>{o||(g.preventDefault(),this.openSortMenu(a))};a.onclick=c,a.onkeydown=g=>{o||(g.key==="Enter"||g.key===" ")&&c(g)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-sort-popover"}),s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateSortMenuBody(i,n);let a=new P.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let i=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,P.setIcon)(i,"sliders-horizontal"),e.title="Filters / view options";let s=!!this.tagFilter,n=!!this.colorFilter,o=this.timeFilter!=="all",a=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",r=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentAttachmentsOnly()||this.currentIncludeAttachments();(s||n||o||a||r)&&e.addClass("is-active");let l=c=>{c.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=l,e.onkeydown=c=>{(c.key==="Enter"||c.key===" ")&&l(c)}}openMobileFiltersMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-mobile-filters-popover").forEach(p=>p.remove());let i=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),s=t.getBoundingClientRect(),n=e.defaultView??window;i.style.right=`${Math.max(8,n.innerWidth-s.right)}px`,i.style.left="auto",i.style.top=`${s.bottom+4}px`,i.style.maxWidth="min(360px, calc(100vw - 16px))",i.style.width="max-content",i.style.minWidth="260px";let o=()=>{i.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(g)}catch{}},a=p=>{!i.contains(p.target)&&p.target!==t&&!t.contains(p.target)&&o()},r=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:p=>this.populateTagMenuBody(p,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:p=>this.populateColorMenuBody(p,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let p=fs.find(d=>d.key===this.timeFilter);return p?this.timeFilterCalendar?p.calShort:p.rollShort:"All"},populate:p=>this.populateTimeMenuBody(p,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":yi[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:()=>us[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,o)}],l="",c=()=>{i.empty();for(let p of r){let d=i.createDiv({cls:"stashpad-mobile-filters-section"}),I=d.createDiv({cls:"stashpad-mobile-filters-header"}),u=I.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,P.setIcon)(u,l===p.key?"chevron-down":"chevron-right"),I.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),I.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),I.onclick=f=>{f.preventDefault(),f.stopPropagation(),l=l===p.key?"":p.key,c()},l===p.key){let f=d.createDiv({cls:"stashpad-mobile-filters-body"});p.populate(f)}}};c();let g=new P.Scope(this.app.scope);g.register([],"Escape",p=>(p.preventDefault(),o(),!1)),this.app.keymap?.pushScope(g),setTimeout(()=>{e.addEventListener("mousedown",a,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),i=t.createDiv({cls:"stashpad-view-btn"});i.setAttribute("role","button"),i.setAttribute("tabindex","0");let s=i.createSpan({cls:"stashpad-view-icon"});(0,P.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(us[e]),(e!=="nested"||this.currentEncryptionFilter()!=="all")&&i.addClass("is-active"),i.title=e==="nested"?"View: Nested (the default). Click to switch to Flat or Everything.":e==="flat"?"View: Flat \u2014 all descendants of the current focus, flat by sort order. Drag-reorder is disabled in this mode. Click to change.":"View: Everything \u2014 all descendants of the current focus PLUS non-Stashpad files in the folder, flat by created/ctime. Click to change.";let o=a=>{a.preventDefault(),this.openViewMenu(i)};i.onclick=o,i.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&o(a)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(r=>r.remove());let i=e.body.createDiv({cls:"stashpad-view-popover"});P.Platform.isMobile&&i.addClass("is-mobile");let s=t.getBoundingClientRect();i.style.left=`${Math.max(8,s.left)}px`,i.style.top=`${s.bottom+4}px`,i.style.minWidth=`${s.width}px`,i.style.maxWidth="min(320px, calc(100vw - 16px))",i.style.width="max-content";let n=()=>{i.remove(),e.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(a)}catch{}},o=r=>{!i.contains(r.target)&&r.target!==t&&!t.contains(r.target)&&n()};this.populateViewMenuBody(i,n);let a=new P.Scope(this.app.scope);a.register([],"Escape",r=>(r.preventDefault(),n(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",o,!0)},0)}populateViewMenuBody(t,e){let i=this.currentViewMode(),s=(y,v)=>{let S=t.createDiv({cls:"stashpad-view-popover-row"});y===i&&S.addClass("is-active"),S.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:us[y]}),S.createDiv({cls:"stashpad-view-popover-desc",text:v}),S.onclick=async F=>{F.preventDefault(),F.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(),v=(S,M,F)=>{let N=t.createDiv({cls:"stashpad-view-popover-row"});S===y&&N.addClass("is-active"),N.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:M}),N.createDiv({cls:"stashpad-view-popover-desc",text:F}),N.onclick=async Q=>{Q.preventDefault(),Q.stopPropagation(),S!==y&&(await this.setEncryptionFilter(S),this.refreshList()),e()}};v("all","Encryption: show all","Both locked \u{1F512} and decrypted notes."),v("locked","Encryption: locked only","Show only locked \u{1F512} stubs."),v("unlocked","Encryption: decrypted only","Hide locked \u{1F512} stubs."),t.createDiv({cls:"stashpad-view-popover-divider"})}let n=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),o=n.createEl("input",{type:"checkbox"});o.checked=this.currentHideChildless(),n.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),n.createDiv({cls:"stashpad-view-popover-desc",text:i==="nested"?"Show only notes that have children. Applied at this level.":"Hide top-level notes without children; keep every parent's full subtree so no task is overlooked."}),n.onclick=async y=>{y.target!==o&&(y.preventDefault(),o.checked=!o.checked),await this.setHideChildless(o.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),r=a.createEl("input",{type:"checkbox"});r.checked=this.currentHideCompleted(),a.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide completed notes"}),a.createDiv({cls:"stashpad-view-popover-desc",text:"Hide notes marked complete. A completed parent stays visible while any descendant is still incomplete."}),a.onclick=async y=>{y.target!==r&&(y.preventDefault(),r.checked=!r.checked),await this.setHideCompleted(r.checked),this.refreshList()};let l=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),c=l.createEl("input",{type:"checkbox"});c.checked=this.currentAttachmentsOnly(),l.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),l.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),l.onclick=async y=>{y.target!==c&&(y.preventDefault(),c.checked=!c.checked),await this.setAttachmentsOnly(c.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let g=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&g.addClass("is-disabled");let p=g.createEl("input",{type:"checkbox"});p.checked=this.currentIncludeAttachments(),p.disabled=i!=="everything",g.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),g.createDiv({cls:"stashpad-view-popover-desc",text:i==="everything"?"Show attachments referenced by notes as their own rows in the file list. Off by default \u2014 they already appear inline on the notes that embed them.":"Only applies in Everything mode."}),g.onclick=async y=>{i==="everything"&&(y.target!==p&&(y.preventDefault(),p.checked=!p.checked),await this.setIncludeAttachments(p.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let d=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),I=d.createEl("input",{type:"checkbox"});I.checked=this.importedOnly,d.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),d.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),d.onclick=y=>{y.target!==I&&(y.preventDefault(),I.checked=!I.checked),this.importedOnly=I.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let u=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let y of this.app.vault.getMarkdownFiles()){if((y.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let v=ne(this.app.metadataCache.getFileCache(y)?.frontmatter?.author);v&&u.set(v.id,v.name)}let C=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),m=C.createDiv({cls:"stashpad-view-popover-main"});m.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let E=m.createEl("select",{cls:"stashpad-view-author-select"}),w=E.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[y,v]of[...u.entries()].sort((S,M)=>S[1].localeCompare(M[1]))){let S=E.createEl("option",{text:v,value:y});this.authorFilter===y&&(S.selected=!0)}E.onclick=y=>y.stopPropagation(),E.onchange=()=>{this.authorFilter=E.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},C.createDiv({cls:"stashpad-view-popover-desc",text:u.size?"Show only notes by the chosen author.":"No authored notes in this folder yet."})}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let i=this.noteFolder,s=this.focusId,n=this.sortStore.getMode(i,s);for(let o of Bn){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:yi[o]}),a.onclick=async r=>{r.preventDefault(),r.stopPropagation(),e(),o!==n&&(this.sortStore.setMode(i,s,o),await this.sortStore.save(i),this.tree.rebuild(i),this.render())}}}populateTimeMenuBody(t,e){let i=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),s=i.createEl("input",{type:"checkbox"});s.checked=this.timeFilterCalendar,i.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),i.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),i.onclick=n=>{n.target!==s&&(n.preventDefault(),s.checked=!s.checked),this.timeFilterCalendar=s.checked,this.persistFocus(),this.refreshList()};for(let n of fs){let o=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===n.key&&o.addClass("is-active");let a=this.timeFilterCalendar?n.calLong:n.rollLong;o.createSpan({cls:"stashpad-sort-popover-label",text:a}),o.onclick=r=>{r.preventDefault(),r.stopPropagation(),e(),this.timeFilter!==n.key&&this.setTimeFilter(n.key)}}}populateColorMenuBody(t,e,i){let s=(n,o,a)=>{let r=t.createDiv({cls:"stashpad-color-filter-popover-row"}),l=r.createSpan({cls:"stashpad-color-filter-swatch"});o?l.style.background=o:l.addClass("is-empty");let c=r.createSpan({cls:"stashpad-color-filter-popover-label"});c.setText(n),o&&(c.style.color=o),r.onclick=g=>{g.preventDefault(),g.stopPropagation(),a(),i()}};s("All colors",null,()=>this.setColorFilter(null));for(let n of e){let o=this.plugin.getColorAlias(this.noteFolder,n.hex),a=o?`${o} (${n.count})`:`${n.hex} (${n.count})`;s(a,n.hex,()=>this.setColorFilter(n.hex))}}populateTagMenuBody(t,e){let i=this.collectFolderTags(),s=(n,o)=>{let a=t.createDiv({cls:"stashpad-color-filter-popover-row"});a.createSpan({cls:"stashpad-color-filter-swatch is-empty"}),a.createSpan({cls:"stashpad-color-filter-popover-label"}).setText(n),(this.tagFilter??"")===(o??"")&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),c.stopPropagation(),this.setTagFilter(o),e()}};s(i.length===0?"No tags":"All tags",null);for(let n of i)s(`${n.label} (${n.count})`,n.raw)}setColorFilter(t){let e=t?t.toLowerCase():null;(this.colorFilter??null)!==e&&(this.colorFilter=e,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}setTimeFilter(t){this.timeFilter!==t&&(this.timeFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}reconcileSelectionAfterFilter(){let t=this.filterChildren(this.collectViewItems(this.focusId)),e=new Set(t.map(i=>i.id));for(let i of[...this.selection])e.has(i)||this.selection.delete(i);if(this.firstSelectedId&&!e.has(this.firstSelectedId)&&(this.firstSelectedId=null),this.lastSelected&&!e.has(this.lastSelected)&&(this.lastSelected=null),this.selection.size>0){let i=t.findIndex(s=>this.selection.has(s.id));this.cursorIdx=i>=0?i:Math.min(this.cursorIdx,t.length-1)}else this.cursorIdx>=t.length&&(this.cursorIdx=t.length-1)}renderTinyHeader(t){let e=t.createDiv({cls:"stashpad-tiny-header"}),i=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});ge(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==T||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==T?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});ge(n,"arrow-right","\u203A"),n.title=this.navForwardSnapshots.length>0?"Forward":"No forward history",this.navForwardSnapshots.length===0&&n.addClass("is-disabled"),n.onclick=()=>this.navigateForward();let o=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),r=this.focusId===T?a:`${a} / ${this.titleForNode(o).trim()}`,l=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=l.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,P.setIcon)(c,"folder"),l.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:r}),l.title=`${this.noteFolder}${this.focusId!==T?` / ${this.titleForNode(o).trim()}`:""} +Click to switch / create folder.`,l.onclick=u=>{u.preventDefault(),this.plugin.openFolderPicker()};let g=e.createDiv({cls:"stashpad-tiny-sticky"}),p=g.createEl("input",{type:"checkbox"});if(p.checked=this.tinyAlwaysOnTop,g.createSpan({text:"Sticky"}),p.onchange=()=>{this.tinyAlwaysOnTop=p.checked,this.applyTinyAlwaysOnTop()},!P.Platform.isMobile){let u=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,P.setIcon)(u,"contrast"),u.title="Window transparency",this.tinyOpacity<1&&u.addClass("is-active"),u.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(u)}}let d=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,P.setIcon)(d,this.compactMode?"panel-top":"rows-2"),d.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&d.addClass("is-active"),d.onclick=()=>{this.toggleCompactMode()};let I=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,P.setIcon)(I,"maximize-2"),I.title="Exit tiny mode",I.onclick=()=>{this.exitTinyMode()}}toggleTinyOpacityPopover(t){if(this.tinyOpacityPopover){this.tinyOpacityPopover.remove(),this.tinyOpacityPopover=null;return}let e=document.createElement("div");e.className="stashpad-tiny-opacity-popover",e.createSpan({cls:"stashpad-tiny-opacity-label",text:"Transparency"});let i=e.createEl("input",{type:"range"});i.min="30",i.max="100",i.step="1",i.value=String(Math.round(this.tinyOpacity*100));let s=e.createSpan({cls:"stashpad-tiny-opacity-pct",text:`${i.value}%`});i.addEventListener("input",()=>{let c=Math.min(100,Math.max(30,parseInt(i.value,10)||100));this.tinyOpacity=c/100,s.setText(`${c}%`),this.applyTinyOpacity(),t.toggleClass("is-active",this.tinyOpacity<1)}),i.addEventListener("change",()=>{this.app.workspace.requestSaveLayout()}),this.viewRoot.appendChild(e);let n=t.getBoundingClientRect(),o=this.viewRoot.getBoundingClientRect();e.style.top=`${n.bottom-o.top+4}px`,e.style.left=`${Math.max(4,Math.min(n.left-o.left,o.width-180))}px`;let a=c=>{e.contains(c.target)||c.target===t||t.contains(c.target)||l()},r=c=>{c.key==="Escape"&&l()},l=()=>{e.remove(),this.tinyOpacityPopover=null,document.removeEventListener("mousedown",a,!0),document.removeEventListener("keydown",r,!0)};setTimeout(()=>{document.addEventListener("mousedown",a,!0),document.addEventListener("keydown",r,!0)},0),this.tinyOpacityPopover=e,i.focus()}getOwnElectronWindow(){try{let t=this.containerEl?.ownerDocument?.defaultView??window,s=((t?.require?.("electron")??window.require?.("electron"))?.remote??t?.electron?.remote??t?.["@electron/remote"])?.getCurrentWindow?.()??t?.electronWindow??null;if(!s)try{let n=window.require?.("electron"),o=n?.remote??n?.["@electron/remote"],r=(o?.BrowserWindow??n?.BrowserWindow)?.getAllWindows?.()??[];r.length===1?s=r[0]:r.length>1&&(s=o?.getFocusedWindow?.()??null??r[r.length-1])}catch(n){console.debug("[Stashpad] BrowserWindow.getAllWindows fallback failed",n)}return s||console.debug("[Stashpad] couldn't resolve own electron window"),s??null}catch(t){return console.debug("[Stashpad] resolve own electron window failed",t),null}}applyTinyAlwaysOnTop(){let t=this.getOwnElectronWindow();if(t)try{t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop)}catch(e){console.debug("[Stashpad] setAlwaysOnTop failed",e)}}applyTinyOpacity(){let t=this.getOwnElectronWindow();if(!t)return;let e=Math.min(1,Math.max(.3,this.tinyOpacity));try{t.setOpacity?.(e)}catch(i){console.debug("[Stashpad] setOpacity failed",i)}}applyTinyWindow(){let t=this.getOwnElectronWindow();if(t)try{if(this.tinyMode){t.setMinimumSize?.(220,260);let s=100,n=100;try{let o=t.getBounds?.();o&&typeof o.x=="number"&&(s=o.x,n=o.y)}catch{}try{t.setBounds?.({x:s,y:n,width:280,height:360})}catch{}try{t.setSize?.(280,360)}catch{}t.setAlwaysOnTop?.(!!this.tinyAlwaysOnTop);try{t.setOpacity?.(Math.min(1,Math.max(.3,this.tinyOpacity)))}catch{}}else t.setAlwaysOnTop?.(!1)}catch(e){console.debug("[Stashpad] tiny window apply failed",e)}}async exitTinyMode(){this.tinyMode=!1,this.tinyAlwaysOnTop=!1,this.tinyOpacity=1;try{this.getOwnElectronWindow()?.setOpacity?.(1)}catch{}this.compactMode=!1,this.applyTinyWindow();let t=this.getOwnElectronWindow();try{if(t?.setMinimumSize?.(400,300),P.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(P.Platform.isMobile?((0,P.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(T),this.focusId===T){let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,P.setIcon)(g,"panel-top"),g.title="Exit compact mode",g.onclick=p=>{p.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(c=>{let g=this.titleForNode(c),p=g.length>s?g.slice(0,s-1)+"\u2026":g;return{id:c.id,label:p}}),r=c=>c.reduce((g,p)=>g+p.label.length+3,0);if(r(a)>n&&a.length>2){let c=!1;for(;r(a)>n&&a.length>2;)a.splice(1,1),c||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),c=!0)}for(let c of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),c.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:c.label}).title=o.map(g=>this.titleForNode(g)).join(" / ");else{let g=c.id,p=e.createSpan({cls:"stashpad-crumb",text:c.label});p.title=c.label,p.onclick=()=>this.navigateTo(g),p.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,g)},P.Platform.isMobile&&this.attachLongPress(p,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,T)}),P.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,T))}let l=this.tree.getChildren(this.focusId).length;if(l>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${l}`}).title=`${l} direct child${l===1?"":"ren"}`),this.compactMode){let c=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,P.setIcon)(c,"panel-top"),c.title="Exit compact mode",c.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}}attachLongPress(t,e){let i=null,s=0,n=0,o=()=>{i!=null&&(window.clearTimeout(i),i=null)};t.addEventListener("touchstart",a=>{let r=a.touches[0];s=r?.clientX??0,n=r?.clientY??0,o(),i=window.setTimeout(()=>{i=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let r=a.touches[0];r&&(Math.abs(r.clientX-s)>10||Math.abs(r.clientY-n)>10)&&o()},{passive:!0}),t.addEventListener("touchend",o),t.addEventListener("touchcancel",o)}openCrumbMenu(t,e){let i=this.tree.get(e);if(!i)return;let s=new P.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,P.setIcon)(o,"pencil"),o.title="Edit in new tab",o.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(i)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),i=t.querySelector(".stashpad-focused-mini");!e||!i||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(s=>{for(let n of s)i.toggleClass("is-visible",!n.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let i=e.file,s=t.createDiv({cls:"stashpad-focused"}),o=s.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});o.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),o.createDiv({cls:"stashpad-focused-grip-spacer"});let a=s.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",g=>this.handleRenderedClick(g,e));let r=s.createDiv({cls:"stashpad-focused-actions"}),l=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,P.setIcon)(l,"pencil"),l.title="Edit in new tab",l.onclick=()=>void this.openFileAtEnd(i);let c=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,P.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:P.Platform.isMobile,toggleHost:r,toggleAnchor:l})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(a=>a.id===this.focusId),n=i.slice(s+1,i.length-1);if(n.length===0)return;let o=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,r)=>{let l=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});l.title=`Focus into "${this.titleForNode(a)}"`,l.onclick=c=>{c.stopPropagation(),this.navigateTo(a.id)},r<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Oi(this.app,t,P.Platform.isMobile)}bulkActionMessage(t){let e=t.nodes.map(a=>`"${this.titleForNode(a).trim()||"(untitled)"}"`),i=t.suffix?` ${t.suffix}`:"",s=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${i}${s}`;if(e.length===1)return`${t.verb} ${e[0]}${i}${s}`;let n=t.bulletMax??10,o=e.length<=n?e.map(a=>`\u2022 ${a}`).join(` `):e.slice(0,n).map(a=>`\u2022 ${a}`).join(` `)+` \u2026+ ${e.length-n} more`;return`${t.verb} ${e.length} notes${i}${s}: -${o}`}titleList(t,e=3){if(!t.length)return"";let i=t.map(n=>this.titleForNode(n).trim()||"(untitled)");return i.length<=e?i.map(n=>`"${n}"`).join(", "):`${i.slice(0,e).map(n=>`"${n}"`).join(", ")}, +${i.length-e} more`}titleForNode(t){if(!t.file)return"Untitled";let i=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return i||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}async forceManualMode(t){let e=this.noteFolder;this.sortStore.getMode(e,t)!=="manual"&&(this.sortStore.setMode(e,t,"manual"),await this.sortStore.save(e))}renderNote(t,e,i){if(!e.file||this.currentEncryptionFilter()==="locked")return;let s=e.file,n=this.tree.getChildren(e.id).length,o=this.selection.has(e.id),a=i===this.cursorIdx,r=this.inListPicker?.activeIdx===i,l=t.createDiv({cls:"stashpad-note"});o&&l.addClass("is-selected"),a&&l.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&l.addClass("is-cursor-expanded"),r&&l.addClass("is-pick-target"),this.isCompleted(e)&&l.addClass("is-completed"),this.isCutPending(e.id)?l.addClass("is-cut-pending"):this.isCopyPending(e.id)&&l.addClass("is-copy-pending"),l.dataset.idx=String(i),l.dataset.id=e.id;let c=this.currentViewMode()==="nested";l.draggable=c,c&&this.dnd.attachRowDnD(l,e,i),l.addEventListener("click",y=>this.handleRowClick(y,i,e)),l.addEventListener("dblclick",y=>{!this.plugin.settings.doubleClickToFocus||y.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(y.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let g=this.isTask(e)||this.compactMode;g&&(l.addClass("is-task"),P.Platform.isMobile||this.addTaskCheckbox(l,e));let p=l.createDiv({cls:"stashpad-note-meta"}),d=p.createDiv({cls:"stashpad-note-meta-top"});d.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let I=this.colorForNode(e),u=d.createDiv({cls:"stashpad-note-grip"});I&&u.addClass("has-color"),(0,P.setIcon)(u,"grip-vertical"),u.title=I?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=c,c||(u.title=I?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),I&&u.style.setProperty("--stashpad-note-color",I);let f=g&&P.Platform.isMobile;if(n>0||f){let y=p.createDiv({cls:"stashpad-note-meta-bottom"});if(f&&this.addTaskCheckbox(y,e),n>0){let v=y.createSpan({cls:"stashpad-note-enter"});I&&(v.style.color=I),(0,P.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=S=>{S.stopPropagation(),this.navigateTo(e.id)}}}if(I)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",I);else{let y=this.inheritedColorForNode(e);y&&y.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",y.hex),l.style.setProperty("--stashpad-inherited-depth",String(y.depth)))}let C=l.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(C,e);let m=C.createDiv({cls:"stashpad-note-body-content"}),E=l.createDiv({cls:"stashpad-note-actions"}),w;if(P.Platform.isMobile){let y=E.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,P.setIcon)(y,"ellipsis-vertical"),y.title="Actions",y.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},w=y}else{let y=E.createEl("button",{cls:"stashpad-pencil"});(0,P.setIcon)(y,"pencil"),y.title="Edit in new tab",y.onclick=S=>{S.stopPropagation(),this.openFileAtEnd(s)};let v=E.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,P.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=S=>{S.stopPropagation(),this.navigateTo(e.id)},w=y}this.renderNoteBody(m,e,{clamp:!0,toggleHost:E,toggleAnchor:w}),l.oncontextmenu=y=>{y.preventDefault(),this.openNoteMenu(y,e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,P.setIcon)(i,s?"check-square":"square"),i.title=s?"Mark not done":"Mark done",i.addEventListener("mousedown",n=>n.stopPropagation()),i.addEventListener("dblclick",n=>{n.preventDefault(),n.stopPropagation()}),i.onclick=n=>{n.preventDefault(),n.stopPropagation(),this.toggleCompletedForNode(e)}}renderNoteBody(t,e,i={clamp:!0}){if(!e.file)return;if(this.bodyRenderer.hasFreshRenderCache(e.file)||!this.bodyRenderer.isArmed()){this.renderNoteBodyNow(t,e,i);return}t.empty();let s=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});s.textContent=this.titleForNode(e),this.bodyRenderer.defer(t,()=>this.renderNoteBodyNow(t,e,i))}renderNoteBodyNow(t,e,i={clamp:!0}){if(!e.file)return;let s=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.bodyRenderer.getOrComputeRender(s).then(o=>{if(t.__stashpadRenderToken!==n)return;let{text:a,attachments:r,html:l}=o;t.empty();let c=t.createDiv({cls:"stashpad-note-text"}),g=this.expandedNotes.has(e.id);if(i.clamp&&!g&&c.addClass("is-clamped"),this.compactMode||this.tinyMode?(c.addClass("is-plain"),c.textContent=a):c.innerHTML=l,r.length>0&&this.renderAttachmentRail(t,r),this.renderAuthorshipFooter(t,e),!i.clamp)return;let p=this.lastListWidth;if(o.ovW===p&&o.ovV!==void 0&&!g){o.ovV?this.attachExpandToggle(i,t,e,g):c.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let d=c.scrollHeight>c.clientHeight+4;if(o.ovW=p,o.ovV=d,!d&&!g){c.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,g)})})}attachExpandToggle(t,e,i,s){let n=!!t.toggleHost,o=t.toggleHost??e;o.querySelector(".stashpad-expand-toggle")?.remove();let a=o.createEl("button",{cls:"stashpad-expand-toggle"});a.title=s?"Show less":"Show more",n||P.Platform.isMobile?((0,P.setIcon)(a,s?"chevron-up":"chevron-down"),a.addClass("is-icon"),n&&a.addClass("is-inline")):a.setText(s?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(a,t.toggleAnchor),a.onclick=r=>{r.stopPropagation(),this.expandedNotes.has(i.id)?this.expandedNotes.delete(i.id):this.expandedNotes.add(i.id),e.empty(),this.renderNoteBody(e,i,t)}}renderAttachmentRail(t,e){let i=t.createDiv({cls:"stashpad-rail"});for(let s of e){let n=this.app.metadataCache.getFirstLinkpathDest(s,""),o=(s.split(".").pop()??"").toLowerCase(),a=i.createDiv({cls:"stashpad-att"});if(a.title=s,n&&fr.has(o)){let r=a.createEl("img",{cls:"stashpad-att-img"});r.src=this.app.vault.getResourcePath(n),r.alt=s}else{a.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let r=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:r})}a.onclick=r=>{r.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=It(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=t.createDiv({cls:"stashpad-composer"}),a=n.createDiv({cls:"stashpad-composer-input-wrap"}).createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});a.value=this.composerDraft,this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,P.debounce)(D=>{this.saveDraft(D)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value)}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let r=null,l=()=>{r||(r=new P.Scope(this.app.scope),r.register([],"Escape",()=>(this.composerExitAt=Date.now(),a.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),r.register(["Mod"],"z",()=>!0),r.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(r))},c=()=>{if(r){try{this.app.keymap?.popScope(r)}catch{}r=null}};if(a.addEventListener("focus",l),a.addEventListener("blur",c),document.activeElement===a&&l(),P.Platform.isMobile){let D=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),D()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),D(),P.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new Je(this.app,a),this.composerAutocomplete.attach();let g=async D=>{let K="";for(let N of D){let Y=await this.importAttachment(N);if(!Y)continue;let q=a.value+K,_=q&&!q.endsWith(` +${o}`}titleList(t,e=3){if(!t.length)return"";let i=t.map(n=>this.titleForNode(n).trim()||"(untitled)");return i.length<=e?i.map(n=>`"${n}"`).join(", "):`${i.slice(0,e).map(n=>`"${n}"`).join(", ")}, +${i.length-e} more`}titleForNode(t){if(!t.file)return"Untitled";let i=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return i||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}async forceManualMode(t){let e=this.noteFolder;this.sortStore.getMode(e,t)!=="manual"&&(this.sortStore.setMode(e,t,"manual"),await this.sortStore.save(e))}renderNote(t,e,i){if(!e.file||this.currentEncryptionFilter()==="locked")return;let s=e.file,n=this.tree.getChildren(e.id).length,o=this.selection.has(e.id),a=i===this.cursorIdx,r=this.inListPicker?.activeIdx===i,l=t.createDiv({cls:"stashpad-note"});o&&l.addClass("is-selected"),a&&l.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&l.addClass("is-cursor-expanded"),r&&l.addClass("is-pick-target"),this.isCompleted(e)&&l.addClass("is-completed"),this.isCutPending(e.id)?l.addClass("is-cut-pending"):this.isCopyPending(e.id)&&l.addClass("is-copy-pending"),l.dataset.idx=String(i),l.dataset.id=e.id;let c=this.currentViewMode()==="nested";l.draggable=c,c&&this.dnd.attachRowDnD(l,e,i),l.addEventListener("click",y=>this.handleRowClick(y,i,e)),l.addEventListener("dblclick",y=>{!this.plugin.settings.doubleClickToFocus||y.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(y.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let g=this.isTask(e)||this.compactMode;g&&(l.addClass("is-task"),P.Platform.isMobile||this.addTaskCheckbox(l,e));let p=l.createDiv({cls:"stashpad-note-meta"}),d=p.createDiv({cls:"stashpad-note-meta-top"});d.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let I=this.colorForNode(e),u=d.createDiv({cls:"stashpad-note-grip"});I&&u.addClass("has-color"),(0,P.setIcon)(u,"grip-vertical"),u.title=I?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=c,c||(u.title=I?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),I&&u.style.setProperty("--stashpad-note-color",I);let f=g&&P.Platform.isMobile;if(n>0||f){let y=p.createDiv({cls:"stashpad-note-meta-bottom"});if(f&&this.addTaskCheckbox(y,e),n>0){let v=y.createSpan({cls:"stashpad-note-enter"});I&&(v.style.color=I),(0,P.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=S=>{S.stopPropagation(),this.navigateTo(e.id)}}}if(I)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",I);else{let y=this.inheritedColorForNode(e);y&&y.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",y.hex),l.style.setProperty("--stashpad-inherited-depth",String(y.depth)))}let C=l.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(C,e);let m=C.createDiv({cls:"stashpad-note-body-content"}),E=l.createDiv({cls:"stashpad-note-actions"}),w;if(P.Platform.isMobile){let y=E.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,P.setIcon)(y,"ellipsis-vertical"),y.title="Actions",y.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},w=y}else{let y=E.createEl("button",{cls:"stashpad-pencil"});(0,P.setIcon)(y,"pencil"),y.title="Edit in new tab",y.onclick=S=>{S.stopPropagation(),this.openFileAtEnd(s)};let v=E.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,P.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=S=>{S.stopPropagation(),this.navigateTo(e.id)},w=y}this.renderNoteBody(m,e,{clamp:!0,toggleHost:E,toggleAnchor:w}),l.oncontextmenu=y=>{y.preventDefault(),this.openNoteMenu(y,e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,P.setIcon)(i,s?"check-square":"square"),i.title=s?"Mark not done":"Mark done",i.addEventListener("mousedown",n=>n.stopPropagation()),i.addEventListener("dblclick",n=>{n.preventDefault(),n.stopPropagation()}),i.onclick=n=>{n.preventDefault(),n.stopPropagation(),this.toggleCompletedForNode(e)}}renderNoteBody(t,e,i={clamp:!0}){if(!e.file)return;if(this.bodyRenderer.hasFreshRenderCache(e.file)||!this.bodyRenderer.isArmed()){this.renderNoteBodyNow(t,e,i);return}t.empty();let s=t.createDiv({cls:"stashpad-note-text is-plain is-lazy-placeholder"});s.textContent=this.titleForNode(e),this.bodyRenderer.defer(t,()=>this.renderNoteBodyNow(t,e,i))}renderNoteBodyNow(t,e,i={clamp:!0}){if(!e.file)return;let s=e.file,n=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=n,this.bodyRenderer.getOrComputeRender(s).then(o=>{if(t.__stashpadRenderToken!==n)return;let{text:a,attachments:r,html:l}=o;t.empty();let c=t.createDiv({cls:"stashpad-note-text"}),g=this.expandedNotes.has(e.id);if(i.clamp&&!g&&c.addClass("is-clamped"),this.compactMode||this.tinyMode?(c.addClass("is-plain"),c.textContent=a):c.innerHTML=l,r.length>0&&this.renderAttachmentRail(t,r),this.renderAuthorshipFooter(t,e),!i.clamp)return;let p=this.lastListWidth;if(o.ovW===p&&o.ovV!==void 0&&!g){o.ovV?this.attachExpandToggle(i,t,e,g):c.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let d=c.scrollHeight>c.clientHeight+4;if(o.ovW=p,o.ovV=d,!d&&!g){c.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,g)})})}attachExpandToggle(t,e,i,s){let n=!!t.toggleHost,o=t.toggleHost??e;o.querySelector(".stashpad-expand-toggle")?.remove();let a=o.createEl("button",{cls:"stashpad-expand-toggle"});a.title=s?"Show less":"Show more",n||P.Platform.isMobile?((0,P.setIcon)(a,s?"chevron-up":"chevron-down"),a.addClass("is-icon"),n&&a.addClass("is-inline")):a.setText(s?"Show less":"Show more"),t.toggleAnchor&&t.toggleAnchor.parentElement===o&&o.insertBefore(a,t.toggleAnchor),a.onclick=r=>{r.stopPropagation(),this.expandedNotes.has(i.id)?this.expandedNotes.delete(i.id):this.expandedNotes.add(i.id),e.empty(),this.renderNoteBody(e,i,t)}}renderAttachmentRail(t,e){let i=t.createDiv({cls:"stashpad-rail"});for(let s of e){let n=this.app.metadataCache.getFirstLinkpathDest(s,""),o=(s.split(".").pop()??"").toLowerCase(),a=i.createDiv({cls:"stashpad-att"});if(a.title=s,n&&fr.has(o)){let r=a.createEl("img",{cls:"stashpad-att-img"});r.src=this.app.vault.getResourcePath(n),r.alt=s}else{a.createDiv({cls:"stashpad-att-ext",text:o.toUpperCase()||"?"});let r=(s.split("/").pop()??s).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:r})}a.onclick=r=>{r.stopPropagation(),n&&this.app.workspace.getLeaf("tab").openFile(n)}}}renderComposer(t){let e=pt(),i=this.modeEnterSubmits,s=this.modeSplit??e.splitOnLines,n=t.createDiv({cls:"stashpad-composer"}),a=n.createDiv({cls:"stashpad-composer-input-wrap"}).createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(i,s)}});a.value=this.composerDraft,this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,P.debounce)(D=>{this.saveDraft(D)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value)}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let r=null,l=()=>{r||(r=new P.Scope(this.app.scope),r.register([],"Escape",()=>(this.composerExitAt=Date.now(),a.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),r.register(["Mod"],"z",()=>!0),r.register(["Mod","Shift"],"z",()=>!0),this.app.keymap?.pushScope(r))},c=()=>{if(r){try{this.app.keymap?.popScope(r)}catch{}r=null}};if(a.addEventListener("focus",l),a.addEventListener("blur",c),document.activeElement===a&&l(),P.Platform.isMobile){let D=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),D()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),D(),P.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new Oe(this.app,a),this.composerAutocomplete.attach();let g=async D=>{let K="";for(let x of D){let Y=await this.importAttachment(x);if(!Y)continue;let q=a.value+K,_=q&&!q.endsWith(` `)?` `:"";K+=`${_}${Y} -`}K&&(a.value=a.value+K,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",D=>{if(!(!D.dataTransfer||!Array.from(D.dataTransfer.types).includes("Files"))){D.preventDefault(),D.stopPropagation();try{D.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",D=>{let K=Array.from(D.dataTransfer?.files??[]);K.length!==0&&(D.preventDefault(),D.stopPropagation(),g(K))}),a.addEventListener("paste",D=>{let K=this.plugin.noteClipboard;if(K?.mode==="cut"&&K.text&&D.clipboardData?.getData("text/plain")===K.text){if(this.focusedInsideCut(K.ids)){D.preventDefault(),new P.Notice("Can't paste a cut note into the note you're cutting.");return}D.preventDefault(),this.completeCutIntoComposer();return}let N=[],Y=D.clipboardData;if(Y){for(let q of Array.from(Y.files??[]))N.push(q);if(N.length===0){for(let q of Array.from(Y.items??[]))if(q.kind==="file"){let _=q.getAsFile();_&&N.push(_)}}N.length!==0&&(D.preventDefault(),D.stopPropagation(),g(N))}});let p=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});p.style.display="none";let d=n.createDiv({cls:"stashpad-composer-btn-rail"}),I=d.createDiv({cls:"stashpad-composer-btn-group"}),u=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.setIcon)(u,"list-end"),u.title=s?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",s&&u.addClass("is-active"),u.onmousedown=D=>D.preventDefault(),u.onclick=D=>{D.preventDefault(),this.toggleSplit()};let f=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.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=D=>D.preventDefault(),f.onclick=D=>{D.preventDefault();let K=document.activeElement===a;this.openDestinationPicker(K)};let C=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.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=D=>D.preventDefault(),C.onclick=D=>{D.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let m=D=>{let K=a.value&&!a.value.endsWith(` +`}K&&(a.value=a.value+K,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",D=>{if(!(!D.dataTransfer||!Array.from(D.dataTransfer.types).includes("Files"))){D.preventDefault(),D.stopPropagation();try{D.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",D=>{let K=Array.from(D.dataTransfer?.files??[]);K.length!==0&&(D.preventDefault(),D.stopPropagation(),g(K))}),a.addEventListener("paste",D=>{let K=this.plugin.noteClipboard;if(K?.mode==="cut"&&K.text&&D.clipboardData?.getData("text/plain")===K.text){if(this.focusedInsideCut(K.ids)){D.preventDefault(),new P.Notice("Can't paste a cut note into the note you're cutting.");return}D.preventDefault(),this.completeCutIntoComposer();return}let x=[],Y=D.clipboardData;if(Y){for(let q of Array.from(Y.files??[]))x.push(q);if(x.length===0){for(let q of Array.from(Y.items??[]))if(q.kind==="file"){let _=q.getAsFile();_&&x.push(_)}}x.length!==0&&(D.preventDefault(),D.stopPropagation(),g(x))}});let p=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});p.style.display="none";let d=n.createDiv({cls:"stashpad-composer-btn-rail"}),I=d.createDiv({cls:"stashpad-composer-btn-group"}),u=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.setIcon)(u,"list-end"),u.title=s?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",s&&u.addClass("is-active"),u.onmousedown=D=>D.preventDefault(),u.onclick=D=>{D.preventDefault(),this.toggleSplit()};let f=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.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=D=>D.preventDefault(),f.onclick=D=>{D.preventDefault();let K=document.activeElement===a;this.openDestinationPicker(K)};let C=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.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=D=>D.preventDefault(),C.onclick=D=>{D.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let m=D=>{let K=a.value&&!a.value.endsWith(` `)?` `:"";a.value+=`${K}${D} -`,this.composerDraft=a.value},E=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.setIcon)(E,"paperclip"),E.title="Attach files",E.onmousedown=D=>D.preventDefault(),E.onclick=D=>{D.preventDefault();let K=document.activeElement===a;if(p.click(),K){let N=()=>{a.focus()};setTimeout(N,100),setTimeout(N,500)}},p.addEventListener("change",async()=>{let D=Array.from(p.files??[]);p.value="";for(let K of D){let N=await this.importAttachment(K);N&&m(N)}a.focus()});let w=d.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,P.setIcon)(w,"chevron-left"),w.title="Show more composer options",d.insertBefore(w,I);let y=D=>{d.toggleClass("is-expanded",D),w.title=D?"Hide options":"Show more composer options",(0,P.setIcon)(w,D?"chevron-right":"chevron-left")};w.onmousedown=D=>D.preventDefault(),w.onclick=D=>{D.preventDefault(),y(!d.hasClass("is-expanded"))},y(!1);let v=()=>n.clientWidth<700,S=()=>{let D=v();n.toggleClass("is-narrow",D),y(!D)};S(),requestAnimationFrame(S);let U=new ResizeObserver(S);U.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=U;let F=d.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});F.title="Send (Enter)",(0,P.setIcon)(F,"arrow-up");let x=async()=>{let D=a.value.trim();if(!D)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(D)}catch{}let K=this.modeSplit??It().splitOnLines,N=this.nextDestination,Y=this.nextDestinationFolder,q=!!Y&&Y!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!q,this.scrollToBottomOnNextRender=!q;let _=q?{targetFolder:Y}:void 0;if(K)for(let L of D.split(/\r?\n/)){let T=L.trim();T&&await this.createNoteUnder(T,N,_)}else await this.createNoteUnder(D,N,_);It().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,q&&this.composerInputEl?.focus())};F.onclick=()=>void x(),a.addEventListener("keydown",D=>{let K=this.modeEnterSubmits;if(D.key==="Escape"){D.preventDefault(),D.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(D.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(D.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let N=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,Y=N?this.currentChildren.findIndex(q=>q.id===N):-1;this.cursorIdx=Y>=0?Y:this.currentChildren.length-1,this.selectCursor(!1)}return}D.key==="Enter"&&!D.isComposing&&(K?!D.shiftKey:D.shiftKey)&&(D.preventDefault(),D.stopPropagation(),D.stopImmediatePropagation(),x())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return P.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=It().bindings,o=g=>{let p=n[g];return p.primary&&p.secondary?p.preferRight?p.secondary:p.primary:p.primary||p.secondary},a=yi(o("toggleSplit")),r=yi(o("pickDestination")),l=yi(o("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${r} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===M)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(M),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let a=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(a){let r=this.app.internalPlugins?.plugins?.["global-search"],l=r?.instance?.openGlobalSearch?.bind(r.instance);l&&l(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=t.target,n=s?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let l=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(l){let c=this.app.internalPlugins?.plugins?.["global-search"],g=c?.instance?.openGlobalSearch?.bind(c.instance);g&&g(`tag:#${l}`)}return}let o=s?.closest?.(".internal-link");if(o){t.preventDefault(),t.stopPropagation();let r=o.getAttribute("data-href")||o.getAttribute("href");if(r){let l=i.file?.path||"";this.app.workspace.openLinkText(r,l,!0)}return}if(s?.tagName==="A"&&s.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}let a=this.selection.size===0;if(t.shiftKey&&this.lastSelected){this.cursorIdx=e;let r=this.currentChildren.findIndex(l=>l.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),r!==-1){let[l,c]=r<e?[r,e]:[e,r];for(let g=l;g<=c;g++)this.selection.add(this.currentChildren[g].id)}else this.selection.add(i.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(i.id))if(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null),this.lastSelected===i.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let r=this.lastSelected??[...this.selection][this.selection.size-1],l=r?this.currentChildren.findIndex(c=>c.id===r):-1;l>=0&&(this.cursorIdx=l)}else this.cursorIdx=e,a&&(this.firstSelectedId=i.id),this.selection.add(i.id);else this.mobileSelectMode?(this.cursorIdx=e,this.selection.has(i.id)?(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null)):this.selection.add(i.id)):(this.cursorIdx=e,this.selection.clear(),this.selection.add(i.id),this.firstSelectedId=i.id,this.lastSelected=i.id);this.selection.size===0&&(this.firstSelectedId=null),this.selection.has(i.id)&&(this.lastSelected=i.id),this.viewRoot.focus({preventScroll:!0}),this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}revealCursorRow(){let t=()=>{if(this.cursorIdx<0)return;let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let i=this.listEl,s=i.getBoundingClientRect(),n=e.getBoundingClientRect(),o=4,a=s.top+o,r=s.bottom-o;if(P.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let l=this.viewRoot?.querySelector(".stashpad-composer");l&&(r=Math.min(r,l.getBoundingClientRect().top-o))}n.top<a?i.scrollTop+=n.top-a:n.bottom>r&&(i.scrollTop+=n.bottom-r)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}jumpToTop(){this.currentChildren.length!==0&&(this.cursorIdx=0,this.selectCursor(!1))}jumpToBottom(){this.currentChildren.length!==0&&(this.cursorIdx=this.currentChildren.length-1,this.selectCursor(!1))}selectCursor(t){let e=this.currentChildren[this.cursorIdx];if(e){if(!t)this.selection.clear(),this.selection.add(e.id),this.firstSelectedId=e.id,this.lastSelected=e.id;else{let i=this.firstSelectedId??e.id,s=this.currentChildren.findIndex(n=>n.id===i);if(s===-1)this.selection.add(e.id),this.firstSelectedId=e.id;else{let[n,o]=s<this.cursorIdx?[s,this.cursorIdx]:[this.cursorIdx,s];this.selection.clear();for(let a=n;a<=o;a++)this.selection.add(this.currentChildren[a].id);this.firstSelectedId=i}this.lastSelected=e.id}this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}}repaintSelectionClasses(){if(!this.listEl)return;let t=!!this.plugin.settings.autoExpandCursorRow,e=this.inListPicker?.activeIdx??-1;this.listEl.querySelectorAll(".stashpad-note").forEach(s=>{let n=Number(s.dataset.idx),o=s.dataset.id??"",a=n===this.cursorIdx;s.classList.toggle("is-cursor",a),s.classList.toggle("is-selected",this.selection.has(o)),s.classList.toggle("is-cursor-expanded",t&&a),s.classList.toggle("is-pick-target",n===e)})}revealRowAt(t){if(!this.listEl)return;let e=this.listEl.querySelector(`.stashpad-note[data-idx="${t}"]`);if(!e)return;let i=e.getBoundingClientRect(),s=this.listEl.getBoundingClientRect();(i.top<s.top||i.bottom>s.bottom)&&e.scrollIntoView({block:"nearest",behavior:"auto"})}getActionTargets(){if(this.selection.size>0)return[...this.selection].map(e=>this.tree.get(e)).filter(e=>!!e&&!!e.file);let t=this.currentChildren[this.cursorIdx];return t?[t]:[]}async cmdLockSelection(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(o=>o.id)),i=new Set((this.plugin.settings.lockedSubtrees??[]).map(o=>o.rootId).filter(o=>!!o)),s=t.filter(o=>{if(i.has(o.id))return!1;let a=o.parent;for(;a;){if(e.has(a))return!1;a=this.tree.get(a)?.parent??null}return!0});if(s.length===0){new P.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??M),r=a.indexOf(o.id),l=r>0?a[r-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,l,{silent:!0})&&n++}n>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Locked ${n} stash${n===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}async cmdMoveToArchive(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=(this.plugin.settings.archiveFolders??[]).filter(o=>o!==this.noteFolder);if(t.length===0){new P.Notice("No archive folder available. Mark a folder as archive first (folder panel \u2192 right-click \u2192 \u201CMark as archive\u201D).",8e3);return}let e=this.getActionTargets();if(e.length===0)return;let i=this.plugin.settings.defaultArchiveFolder,s=i&&t.includes(i)?i:t.length===1?t[0]:null,n=o=>{this.archiveSources(e,o)};if(s){n(s);return}new vn(this.app,t,n).open()}async archiveSources(t,e){let i=this.noteFolder,s=new Set(t.map(l=>l.id)),n=t.filter(l=>{let c=l.parent;for(;c;){if(s.has(c))return!1;c=this.tree.get(c)?.parent??null}return!0});if(n.length===0)return;let o=n.map(l=>l.id),a=[];for(let l of n){let c=this.order.getOrder(i,l.parent??M),g=c.indexOf(l.id),p=g>0?c[g-1]:null,d=await this.plugin.lockNoteSubtree(i,l.id,p,{silent:!0,blobFolder:e});d&&a.push(d.blobPath)}if(a.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let r=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${a.length} note${a.length===1?"":"s"} \u2192 \u201C${r}\u201D. Undo to bring ${a.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${a.length})`,undo:async()=>{for(let l of a)try{await this.plugin.unlockBundleAt(l,{silent:!0,destFolder:i})}catch(c){console.warn("[Stashpad] archive undo failed",l,c)}a=[],this.tree.rebuild(i),this.render()},redo:async()=>{a=[];for(let l of o){let c=await this.plugin.lockNoteSubtree(i,l,null,{silent:!0,blobFolder:e});c&&a.push(c.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(n=>n.id)),i=t.filter(n=>{let o=n.parent;for(;o;){if(e.has(o))return!1;o=this.tree.get(o)?.parent??null}return!0});if(i.length===0)return;let s=i.length;new Ft(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 P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let e=new Set(t.map(a=>a.id)),i=t.filter(a=>{let r=a.parent;for(;r;){if(e.has(r))return!1;r=this.tree.get(r)?.parent??null}return!0});if(i.length===0)return;let s=this.noteFolder,n=i.map(a=>a.id),o=[];for(let a of n){let r=await this.plugin.encryptDeleteSubtree(s,a);r&&o.push(r)}o.length!==0&&(this.selection.clear(),this.lastSelected=null,this.tree.rebuild(s),this.render(),this.plugin.notifications.show({message:`Securely deleted ${o.length} note${o.length===1?"":"s"} \u2192 encrypted trash. Undo to bring ${o.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:s}),this.plugin.getUndoStack(s).push({label:`Secure delete (${o.length})`,undo:async()=>{for(let a of o)try{await this.plugin.restoreDeletedAt(a,{silent:!0})}catch(r){console.warn("[Stashpad] secure-delete undo failed",a,r)}o=[],this.tree.rebuild(s),this.render()},redo:async()=>{o=[];for(let a of n){let r=await this.plugin.encryptDeleteSubtree(s,a);r&&o.push(r)}this.tree.rebuild(s),this.render()}}))}async cmdUnlockAll(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=new Set,e=new Set,i=this.getActionTargets().map(n=>n.id);for(;i.length;){let n=i.pop();if(!e.has(n)){e.add(n);for(let o of this.tree.getChildren(n))i.push(o.id)}}for(let n of e)for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob);if(t.size===0){let n=(this.tree.get(this.focusId)??this.tree.getRoot()).id;for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob)}if(t.size===0){new P.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??It().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new te(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===M?"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===M&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:M,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!==M&&!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===M},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new te(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 te(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 te(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",placeholder:`Create "${s}" under which note?`,allowCreate:!1,crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(n=>n!==this.noteFolder),localFolder:this.noteFolder,onPick:async n=>{let o=n.crossFolder?n.crossId??n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!o)return;let r=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",l=this.app.workspace,c=l.getLeaf("tab");await c.setViewState({type:ct,active:!0,state:{focusId:o,folderOverride:a===r?null:a}}),l.revealLeaf(c);let g=c.view;if(g&&typeof g.createNoteUnder=="function"){let p=await g.createNoteUnder(s,o);p&&typeof g.navigateTo=="function"&&g.navigateTo(p)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.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===M&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:M,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let r=n.get(a);r||(r=[],n.set(a,r)),r.push(o)}for(let o of i){let a=n.get(o)??[],r=new Map;for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter;typeof c?.id=="string"&&r.set(c.id,l)}for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id:"";if(!g||g===M)continue;let p=l.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),d,I=c?.parent??null;if(I&&I!==M){let u=r.get(I);u&&(d=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:l,folder:o,id:g,title:p,body:"",parentBlurb:d,parentId:I??null})}}return e}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===M){i.push(s.id);continue}let o=n.parent??M;await this.changeParent(s,o),e.push(s)}if(e.length===0){new P.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 Ee(this.app,i,s,async(n,o)=>{let a=[];for(let g of t)if(g.file){a.push({id:g.id,path:g.file.path,was:this.colorForNode(g)??null});try{await this.app.fileManager.processFrontMatter(g.file,p=>{n?p.color=n:delete p.color})}catch(p){new P.Notice(`Couldn't set color for ${g.id}: ${p.message}`)}}if(o.addToPalette&&typeof n=="string"){let g=[...this.plugin.settings.customPalette??[]],p=n.toLowerCase();g.some(d=>d.toLowerCase()===p)||(g.push(n),this.plugin.settings.customPalette=g,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:M,payload:{color:n}}))}this.render();let r=this.noteFolder,l=n,c=async g=>{for(let p of g){let d=this.app.vault.getAbstractFileByPath(p.path);if(d)try{await this.app.fileManager.processFrontMatter(d,I=>{p.col?I.color=p.col:delete I.color})}catch{}}this.tree.rebuild(r),this.render()};this.plugin.getUndoStack(r).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>c(a.map(g=>({path:g.path,col:g.was}))),redo:()=>c(a.map(g=>({path:g.path,col:l})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:M,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new te(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 P.Notice("Target folder is empty");return}let n=[],o=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(p.path);let a=(p,d)=>{if(!p.file)return;let I=p.file,u=`${s}/${I.name}`;if(o.has(u)){let f=I.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:I.basename,m=f?f[2]:"";for(let E=1;E<1e3;E++){let w=`${C}-${E}${m}.md`,y=`${s}/${w}`;if(!o.has(y)){u=y;break}}}o.add(u),n.push({id:p.id,file:I,oldPath:I.path,newPath:u,oldParent:p.parent,isRoot:d});for(let f of this.tree.getChildren(p.id))a(f,!1)};for(let p of t)a(p,!0);if(!n.length)return;await this.ensureFolder(s);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,d=>{d.parent=i}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?i:p.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(d){new P.Notice(`Move failed for ${p.id}: ${d.message}`)}if(It().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{Ke(this.app,p),Ke(this.app,s)},350)}let r=this.titleList(t);this.tree.rebuild(this.noteFolder);let l=i===M?"Open home":"Open parent",c=Math.max(0,n.length-t.length),g=t.length===1?`Moved ${r}${c>0?` and its ${c} nested note${c===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${r}${c>0?` (${c} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:g,kind:"success",category:"move",duration:0,affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:l,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.newPath);if(d)try{await this.app.fileManager.renameFile(d,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.oldPath);if(d)try{await this.app.fileManager.renameFile(d,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=i})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}nextPickableIdx(t,e){for(let i=t+e;i>=0&&i<this.currentChildren.length;i+=e){let s=this.currentChildren[i];if(s&&!this.selection.has(s.id))return i}return t}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;if(this.currentChildren[t]&&this.selection.has(this.currentChildren[t].id)){let n=this.nextPickableIdx(t,-1);t=n!==t?n:this.nextPickableIdx(t,1)}this.inListPicker={activeIdx:t};let e=It().bindings.move,i=yi(e.primary||e.secondary||"M");new P.Notice(`Arrows to pick parent, Enter confirms, ${i} for the full picker, Esc cancels.`);let s=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let n=this.listEl;n.scrollTop=s,requestAnimationFrame(()=>{n.scrollTop=s}),setTimeout(()=>{n.scrollTop=s},60)}}async commitInListPicker(){if(!this.inListPicker)return;let t=this.currentChildren[this.inListPicker.activeIdx];if(this.inListPicker=null,!t){this.render();return}let e=this.getActionTargets().filter(a=>a.id!==t.id),i=new Map(e.map(a=>[a.id,this.tree.getChildren(a.id).length])),s=[];for(let a of e)await this.changeParent(a,t.id,{silentSuccess:!0})&&s.push(a);if(this.notifyBatchMove(s,t.id,i),this.plugin.settings.autoNavOnMoveIn){this.navigateTo(t.id);return}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"});let n=this.selectionGuardKey,o=()=>{if(this.selectionGuardKey!==n)return;let a=this.currentChildren.findIndex(r=>r.id===t.id);a<0||this.selection.size===1&&this.selection.has(t.id)&&this.cursorIdx===a||(this.selection.clear(),this.selection.add(t.id),this.cursorIdx=a,this.render({kind:"follow-cursor"}))};setTimeout(o,120),setTimeout(o,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new P.Notice("Select 2+ notes to merge.");return}t.sort((u,f)=>(u.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],a=[];for(let u of t){if(!u.file)continue;let f=await this.app.vault.cachedRead(u.file);a.push(this.stripFrontmatter(f).trim())}let r=a.map(u=>u.trim()).filter(Boolean).join(` +`,this.composerDraft=a.value},E=I.createEl("button",{cls:"stashpad-composer-btn"});(0,P.setIcon)(E,"paperclip"),E.title="Attach files",E.onmousedown=D=>D.preventDefault(),E.onclick=D=>{D.preventDefault();let K=document.activeElement===a;if(p.click(),K){let x=()=>{a.focus()};setTimeout(x,100),setTimeout(x,500)}},p.addEventListener("change",async()=>{let D=Array.from(p.files??[]);p.value="";for(let K of D){let x=await this.importAttachment(K);x&&m(x)}a.focus()});let w=d.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,P.setIcon)(w,"chevron-left"),w.title="Show more composer options",d.insertBefore(w,I);let y=D=>{d.toggleClass("is-expanded",D),w.title=D?"Hide options":"Show more composer options",(0,P.setIcon)(w,D?"chevron-right":"chevron-left")};w.onmousedown=D=>D.preventDefault(),w.onclick=D=>{D.preventDefault(),y(!d.hasClass("is-expanded"))},y(!1);let v=()=>n.clientWidth<700,S=()=>{let D=v();n.toggleClass("is-narrow",D),y(!D)};S(),requestAnimationFrame(S);let M=new ResizeObserver(S);M.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=M;let F=d.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});F.title="Send (Enter)",(0,P.setIcon)(F,"arrow-up");let N=async()=>{let D=a.value.trim();if(!D)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(D)}catch{}let K=this.modeSplit??pt().splitOnLines,x=this.nextDestination,Y=this.nextDestinationFolder,q=!!Y&&Y!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!q,this.scrollToBottomOnNextRender=!q;let _=q?{targetFolder:Y}:void 0;if(K)for(let L of D.split(/\r?\n/)){let U=L.trim();U&&await this.createNoteUnder(U,x,_)}else await this.createNoteUnder(D,x,_);pt().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,q&&this.composerInputEl?.focus())};F.onclick=()=>void N(),a.addEventListener("keydown",D=>{let K=this.modeEnterSubmits;if(D.key==="Escape"){D.preventDefault(),D.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(D.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(D.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let x=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,Y=x?this.currentChildren.findIndex(q=>q.id===x):-1;this.cursorIdx=Y>=0?Y:this.currentChildren.length-1,this.selectCursor(!1)}return}D.key==="Enter"&&!D.isComposing&&(K?!D.shiftKey:D.shiftKey)&&(D.preventDefault(),D.stopPropagation(),D.stopImmediatePropagation(),N())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return P.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=pt().bindings,o=g=>{let p=n[g];return p.primary&&p.secondary?p.preferRight?p.secondary:p.primary:p.primary||p.secondary},a=wi(o("toggleSplit")),r=wi(o("pickDestination")),l=wi(o("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${r} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===T)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(T),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let a=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(a){let r=this.app.internalPlugins?.plugins?.["global-search"],l=r?.instance?.openGlobalSearch?.bind(r.instance);l&&l(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=t.target,n=s?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let l=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(l){let c=this.app.internalPlugins?.plugins?.["global-search"],g=c?.instance?.openGlobalSearch?.bind(c.instance);g&&g(`tag:#${l}`)}return}let o=s?.closest?.(".internal-link");if(o){t.preventDefault(),t.stopPropagation();let r=o.getAttribute("data-href")||o.getAttribute("href");if(r){let l=i.file?.path||"";this.app.workspace.openLinkText(r,l,!0)}return}if(s?.tagName==="A"&&s.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}let a=this.selection.size===0;if(t.shiftKey&&this.lastSelected){this.cursorIdx=e;let r=this.currentChildren.findIndex(l=>l.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),r!==-1){let[l,c]=r<e?[r,e]:[e,r];for(let g=l;g<=c;g++)this.selection.add(this.currentChildren[g].id)}else this.selection.add(i.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(i.id))if(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null),this.lastSelected===i.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let r=this.lastSelected??[...this.selection][this.selection.size-1],l=r?this.currentChildren.findIndex(c=>c.id===r):-1;l>=0&&(this.cursorIdx=l)}else this.cursorIdx=e,a&&(this.firstSelectedId=i.id),this.selection.add(i.id);else this.mobileSelectMode?(this.cursorIdx=e,this.selection.has(i.id)?(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null)):this.selection.add(i.id)):(this.cursorIdx=e,this.selection.clear(),this.selection.add(i.id),this.firstSelectedId=i.id,this.lastSelected=i.id);this.selection.size===0&&(this.firstSelectedId=null),this.selection.has(i.id)&&(this.lastSelected=i.id),this.viewRoot.focus({preventScroll:!0}),this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}revealCursorRow(){let t=()=>{if(this.cursorIdx<0)return;let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let i=this.listEl,s=i.getBoundingClientRect(),n=e.getBoundingClientRect(),o=4,a=s.top+o,r=s.bottom-o;if(P.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let l=this.viewRoot?.querySelector(".stashpad-composer");l&&(r=Math.min(r,l.getBoundingClientRect().top-o))}n.top<a?i.scrollTop+=n.top-a:n.bottom>r&&(i.scrollTop+=n.bottom-r)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}jumpToTop(){this.currentChildren.length!==0&&(this.cursorIdx=0,this.selectCursor(!1))}jumpToBottom(){this.currentChildren.length!==0&&(this.cursorIdx=this.currentChildren.length-1,this.selectCursor(!1))}selectCursor(t){let e=this.currentChildren[this.cursorIdx];if(e){if(!t)this.selection.clear(),this.selection.add(e.id),this.firstSelectedId=e.id,this.lastSelected=e.id;else{let i=this.firstSelectedId??e.id,s=this.currentChildren.findIndex(n=>n.id===i);if(s===-1)this.selection.add(e.id),this.firstSelectedId=e.id;else{let[n,o]=s<this.cursorIdx?[s,this.cursorIdx]:[this.cursorIdx,s];this.selection.clear();for(let a=n;a<=o;a++)this.selection.add(this.currentChildren[a].id);this.firstSelectedId=i}this.lastSelected=e.id}this.repaintSelectionClasses(),this.revealCursorRow(),this.stampSelectedCursor(),this.plugin.notifyStashpadSelectionChanged()}}repaintSelectionClasses(){if(!this.listEl)return;let t=!!this.plugin.settings.autoExpandCursorRow,e=this.inListPicker?.activeIdx??-1;this.listEl.querySelectorAll(".stashpad-note").forEach(s=>{let n=Number(s.dataset.idx),o=s.dataset.id??"",a=n===this.cursorIdx;s.classList.toggle("is-cursor",a),s.classList.toggle("is-selected",this.selection.has(o)),s.classList.toggle("is-cursor-expanded",t&&a),s.classList.toggle("is-pick-target",n===e)})}revealRowAt(t){if(!this.listEl)return;let e=this.listEl.querySelector(`.stashpad-note[data-idx="${t}"]`);if(!e)return;let i=e.getBoundingClientRect(),s=this.listEl.getBoundingClientRect();(i.top<s.top||i.bottom>s.bottom)&&e.scrollIntoView({block:"nearest",behavior:"auto"})}getActionTargets(){if(this.selection.size>0)return[...this.selection].map(e=>this.tree.get(e)).filter(e=>!!e&&!!e.file);let t=this.currentChildren[this.cursorIdx];return t?[t]:[]}async cmdLockSelection(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(o=>o.id)),i=new Set((this.plugin.settings.lockedSubtrees??[]).map(o=>o.rootId).filter(o=>!!o)),s=t.filter(o=>{if(i.has(o.id))return!1;let a=o.parent;for(;a;){if(e.has(a))return!1;a=this.tree.get(a)?.parent??null}return!0});if(s.length===0){new P.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??T),r=a.indexOf(o.id),l=r>0?a[r-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,l,{silent:!0})&&n++}n>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Locked ${n} stash${n===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}async cmdMoveToArchive(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=(this.plugin.settings.archiveFolders??[]).filter(o=>o!==this.noteFolder);if(t.length===0){new P.Notice("No archive folder available. Mark a folder as archive first (folder panel \u2192 right-click \u2192 \u201CMark as archive\u201D).",8e3);return}let e=this.getActionTargets();if(e.length===0)return;let i=this.plugin.settings.defaultArchiveFolder,s=i&&t.includes(i)?i:t.length===1?t[0]:null,n=o=>{this.archiveSources(e,o)};if(s){n(s);return}new kn(this.app,t,n).open()}async archiveSources(t,e){let i=this.noteFolder,s=new Set(t.map(l=>l.id)),n=t.filter(l=>{let c=l.parent;for(;c;){if(s.has(c))return!1;c=this.tree.get(c)?.parent??null}return!0});if(n.length===0)return;let o=n.map(l=>l.id),a=[];for(let l of n){let c=this.order.getOrder(i,l.parent??T),g=c.indexOf(l.id),p=g>0?c[g-1]:null,d=await this.plugin.lockNoteSubtree(i,l.id,p,{silent:!0,blobFolder:e});d&&a.push(d.blobPath)}if(a.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let r=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${a.length} note${a.length===1?"":"s"} \u2192 \u201C${r}\u201D. Undo to bring ${a.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${a.length})`,undo:async()=>{for(let l of a)try{await this.plugin.unlockBundleAt(l,{silent:!0,destFolder:i})}catch(c){console.warn("[Stashpad] archive undo failed",l,c)}a=[],this.tree.rebuild(i),this.render()},redo:async()=>{a=[];for(let l of o){let c=await this.plugin.lockNoteSubtree(i,l,null,{silent:!0,blobFolder:e});c&&a.push(c.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=this.getActionTargets();if(t.length===0)return;let e=new Set(t.map(n=>n.id)),i=t.filter(n=>{let o=n.parent;for(;o;){if(e.has(o))return!1;o=this.tree.get(o)?.parent??null}return!0});if(i.length===0)return;let s=i.length;new Ft(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 P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let e=new Set(t.map(a=>a.id)),i=t.filter(a=>{let r=a.parent;for(;r;){if(e.has(r))return!1;r=this.tree.get(r)?.parent??null}return!0});if(i.length===0)return;let s=this.noteFolder,n=i.map(a=>a.id),o=[];for(let a of n){let r=await this.plugin.encryptDeleteSubtree(s,a);r&&o.push(r)}o.length!==0&&(this.selection.clear(),this.lastSelected=null,this.tree.rebuild(s),this.render(),this.plugin.notifications.show({message:`Securely deleted ${o.length} note${o.length===1?"":"s"} \u2192 encrypted trash. Undo to bring ${o.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:s}),this.plugin.getUndoStack(s).push({label:`Secure delete (${o.length})`,undo:async()=>{for(let a of o)try{await this.plugin.restoreDeletedAt(a,{silent:!0})}catch(r){console.warn("[Stashpad] secure-delete undo failed",a,r)}o=[],this.tree.rebuild(s),this.render()},redo:async()=>{o=[];for(let a of n){let r=await this.plugin.encryptDeleteSubtree(s,a);r&&o.push(r)}this.tree.rebuild(s),this.render()}}))}async cmdUnlockAll(){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=new Set,e=new Set,i=this.getActionTargets().map(n=>n.id);for(;i.length;){let n=i.pop();if(!e.has(n)){e.add(n);for(let o of this.tree.getChildren(n))i.push(o.id)}}for(let n of e)for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob);if(t.size===0){let n=(this.tree.get(this.focusId)??this.tree.getRoot()).id;for(let o of this.plugin.lockedSubtreesFor(this.noteFolder,n))t.add(o.blob)}if(t.size===0){new P.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??pt().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new te(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===T?"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===T&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:T,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!==T&&!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===T},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new te(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 te(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 te(this.app,this.tree,n=>this.titleForNode(n),{mode:"pick",placeholder:`Create "${s}" under which note?`,allowCreate:!1,crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(n=>n!==this.noteFolder),localFolder:this.noteFolder,onPick:async n=>{let o=n.crossFolder?n.crossId??n.id.replace(/^cross:/,""):n.node?.id,a=n.crossFolder??this.noteFolder;if(!o)return;let r=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",l=this.app.workspace,c=l.getLeaf("tab");await c.setViewState({type:ct,active:!0,state:{focusId:o,folderOverride:a===r?null:a}}),l.revealLeaf(c);let g=c.view;if(g&&typeof g.createNoteUnder=="function"){let p=await g.createNoteUnder(s,o);p&&typeof g.navigateTo=="function"&&g.navigateTo(p)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.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===T&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:T,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let r=n.get(a);r||(r=[],n.set(a,r)),r.push(o)}for(let o of i){let a=n.get(o)??[],r=new Map;for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter;typeof c?.id=="string"&&r.set(c.id,l)}for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id:"";if(!g||g===T)continue;let p=l.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),d,I=c?.parent??null;if(I&&I!==T){let u=r.get(I);u&&(d=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:l,folder:o,id:g,title:p,body:"",parentBlurb:d,parentId:I??null})}}return e}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===T){i.push(s.id);continue}let o=n.parent??T;await this.changeParent(s,o),e.push(s)}if(e.length===0){new P.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 Ee(this.app,i,s,async(n,o)=>{let a=[];for(let g of t)if(g.file){a.push({id:g.id,path:g.file.path,was:this.colorForNode(g)??null});try{await this.app.fileManager.processFrontMatter(g.file,p=>{n?p.color=n:delete p.color})}catch(p){new P.Notice(`Couldn't set color for ${g.id}: ${p.message}`)}}if(o.addToPalette&&typeof n=="string"){let g=[...this.plugin.settings.customPalette??[]],p=n.toLowerCase();g.some(d=>d.toLowerCase()===p)||(g.push(n),this.plugin.settings.customPalette=g,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:T,payload:{color:n}}))}this.render();let r=this.noteFolder,l=n,c=async g=>{for(let p of g){let d=this.app.vault.getAbstractFileByPath(p.path);if(d)try{await this.app.fileManager.processFrontMatter(d,I=>{p.col?I.color=p.col:delete I.color})}catch{}}this.tree.rebuild(r),this.render()};this.plugin.getUndoStack(r).push({label:a.length===1?"Color change":`Color change (${a.length})`,undo:()=>c(a.map(g=>({path:g.path,col:g.was}))),redo:()=>c(a.map(g=>({path:g.path,col:l})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:T,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new te(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 P.Notice("Target folder is empty");return}let n=[],o=new Set;for(let p of this.app.vault.getMarkdownFiles())(p.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(p.path);let a=(p,d)=>{if(!p.file)return;let I=p.file,u=`${s}/${I.name}`;if(o.has(u)){let f=I.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:I.basename,m=f?f[2]:"";for(let E=1;E<1e3;E++){let w=`${C}-${E}${m}.md`,y=`${s}/${w}`;if(!o.has(y)){u=y;break}}}o.add(u),n.push({id:p.id,file:I,oldPath:I.path,newPath:u,oldParent:p.parent,isRoot:d});for(let f of this.tree.getChildren(p.id))a(f,!1)};for(let p of t)a(p,!0);if(!n.length)return;await this.ensureFolder(s);for(let p of n)try{await this.app.fileManager.renameFile(p.file,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(p.file,d=>{d.parent=i}),await this.log.append({type:"parent_change",id:p.id,payload:{from:p.oldParent,to:p.isRoot?i:p.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(d){new P.Notice(`Move failed for ${p.id}: ${d.message}`)}if(pt().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{ze(this.app,p),ze(this.app,s)},350)}let r=this.titleList(t);this.tree.rebuild(this.noteFolder);let l=i===T?"Open home":"Open parent",c=Math.max(0,n.length-t.length),g=t.length===1?`Moved ${r}${c>0?` and its ${c} nested note${c===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${r}${c>0?` (${c} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:g,kind:"success",category:"move",duration:0,affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:l,onClick:()=>{this.switchToFolderAndFocus(s,i)}}]}),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${n.length})`,undo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.newPath);if(d)try{await this.app.fileManager.renameFile(d,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let d=this.app.vault.getAbstractFileByPath(p.oldPath);if(d)try{await this.app.fileManager.renameFile(d,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(d,I=>{I.parent=i})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}nextPickableIdx(t,e){for(let i=t+e;i>=0&&i<this.currentChildren.length;i+=e){let s=this.currentChildren[i];if(s&&!this.selection.has(s.id))return i}return t}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;if(this.currentChildren[t]&&this.selection.has(this.currentChildren[t].id)){let n=this.nextPickableIdx(t,-1);t=n!==t?n:this.nextPickableIdx(t,1)}this.inListPicker={activeIdx:t};let e=pt().bindings.move,i=wi(e.primary||e.secondary||"M");new P.Notice(`Arrows to pick parent, Enter confirms, ${i} for the full picker, Esc cancels.`);let s=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let n=this.listEl;n.scrollTop=s,requestAnimationFrame(()=>{n.scrollTop=s}),setTimeout(()=>{n.scrollTop=s},60)}}async commitInListPicker(){if(!this.inListPicker)return;let t=this.currentChildren[this.inListPicker.activeIdx];if(this.inListPicker=null,!t){this.render();return}let e=this.getActionTargets().filter(a=>a.id!==t.id),i=new Map(e.map(a=>[a.id,this.tree.getChildren(a.id).length])),s=[];for(let a of e)await this.changeParent(a,t.id,{silentSuccess:!0})&&s.push(a);if(this.notifyBatchMove(s,t.id,i),this.plugin.settings.autoNavOnMoveIn){this.navigateTo(t.id);return}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"});let n=this.selectionGuardKey,o=()=>{if(this.selectionGuardKey!==n)return;let a=this.currentChildren.findIndex(r=>r.id===t.id);a<0||this.selection.size===1&&this.selection.has(t.id)&&this.cursorIdx===a||(this.selection.clear(),this.selection.add(t.id),this.cursorIdx=a,this.render({kind:"follow-cursor"}))};setTimeout(o,120),setTimeout(o,400)}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new P.Notice("Select 2+ notes to merge.");return}t.sort((u,f)=>(u.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],a=[];for(let u of t){if(!u.file)continue;let f=await this.app.vault.cachedRead(u.file);a.push(this.stripFrontmatter(f).trim())}let r=a.map(u=>u.trim()).filter(Boolean).join(` `),l=await this.app.vault.read(e.file),c=l.startsWith("---")?l.indexOf(` ---`,3)+4:0,p=`${l.slice(0,c)} ${r} -`;await this.app.vault.modify(e.file,p);for(let u=1;u<t.length;u++){let f=t[u];if(f.file){for(let C of this.tree.getChildren(f.id))C.file&&o.push({childId:C.id,childPath:C.file.path,oldParent:C.parent}),await this.changeParent(C,e.id,{record:!1});await this.app.fileManager.trashFile(f.file),await this.log.append({type:"delete",id:f.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let d=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${d}"`}),kind:"success",category:"merge",affectedIds:t.map(u=>u.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let u=e.id,f=this.selectionGuardKey,C=()=>{if(this.selectionGuardKey!==f||this.selection.has(u))return;let m=this.currentChildren.findIndex(E=>E.id===u);m<0||(this.selection.add(u),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let I=this.noteFolder;this.plugin.getUndoStack(I).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(f=>f.id));let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,s);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=f.oldParent})}this.pendingFocusIds=t.map(f=>f.id),this.tree.rebuild(I),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,p);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=e.id})}this.tree.rebuild(I),this.render()}})}cmdCopy(){return yn(this)}cmdCopyCodeBlock(){return Oo(this)}cmdCopyTree(){return Ko(this)}cmdCopyOutline(){return Yo(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.expandedNotes.has(i.id));for(let i of t)e?this.expandedNotes.add(i.id):this.expandedNotes.delete(i.id);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new P.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let s=this.tree.getChildren(t.id).slice(),n=t.file,o=await this.app.vault.read(n),a=this.stripFrontmatter(o),r=this.app.metadataCache.getFileCache(n)?.frontmatter??{},l=Bt(),c=Nt(a,this.activeStopwords()),g=xt(c,l),p=`${this.noteFolder}/${g}`,d=new Date().toISOString(),I=this.extractAttachments(a),u=["---",`id: ${l}`,`parent: ${e}`,`created: ${d}`];if(I.length>0){u.push("attachments:");for(let C of I)u.push(` - "${C.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(p,u.join(` -`)),i.push(p);let f=this.app.vault.getAbstractFileByPath(p);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,E]of Object.entries(r))se.includes(m)||(C[m]=E)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:f,created:d})}catch{}this.fmSync.scheduleParentChange(l,null,e)}for(let C of s)await this.cloneSubtree(C,l,i);return l}async cmdClone(){let t=this.getActionTargets();if(!t.length){new P.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let r of t){if(!r.file)continue;let l=r.parent??this.focusId,c=await this.cloneSubtree(r,l,i);c&&s.push(c)}if(!s.length)return;this.tree.rebuild(e),this.pendingFocusIds=s.slice(),this.render();let n=i.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:we(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),o=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(e).push({label:`Clone ${s.length} note${s.length===1?"":"s"}`,undo:async()=>{for(let r of[...i].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:a,suffix:`(${i.length} file${i.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:s,folder:this.noteFolder})}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new P.Notice("Nothing to copy.");return}await yn(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,p);for(let u=1;u<t.length;u++){let f=t[u];if(f.file){for(let C of this.tree.getChildren(f.id))C.file&&o.push({childId:C.id,childPath:C.file.path,oldParent:C.parent}),await this.changeParent(C,e.id,{record:!1});await this.app.fileManager.trashFile(f.file),await this.log.append({type:"delete",id:f.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let d=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${d}"`}),kind:"success",category:"merge",affectedIds:t.map(u=>u.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let u=e.id,f=this.selectionGuardKey,C=()=>{if(this.selectionGuardKey!==f||this.selection.has(u))return;let m=this.currentChildren.findIndex(E=>E.id===u);m<0||(this.selection.add(u),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let I=this.noteFolder;this.plugin.getUndoStack(I).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(f=>f.id));let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,s);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=f.oldParent})}this.pendingFocusIds=t.map(f=>f.id),this.tree.rebuild(I),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let u=this.app.vault.getAbstractFileByPath(i);u&&await this.app.vault.modify(u,p);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=e.id})}this.tree.rebuild(I),this.render()}})}cmdCopy(){return vn(this)}cmdCopyCodeBlock(){return Oo(this)}cmdCopyTree(){return Ko(this)}cmdCopyOutline(){return Yo(this)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(i=>!this.expandedNotes.has(i.id));for(let i of t)e?this.expandedNotes.add(i.id):this.expandedNotes.delete(i.id);this.render()}async cloneSubtree(t,e,i){if(!t.file)return null;if(t.id===e||this.isDescendant(e,t.id))return new P.Notice(`Can't insert "${this.titleForNode(t)}" into itself or a descendant \u2014 that would loop forever.`),null;let s=this.tree.getChildren(t.id).slice(),n=t.file,o=await this.app.vault.read(n),a=this.stripFrontmatter(o),r=this.app.metadataCache.getFileCache(n)?.frontmatter??{},l=mt(),c=xt(a,this.activeStopwords()),g=Mt(c,l),p=`${this.noteFolder}/${g}`,d=new Date().toISOString(),I=this.extractAttachments(a),u=["---",`id: ${l}`,`parent: ${e}`,`created: ${d}`];if(I.length>0){u.push("attachments:");for(let C of I)u.push(` - "${C.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(p,u.join(` +`)),i.push(p);let f=this.app.vault.getAbstractFileByPath(p);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,E]of Object.entries(r))se.includes(m)||(C[m]=E)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:f,created:d})}catch{}this.fmSync.scheduleParentChange(l,null,e)}for(let C of s)await this.cloneSubtree(C,l,i);return l}async cmdClone(){let t=this.getActionTargets();if(!t.length){new P.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let r of t){if(!r.file)continue;let l=r.parent??this.focusId,c=await this.cloneSubtree(r,l,i);c&&s.push(c)}if(!s.length)return;this.tree.rebuild(e),this.pendingFocusIds=s.slice(),this.render();let n=i.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:we(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),o=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(e).push({label:`Clone ${s.length} note${s.length===1?"":"s"}`,undo:async()=>{for(let r of[...i].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Cloned",nodes:a,suffix:`(${i.length} file${i.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:s,folder:this.noteFolder})}async cmdCopyNotes(){let t=this.getActionTargets();if(!t.length){new P.Notice("Nothing to copy.");return}await vn(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!==M&&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 P.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(` +${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!==T&&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 P.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 P.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){new P.Notice("Those notes were cut/copied in another folder \u2014 cross-folder paste isn't supported yet.");return}let e=t.ids.map(g=>this.tree.get(g)).filter(g=>!!g&&!!g.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new P.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??M;if(t.mode==="cut"){let g=new Set(t.ids);for(let d=s;d&&d!==M;d=this.tree.get(d)?.parent??null)if(g.has(d)){new P.Notice("Can't paste cut notes under themselves.");return}let p=i&&!g.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(d=>d.id),s,p,"after");return}let n=this.noteFolder,o=[],a=[];for(let g of e){let p=await this.cloneSubtree(g,s,o);p&&a.push(p)}if(!a.length)return;this.tree.rebuild(n),this.pendingFocusIds=a.slice(),this.render();let r=o.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>!!g&&g.extension==="md").map(g=>({id:we(g.basename)??g.basename,parent:null,children:[],file:g,created:new Date().toISOString()})),l=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(n).push({label:`Paste ${a.length} note${a.length===1?"":"s"}`,undo:async()=>{for(let g of[...o].reverse()){let p=this.app.vault.getAbstractFileByPath(g);if(p)try{await this.app.fileManager.trashFile(p)}catch{}}this.tree.rebuild(n),this.render()},redo:async()=>{await this.restoreSnapshots(l,a)}});let c=a.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:c,suffix:`(${o.length} file${o.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:a,folder:n,duration:0})}async completeCutIntoComposer(){let t=this.plugin.noteClipboard;if(!t||t.mode!=="cut"||t.folder!==this.noteFolder)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,d)=>{if(!s.has(p.id)){s.add(p.id),i.push({node:p,depth:d});for(let I of this.tree.getChildren(p.id))n(I,d+1)}};for(let p of e)n(p,0);let o=this.noteFolder,a=It().prefixTimestampsOnCopy,r=[];for(let{node:p,depth:d}of i)if(p.file)try{let I=this.stripFrontmatter(await this.app.vault.cachedRead(p.file)).trim().split(/\r?\n/).join(" "),u=a?`${this.formatTimeInline(p.created)} `:"";r.push(`${" ".repeat(d)}- ${u}${I}`)}catch{}this.insertIntoComposer(r.join(` -`));let l=i.map(p=>p.node),c=await this.snapshotNotes(l,!1);for(let p of[...l].reverse())if(p.file)try{await this.app.fileManager.trashFile(p.file)}catch(d){console.warn("[Stashpad] cut-paste delete failed",p.file.path,d)}this.selection.clear(),this.tree.rebuild(o),this.render();let g=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(c,g)},redo:async()=>{for(let p of[...c.notes]){let d=this.app.vault.getAbstractFileByPath(p.path);if(d)try{await this.app.fileManager.trashFile(d)}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"} (${l.length} note${l.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:g,folder:o,duration:0})}cmdInsertTemplate(){new te(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 P.Notice("Cross-Stashpad templates aren't supported yet \u2014 pick a note from this Stashpad.");return}let e=this.tree.get(t.id);if(!e?.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(e,this.focusId,s);if(!n)return;this.tree.rebuild(i),this.pendingFocusIds=[n],this.render();let o=s.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:we(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let r of[...s].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(a=>a.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(a=>a.hex===n)||(this.colorFilter=null)}let i=this.lastCursorByFocus.get(t),s;i&&this.tree.get(i)?(this.pendingFocusIds=[i],s={kind:"scroll-to-id",id:i,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==M&&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(M)}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 P.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(o))),s++)}s||i.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),i.showAtMouseEvent(new MouseEvent("click",{clientX:200,clientY:400}))}async bootstrapFolder(){if(this.bootstrappedFolders.has(this.noteFolder))return;await this.ensureFolder(this.noteFolder),await this.ensureHomeNote(),await this.migrateNullParents();let t=(this.plugin.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),e=(this.plugin.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");t&&await this.ensureFolder(`${this.noteFolder}/${t}`),e&&await this.ensureFolder(`${this.noteFolder}/${e}`),await this.order.load(this.noteFolder),await this.sortStore.load(this.noteFolder),this.bootstrappedFolders.add(this.noteFolder)}backfillFrontmatterSync(){let t=[M],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 P.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??T,d=t.mode,I=t.folder,u=await this.plugin.crossFolderPaste(I,t.ids,this.noteFolder,p,d);if(!u||!u.rootIds.length)return;d==="cut"&&this.plugin.clearNoteClipboard();let f=this.noteFolder;this.tree.rebuild(f),this.pendingFocusIds=u.rootIds.slice(),this.render(),d==="cut"&&this.plugin.refreshOpenViewsForFolder(I);let C=I.split("/").pop(),m=u.rootIds.length,E=()=>{this.tree.rebuild(f),this.render(),this.plugin.refreshOpenViewsForFolder(I)};this.plugin.getUndoStack(f).push({label:`${d==="cut"?"Move":"Paste"} ${m} note${m===1?"":"s"} from ${C}`,undo:async()=>{await u.undo(),E()},redo:async()=>{await u.redo(),E()}});let w=d==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${w} ${m} note${m===1?"":"s"} (${u.noteCount} total) from "${C}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:d==="cut"?"move":"clone",affectedIds:u.rootIds,folder:f,duration:0});return}let e=t.ids.map(g=>this.tree.get(g)).filter(g=>!!g&&!!g.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new P.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??T;if(t.mode==="cut"){let g=new Set(t.ids);for(let d=s;d&&d!==T;d=this.tree.get(d)?.parent??null)if(g.has(d)){new P.Notice("Can't paste cut notes under themselves.");return}let p=i&&!g.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(d=>d.id),s,p,"after");return}let n=this.noteFolder,o=[],a=[];for(let g of e){let p=await this.cloneSubtree(g,s,o);p&&a.push(p)}if(!a.length)return;this.tree.rebuild(n),this.pendingFocusIds=a.slice(),this.render();let r=o.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>!!g&&g.extension==="md").map(g=>({id:we(g.basename)??g.basename,parent:null,children:[],file:g,created:new Date().toISOString()})),l=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(n).push({label:`Paste ${a.length} note${a.length===1?"":"s"}`,undo:async()=>{for(let g of[...o].reverse()){let p=this.app.vault.getAbstractFileByPath(g);if(p)try{await this.app.fileManager.trashFile(p)}catch{}}this.tree.rebuild(n),this.render()},redo:async()=>{await this.restoreSnapshots(l,a)}});let c=a.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:c,suffix:`(${o.length} file${o.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:a,folder:n,duration:0})}async completeCutIntoComposer(){let t=this.plugin.noteClipboard;if(!t||t.mode!=="cut")return;if(t.folder!==this.noteFolder){let p=t.folder,d=t.ids.slice();this.plugin.clearNoteClipboard();let I=await this.plugin.orderedSubtreeNodes(p,d),u=pt().prefixTimestampsOnCopy,f=[];for(let{file:y,created:v,depth:S}of I)try{let M=this.stripFrontmatter(await this.app.vault.cachedRead(y)).trim().split(/\r?\n/).join(" "),F=u?`${this.formatTimeInline(v)} `:"";f.push(`${" ".repeat(S)}- ${F}${M}`)}catch{}this.insertIntoComposer(f.length?f.join(` +`):t.text??"");let C=await this.plugin.subtreeFilePaths(p,d),m=await this.plugin.snapshotPaths(C),E=await this.plugin.trashSubtrees(p,d);this.plugin.refreshOpenViewsForFolder(p);let w=E.filter(y=>y.extension==="md").length;this.plugin.getUndoStack(p).push({label:`Cut ${d.length} note${d.length===1?"":"s"} into composer (from ${p.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(m),this.plugin.refreshOpenViewsForFolder(p)},redo:async()=>{await this.plugin.trashSubtrees(p,d),this.plugin.refreshOpenViewsForFolder(p)}}),this.plugin.notifications.show({message:`Pasted the text of ${d.length} cut note${d.length===1?"":"s"} from "${p.split("/").pop()}" into the composer and removed the original${w===1?"":"s"} (${w} note${w===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:d,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,d)=>{if(!s.has(p.id)){s.add(p.id),i.push({node:p,depth:d});for(let I of this.tree.getChildren(p.id))n(I,d+1)}};for(let p of e)n(p,0);let o=this.noteFolder,a=pt().prefixTimestampsOnCopy,r=[];for(let{node:p,depth:d}of i)if(p.file)try{let I=this.stripFrontmatter(await this.app.vault.cachedRead(p.file)).trim().split(/\r?\n/).join(" "),u=a?`${this.formatTimeInline(p.created)} `:"";r.push(`${" ".repeat(d)}- ${u}${I}`)}catch{}this.insertIntoComposer(r.join(` +`));let l=i.map(p=>p.node),c=await this.snapshotNotes(l,!1);for(let p of[...l].reverse())if(p.file)try{await this.app.fileManager.trashFile(p.file)}catch(d){console.warn("[Stashpad] cut-paste delete failed",p.file.path,d)}this.selection.clear(),this.tree.rebuild(o),this.render();let g=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(c,g)},redo:async()=>{for(let p of[...c.notes]){let d=this.app.vault.getAbstractFileByPath(p.path);if(d)try{await this.app.fileManager.trashFile(d)}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"} (${l.length} note${l.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:g,folder:o,duration:0})}cmdInsertTemplate(){new te(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 P.Notice("Cross-Stashpad templates aren't supported yet \u2014 pick a note from this Stashpad.");return}let e=this.tree.get(t.id);if(!e?.file)return;let i=this.noteFolder,s=[],n=await this.cloneSubtree(e,this.focusId,s);if(!n)return;this.tree.rebuild(i),this.pendingFocusIds=[n],this.render();let o=s.map(r=>this.app.vault.getAbstractFileByPath(r)).filter(r=>!!r&&r.extension==="md").map(r=>({id:we(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let r of[...s].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(a=>a.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(a=>a.hex===n)||(this.colorFilter=null)}let i=this.lastCursorByFocus.get(t),s;i&&this.tree.get(i)?(this.pendingFocusIds=[i],s={kind:"scroll-to-id",id:i,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==T&&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(T)}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 P.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(o))),s++)}s||i.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),i.showAtMouseEvent(new MouseEvent("click",{clientX:200,clientY:400}))}async bootstrapFolder(){if(this.bootstrappedFolders.has(this.noteFolder))return;await this.ensureFolder(this.noteFolder),await this.ensureHomeNote(),await this.migrateNullParents();let t=(this.plugin.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),e=(this.plugin.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");t&&await this.ensureFolder(`${this.noteFolder}/${t}`),e&&await this.ensureFolder(`${this.noteFolder}/${e}`),await this.order.load(this.noteFolder),await this.sortStore.load(this.noteFolder),this.bootstrappedFolders.add(this.noteFolder)}backfillFrontmatterSync(){let t=[T],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!==M)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let l=this.app.vault.getAbstractFileByPath(e);if(l instanceof P.TFile)return l}catch(l){console.warn("[Stashpad] home note rename failed; keeping legacy path",l)}return o}let s=new Date().toISOString(),n=["---",`id: ${M}`,"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===M)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=M}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:M,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:ct,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let r=!1;return e.iterateAllLeaves(l=>{l===s&&(r=!0)}),r})())return;e.offref(n),(()=>{let r=!1;return e.iterateAllLeaves(l=>{l===i&&(r=!0)}),r})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))})}async openNoteInNewTab(t,e){let i=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!i||!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",n=this.app.workspace,o=n.getLeaf("tab");await o.setViewState({type:ct,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:ct,active:!0,state:{focusId:M,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let c=!1;return s.iterateAllLeaves(g=>{g===o&&(c=!0)}),c})())return;s.offref(a),(()=>{let c=!1;return s.iterateAllLeaves(g=>{g===n&&(c=!0)}),c})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new P.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.openFile(t,{active:!0}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let c=!1;return e.iterateAllLeaves(g=>{g===s&&(c=!0)}),c})())return;e.offref(n),(()=>{let c=!1;return e.iterateAllLeaves(g=>{g===i&&(c=!0)}),c})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))}),a=s.view?.editor;a&&requestAnimationFrame(()=>{try{let r=a.lastLine(),l=a.getLine(r)?.length??0;a.setCursor({line:r,ch:l}),a.scrollIntoView({from:{line:r,ch:l},to:{line:r,ch:l}},!0),a.focus()}catch{}})}cmdSelectAll(){if(this.currentChildren.length!==0){this.selection.clear();for(let t of this.currentChildren)this.selection.add(t.id);this.firstSelectedId=this.currentChildren[0].id,this.lastSelected=this.currentChildren[this.currentChildren.length-1].id,this.cursorIdx=this.currentChildren.length-1,this.render()}}async cmdTogglePin(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new P.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 P.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new P.Notice(`Unpinned ${s} note${s===1?"":"s"} from sidebar.`)}async cmdToggleComplete(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new P.Notice("Nothing to toggle.");return}let i=t.some(a=>!this.isCompleted(a)),s=[],n=[];for(let a of t){if(!a.file)continue;let r=this.isCompleted(a);s.push({id:a.id,path:a.file.path,was:r}),r!==i&&(await this.app.fileManager.processFrontMatter(a.file,l=>{i?l.completed=!0:delete l.completed}),this.completedState.set(a.file.path,i),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:i?"Marked complete":"Unmarked",nodes:a}),kind:"success",category:i?"complete":"uncomplete",affectedIds:n,folder:this.noteFolder})}let o=this.noteFolder;this.plugin.getUndoStack(o).push({label:`${i?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let r of s){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.was?c.completed=!0:delete c.completed}),n.includes(r.id)&&a.push(r.id))}a.length>0&&await this.log.append({type:i?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(o),this.render()},redo:async()=>{for(let a of s){let r=this.app.vault.getAbstractFileByPath(a.path);r&&await this.app.fileManager.processFrontMatter(r,l=>{i?l.completed=!0:delete l.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}taggedFromFm(t){return t?De(t,"task")||t.task===!0:!1}cmdSetDue(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new P.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=me(i??{});new oi(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let l of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,l.id,l.name);let a=i.map(l=>this.plugin.authorRefFor(this.noteFolder,l.id,l.name));for(let l of t){if(!l.file)continue;let c=this.app.metadataCache.getFileCache(l.file)?.frontmatter,g=this.isTaskTagged(l);s.push({id:l.id,path:l.file.path,due:c?.due,task:c?.task,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy,wasTagged:g}),await this.app.fileManager.processFrontMatter(l.file,d=>{e===null?delete d.due:(d.due=e,d.task=!0),a.length>0?(d.assignedTo=a,o&&(d.assignedBy=o.link),d.task=!0):(delete d.assignedTo,delete d.assignedBy)});let p=e!==null||a.length>0;this.taskTaggedState.set(l.file.path,p||g),n.push(l.id)}if(this.render(),n.length>0){let l=n.map(c=>this.tree.get(c)).filter(c=>!!c);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${Wt(Date.parse(e),this.plugin.settings)}`,nodes:l}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let r=this.noteFolder;this.plugin.getUndoStack(r).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let l of s){let c=this.app.vault.getAbstractFileByPath(l.path);c&&(await this.app.fileManager.processFrontMatter(c,g=>{l.due===void 0?delete g.due:g.due=l.due,l.task===void 0?delete g.task:g.task=l.task,l.assignedTo===void 0?delete g.assignedTo:g.assignedTo=l.assignedTo,l.assignedBy===void 0?delete g.assignedBy:g.assignedBy=l.assignedBy}),this.taskTaggedState.set(l.path,l.wasTagged))}this.tree.rebuild(r),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new P.Notice("Nothing to assign.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=this.plugin.collectKnownAuthors(),n=me(i??{});new ni(this.app,{knownAuthors:s,currentAssignees:n},o=>{this.applyAssignees(t,o)}).open()}async applyAssignees(t,e){let i=this.authorship.currentAuthorLink();for(let r of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,r.id,r.name);let s=e.map(r=>this.plugin.authorRefFor(this.noteFolder,r.id,r.name)),n=[],o=[];for(let r of t){if(!r.file)continue;let l=this.app.metadataCache.getFileCache(r.file)?.frontmatter,c=this.isTaskTagged(r);n.push({path:r.file.path,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,task:l?.task,wasTagged:c}),await this.app.fileManager.processFrontMatter(r.file,g=>{s.length>0?(g.assignedTo=s,i&&(g.assignedBy=i.link),g.task=!0):(delete g.assignedTo,delete g.assignedBy)}),this.taskTaggedState.set(r.file.path,s.length>0||c),o.push(r.id)}if(this.render(),o.length>0){let r=o.map(c=>this.tree.get(c)).filter(c=>!!c),l=e.map(c=>c.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:s.length>0?`Assigned to ${l}`:"Cleared assignment",nodes:r}),kind:"success",category:"edit",affectedIds:o,folder:this.noteFolder})}let a=this.noteFolder;this.plugin.getUndoStack(a).push({label:s.length>0?`Assign (${t.length})`:`Clear assignment (${t.length})`,undo:async()=>{for(let r of n){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.assignedTo===void 0?delete c.assignedTo:c.assignedTo=r.assignedTo,r.assignedBy===void 0?delete c.assignedBy:c.assignedBy=r.assignedBy,r.task===void 0?delete c.task:c.task=r.task}),this.taskTaggedState.set(r.path,r.wasTagged))}this.tree.rebuild(a),this.render()}})}isTask(t){return t.file?this.isTaskTagged(t)?!0:this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed!==void 0:!1}async cmdToggleTask(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new P.Notice("Nothing to toggle.");return}let e=t.some(a=>!this.isTaskTagged(a)),i=[],s=[];for(let a of t){if(!a.file)continue;let r=this.isTaskTagged(a),l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:l?.tags,completed:l?.completed,task:l?.task,wasTagged:r}),r===e)continue;let c=!1;await this.app.fileManager.processFrontMatter(a.file,g=>{e?(Ms(g,"task"),g.completed===void 0&&(g.completed=!1),c=g.completed===!0,delete g.task):(Hs(g,"task"),delete g.completed,delete g.task,c=!1)}),this.completedState.set(a.file.path,c),this.taskTaggedState.set(a.file.path,e),s.push(a.id)}if(this.render(),s.length>0){let a=e?"marked as task":"unmarked as task",r;if(s.length===1){let l=this.tree.get(s[0]);r=`"${l&&this.titleForNode(l).trim()||"(untitled)"}" ${a}`}else r=`${s.length} notes ${a}`;this.plugin.notifications.show({message:r,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);r&&(await this.app.fileManager.processFrontMatter(r,l=>{a.tags===void 0?delete l.tags:l.tags=a.tags,a.completed===void 0?delete l.completed:l.completed=a.completed,a.task===void 0?delete l.task:l.task=a.task}),this.completedState.set(a.path,!!a.completed),this.taskTaggedState.set(a.path,a.wasTagged))}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:o,redo:async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);if(!r)continue;let l=!1;await this.app.fileManager.processFrontMatter(r,c=>{e?(Ms(c,"task"),c.completed===void 0&&(c.completed=!1),l=c.completed===!0,delete c.task):(Hs(c,"task"),delete c.completed,delete c.task,l=!1)}),this.completedState.set(a.path,l),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==M&&!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 S of t){let U=this.tree.get(S);U?.file&&(n.push({id:S,path:U.file.path,oldParent:U.parent}),o.add(U.parent??M))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(S=>this.tree.get(S)).filter(S=>!!S)),r=this.noteFolder,l={};for(let S of o)l[S]=this.order.getOrder(r,S).slice();for(let S of n){let U=this.app.vault.getAbstractFileByPath(S.path);U&&(await this.app.fileManager.processFrontMatter(U,F=>{F.parent=e}),this.fmSync.scheduleParentChange(S.id,S.oldParent,e),await this.log.append({type:"parent_change",id:S.id,payload:{from:S.oldParent,to:e,reason:"drag"}}),this.order.removeChild(r,S.id))}this.tree.rebuild(r);let c=this.tree.getChildren(e).map(S=>S.id),g=new Set(t),p=c.filter(S=>!g.has(S)),d=p.indexOf(i);d<0&&(d=p.length),s==="after"&&(d+=1);let I=[...p.slice(0,d),...t.filter(S=>!!this.tree.get(S)),...p.slice(d)];this.order.setOrder(r,e,I),await this.order.save(r),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}});let u=this.focusId===e,f=u?t[0]:e,C=u?t.slice():[e];u?this.pendingFocusIds=C:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=C),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let m=this.selectionGuardKey,E=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let S=this.currentChildren.findIndex(U=>U.id===f);S<0||(this.selection.add(f),this.cursorIdx=S,this.render({kind:"follow-cursor"}))};setTimeout(E,120),setTimeout(E,400);let w=t.map(S=>this.tree.get(S)).filter(S=>!!S),y=this.tree.get(e),v=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${v}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:r,actions:e===M?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(r).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let S of n){let U=this.app.vault.getAbstractFileByPath(S.path);U&&(await this.app.fileManager.processFrontMatter(U,F=>{S.oldParent===null||S.oldParent===void 0?F.parent=M:F.parent=S.oldParent}),await this.log.append({type:"parent_change",id:S.id,payload:{from:e,to:S.oldParent,reason:"drag-undo"}}))}for(let[S,U]of Object.entries(l))if(U.length===0){let F=this.order.cache.get(r)??{};delete F[S],this.order.cache.set(r,F)}else this.order.setOrder(r,S,U);await this.order.save(r),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(r),this.render()},redo:async()=>{for(let S of n){let U=this.app.vault.getAbstractFileByPath(S.path);U&&(await this.app.fileManager.processFrontMatter(U,F=>{F.parent=e}),this.order.removeChild(r,S.id))}this.order.setOrder(r,e,I),await this.order.save(r),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(r),this.render()}})}async reorderToTarget(t,e,i){let s=this.tree.get(e);if(!s)return;let n=t.map(m=>this.tree.get(m)).filter(m=>!!m&&!!m.file);if(n.length===0)return;if(n.some(m=>m.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(i==="into"){for(let m of n)if(this.isDescendant(e,m.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(m)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let o=i==="into"?e:s.parent??M;if(n.some(m=>(m.parent??M)!==o)){let m=It(),E=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(m.confirmCrossParentDrag){let w=this.titleForNode(s),y=n.length,v=i==="into"?"Nest":"Move",S=i==="into"?"as children of":"under";new Ft(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${v} ${y} note${y===1?"":"s"} ${S} "${w}"? Their parent will change.`,v,U=>{U&&E()}).open()}else await E();return}let r=o,l=n.map(m=>m.id),c=this.tree.getChildren(r).map(m=>m.id),g=new Set(l),p=c.filter(m=>!g.has(m)),d=p.indexOf(e);if(d<0)return;i==="after"&&(d+=1);let I=[...p.slice(0,d),...l,...p.slice(d)];if(En(I,c))return;let u=this.noteFolder,f=this.order.getOrder(u,r).slice();this.order.setOrder(u,r,I),await this.order.save(u),await this.forceManualMode(r),await this.log.append({type:"reorder",id:r,payload:{dir:"drag",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render();let C=l.map(m=>this.tree.get(m)).filter(m=>!!m);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:C}),kind:"success",category:"reorder",affectedIds:l,folder:u}),this.plugin.getUndoStack(u).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(u)??{};delete m[r],this.order.cache.set(u,m)}else this.order.setOrder(u,r,f);await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"undo",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render()},redo:async()=>{this.order.setOrder(u,r,I),await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"redo:drag",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render()}})}cmdMoveUp(){this.reorderSelection("up")}cmdMoveDown(){this.reorderSelection("down")}cmdMoveToTop(){this.reorderSelection("top")}cmdMoveToBottom(){this.reorderSelection("bottom")}async reorderSelection(t){let e=[];if(this.selection.size>0){let g=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(g.length===0)return;if(new Set(g.map(d=>d.parent)).size>1){new P.Notice("Reorder requires a single-parent selection.");return}e=g}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new P.Notice("Nothing to reorder.");return}let i=e[0].parent??M,s=this.tree.getChildren(i).map(g=>g.id);if(s.length===0)return;let n=new Set(e.map(g=>g.id)),o=s.filter(g=>n.has(g));if(o.length===0)return;let a=qo(s,o,t);if(En(a,s))return;let r=this.noteFolder,l=this.order.getOrder(r,i).slice();this.order.setOrder(r,i,a),await this.order.save(r),await this.forceManualMode(i),await this.log.append({type:"reorder",id:i,payload:{dir:t,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let c=o.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:c,destination:t}),kind:"success",category:"reorder",affectedIds:o,folder:r}),this.plugin.getUndoStack(r).push({label:`Reorder (${t})`,undo:async()=>{if(l.length===0){let g=this.order.cache.get(r)??{};delete g[i],this.order.cache.set(r,g)}else this.order.setOrder(r,i,l);await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:"undo",parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()},redo:async()=>{this.order.setOrder(r,i,a),await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:`redo:${t}`,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let I=this.tree.get(this.focusId);I?.file&&(t=[I])}if(t.length===0){new P.Notice("Nothing selected to delete.");return}if((this.plugin.settings.encryptTrash??!1)&&!(this.plugin.settings.encryptTrashFollowObsidian??!1)){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("\u201CEncrypt items sent to trash\u201D is ON but encryption isn't set up (Settings \u2192 Encryption). Nothing was deleted.");return}await this.secureDeleteSources(t);return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],i=new Set,s=I=>{if(!i.has(I.id)){i.add(I.id);for(let u of this.tree.getChildren(I.id))s(u);e.push(I)}};for(let I of t)s(I);let n=e.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.read(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(Ce(C))}let r=[...new Set(a)],l=e.length-t.length,c=async I=>{let u=await this.snapshotNotes(e,I),f=0;if(I)for(let D of r){let K=this.app.metadataCache.getFirstLinkpathDest(D,"");if(K)try{await this.app.fileManager.trashFile(K),await this.log.append({type:"attachment_remove",id:M,payload:{path:K.path}}),this.plugin.notifications.show({message:`Deleted attachment "${K.name}"`,kind:"warning",category:"attachment",affectedPaths:[K.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let D of e)D.parent&&C.add(D.parent);let m=this.authorship.collectAuthorIds(e),E=new Set(t.map(D=>D.id)),w=this.currentChildren.map((D,K)=>E.has(D.id)?K:-1).filter(D=>D>=0),y=w.length>0?w[0]:-1,v=null;if(y>=0){for(let D=y+1;D<this.currentChildren.length;D++)if(!E.has(this.currentChildren[D].id)){v=this.currentChildren[D].id;break}if(!v){for(let D=y-1;D>=0;D--)if(!E.has(this.currentChildren[D].id)){v=this.currentChildren[D].id;break}}}for(let D of e)if(D.file){try{await this.app.fileManager.trashFile(D.file)}catch{}await this.log.append({type:"delete",id:D.id,payload:{path:D.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,v&&(this.pendingFocusIds=[v]),this.tree.rebuild(this.noteFolder);for(let D of C)e.some(K=>K.id===D)||this.fmSync.scheduleParentOfDeleted(D);this.render({kind:"follow-cursor"});let S=f>0?` with ${f} attachment${f===1?"":"s"}`:"",U=this.noteFolder,F=t.map(D=>D.id),x=!1,Q=async()=>{x||(x=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,F.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:S.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(D=>D.id),affectedAuthorIds:m,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void Q()}]}),this.plugin.getUndoStack(U).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await Q()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,x=!1,await this.trashNotesAndAttachments(u)}}),this.focusView()},g=It(),p=g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await c(!1);return}new xe(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,r.length,d,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new P.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 P.Notice("Note is too short to split.");return}let a=s,r=i.path,l=async(c,g,p)=>{if(!c.trim()||!g.trim()){new P.Notice("Split would leave one part empty.");return}try{let d=s.startsWith("---")?s.slice(0,s.indexOf(` +Error: ${e.message}`,kind:"error",category:"system",duration:0,affectedPaths:[t],folder:this.noteFolder})}))}async ensureHomeNote(){let t=this.noteFolder,e=`${t}/${this.buildHomeFilename(t)}`,i=this.app.vault.getMarkdownFiles().filter(o=>o.path.startsWith(t+"/"));for(let o of i){if(this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==T)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let l=this.app.vault.getAbstractFileByPath(e);if(l instanceof P.TFile)return l}catch(l){console.warn("[Stashpad] home note rename failed; keeping legacy path",l)}return o}let s=new Date().toISOString(),n=["---",`id: ${T}`,"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===T)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=T}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:T,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:ct,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let r=!1;return e.iterateAllLeaves(l=>{l===s&&(r=!0)}),r})())return;e.offref(n),(()=>{let r=!1;return e.iterateAllLeaves(l=>{l===i&&(r=!0)}),r})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))})}async openNoteInNewTab(t,e){let i=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!i||!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",n=this.app.workspace,o=n.getLeaf("tab");await o.setViewState({type:ct,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:ct,active:!0,state:{focusId:T,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let c=!1;return s.iterateAllLeaves(g=>{g===o&&(c=!0)}),c})())return;s.offref(a),(()=>{let c=!1;return s.iterateAllLeaves(g=>{g===n&&(c=!0)}),c})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new P.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.openFile(t,{active:!0}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let c=!1;return e.iterateAllLeaves(g=>{g===s&&(c=!0)}),c})())return;e.offref(n),(()=>{let c=!1;return e.iterateAllLeaves(g=>{g===i&&(c=!0)}),c})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))}),a=s.view?.editor;a&&requestAnimationFrame(()=>{try{let r=a.lastLine(),l=a.getLine(r)?.length??0;a.setCursor({line:r,ch:l}),a.scrollIntoView({from:{line:r,ch:l},to:{line:r,ch:l}},!0),a.focus()}catch{}})}cmdSelectAll(){if(this.currentChildren.length!==0){this.selection.clear();for(let t of this.currentChildren)this.selection.add(t.id);this.firstSelectedId=this.currentChildren[0].id,this.lastSelected=this.currentChildren[this.currentChildren.length-1].id,this.cursorIdx=this.currentChildren.length-1,this.render()}}async cmdTogglePin(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new P.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 P.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new P.Notice(`Unpinned ${s} note${s===1?"":"s"} from sidebar.`)}async cmdToggleComplete(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new P.Notice("Nothing to toggle.");return}let i=t.some(a=>!this.isCompleted(a)),s=[],n=[];for(let a of t){if(!a.file)continue;let r=this.isCompleted(a);s.push({id:a.id,path:a.file.path,was:r}),r!==i&&(await this.app.fileManager.processFrontMatter(a.file,l=>{i?l.completed=!0:delete l.completed}),this.completedState.set(a.file.path,i),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(r=>this.tree.get(r)).filter(r=>!!r);this.plugin.notifications.show({message:this.bulkActionMessage({verb:i?"Marked complete":"Unmarked",nodes:a}),kind:"success",category:i?"complete":"uncomplete",affectedIds:n,folder:this.noteFolder})}let o=this.noteFolder;this.plugin.getUndoStack(o).push({label:`${i?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let r of s){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.was?c.completed=!0:delete c.completed}),n.includes(r.id)&&a.push(r.id))}a.length>0&&await this.log.append({type:i?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(o),this.render()},redo:async()=>{for(let a of s){let r=this.app.vault.getAbstractFileByPath(a.path);r&&await this.app.fileManager.processFrontMatter(r,l=>{i?l.completed=!0:delete l.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}taggedFromFm(t){return t?Ne(t,"task")||t.task===!0:!1}cmdSetDue(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new P.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=me(i??{});new ri(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let l of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,l.id,l.name);let a=i.map(l=>this.plugin.authorRefFor(this.noteFolder,l.id,l.name));for(let l of t){if(!l.file)continue;let c=this.app.metadataCache.getFileCache(l.file)?.frontmatter,g=this.isTaskTagged(l);s.push({id:l.id,path:l.file.path,due:c?.due,task:c?.task,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy,wasTagged:g}),await this.app.fileManager.processFrontMatter(l.file,d=>{e===null?delete d.due:(d.due=e,d.task=!0),a.length>0?(d.assignedTo=a,o&&(d.assignedBy=o.link),d.task=!0):(delete d.assignedTo,delete d.assignedBy)});let p=e!==null||a.length>0;this.taskTaggedState.set(l.file.path,p||g),n.push(l.id)}if(this.render(),n.length>0){let l=n.map(c=>this.tree.get(c)).filter(c=>!!c);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${$t(Date.parse(e),this.plugin.settings)}`,nodes:l}),kind:"success",category:"edit",affectedIds:n,folder:this.noteFolder})}let r=this.noteFolder;this.plugin.getUndoStack(r).push({label:e===null?`Clear due date (${t.length})`:`Set due date (${t.length})`,undo:async()=>{for(let l of s){let c=this.app.vault.getAbstractFileByPath(l.path);c&&(await this.app.fileManager.processFrontMatter(c,g=>{l.due===void 0?delete g.due:g.due=l.due,l.task===void 0?delete g.task:g.task=l.task,l.assignedTo===void 0?delete g.assignedTo:g.assignedTo=l.assignedTo,l.assignedBy===void 0?delete g.assignedBy:g.assignedBy=l.assignedBy}),this.taskTaggedState.set(l.path,l.wasTagged))}this.tree.rebuild(r),this.render()}})}cmdAssign(){let t=this.getActionTargets();if(t.length===0){let o=this.tree.get(this.focusId);o?.file&&(t=[o])}if(t.length===0){new P.Notice("Nothing to assign.");return}let e=t[0],i=e.file?this.app.metadataCache.getFileCache(e.file)?.frontmatter:null,s=this.plugin.collectKnownAuthors(),n=me(i??{});new ai(this.app,{knownAuthors:s,currentAssignees:n},o=>{this.applyAssignees(t,o)}).open()}async applyAssignees(t,e){let i=this.authorship.currentAuthorLink();for(let r of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,r.id,r.name);let s=e.map(r=>this.plugin.authorRefFor(this.noteFolder,r.id,r.name)),n=[],o=[];for(let r of t){if(!r.file)continue;let l=this.app.metadataCache.getFileCache(r.file)?.frontmatter,c=this.isTaskTagged(r);n.push({path:r.file.path,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,task:l?.task,wasTagged:c}),await this.app.fileManager.processFrontMatter(r.file,g=>{s.length>0?(g.assignedTo=s,i&&(g.assignedBy=i.link),g.task=!0):(delete g.assignedTo,delete g.assignedBy)}),this.taskTaggedState.set(r.file.path,s.length>0||c),o.push(r.id)}if(this.render(),o.length>0){let r=o.map(c=>this.tree.get(c)).filter(c=>!!c),l=e.map(c=>c.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:s.length>0?`Assigned to ${l}`:"Cleared assignment",nodes:r}),kind:"success",category:"edit",affectedIds:o,folder:this.noteFolder})}let a=this.noteFolder;this.plugin.getUndoStack(a).push({label:s.length>0?`Assign (${t.length})`:`Clear assignment (${t.length})`,undo:async()=>{for(let r of n){let l=this.app.vault.getAbstractFileByPath(r.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{r.assignedTo===void 0?delete c.assignedTo:c.assignedTo=r.assignedTo,r.assignedBy===void 0?delete c.assignedBy:c.assignedBy=r.assignedBy,r.task===void 0?delete c.task:c.task=r.task}),this.taskTaggedState.set(r.path,r.wasTagged))}this.tree.rebuild(a),this.render()}})}isTask(t){return t.file?this.isTaskTagged(t)?!0:this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed!==void 0:!1}async cmdToggleTask(){let t=this.getActionTargets();if(t.length===0){let a=this.tree.get(this.focusId);a?.file&&(t=[a])}if(t.length===0){new P.Notice("Nothing to toggle.");return}let e=t.some(a=>!this.isTaskTagged(a)),i=[],s=[];for(let a of t){if(!a.file)continue;let r=this.isTaskTagged(a),l=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:l?.tags,completed:l?.completed,task:l?.task,wasTagged:r}),r===e)continue;let c=!1;await this.app.fileManager.processFrontMatter(a.file,g=>{e?(Hs(g,"task"),g.completed===void 0&&(g.completed=!1),c=g.completed===!0,delete g.task):(Us(g,"task"),delete g.completed,delete g.task,c=!1)}),this.completedState.set(a.file.path,c),this.taskTaggedState.set(a.file.path,e),s.push(a.id)}if(this.render(),s.length>0){let a=e?"marked as task":"unmarked as task",r;if(s.length===1){let l=this.tree.get(s[0]);r=`"${l&&this.titleForNode(l).trim()||"(untitled)"}" ${a}`}else r=`${s.length} notes ${a}`;this.plugin.notifications.show({message:r,kind:"success",category:"edit",affectedIds:s,folder:this.noteFolder})}let n=this.noteFolder,o=async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);r&&(await this.app.fileManager.processFrontMatter(r,l=>{a.tags===void 0?delete l.tags:l.tags=a.tags,a.completed===void 0?delete l.completed:l.completed=a.completed,a.task===void 0?delete l.task:l.task=a.task}),this.completedState.set(a.path,!!a.completed),this.taskTaggedState.set(a.path,a.wasTagged))}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:o,redo:async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);if(!r)continue;let l=!1;await this.app.fileManager.processFrontMatter(r,c=>{e?(Hs(c,"task"),c.completed===void 0&&(c.completed=!1),l=c.completed===!0,delete c.task):(Us(c,"task"),delete c.completed,delete c.task,l=!1)}),this.completedState.set(a.path,l),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==T&&!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 S of t){let M=this.tree.get(S);M?.file&&(n.push({id:S,path:M.file.path,oldParent:M.parent}),o.add(M.parent??T))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(S=>this.tree.get(S)).filter(S=>!!S)),r=this.noteFolder,l={};for(let S of o)l[S]=this.order.getOrder(r,S).slice();for(let S of n){let M=this.app.vault.getAbstractFileByPath(S.path);M&&(await this.app.fileManager.processFrontMatter(M,F=>{F.parent=e}),this.fmSync.scheduleParentChange(S.id,S.oldParent,e),await this.log.append({type:"parent_change",id:S.id,payload:{from:S.oldParent,to:e,reason:"drag"}}),this.order.removeChild(r,S.id))}this.tree.rebuild(r);let c=this.tree.getChildren(e).map(S=>S.id),g=new Set(t),p=c.filter(S=>!g.has(S)),d=p.indexOf(i);d<0&&(d=p.length),s==="after"&&(d+=1);let I=[...p.slice(0,d),...t.filter(S=>!!this.tree.get(S)),...p.slice(d)];this.order.setOrder(r,e,I),await this.order.save(r),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}});let u=this.focusId===e,f=u?t[0]:e,C=u?t.slice():[e];u?this.pendingFocusIds=C:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=C),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let m=this.selectionGuardKey,E=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let S=this.currentChildren.findIndex(M=>M.id===f);S<0||(this.selection.add(f),this.cursorIdx=S,this.render({kind:"follow-cursor"}))};setTimeout(E,120),setTimeout(E,400);let w=t.map(S=>this.tree.get(S)).filter(S=>!!S),y=this.tree.get(e),v=y?this.titleForNode(y):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${v}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:r,actions:e===T?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(r).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let S of n){let M=this.app.vault.getAbstractFileByPath(S.path);M&&(await this.app.fileManager.processFrontMatter(M,F=>{S.oldParent===null||S.oldParent===void 0?F.parent=T:F.parent=S.oldParent}),await this.log.append({type:"parent_change",id:S.id,payload:{from:e,to:S.oldParent,reason:"drag-undo"}}))}for(let[S,M]of Object.entries(l))if(M.length===0){let F=this.order.cache.get(r)??{};delete F[S],this.order.cache.set(r,F)}else this.order.setOrder(r,S,M);await this.order.save(r),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(r),this.render()},redo:async()=>{for(let S of n){let M=this.app.vault.getAbstractFileByPath(S.path);M&&(await this.app.fileManager.processFrontMatter(M,F=>{F.parent=e}),this.order.removeChild(r,S.id))}this.order.setOrder(r,e,I),await this.order.save(r),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(r),this.render()}})}async reorderToTarget(t,e,i){let s=this.tree.get(e);if(!s)return;let n=t.map(m=>this.tree.get(m)).filter(m=>!!m&&!!m.file);if(n.length===0)return;if(n.some(m=>m.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(i==="into"){for(let m of n)if(this.isDescendant(e,m.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(m)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let o=i==="into"?e:s.parent??T;if(n.some(m=>(m.parent??T)!==o)){let m=pt(),E=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(m.confirmCrossParentDrag){let w=this.titleForNode(s),y=n.length,v=i==="into"?"Nest":"Move",S=i==="into"?"as children of":"under";new Ft(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${v} ${y} note${y===1?"":"s"} ${S} "${w}"? Their parent will change.`,v,M=>{M&&E()}).open()}else await E();return}let r=o,l=n.map(m=>m.id),c=this.tree.getChildren(r).map(m=>m.id),g=new Set(l),p=c.filter(m=>!g.has(m)),d=p.indexOf(e);if(d<0)return;i==="after"&&(d+=1);let I=[...p.slice(0,d),...l,...p.slice(d)];if(wn(I,c))return;let u=this.noteFolder,f=this.order.getOrder(u,r).slice();this.order.setOrder(u,r,I),await this.order.save(u),await this.forceManualMode(r),await this.log.append({type:"reorder",id:r,payload:{dir:"drag",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render();let C=l.map(m=>this.tree.get(m)).filter(m=>!!m);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:C}),kind:"success",category:"reorder",affectedIds:l,folder:u}),this.plugin.getUndoStack(u).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(u)??{};delete m[r],this.order.cache.set(u,m)}else this.order.setOrder(u,r,f);await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"undo",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render()},redo:async()=>{this.order.setOrder(u,r,I),await this.order.save(u),await this.log.append({type:"reorder",id:r,payload:{dir:"redo:drag",parent:r,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(u),this.render()}})}cmdMoveUp(){this.reorderSelection("up")}cmdMoveDown(){this.reorderSelection("down")}cmdMoveToTop(){this.reorderSelection("top")}cmdMoveToBottom(){this.reorderSelection("bottom")}async reorderSelection(t){let e=[];if(this.selection.size>0){let g=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(g.length===0)return;if(new Set(g.map(d=>d.parent)).size>1){new P.Notice("Reorder requires a single-parent selection.");return}e=g}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new P.Notice("Nothing to reorder.");return}let i=e[0].parent??T,s=this.tree.getChildren(i).map(g=>g.id);if(s.length===0)return;let n=new Set(e.map(g=>g.id)),o=s.filter(g=>n.has(g));if(o.length===0)return;let a=qo(s,o,t);if(wn(a,s))return;let r=this.noteFolder,l=this.order.getOrder(r,i).slice();this.order.setOrder(r,i,a),await this.order.save(r),await this.forceManualMode(i),await this.log.append({type:"reorder",id:i,payload:{dir:t,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let c=o.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Moved",nodes:c,destination:t}),kind:"success",category:"reorder",affectedIds:o,folder:r}),this.plugin.getUndoStack(r).push({label:`Reorder (${t})`,undo:async()=>{if(l.length===0){let g=this.order.cache.get(r)??{};delete g[i],this.order.cache.set(r,g)}else this.order.setOrder(r,i,l);await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:"undo",parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()},redo:async()=>{this.order.setOrder(r,i,a),await this.order.save(r),await this.log.append({type:"reorder",id:i,payload:{dir:`redo:${t}`,parent:i,ids:o,count:o.length}}),this.pendingFocusIds=o.slice(),this.tree.rebuild(r),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let I=this.tree.get(this.focusId);I?.file&&(t=[I])}if(t.length===0){new P.Notice("Nothing selected to delete.");return}if((this.plugin.settings.encryptTrash??!1)&&!(this.plugin.settings.encryptTrashFollowObsidian??!1)){if(!this.plugin.encryption?.isConfigured?.()){new P.Notice("\u201CEncrypt items sent to trash\u201D is ON but encryption isn't set up (Settings \u2192 Encryption). Nothing was deleted.");return}await this.secureDeleteSources(t);return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],i=new Set,s=I=>{if(!i.has(I.id)){i.add(I.id);for(let u of this.tree.getChildren(I.id))s(u);e.push(I)}};for(let I of t)s(I);let n=e.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.read(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(Ce(C))}let r=[...new Set(a)],l=e.length-t.length,c=async I=>{let u=await this.snapshotNotes(e,I),f=0;if(I)for(let D of r){let K=this.app.metadataCache.getFirstLinkpathDest(D,"");if(K)try{await this.app.fileManager.trashFile(K),await this.log.append({type:"attachment_remove",id:T,payload:{path:K.path}}),this.plugin.notifications.show({message:`Deleted attachment "${K.name}"`,kind:"warning",category:"attachment",affectedPaths:[K.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let D of e)D.parent&&C.add(D.parent);let m=this.authorship.collectAuthorIds(e),E=new Set(t.map(D=>D.id)),w=this.currentChildren.map((D,K)=>E.has(D.id)?K:-1).filter(D=>D>=0),y=w.length>0?w[0]:-1,v=null;if(y>=0){for(let D=y+1;D<this.currentChildren.length;D++)if(!E.has(this.currentChildren[D].id)){v=this.currentChildren[D].id;break}if(!v){for(let D=y-1;D>=0;D--)if(!E.has(this.currentChildren[D].id)){v=this.currentChildren[D].id;break}}}for(let D of e)if(D.file){try{await this.app.fileManager.trashFile(D.file)}catch{}await this.log.append({type:"delete",id:D.id,payload:{path:D.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,v&&(this.pendingFocusIds=[v]),this.tree.rebuild(this.noteFolder);for(let D of C)e.some(K=>K.id===D)||this.fmSync.scheduleParentOfDeleted(D);this.render({kind:"follow-cursor"});let S=f>0?` with ${f} attachment${f===1?"":"s"}`:"",M=this.noteFolder,F=t.map(D=>D.id),N=!1,Q=async()=>{N||(N=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,F.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:S.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(D=>D.id),affectedAuthorIds:m,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void Q()}]}),this.plugin.getUndoStack(M).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await Q()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,N=!1,await this.trashNotesAndAttachments(u)}}),this.focusView()},g=pt(),p=g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await c(!1);return}new Te(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,r.length,d,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new P.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 P.Notice("Note is too short to split.");return}let a=s,r=i.path,l=async(c,g,p)=>{if(!c.trim()||!g.trim()){new P.Notice("Split would leave one part empty.");return}try{let d=s.startsWith("---")?s.slice(0,s.indexOf(` ---`,3)+4):"",I=d+(d?` `:"")+c+` -`;await this.app.vault.modify(i,I);let u=e.parent??M,f=Date.parse(e.created||""),C=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),m=await this.createNoteUnder(g,u,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:m,...p}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let E=m?this.tree.get(m):void 0,w=E?.file?.path,y=w?await this.app.vault.read(E.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(w){let U=this.app.vault.getAbstractFileByPath(w);if(U)try{await this.app.fileManager.trashFile(U)}catch{}}let S=this.app.vault.getAbstractFileByPath(r);S&&await this.app.vault.modify(S,a),this.tree.rebuild(v),this.render()},redo:async()=>{let S=this.app.vault.getAbstractFileByPath(r);S&&await this.app.vault.modify(S,I),w&&y&&!await this.app.vault.adapter.exists(w)&&await this.app.vault.create(w,y),this.tree.rebuild(v),this.render()}})}catch(d){new P.Notice(`Stashpad: split failed (${d.message})`),console.error(d)}};new ti(this.app,n,async c=>{let g=o.slice(0,c).join(` +`;await this.app.vault.modify(i,I);let u=e.parent??T,f=Date.parse(e.created||""),C=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),m=await this.createNoteUnder(g,u,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:m,...p}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let E=m?this.tree.get(m):void 0,w=E?.file?.path,y=w?await this.app.vault.read(E.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(w){let M=this.app.vault.getAbstractFileByPath(w);if(M)try{await this.app.fileManager.trashFile(M)}catch{}}let S=this.app.vault.getAbstractFileByPath(r);S&&await this.app.vault.modify(S,a),this.tree.rebuild(v),this.render()},redo:async()=>{let S=this.app.vault.getAbstractFileByPath(r);S&&await this.app.vault.modify(S,I),w&&y&&!await this.app.vault.adapter.exists(w)&&await this.app.vault.create(w,y),this.tree.rebuild(v),this.render()}})}catch(d){new P.Notice(`Stashpad: split failed (${d.message})`),console.error(d)}};new ii(this.app,n,async c=>{let g=o.slice(0,c).join(` `).replace(/\s+$/,""),p=o.slice(c).join(` -`).replace(/^\s+|\s+$/g,"");await l(g,p,{mode:"line",splitAtLine:c})},async c=>{let g=n.slice(0,c).replace(/\s+$/,""),p=n.slice(c).replace(/^\s+|\s+$/g,"");await l(g,p,{mode:"cursor",splitAtChar:c})}).open()}cmdOpenInNewStashpadTab(t){let e=t??this.resolveActionTarget();e?.file&&this.openInNewStashpadTab(e.id)}cmdCloneStashpadTab(){let t=this.tree.get(this.focusId);t?.file?this.cmdOpenInNewStashpadTab(t):this.openInNewStashpadTab(this.focusId)}resolveActionTarget(){if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return this.currentChildren[this.cursorIdx];let t=this.tree.get(this.focusId);return t?.file?t:void 0}cmdExportStash(t){return zo(this,t)}cmdImportStash(){return Vo(this)}processStashFile(t){return wn(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=Bt(),a=null;{let f=(this.plugin.settings.noteTemplates??{})[s];if(f){let C=this.app.vault.getAbstractFileByPath(f);if(C&&C.extension==="md")try{let m=await this.app.vault.cachedRead(C),E=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},E.includes("{{body}}")?t=E.replace(/\{\{body\}\}/g,t):t.trim()?E.trim()&&(t=`${t} +`).replace(/^\s+|\s+$/g,"");await l(g,p,{mode:"line",splitAtLine:c})},async c=>{let g=n.slice(0,c).replace(/\s+$/,""),p=n.slice(c).replace(/^\s+|\s+$/g,"");await l(g,p,{mode:"cursor",splitAtChar:c})}).open()}cmdOpenInNewStashpadTab(t){let e=t??this.resolveActionTarget();e?.file&&this.openInNewStashpadTab(e.id)}cmdCloneStashpadTab(){let t=this.tree.get(this.focusId);t?.file?this.cmdOpenInNewStashpadTab(t):this.openInNewStashpadTab(this.focusId)}resolveActionTarget(){if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return this.currentChildren[this.cursorIdx];let t=this.tree.get(this.focusId);return t?.file?t:void 0}cmdExportStash(t){return zo(this,t)}cmdImportStash(){return Vo(this)}processStashFile(t){return Fn(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=mt(),a=null;{let f=(this.plugin.settings.noteTemplates??{})[s];if(f){let C=this.app.vault.getAbstractFileByPath(f);if(C&&C.extension==="md")try{let m=await this.app.vault.cachedRead(C),E=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},E.includes("{{body}}")?t=E.replace(/\{\{body\}\}/g,t):t.trim()?E.trim()&&(t=`${t} -${E}`):t=E}catch(m){console.warn("[Stashpad] template read failed",m)}}}let r=Nt(t,this.activeStopwords()),l=xt(r,o),c=`${s}/${l}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),I=this.authorship.currentAuthorLink();I&&this.authorship.ensureAuthorFile(I);let u=["---",`id: ${o}`,`parent: ${g}`,`created: ${p}`,`modified: ${p}`];if(I&&u.push(`author: "${I.link.replace(/"/g,'\\"')}"`),d.length>0){u.push("attachments:");for(let f of d)u.push(` - "${f.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",t);try{let f=u.join(` -`);this.plugin.importService.suppress(c,6e4),await bt.timeAsync("write.createNote.file",()=>this.app.vault.create(c,f));try{let C=this.app.vault.getAbstractFileByPath(c);if(C&&C.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:g,children:[],file:C,created:p}),this.render(),this.fmSync.scheduleParentChange(o,null,g);else{this.render();let m=s.split("/").pop()||s,E=(t.split(` -`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${E}" landed in \`${m}\``,kind:"success",category:"create",duration:0,folder:s,affectedIds:[o],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(s,o)}}]})}if(a)try{await this.app.fileManager.processFrontMatter(C,m=>{for(let[E,w]of Object.entries(a))se.includes(E)||m[E]===void 0&&(m[E]=w)})}catch(m){console.warn("[Stashpad] template fm overlay failed",m)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:c,parent:g}}),i.record!==!1){let C=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let m=this.app.vault.getAbstractFileByPath(c);if(m)try{await this.app.fileManager.trashFile(m)}catch{}if(this.composerDraft=C,this.saveDraft(C),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=C;let E=C.length;this.composerInputEl.setSelectionRange(E,E),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(c)||await this.app.vault.create(c,f),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(C),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(f){return new P.Notice(`Stashpad: failed to create note (${f.message})`),null}}extractAttachments(t){let e=[],i=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,s;for(;(s=i.exec(t))!==null;)e.push(s[1]);return e}async ensureFolder(t){if(await this.app.vault.adapter.exists(t)){let e=this.app.vault.getAbstractFileByPath(t);if(e&&!(e instanceof P.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${n}-${s}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:M,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 P.Notice(`Stashpad: attachment failed (${e.message})`),null}}claimSelectedAsAuthor(){this.authorship.claimSelectedAsAuthor()}claimFolderAsAuthor(){this.authorship.claimFolderAsAuthor()}claimSelectedWithContributor(){this.authorship.claimSelectedWithContributor()}claimFolderWithContributor(){this.authorship.claimFolderWithContributor()}renderAuthorshipFooter(t,e){if(!e.file)return;let i=this.plugin.settings;if(!i.showAuthor&&!i.showContributors&&!i.showLastEdit)return;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof s.author=="string"?s.author:"",o=Array.isArray(s.contributors)?s.contributors.filter(I=>typeof I=="string"&&I.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",r=i.showAuthor&&!!n,l=i.showContributors&&o.length>0,c=i.showLastEdit&&!!a;if(!r&&!l&&!c)return;let g=t.createDiv({cls:"stashpad-note-authorship"}),p=(I,u)=>{let f=u.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,E=C>=0?f.slice(C+1):f.split("/").pop()??f,w=I.createEl("a",{cls:"internal-link",text:E});w.setAttribute("data-href",m),w.setAttribute("href",m)},d=[];r&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(I,n)}),l&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&I.createSpan({text:", "}),p(I,u)})}),c&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"edited "}),I.createSpan({text:this.formatTimeInline(a)})}),d.forEach((I,u)=>{u>0&&g.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=g.createSpan({cls:"stashpad-authorship-piece"});I(f)}),g.addEventListener("click",I=>this.handleRenderedClick(I,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Yt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,P.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=we(t.basename);if(!e||e===M)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Nt(s,this.activeStopwords()),o=xt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let r=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:r,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,P.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(e),s=this.extractAttachments(i),n=this.app.metadataCache.getFileCache(t)?.frontmatter,a=(Array.isArray(n?.attachments)?n.attachments:[]).filter(c=>typeof c=="string").map(c=>Ce(c));if(a.length===s.length&&a.every((c,g)=>c===s[g]))return;let l=s.map(c=>Ot(c));await this.app.fileManager.processFrontMatter(t,c=>{c.attachments=l})}stripFrontmatter(t){let e=t.replace(/^/,""),i=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return i?e.slice(i[0].length):e}formatTime(t){if(!t)return"";let e=(0,P.moment)(t);if(!e.isValid())return"";if(It().useTemplatesFormat){let s=es(this.app);if(s)return`${e.format(s.dateFormat)} +${E}`):t=E}catch(m){console.warn("[Stashpad] template read failed",m)}}}let r=xt(t,this.activeStopwords()),l=Mt(r,o),c=`${s}/${l}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),I=this.authorship.currentAuthorLink();I&&this.authorship.ensureAuthorFile(I);let u=["---",`id: ${o}`,`parent: ${g}`,`created: ${p}`,`modified: ${p}`];if(I&&u.push(`author: "${I.link.replace(/"/g,'\\"')}"`),d.length>0){u.push("attachments:");for(let f of d)u.push(` - "${f.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",t);try{let f=u.join(` +`);this.plugin.importService.suppress(c,6e4),await Nt.timeAsync("write.createNote.file",()=>this.app.vault.create(c,f));try{let C=this.app.vault.getAbstractFileByPath(c);if(C&&C.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:g,children:[],file:C,created:p}),this.render(),this.fmSync.scheduleParentChange(o,null,g);else{this.render();let m=s.split("/").pop()||s,E=(t.split(` +`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${E}" landed in \`${m}\``,kind:"success",category:"create",duration:0,folder:s,affectedIds:[o],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(s,o)}}]})}if(a)try{await this.app.fileManager.processFrontMatter(C,m=>{for(let[E,w]of Object.entries(a))se.includes(E)||m[E]===void 0&&(m[E]=w)})}catch(m){console.warn("[Stashpad] template fm overlay failed",m)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:c,parent:g}}),i.record!==!1){let C=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let m=this.app.vault.getAbstractFileByPath(c);if(m)try{await this.app.fileManager.trashFile(m)}catch{}if(this.composerDraft=C,this.saveDraft(C),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=C;let E=C.length;this.composerInputEl.setSelectionRange(E,E),this.composerInputEl.focus()}n||this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{await this.app.vault.adapter.exists(c)||await this.app.vault.create(c,f),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(C),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(f){return new P.Notice(`Stashpad: failed to create note (${f.message})`),null}}extractAttachments(t){let e=[],i=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,s;for(;(s=i.exec(t))!==null;)e.push(s[1]);return e}async ensureFolder(t){if(await this.app.vault.adapter.exists(t)){let e=this.app.vault.getAbstractFileByPath(t);if(e&&!(e instanceof P.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${n}-${s}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:T,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 P.Notice(`Stashpad: attachment failed (${e.message})`),null}}claimSelectedAsAuthor(){this.authorship.claimSelectedAsAuthor()}claimFolderAsAuthor(){this.authorship.claimFolderAsAuthor()}claimSelectedWithContributor(){this.authorship.claimSelectedWithContributor()}claimFolderWithContributor(){this.authorship.claimFolderWithContributor()}renderAuthorshipFooter(t,e){if(!e.file)return;let i=this.plugin.settings;if(!i.showAuthor&&!i.showContributors&&!i.showLastEdit)return;let s=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},n=typeof s.author=="string"?s.author:"",o=Array.isArray(s.contributors)?s.contributors.filter(I=>typeof I=="string"&&I.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",r=i.showAuthor&&!!n,l=i.showContributors&&o.length>0,c=i.showLastEdit&&!!a;if(!r&&!l&&!c)return;let g=t.createDiv({cls:"stashpad-note-authorship"}),p=(I,u)=>{let f=u.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,E=C>=0?f.slice(C+1):f.split("/").pop()??f,w=I.createEl("a",{cls:"internal-link",text:E});w.setAttribute("data-href",m),w.setAttribute("href",m)},d=[];r&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(I,n)}),l&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&I.createSpan({text:", "}),p(I,u)})}),c&&d.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"edited "}),I.createSpan({text:this.formatTimeInline(a)})}),d.forEach((I,u)=>{u>0&&g.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=g.createSpan({cls:"stashpad-authorship-piece"});I(f)}),g.addEventListener("click",I=>this.handleRenderedClick(I,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Yt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,P.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=we(t.basename);if(!e||e===T)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=xt(s,this.activeStopwords()),o=Mt(n,e);if(t.name===o)return;let a=t.parent?`${t.parent.path}/${o}`:o;if(this.app.vault.getAbstractFileByPath(a))return;let r=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:r,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,P.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(e),s=this.extractAttachments(i),n=this.app.metadataCache.getFileCache(t)?.frontmatter,a=(Array.isArray(n?.attachments)?n.attachments:[]).filter(c=>typeof c=="string").map(c=>Ce(c));if(a.length===s.length&&a.every((c,g)=>c===s[g]))return;let l=s.map(c=>Ot(c));await this.app.fileManager.processFrontMatter(t,c=>{c.attachments=l})}stripFrontmatter(t){let e=t.replace(/^/,""),i=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return i?e.slice(i[0].length):e}formatTime(t){if(!t)return"";let e=(0,P.moment)(t);if(!e.isValid())return"";if(pt().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,P.moment)(t);if(!e.isValid())return"";if(It().useTemplatesFormat){let s=es(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,P.Platform.isMobile){let a=0,r=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(r,120))};window.setTimeout(r,60);return}this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},i=new ResizeObserver(e);for(let a of Array.from(t.children))a instanceof HTMLElement&&i.observe(a);this.stickyRowObserver=i;let s=performance.now(),n=t.scrollHeight,o=()=>{if(!this.stickToListBottom)return;let a=t.scrollHeight;a!==n&&(t.scrollTop=a,n=a),performance.now()-s<3e4?requestAnimationFrame(o):(this.stickToListBottom=!1,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null)};requestAnimationFrame(o)}openNoteMenu(t,e){if(!e.file)return;let i=e.file,s=new P.Menu;s.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(r=>r.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),s.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(r=>r.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),this.plugin.encryption?.isConfigured?.()&&s.addItem(r=>r.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let l=this.order.getOrder(this.noteFolder,e.parent??M),c=l.indexOf(e.id),g=c>0?l[c-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,g)&&this.render()})),s.addSeparator(),s.addItem(r=>r.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(r=>r.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,M),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==M&&this.navigateTo(M)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(r=>r.setTitle(o?"Unpin from sidebar":"Pin to sidebar").setIcon(o?"pin-off":"pin").onClick(async()=>{o?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),s.addItem(r=>r.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let a=this.isCompleted(e);s.addItem(r=>r.setTitle(a?"Mark incomplete":"Mark complete").setIcon(a?"circle":"check-circle").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleComplete()})),s.addSeparator(),s.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),await this.cmdDelete()})),s.addSeparator(),s.addItem(r=>r.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=I=>{for(let u of this.tree.getChildren(I.id))i(u),e.push(u)};i(t);let s=[...e,t],n=s.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.cachedRead(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(Ce(C))}let r=[...new Set(a)],l=this.authorship.collectAuthorIds(s),c=async I=>{let u=await this.snapshotNotes(s,I),f=0;if(I)for(let x of r){let Q=this.app.metadataCache.getFirstLinkpathDest(x,"");if(Q)try{await this.app.fileManager.trashFile(Q),await this.log.append({type:"attachment_remove",id:M,payload:{path:Q.path}}),this.plugin.notifications.show({message:`Deleted attachment "${Q.name}"`,kind:"warning",category:"attachment",affectedPaths:[Q.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let x of s)x.parent&&C.add(x.parent);let m=this.currentChildren.findIndex(x=>x.id===t.id),E=null;if(m>=0){for(let x=m+1;x<this.currentChildren.length;x++)if(this.currentChildren[x].id!==t.id){E=this.currentChildren[x].id;break}if(!E){for(let x=m-1;x>=0;x--)if(this.currentChildren[x].id!==t.id){E=this.currentChildren[x].id;break}}}for(let x of s)if(x.file){try{await this.app.fileManager.trashFile(x.file)}catch{}await this.log.append({type:"delete",id:x.id,payload:{path:x.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let x of C)s.some(Q=>Q.id===x)||this.fmSync.scheduleParentOfDeleted(x);let w=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,v=t.id,S=f>0?` with ${f} attachment${f===1?"":"s"}`:"",U=!1,F=async()=>{U||(U=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[v]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${S}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:l,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void F()}]}),this.plugin.getUndoStack(w).push({label:y,undo:async()=>{await F()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,U=!1,await this.trashNotesAndAttachments(u)}})},g=It(),p=e.length>0&&g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await c(!1),this.focusView();return}new xe(this.app,this.titleForNode(t),e.length,r.length,d,async I=>{await c(I),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new P.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===M){new P.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new P.Notice("Couldn't find the parent note.");return}let i=e.parent??M,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(r=>r.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new Ft(this.app,"Swap notes?",a.join(` +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,P.moment)(t);if(!e.isValid())return"";if(pt().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,P.Platform.isMobile){let a=0,r=()=>{!this.stickToListBottom||a>=8||(a++,Date.now()>=this.keyboardTransitionUntil&&(t.scrollTop=t.scrollHeight),window.setTimeout(r,120))};window.setTimeout(r,60);return}this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},i=new ResizeObserver(e);for(let a of Array.from(t.children))a instanceof HTMLElement&&i.observe(a);this.stickyRowObserver=i;let s=performance.now(),n=t.scrollHeight,o=()=>{if(!this.stickToListBottom)return;let a=t.scrollHeight;a!==n&&(t.scrollTop=a,n=a),performance.now()-s<3e4?requestAnimationFrame(o):(this.stickToListBottom=!1,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null)};requestAnimationFrame(o)}openNoteMenu(t,e){if(!e.file)return;let i=e.file,s=new P.Menu;s.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(r=>r.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),s.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(r=>r.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),this.plugin.encryption?.isConfigured?.()&&s.addItem(r=>r.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let l=this.order.getOrder(this.noteFolder,e.parent??T),c=l.indexOf(e.id),g=c>0?l[c-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,g)&&this.render()})),s.addSeparator(),s.addItem(r=>r.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(r=>r.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,T),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==T&&this.navigateTo(T)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(r=>r.setTitle(o?"Unpin from sidebar":"Pin to sidebar").setIcon(o?"pin-off":"pin").onClick(async()=>{o?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),s.addItem(r=>r.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let a=this.isCompleted(e);s.addItem(r=>r.setTitle(a?"Mark incomplete":"Mark complete").setIcon(a?"circle":"check-circle").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleComplete()})),s.addSeparator(),s.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),await this.cmdDelete()})),s.addSeparator(),s.addItem(r=>r.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=I=>{for(let u of this.tree.getChildren(I.id))i(u),e.push(u)};i(t);let s=[...e,t],n=s.filter(I=>!!I.file),o=await Promise.all(n.map(I=>this.app.vault.cachedRead(I.file))),a=[];for(let I=0;I<n.length;I++){let u=n[I];a.push(...this.extractAttachments(this.stripFrontmatter(o[I])));let f=this.app.metadataCache.getFileCache(u.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(Ce(C))}let r=[...new Set(a)],l=this.authorship.collectAuthorIds(s),c=async I=>{let u=await this.snapshotNotes(s,I),f=0;if(I)for(let N of r){let Q=this.app.metadataCache.getFirstLinkpathDest(N,"");if(Q)try{await this.app.fileManager.trashFile(Q),await this.log.append({type:"attachment_remove",id:T,payload:{path:Q.path}}),this.plugin.notifications.show({message:`Deleted attachment "${Q.name}"`,kind:"warning",category:"attachment",affectedPaths:[Q.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let N of s)N.parent&&C.add(N.parent);let m=this.currentChildren.findIndex(N=>N.id===t.id),E=null;if(m>=0){for(let N=m+1;N<this.currentChildren.length;N++)if(this.currentChildren[N].id!==t.id){E=this.currentChildren[N].id;break}if(!E){for(let N=m-1;N>=0;N--)if(this.currentChildren[N].id!==t.id){E=this.currentChildren[N].id;break}}}for(let N of s)if(N.file){try{await this.app.fileManager.trashFile(N.file)}catch{}await this.log.append({type:"delete",id:N.id,payload:{path:N.file.path,attachmentsRemoved:I?r:[]}})}this.selection.clear(),this.cursorIdx=-1,E&&(this.pendingFocusIds=[E]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let N of C)s.some(Q=>Q.id===N)||this.fmSync.scheduleParentOfDeleted(N);let w=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,v=t.id,S=f>0?` with ${f} attachment${f===1?"":"s"}`:"",M=!1,F=async()=>{M||(M=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[v]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${S}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:l,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void F()}]}),this.plugin.getUndoStack(w).push({label:y,undo:async()=>{await F()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,M=!1,await this.trashNotesAndAttachments(u)}})},g=pt(),p=e.length>0&&g.confirmBulkDelete,d=r.length>0&&g.confirmAttachmentDelete;if(!p&&!d){await c(!1),this.focusView();return}new Te(this.app,this.titleForNode(t),e.length,r.length,d,async I=>{await c(I),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new P.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===T){new P.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new P.Notice("Couldn't find the parent note.");return}let i=e.parent??T,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(r=>r.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new Ft(this.app,"Swap notes?",a.join(` `),"Swap",async r=>{r&&await this.swapParentChild(e,t,i)}).open()}offerSwapForDescendantMove(t,e){let i=this.tree.get(e);if(!i?.file){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder});return}if(i.parent!==t.id){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under "${this.titleForNode(i)}" \u2014 it's a deeper descendant. Only direct parent \u2194 child swaps are supported (try moving "${this.titleForNode(i)}" up first, then swap).`,kind:"warning",category:"move",affectedIds:[t.id,i.id],folder:this.noteFolder});return}let s=this.titleForNode(t),n=this.titleForNode(i),o=this.tree.getChildren(t.id).filter(r=>r.id!==i.id).length,a=[`"${s}" becomes a child of "${n}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new Ft(this.app,"Confirm Note Swap",a.join(` -`),"Swap",async r=>{if(!r)return;let l=t.parent??M;await this.swapParentChild(t,i,l)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new P.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(d=>d.id!==e.id).filter(d=>!!d.file),a=o.map(d=>({id:d.id,path:d.file.path,was:d.parent})),r=this.order.getOrder(s,i).slice(),l=this.order.getOrder(s,e.id).slice(),c=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,d=>{d.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,d=>{d.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let d of o)await this.app.fileManager.processFrontMatter(d.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(d.id,t.id,e.id);if(r.length>0){let d=r.includes(t.id)?r.map(I=>I===t.id?e.id:I):[...r.filter(I=>I!==e.id),e.id];this.order.setOrder(s,i,d)}let g=o.map(d=>d.id),p=[t.id,...l.filter(d=>d!==t.id&&!g.includes(d)),...g];this.order.setOrder(s,e.id,p),this.order.setOrder(s,t.id,[]),await this.order.save(s),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:i,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let d of a)await this.log.append({type:"parent_change",id:d.id,payload:{from:d.was,to:e.id,reason:"swap"}});this.tree.rebuild(s),this.pendingFocusIds=[e.id],this.render({kind:"follow-cursor"}),this.plugin.notifications.show({message:`Swapped "${this.titleForNode(e)}" \u2194 "${this.titleForNode(t)}".`,kind:"success",category:"move",affectedIds:[e.id,t.id,...g],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let d=this.tree.get(t.id),I=this.tree.get(e.id);d?.file&&await this.app.fileManager.processFrontMatter(d.file,u=>{n==null||n===M?(delete u.parent,u.parent=M):u.parent=n}),I?.file&&await this.app.fileManager.processFrontMatter(I.file,u=>{u.parent=t.id});for(let u of a){let f=this.app.vault.getAbstractFileByPath(u.path);f&&await this.app.fileManager.processFrontMatter(f,C=>{u.was==null?C.parent=M:C.parent=u.was})}this.order.setOrder(s,i,r),this.order.setOrder(s,e.id,l),this.order.setOrder(s,t.id,c),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=r=>r??M;if(o(n)===o(e)){if(!i.quiet){let r=this.titleForNode(t),l=e===M?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${r}" is already under ${l}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==M&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let a=this.authorship.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(s,r=>{r.parent=e}),this.fmSync.scheduleParentChange(t.id,n,e),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),!i.quiet&&!i.silentSuccess){let r=this.tree.get(e),l=r?this.titleForNode(r):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${l}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===M?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let r=this.noteFolder,l=s.path,c=t.id;this.plugin.getUndoStack(r).push({label:"Move note",undo:async()=>{let g=this.app.vault.getAbstractFileByPath(l);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.parent=n}),this.pendingFocusIds=[c],this.focusId!==n&&this.focusId!==e?(this.selection.clear(),this.cursorIdx=-1):this.focusId===e&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(c))return;let I=this.currentChildren.findIndex(u=>u.id===c);I<0||(this.selection.add(c),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}},redo:async()=>{let g=this.app.vault.getAbstractFileByPath(l);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.parent=e}),this.pendingFocusIds=[c],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(c))return;let I=this.currentChildren.findIndex(u=>u.id===c);I<0||(this.selection.add(c),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===M?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=r=>i.get(r.id)??0,a;if(t.length===1){let r=this.titleForNode(t[0]),l=o(t[0]);a=l>0?`Moved "${r}" and its ${l} ${l===1?"child":"children"} \u2192 ${n}`:`Moved "${r}" \u2192 ${n}`}else{let r=t.reduce((l,c)=>l+o(c),0);a=r>0?`Moved ${t.length} notes (${r} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===M?void 0:0,affectedIds:t.map(r=>r.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===M?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}},vn=class extends P.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)}},fs=class extends P.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");yt();var Cr=ee.moment,Cs=class extends ee.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0}getViewType(){return Se}getDisplayText(){return"Encrypted trash"}getIcon(){return"trash-2"}async onOpen(){this.containerEl.addClass("stashpad-trash-view"),this.registerEvent(this.app.vault.on("create",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),await this.render()}scheduleRender(){this.renderPending||(this.renderPending=!0,window.setTimeout(()=>{this.renderPending=!1,this.render()},150))}async render(){let t=++this.renderGen,e=this.contentEl;e.empty(),e.addClass("stashpad-trash-view-body");let i=e.createDiv({cls:"stashpad-trash-view-header"});i.createEl("h3",{text:"Encrypted trash"});let s=i.createEl("button",{cls:"stashpad-trash-iconbtn"});if((0,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(),await this.render()};let a=new Map;for(let l of n){let c=l.meta?.title?l.meta.originalFolder||"(unknown folder)":" hidden";(a.get(c)??a.set(c,[]).get(c)).push(l)}let r=[...a.keys()].sort((l,c)=>l===" hidden"?1:c===" hidden"?-1:l.localeCompare(c));for(let l of r){let c=l===" hidden",g=e.createDiv({cls:"stashpad-trash-group"}),p=g.createDiv({cls:"stashpad-trash-group-head"});(0,ee.setIcon)(p.createSpan({cls:"stashpad-trash-group-icon"}),c?"lock":"folder"),p.createSpan({text:c?"Hidden (title obscured)":l.split("/").pop()||l}),p.createSpan({cls:"stashpad-trash-group-count",text:String(a.get(l).length)});for(let d of a.get(l)){let I=g.createDiv({cls:"stashpad-trash-row"}),u=I.createDiv({cls:"stashpad-trash-row-main"});u.createSpan({cls:"stashpad-trash-title",text:c?"Locked note":d.meta?.title||"Locked note"});let f=d.meta?.deletedAt?`deleted ${Cr(d.meta.deletedAt).fromNow()}`:"deleted",C=d.meta&&d.meta.count>1?` \xB7 ${d.meta.count} ${d.meta.kind==="rawtrash"?"files":"notes"}`:"";u.createSpan({cls:"stashpad-trash-sub",text:f+C});let m=I.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,ee.setIcon)(m.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),m.onclick=async()=>{m.disabled=!0,await this.plugin.restoreDeletedAt(d.blob)?await this.render():m.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function Wo(h){let{workspace:A}=h.app,t=A.getLeavesOfType(Se);if(t.length>0){A.revealLeaf(t[0]);return}let e=A.getLeaf("tab");await e.setViewState({type:Se,active:!0}),A.revealLeaf(e)}yt();var dt=require("obsidian");yt();Ht();var ms=class h extends dt.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return ue}getDisplayText(){return"Stashpad folders"}getIcon(){return"folders"}async onOpen(){this.render(),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("layout-change",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("create",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender()))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},100))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-folderpanel-root");let e=this.clampFrac(this.plugin.settings.folderPanelPinnedFraction??.5),i=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-pinned"});i.style.flex=`0 0 ${(e*100).toFixed(2)}%`;let s=i.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"});s.createSpan({cls:"stashpad-folderpanel-heading-title",text:"Pinned"});let n=s.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(n,"list"),n.setAttr("aria-label","Pinned view options"),n.onclick=c=>{c.stopPropagation(),this.openPinnedOptionsMenu(c)},this.renderPinned(i.createDiv({cls:"stashpad-folderpanel-list stashpad-folderpanel-pins"}));let o=t.createDiv({cls:"stashpad-folderpanel-divider"});o.createDiv({cls:"stashpad-folderpanel-divider-grip"}),this.attachDividerDrag(t,i,o);let a=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-folders"});a.style.flex="1 1 0";let r=a.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"}),l=r.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});if(l.setAttr("aria-label","Open folder switcher"),l.onmousedown=c=>{c.button===0&&(c.preventDefault(),this.plugin.openFolderPicker())},this.plugin.encryption?.isConfigured?.()){let c=r.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-trash"});(0,dt.setIcon)(c,"trash-2"),c.setAttr("aria-label","Open encrypted trash"),c.onmousedown=g=>{g.button===0&&(g.preventDefault(),g.stopPropagation(),this.plugin.openEncryptedTrash())}}this.renderFolders(a.createDiv({cls:"stashpad-folderpanel-list"}))}clampFrac(t){return Number.isFinite(t)?Math.max(.15,Math.min(.85,t)):.5}attachDividerDrag(t,e,i){let s=null,n=a=>{let r=t.getBoundingClientRect();if(r.height<=0)return;let l=this.clampFrac((a.clientY-r.top)/r.height);s=l,e.style.flex=`0 0 ${(l*100).toFixed(2)}%`},o=a=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(a.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",a=>{a.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(a.pointerId)}catch{}document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)})}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new dt.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinned(t){let e=this.plugin.listPinnedNotes();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No pinned notes yet \u2014 pin a note from its right-click menu."});return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let s=new Map;e.forEach((a,r)=>{let l=s.get(a.folder);l||(l=[],s.set(a.folder,l)),l.push({...a,idx:r})});let n=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,o=Array.from(s.keys());n&&s.has(n)&&(o.splice(o.indexOf(n),1),o.unshift(n));for(let a of o){let r=t.createDiv({cls:"stashpad-pinned-group-header"});a===n&&r.addClass("is-active-folder"),r.createSpan({cls:"stashpad-pinned-group-name",text:a.split("/").pop()||a});for(let l of s.get(a)??[])this.renderPinNote(t,l.folder,l.id,l.file,l.idx)}}else e.forEach((s,n)=>this.renderPinNote(t,s.folder,s.id,s.file,n))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],l;!a&&!r?l=Date.now():a?r?l=(a.pinnedAt+r.pinnedAt)/2:l=a.pinnedAt+1e3:l=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=l})}catch(c){console.warn("[Stashpad] pin reorder failed",c)}this.render()}renderPinNote(t,e,i,s,n){let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,r=o.completed===!0,l=this.childrenOf(e,i),c=l.length>0,g=`${e}|${i}`,p=this.pinExpanded.has(g),d=t.createDiv({cls:"stashpad-pinned-row"});a&&(d.addClass("has-color"),d.style.setProperty("--stashpad-note-color",a)),r&&d.addClass("is-completed"),d.draggable=!0,d.dataset.pinIdx=String(n),d.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),d.addClass("is-dragging")}),d.addEventListener("dragend",()=>d.removeClass("is-dragging")),d.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=d.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;d.toggleClass("drop-before",E),d.toggleClass("drop-after",!E)}),d.addEventListener("dragleave",()=>{d.removeClass("drop-before"),d.removeClass("drop-after")}),d.addEventListener("drop",C=>{C.preventDefault(),d.removeClass("drop-before"),d.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let E=d.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?n:n+1)});let I=d.createSpan({cls:"stashpad-pinned-toggle"});c&&(ye(I,l.length,p),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let u=d.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let f=d.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},d.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),d.oncontextmenu=C=>{C.preventDefault();let m=new dt.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},c&&p){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(C,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let r=typeof o.color=="string"?o.color:null,l=o.completed===!0,c=this.childrenOf(e,a),g=c.length>0,p=`${e}|${a}`,d=this.pinExpanded.has(p),I=t.createDiv({cls:"stashpad-pinned-subrow"});l&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});g&&(ye(u,c.length,d),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(f,"file-text"),r&&(f.style.color=r);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},g&&d&&this.renderPinSubtree(t,e,a,s+1)}}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===M&&(a==null||a===M)){if(o.id===M)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",a=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(a))}),i}onNavigateAway(){dt.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(ct)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=h.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=h.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(h.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==M||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let l of e)switch(this.folderState(l)){case"pinned":s.push(l);break;case"downranked":o.push(l);break;case"hidden":a.push(l);break;default:n.push(l)}let r=[...s,...n,...o];if(r.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let l of r)this.renderFolderRow(t,l,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(h.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let a=o.createSpan({cls:"stashpad-folderpanel-dot"});if(a.setAttr("aria-label",n?"Open in a tab":"Not open"),n&&a.setAttr("title","Open in a tab"),s==="pinned"){let I=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,dt.setIcon)(I,"pin"),I.setAttr("aria-label","Pinned")}let r=this.plugin.isArchiveFolder(e),l=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,dt.setIcon)(l,r?"archive":"folder"),r&&l.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let c=this.folderHomeColor(e);c&&(l.style.color=c);let g=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:g});let d=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(d,"plus-square"),d.setAttr("aria-label","Open in new tab"),d.onmousedown=I=>{I.button===0&&(I.preventDefault(),I.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",I=>{I.button===0&&(I.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=I=>{I.preventDefault(),this.openFolderMenu(I,e)}}renderHiddenSection(t,e){let i=t.createDiv({cls:"stashpad-folderpanel-hidden"}),s=i.createDiv({cls:"stashpad-folderpanel-hidden-header"}),n=s.createSpan({cls:"stashpad-folderpanel-hidden-caret"});(0,dt.setIcon)(n,"chevron-right"),s.createSpan({cls:"stashpad-folderpanel-hidden-title",text:`Hidden (${e.length})`});let o=i.createDiv({cls:"stashpad-folderpanel-hidden-body"});o.style.display="none",s.onclick=()=>{let a=o.style.display!=="none";o.style.display=a?"none":"",(0,dt.setIcon)(n,a?"chevron-right":"chevron-down")};for(let a of e){let r=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),l=a.split("/").pop()||a;r.createSpan({cls:"stashpad-folderpanel-row-label",text:l});let c=r.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(c,"eye"),c.setAttr("aria-label","Unhide"),c.onclick=g=>{g.stopPropagation(),this.setFolderState(a,"normal")}}}jumpToFolder(t){this.plugin.openFolderInStashpad(t)}revealFolder(t){let e=this.app.vault.getAbstractFileByPath(t.replace(/\/+$/,""));if(!(e instanceof dt.TFolder)){new dt.Notice("Couldn't find that folder.");return}let i=this.app.workspace.getLeavesOfType("file-explorer")[0];if(!i){new dt.Notice("File explorer isn't available.");return}this.app.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}openFolderMenu(t,e){let i=new dt.Menu;i.addItem(n=>n.setTitle("Open in new tab").setIcon("plus-square").onClick(()=>void this.plugin.activateViewForFolder(e))),i.addItem(n=>n.setTitle("Reveal in file explorer").setIcon("folder-search").onClick(()=>this.revealFolder(e))),i.addSeparator();let s=this.folderState(e);if(i.addItem(n=>n.setTitle(s==="pinned"?"Unpin":"Pin to top").setIcon("pin").onClick(()=>void this.setFolderState(e,s==="pinned"?"normal":"pinned"))),i.addItem(n=>n.setTitle(s==="downranked"?"Remove downrank":"Downrank").setIcon("arrow-down").onClick(()=>void this.setFolderState(e,s==="downranked"?"normal":"downranked"))),i.addItem(n=>n.setTitle("Hide from list").setIcon("eye-off").onClick(()=>void this.setFolderState(e,"hidden"))),i.addSeparator(),i.addItem(n=>n.setTitle("Rename\u2026").setIcon("pencil").onClick(()=>this.renameFolder(e))),this.plugin.encryption?.isConfigured?.()){i.addSeparator(),i.addItem(a=>a.setTitle("Encrypt (lock) all notes in folder").setIcon("lock").onClick(()=>void this.plugin.lockFolder(e))),this.app.vault.getFiles().some(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")===e.replace(/\/+$/,""))&&i.addItem(a=>a.setTitle("Decrypt (unlock) all notes in folder").setIcon("unlock").onClick(()=>void this.plugin.unlockFolder(e)));let n=e.replace(/\/+$/,""),o=this.plugin.isArchiveFolder(n);i.addItem(a=>a.setTitle(o?"Unmark archive folder":"Mark as archive folder\u2026").setIcon("archive").onClick(async()=>{if(o){this.plugin.settings.archiveFolders=(this.plugin.settings.archiveFolders??[]).filter(r=>r!==n),await this.plugin.saveSettings(),new dt.Notice(`"${n.split("/").pop()}" is no longer an archive folder. Existing locked notes stay locked.`,0),this.render();return}new Ft(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 r=>{r&&(this.plugin.settings.archiveFolders=[...this.plugin.settings.archiveFolders??[],n],await this.plugin.saveSettings(),new dt.Notice(`"${n.split("/").pop()}" is now an archive folder \u2014 notes moved in will be encrypted.`,0),this.render())}).open()})),i.addItem(a=>a.setTitle("Open encrypted trash").setIcon("rotate-ccw").onClick(()=>this.plugin.openEncryptedTrash()))}i.addSeparator(),i.addItem(n=>{n.setTitle("Delete folder\u2026").setIcon("trash").onClick(()=>this.deleteFolder(e)),n.setWarning?.(!0)}),i.showAtMouseEvent(t)}renameFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof dt.TFolder)){new dt.Notice("Couldn't find that folder.");return}let s=i.name;new Fn(this.app,s,async n=>{let o=n.trim().replace(/[\\/:]+/g,"").trim();if(!o||o===s)return;let r=`${i.parent?.path&&i.parent.path!=="/"?`${i.parent.path}/`:""}${o}`;if(this.app.vault.getAbstractFileByPath(r)){new dt.Notice(`"${o}" already exists.`);return}try{await this.app.fileManager.renameFile(i,r),(this.plugin.settings.folder||"").replace(/\/+$/,"")===e&&(this.plugin.settings.folder=r,await this.plugin.saveSettings()),new dt.Notice(`Renamed to "${o}".`)}catch(l){console.warn("[Stashpad] folder rename failed",l),new dt.Notice("Rename failed (see console).")}}).open()}deleteFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof dt.TFolder)){new dt.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 Ft(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()}},Fn=class extends dt.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 Bs(h){let A=h.workspace.getLeavesOfType(ue);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new dt.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ue,active:!0}),h.workspace.revealLeaf(t)}Ht();Me();var Qs=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))}};yt();var Es=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 ys=class{constructor(A,t){this.app=A;this.data={version:1,authors:{}};this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/authors.json`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(A){console.warn("[Stashpad] author registry load failed; starting empty",A),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((A,t)=>(t.lastSeen??"").localeCompare(A.lastSeen??""))}get(A){return this.data.authors[A]??null}record(A){let t=(A.id??"").trim();if(!t)return!1;let e=A.at??new Date().toISOString(),i=(A.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:A.role?.trim()||void 0,department:A.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(i&&i!==s.name&&(s.renames.push({from:s.name,to:i,at:e}),s.name=i,n=!0),A.role!==void 0){let o=A.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(A.department!==void 0){let o=A.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(A,t){let e=t??new Date().toISOString(),i={};for(let s of A){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",r=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&r.push({from:o.name,to:a,at:e}),i[n]={id:n,name:a,role:s.role?.trim()||o?.role||void 0,department:s.department?.trim()||o?.department||void 0,firstSeen:o?.firstSeen??e,lastSeen:e,renames:r}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}save(){return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.write(this.path,JSON.stringify(this.data,null,2))}catch(A){console.warn("[Stashpad] author registry save failed",A)}}),this.writeChain}};var pt=require("obsidian");yt();Kt();Me();xi();Ht();var ws=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),$o="_archive",Xo=new Set([ae,"edtz","stashenc","stashmeta"]),Ve=class Ve{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)&&(ws.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(),Ve.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)||Xo.has(A.extension))return!1;let t=A.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return ws.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}=Mt(await this.app.vault.read(A));if(t&&typeof t.id=="string"&&t.id)return!1}catch{}return!0}async drain(){if(this.drainTimer=null,!this.draining){this.draining=!0;try{let A=[...this.pending.keys()];this.pending.clear();let t=A.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof pt.TFile),e=[];for(let g of t)await this.isStillImportable(g)&&e.push(g);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof pt.TFolder).map(g=>({folder:g,files:this.filesUnder(g.path)})).filter(g=>g.files.length>0),n=s.reduce((g,p)=>g+p.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,r=[],l=e.filter(g=>this.plugin.importLog.findDuplicate(g.name,g.stat?.size??null));if(l.length>0){let g=l.slice(0,5).map(I=>`\u2022 ${I.name}`).join(` +`),"Swap",async r=>{if(!r)return;let l=t.parent??T;await this.swapParentChild(t,i,l)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new P.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(d=>d.id!==e.id).filter(d=>!!d.file),a=o.map(d=>({id:d.id,path:d.file.path,was:d.parent})),r=this.order.getOrder(s,i).slice(),l=this.order.getOrder(s,e.id).slice(),c=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,d=>{d.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,d=>{d.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let d of o)await this.app.fileManager.processFrontMatter(d.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(d.id,t.id,e.id);if(r.length>0){let d=r.includes(t.id)?r.map(I=>I===t.id?e.id:I):[...r.filter(I=>I!==e.id),e.id];this.order.setOrder(s,i,d)}let g=o.map(d=>d.id),p=[t.id,...l.filter(d=>d!==t.id&&!g.includes(d)),...g];this.order.setOrder(s,e.id,p),this.order.setOrder(s,t.id,[]),await this.order.save(s),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:i,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let d of a)await this.log.append({type:"parent_change",id:d.id,payload:{from:d.was,to:e.id,reason:"swap"}});this.tree.rebuild(s),this.pendingFocusIds=[e.id],this.render({kind:"follow-cursor"}),this.plugin.notifications.show({message:`Swapped "${this.titleForNode(e)}" \u2194 "${this.titleForNode(t)}".`,kind:"success",category:"move",affectedIds:[e.id,t.id,...g],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let d=this.tree.get(t.id),I=this.tree.get(e.id);d?.file&&await this.app.fileManager.processFrontMatter(d.file,u=>{n==null||n===T?(delete u.parent,u.parent=T):u.parent=n}),I?.file&&await this.app.fileManager.processFrontMatter(I.file,u=>{u.parent=t.id});for(let u of a){let f=this.app.vault.getAbstractFileByPath(u.path);f&&await this.app.fileManager.processFrontMatter(f,C=>{u.was==null?C.parent=T:C.parent=u.was})}this.order.setOrder(s,i,r),this.order.setOrder(s,e.id,l),this.order.setOrder(s,t.id,c),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=r=>r??T;if(o(n)===o(e)){if(!i.quiet){let r=this.titleForNode(t),l=e===T?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${r}" is already under ${l}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==T&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let a=this.authorship.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(s,r=>{r.parent=e}),this.fmSync.scheduleParentChange(t.id,n,e),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),!i.quiet&&!i.silentSuccess){let r=this.tree.get(e),l=r?this.titleForNode(r):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${l}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===T?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let r=this.noteFolder,l=s.path,c=t.id;this.plugin.getUndoStack(r).push({label:"Move note",undo:async()=>{let g=this.app.vault.getAbstractFileByPath(l);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.parent=n}),this.pendingFocusIds=[c],this.focusId!==n&&this.focusId!==e?(this.selection.clear(),this.cursorIdx=-1):this.focusId===e&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(c))return;let I=this.currentChildren.findIndex(u=>u.id===c);I<0||(this.selection.add(c),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}},redo:async()=>{let g=this.app.vault.getAbstractFileByPath(l);if(g){await this.app.fileManager.processFrontMatter(g,p=>{p.parent=e}),this.pendingFocusIds=[c],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(r),this.render({kind:"follow-cursor"});{let p=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==p||this.selection.has(c))return;let I=this.currentChildren.findIndex(u=>u.id===c);I<0||(this.selection.add(c),this.cursorIdx=I,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===T?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=r=>i.get(r.id)??0,a;if(t.length===1){let r=this.titleForNode(t[0]),l=o(t[0]);a=l>0?`Moved "${r}" and its ${l} ${l===1?"child":"children"} \u2192 ${n}`:`Moved "${r}" \u2192 ${n}`}else{let r=t.reduce((l,c)=>l+o(c),0);a=r>0?`Moved ${t.length} notes (${r} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===T?void 0:0,affectedIds:t.map(r=>r.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===T?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}},kn=class extends P.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)}},ms=class extends P.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");yt();var Cr=ee.moment,Bs=class extends ee.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0}getViewType(){return be}getDisplayText(){return"Encrypted trash"}getIcon(){return"trash-2"}async onOpen(){this.containerEl.addClass("stashpad-trash-view"),this.registerEvent(this.app.vault.on("create",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),await this.render()}scheduleRender(){this.renderPending||(this.renderPending=!0,window.setTimeout(()=>{this.renderPending=!1,this.render()},150))}async render(){let t=++this.renderGen,e=this.contentEl;e.empty(),e.addClass("stashpad-trash-view-body");let i=e.createDiv({cls:"stashpad-trash-view-header"});i.createEl("h3",{text:"Encrypted trash"});let s=i.createEl("button",{cls:"stashpad-trash-iconbtn"});if((0,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(),await this.render()};let a=new Map;for(let l of n){let c=l.meta?.title?l.meta.originalFolder||"(unknown folder)":" hidden";(a.get(c)??a.set(c,[]).get(c)).push(l)}let r=[...a.keys()].sort((l,c)=>l===" hidden"?1:c===" hidden"?-1:l.localeCompare(c));for(let l of r){let c=l===" hidden",g=e.createDiv({cls:"stashpad-trash-group"}),p=g.createDiv({cls:"stashpad-trash-group-head"});(0,ee.setIcon)(p.createSpan({cls:"stashpad-trash-group-icon"}),c?"lock":"folder"),p.createSpan({text:c?"Hidden (title obscured)":l.split("/").pop()||l}),p.createSpan({cls:"stashpad-trash-group-count",text:String(a.get(l).length)});for(let d of a.get(l)){let I=g.createDiv({cls:"stashpad-trash-row"}),u=I.createDiv({cls:"stashpad-trash-row-main"});u.createSpan({cls:"stashpad-trash-title",text:c?"Locked note":d.meta?.title||"Locked note"});let f=d.meta?.deletedAt?`deleted ${Cr(d.meta.deletedAt).fromNow()}`:"deleted",C=d.meta&&d.meta.count>1?` \xB7 ${d.meta.count} ${d.meta.kind==="rawtrash"?"files":"notes"}`:"";u.createSpan({cls:"stashpad-trash-sub",text:f+C});let m=I.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,ee.setIcon)(m.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),m.onclick=async()=>{m.disabled=!0,await this.plugin.restoreDeletedAt(d.blob)?await this.render():m.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function Wo(h){let{workspace:A}=h.app,t=A.getLeavesOfType(be);if(t.length>0){A.revealLeaf(t[0]);return}let e=A.getLeaf("tab");await e.setViewState({type:be,active:!0}),A.revealLeaf(e)}yt();var dt=require("obsidian");yt();Tt();var Qs=class h extends dt.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return ue}getDisplayText(){return"Stashpad folders"}getIcon(){return"folders"}async onOpen(){this.render(),this.registerEvent(this.app.workspace.on("active-leaf-change",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("layout-change",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("create",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender()))}scheduleRender(){this.renderTimer==null&&(this.renderTimer=window.setTimeout(()=>{this.renderTimer=null,this.containerEl.isConnected&&this.render()},100))}render(){let t=this.contentEl;t.empty(),t.addClass("stashpad-folderpanel-root");let e=this.clampFrac(this.plugin.settings.folderPanelPinnedFraction??.5),i=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-pinned"});i.style.flex=`0 0 ${(e*100).toFixed(2)}%`;let s=i.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"});s.createSpan({cls:"stashpad-folderpanel-heading-title",text:"Pinned"});let n=s.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(n,"list"),n.setAttr("aria-label","Pinned view options"),n.onclick=c=>{c.stopPropagation(),this.openPinnedOptionsMenu(c)},this.renderPinned(i.createDiv({cls:"stashpad-folderpanel-list stashpad-folderpanel-pins"}));let o=t.createDiv({cls:"stashpad-folderpanel-divider"});o.createDiv({cls:"stashpad-folderpanel-divider-grip"}),this.attachDividerDrag(t,i,o);let a=t.createDiv({cls:"stashpad-folderpanel-section stashpad-folderpanel-folders"});a.style.flex="1 1 0";let r=a.createDiv({cls:"stashpad-folderpanel-heading stashpad-folderpanel-heading-row"}),l=r.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});if(l.setAttr("aria-label","Open folder switcher"),l.onmousedown=c=>{c.button===0&&(c.preventDefault(),this.plugin.openFolderPicker())},this.plugin.encryption?.isConfigured?.()){let c=r.createEl("button",{cls:"stashpad-folderpanel-iconbtn stashpad-folderpanel-heading-trash"});(0,dt.setIcon)(c,"trash-2"),c.setAttr("aria-label","Open encrypted trash"),c.onmousedown=g=>{g.button===0&&(g.preventDefault(),g.stopPropagation(),this.plugin.openEncryptedTrash())}}this.renderFolders(a.createDiv({cls:"stashpad-folderpanel-list"}))}clampFrac(t){return Number.isFinite(t)?Math.max(.15,Math.min(.85,t)):.5}attachDividerDrag(t,e,i){let s=null,n=a=>{let r=t.getBoundingClientRect();if(r.height<=0)return;let l=this.clampFrac((a.clientY-r.top)/r.height);s=l,e.style.flex=`0 0 ${(l*100).toFixed(2)}%`},o=a=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(a.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",a=>{a.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(a.pointerId)}catch{}document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)})}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new dt.Menu;i.addItem(s=>s.setTitle("Sort by pin order").setChecked(e==="pin-order").onClick(()=>void this.setPinnedGrouping("pin-order"))),i.addItem(s=>s.setTitle("Group by folder").setChecked(e==="folder").onClick(()=>void this.setPinnedGrouping("folder"))),i.showAtMouseEvent(t)}async setPinnedGrouping(t){(this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!==t&&(this.plugin.settings.folderPanelPinnedGrouping=t,await this.plugin.saveSettings(),this.render())}renderPinned(t){let e=this.plugin.listPinnedNotes();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No pinned notes yet \u2014 pin a note from its right-click menu."});return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let s=new Map;e.forEach((a,r)=>{let l=s.get(a.folder);l||(l=[],s.set(a.folder,l)),l.push({...a,idx:r})});let n=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,o=Array.from(s.keys());n&&s.has(n)&&(o.splice(o.indexOf(n),1),o.unshift(n));for(let a of o){let r=t.createDiv({cls:"stashpad-pinned-group-header"});a===n&&r.addClass("is-active-folder"),r.createSpan({cls:"stashpad-pinned-group-name",text:a.split("/").pop()||a});for(let l of s.get(a)??[])this.renderPinNote(t,l.folder,l.id,l.file,l.idx)}}else e.forEach((s,n)=>this.renderPinNote(t,s.folder,s.id,s.file,n))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],l;!a&&!r?l=Date.now():a?r?l=(a.pinnedAt+r.pinnedAt)/2:l=a.pinnedAt+1e3:l=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=l})}catch(c){console.warn("[Stashpad] pin reorder failed",c)}this.render()}renderPinNote(t,e,i,s,n){let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.color=="string"?o.color:null,r=o.completed===!0,l=this.childrenOf(e,i),c=l.length>0,g=`${e}|${i}`,p=this.pinExpanded.has(g),d=t.createDiv({cls:"stashpad-pinned-row"});a&&(d.addClass("has-color"),d.style.setProperty("--stashpad-note-color",a)),r&&d.addClass("is-completed"),d.draggable=!0,d.dataset.pinIdx=String(n),d.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),d.addClass("is-dragging")}),d.addEventListener("dragend",()=>d.removeClass("is-dragging")),d.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=d.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;d.toggleClass("drop-before",E),d.toggleClass("drop-after",!E)}),d.addEventListener("dragleave",()=>{d.removeClass("drop-before"),d.removeClass("drop-after")}),d.addEventListener("drop",C=>{C.preventDefault(),d.removeClass("drop-before"),d.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let E=d.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?n:n+1)});let I=d.createSpan({cls:"stashpad-pinned-toggle"});c&&(ye(I,l.length,p),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let u=d.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let f=d.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},d.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),d.oncontextmenu=C=>{C.preventDefault();let m=new dt.Menu;m.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},c&&p){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(C,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let r=typeof o.color=="string"?o.color:null,l=o.completed===!0,c=this.childrenOf(e,a),g=c.length>0,p=`${e}|${a}`,d=this.pinExpanded.has(p),I=t.createDiv({cls:"stashpad-pinned-subrow"});l&&I.addClass("is-completed"),I.style.paddingLeft=`${s*16}px`;let u=I.createSpan({cls:"stashpad-pinned-toggle"});g&&(ye(u,c.length,d),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let f=I.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(f,"file-text"),r&&(f.style.color=r);let C=I.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},g&&d&&this.renderPinSubtree(t,e,a,s+1)}}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===T&&(a==null||a===T)){if(o.id===T)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",a=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(a))}),i}onNavigateAway(){dt.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(ct)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=h.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=h.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(h.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==T||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let l of e)switch(this.folderState(l)){case"pinned":s.push(l);break;case"downranked":o.push(l);break;case"hidden":a.push(l);break;default:n.push(l)}let r=[...s,...n,...o];if(r.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let l of r)this.renderFolderRow(t,l,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(h.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let a=o.createSpan({cls:"stashpad-folderpanel-dot"});if(a.setAttr("aria-label",n?"Open in a tab":"Not open"),n&&a.setAttr("title","Open in a tab"),s==="pinned"){let I=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,dt.setIcon)(I,"pin"),I.setAttr("aria-label","Pinned")}let r=this.plugin.isArchiveFolder(e),l=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,dt.setIcon)(l,r?"archive":"folder"),r&&l.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let c=this.folderHomeColor(e);c&&(l.style.color=c);let g=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:g});let d=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(d,"plus-square"),d.setAttr("aria-label","Open in new tab"),d.onmousedown=I=>{I.button===0&&(I.preventDefault(),I.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",I=>{I.button===0&&(I.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=I=>{I.preventDefault(),this.openFolderMenu(I,e)}}renderHiddenSection(t,e){let i=t.createDiv({cls:"stashpad-folderpanel-hidden"}),s=i.createDiv({cls:"stashpad-folderpanel-hidden-header"}),n=s.createSpan({cls:"stashpad-folderpanel-hidden-caret"});(0,dt.setIcon)(n,"chevron-right"),s.createSpan({cls:"stashpad-folderpanel-hidden-title",text:`Hidden (${e.length})`});let o=i.createDiv({cls:"stashpad-folderpanel-hidden-body"});o.style.display="none",s.onclick=()=>{let a=o.style.display!=="none";o.style.display=a?"none":"",(0,dt.setIcon)(n,a?"chevron-right":"chevron-down")};for(let a of e){let r=o.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-hidden-row"}),l=a.split("/").pop()||a;r.createSpan({cls:"stashpad-folderpanel-row-label",text:l});let c=r.createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(c,"eye"),c.setAttr("aria-label","Unhide"),c.onclick=g=>{g.stopPropagation(),this.setFolderState(a,"normal")}}}jumpToFolder(t){this.plugin.openFolderInStashpad(t)}revealFolder(t){let e=this.app.vault.getAbstractFileByPath(t.replace(/\/+$/,""));if(!(e instanceof dt.TFolder)){new dt.Notice("Couldn't find that folder.");return}let i=this.app.workspace.getLeavesOfType("file-explorer")[0];if(!i){new dt.Notice("File explorer isn't available.");return}this.app.workspace.revealLeaf(i),i.view?.revealInFolder?.(e)}openFolderMenu(t,e){let i=new dt.Menu;i.addItem(n=>n.setTitle("Open in new tab").setIcon("plus-square").onClick(()=>void this.plugin.activateViewForFolder(e))),i.addItem(n=>n.setTitle("Reveal in file explorer").setIcon("folder-search").onClick(()=>this.revealFolder(e))),i.addSeparator();let s=this.folderState(e);if(i.addItem(n=>n.setTitle(s==="pinned"?"Unpin":"Pin to top").setIcon("pin").onClick(()=>void this.setFolderState(e,s==="pinned"?"normal":"pinned"))),i.addItem(n=>n.setTitle(s==="downranked"?"Remove downrank":"Downrank").setIcon("arrow-down").onClick(()=>void this.setFolderState(e,s==="downranked"?"normal":"downranked"))),i.addItem(n=>n.setTitle("Hide from list").setIcon("eye-off").onClick(()=>void this.setFolderState(e,"hidden"))),i.addSeparator(),i.addItem(n=>n.setTitle("Rename\u2026").setIcon("pencil").onClick(()=>this.renameFolder(e))),this.plugin.encryption?.isConfigured?.()){i.addSeparator(),i.addItem(a=>a.setTitle("Encrypt (lock) all notes in folder").setIcon("lock").onClick(()=>void this.plugin.lockFolder(e))),this.app.vault.getFiles().some(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")===e.replace(/\/+$/,""))&&i.addItem(a=>a.setTitle("Decrypt (unlock) all notes in folder").setIcon("unlock").onClick(()=>void this.plugin.unlockFolder(e)));let n=e.replace(/\/+$/,""),o=this.plugin.isArchiveFolder(n);i.addItem(a=>a.setTitle(o?"Unmark archive folder":"Mark as archive folder\u2026").setIcon("archive").onClick(async()=>{if(o){this.plugin.settings.archiveFolders=(this.plugin.settings.archiveFolders??[]).filter(r=>r!==n),await this.plugin.saveSettings(),new dt.Notice(`"${n.split("/").pop()}" is no longer an archive folder. Existing locked notes stay locked.`,0),this.render();return}new Ft(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 r=>{r&&(this.plugin.settings.archiveFolders=[...this.plugin.settings.archiveFolders??[],n],await this.plugin.saveSettings(),new dt.Notice(`"${n.split("/").pop()}" is now an archive folder \u2014 notes moved in will be encrypted.`,0),this.render())}).open()})),i.addItem(a=>a.setTitle("Open encrypted trash").setIcon("rotate-ccw").onClick(()=>this.plugin.openEncryptedTrash()))}i.addSeparator(),i.addItem(n=>{n.setTitle("Delete folder\u2026").setIcon("trash").onClick(()=>this.deleteFolder(e)),n.setWarning?.(!0)}),i.showAtMouseEvent(t)}renameFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof dt.TFolder)){new dt.Notice("Couldn't find that folder.");return}let s=i.name;new Sn(this.app,s,async n=>{let o=n.trim().replace(/[\\/:]+/g,"").trim();if(!o||o===s)return;let r=`${i.parent?.path&&i.parent.path!=="/"?`${i.parent.path}/`:""}${o}`;if(this.app.vault.getAbstractFileByPath(r)){new dt.Notice(`"${o}" already exists.`);return}try{await this.app.fileManager.renameFile(i,r),(this.plugin.settings.folder||"").replace(/\/+$/,"")===e&&(this.plugin.settings.folder=r,await this.plugin.saveSettings()),new dt.Notice(`Renamed to "${o}".`)}catch(l){console.warn("[Stashpad] folder rename failed",l),new dt.Notice("Rename failed (see console).")}}).open()}deleteFolder(t){let e=t.replace(/\/+$/,""),i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof dt.TFolder)){new dt.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 Ft(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()}},Sn=class extends dt.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 Es(h){let A=h.workspace.getLeavesOfType(ue);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new dt.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ue,active:!0}),h.workspace.revealLeaf(t)}Tt();He();var ys=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))}};yt();var ws=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 vs=class{constructor(A,t){this.app=A;this.data={version:1,authors:{}};this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/authors.json`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(A){console.warn("[Stashpad] author registry load failed; starting empty",A),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((A,t)=>(t.lastSeen??"").localeCompare(A.lastSeen??""))}get(A){return this.data.authors[A]??null}record(A){let t=(A.id??"").trim();if(!t)return!1;let e=A.at??new Date().toISOString(),i=(A.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:A.role?.trim()||void 0,department:A.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(i&&i!==s.name&&(s.renames.push({from:s.name,to:i,at:e}),s.name=i,n=!0),A.role!==void 0){let o=A.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(A.department!==void 0){let o=A.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(A,t){let e=t??new Date().toISOString(),i={};for(let s of A){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",r=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&r.push({from:o.name,to:a,at:e}),i[n]={id:n,name:a,role:s.role?.trim()||o?.role||void 0,department:s.department?.trim()||o?.department||void 0,firstSeen:o?.firstSeen??e,lastSeen:e,renames:r}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}save(){return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.write(this.path,JSON.stringify(this.data,null,2))}catch(A){console.warn("[Stashpad] author registry save failed",A)}}),this.writeChain}};var It=require("obsidian");yt();Kt();He();Mi();Tt();var Fs=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),$o="_archive",Xo=new Set([ae,"edtz","stashenc","stashmeta"]),$e=class $e{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)&&(Fs.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(),$e.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)||Xo.has(A.extension))return!1;let t=A.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return Fs.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(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFile),e=[];for(let g of t)await this.isStillImportable(g)&&e.push(g);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFolder).map(g=>({folder:g,files:this.filesUnder(g.path)})).filter(g=>g.files.length>0),n=s.reduce((g,p)=>g+p.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,r=[],l=e.filter(g=>this.plugin.importLog.findDuplicate(g.name,g.stat?.size??null));if(l.length>0){let g=l.slice(0,5).map(I=>`\u2022 ${I.name}`).join(` `),p=l.length>5?` \u2026and ${l.length-5} more`:"",d=await this.dupChoice(`${l.length} of these look like files you've imported before: ${g}${p} -Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(d==="skip"){let I=new Set(l.map(u=>u.path));if(a=e.filter(u=>!I.has(u.path)),a.length===0&&s.length===0){new pt.Notice(`Skipped ${l.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(d==="replace")for(let I of l){let u=this.plugin.importLog.findDuplicate(I.name,I.stat?.size??null);for(let f of u?.notePaths??[]){let C=this.app.vault.getAbstractFileByPath(f);if(C instanceof pt.TFile)try{r.push({path:f,content:await this.app.vault.read(C)}),await this.app.fileManager.trashFile(C)}catch(m){console.warn("[Stashpad] replace: couldn't remove prior note",f,m)}}}}if(o=a.length+n,o>=Ve.BATCH_CONFIRM_AT){let g=s.length?` (incl. ${s.length} folder${s.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${o} files into Stashpad${g}. Proceed? -Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new pt.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let c=[];for(let g of a)try{let p=g.stat?.size??null,d=g.extension==="md"?await this.importMarkdown(g):await this.importOtherFile(g);d&&(c.push(d),this.plugin.importLog.append({ts:new Date().toISOString(),folder:d.folder,kind:d.kind,originalName:g.name,size:p,sourcePath:g.path,notePaths:d.kind==="folder"?d.notePaths:[d.notePath]}))}catch(p){console.warn("[Stashpad] import failed",g.path,p)}for(let{folder:g}of s)try{let p=await this.importFolder(g);p&&p.kind==="folder"&&(c.push(p),this.plugin.importLog.append({ts:new Date().toISOString(),folder:p.folder,kind:"folder",originalName:p.originalName,size:null,sourcePath:g.path,notePaths:p.notePaths}))}catch(p){console.warn("[Stashpad] folder import failed",g.path,p)}(c.length>0||r.length>0)&&this.announce(c,r)}finally{this.draining=!1}}}async importMarkdown(A){let t=A.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(A),{fm:i,body:s}=Mt(e),n=`${t}/${$o}`;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 pt.TFile))throw new Error(`archive move failed for ${A.path} \u2014 import aborted to avoid data loss`);let a={};for(let[g,p]of Object.entries(i))se.includes(g)||(a[g]=p);a.id=Bt(),a.parent=M;let r=this.preservedTimes(i,A);a.created=r.created,r.modified&&(a.modified=r.modified),a.attachments=Array.isArray(i.attachments)?i.attachments:[],i.author!==void 0&&(a.author=i.author),i.contributors!==void 0&&(a.contributors=i.contributors),a.imported=!0;let l=Nt(s)||A.basename,c=await this.uniquePath(t,xt(l,a.id));return await this.createNote(c,re(a,s)),{kind:"md",folder:t,archivePath:o,notePath:c,originalName:A.name}}async importOtherFile(A){let t=A.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,A.name);await this.app.fileManager.renameFile(A,i);let s=A.basename,n=Bt(),o={id:n,parent:M,created:new Date().toISOString(),attachments:[Ot(i)],imported:!0},a=`${s} +Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(d==="skip"){let I=new Set(l.map(u=>u.path));if(a=e.filter(u=>!I.has(u.path)),a.length===0&&s.length===0){new It.Notice(`Skipped ${l.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(d==="replace")for(let I of l){let u=this.plugin.importLog.findDuplicate(I.name,I.stat?.size??null);for(let f of u?.notePaths??[]){let C=this.app.vault.getAbstractFileByPath(f);if(C instanceof It.TFile)try{r.push({path:f,content:await this.app.vault.read(C)}),await this.app.fileManager.trashFile(C)}catch(m){console.warn("[Stashpad] replace: couldn't remove prior note",f,m)}}}}if(o=a.length+n,o>=$e.BATCH_CONFIRM_AT){let g=s.length?` (incl. ${s.length} folder${s.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${o} files into Stashpad${g}. Proceed? +Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new It.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let c=[];for(let g of a)try{let p=g.stat?.size??null,d=g.extension==="md"?await this.importMarkdown(g):await this.importOtherFile(g);d&&(c.push(d),this.plugin.importLog.append({ts:new Date().toISOString(),folder:d.folder,kind:d.kind,originalName:g.name,size:p,sourcePath:g.path,notePaths:d.kind==="folder"?d.notePaths:[d.notePath]}))}catch(p){console.warn("[Stashpad] import failed",g.path,p)}for(let{folder:g}of s)try{let p=await this.importFolder(g);p&&p.kind==="folder"&&(c.push(p),this.plugin.importLog.append({ts:new Date().toISOString(),folder:p.folder,kind:"folder",originalName:p.originalName,size:null,sourcePath:g.path,notePaths:p.notePaths}))}catch(p){console.warn("[Stashpad] folder import failed",g.path,p)}(c.length>0||r.length>0)&&this.announce(c,r)}finally{this.draining=!1}}}async importMarkdown(A){let t=A.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(A),{fm:i,body:s}=Dt(e),n=`${t}/${$o}`;await this.ensureFolder(n);let o=await this.uniquePath(n,A.name);if(await this.app.fileManager.renameFile(A,o),!(this.app.vault.getAbstractFileByPath(o)instanceof It.TFile))throw new Error(`archive move failed for ${A.path} \u2014 import aborted to avoid data loss`);let a={};for(let[g,p]of Object.entries(i))se.includes(g)||(a[g]=p);a.id=mt(),a.parent=T;let r=this.preservedTimes(i,A);a.created=r.created,r.modified&&(a.modified=r.modified),a.attachments=Array.isArray(i.attachments)?i.attachments:[],i.author!==void 0&&(a.author=i.author),i.contributors!==void 0&&(a.contributors=i.contributors),a.imported=!0;let l=xt(s)||A.basename,c=await this.uniquePath(t,Mt(l,a.id));return await this.createNote(c,re(a,s)),{kind:"md",folder:t,archivePath:o,notePath:c,originalName:A.name}}async importOtherFile(A){let t=A.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,A.name);await this.app.fileManager.renameFile(A,i);let s=A.basename,n=mt(),o={id:n,parent:T,created:new Date().toISOString(),attachments:[Ot(i)],imported:!0},a=`${s} ![[${i}]] -`,r=Nt(s)||s,l=await this.uniquePath(t,xt(r,n));return await this.createNote(l,re(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:l,originalName:A.name}}preservedTimes(A,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(A.created)?A.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(A.modified)?A.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(A){let t=A.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(A){let t=A.parent.path.replace(/\/+$/,""),e=A.name,i=`${t}/${$o}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(A,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let c of this.app.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let g=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof g=="string"&&g&&o.add(g)}let a=[],r=[],l=await this.createFolderNote(t,e,M,r,o);return n instanceof pt.TFolder&&await this.buildNotesFromArchive(n,t,l,r,o,a),a.length&&new pt.Notice(`Stashpad: ${a.length} attachment name collision(s) renamed on import \u2014 check ![[links]] in the imported notes.`),{kind:"folder",folder:t,archivePath:s,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(A,t,e,i,s){let n=Bt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Nt(t)||t,r=await this.uniquePath(A,xt(a,n));return await this.createNote(r,re(o,`${t} -`)),i.push(r),n}async mergeReservedFolder(A,t,e){await this.ensureFolder(t);for(let i of[...A.children])if(i instanceof pt.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof pt.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 pt.TFolder)if(ws.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let a=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,a,i,s,n)}else if(o instanceof pt.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:r,body:l}=Mt(a),c={};for(let[f,C]of Object.entries(r))se.includes(f)||(c[f]=C);let g=typeof r.id=="string"&&r.id?r.id:null,p=g&&!s.has(g)?g:Bt();s.add(p),c.id=p,c.parent=e;let d=this.preservedTimes(r,o);c.created=d.created,d.modified&&(c.modified=d.modified),c.attachments=Array.isArray(r.attachments)?r.attachments:[];let I=Nt(l)||o.basename,u=await this.uniquePath(t,xt(I,c.id));await this.createNote(u,re(c,l)),i.push(u)}else{if(Xo.has(o.extension))continue;{let a=Bt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[Ot(o.path)]},l=`${o.basename} +`,r=xt(s)||s,l=await this.uniquePath(t,Mt(r,n));return await this.createNote(l,re(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:l,originalName:A.name}}preservedTimes(A,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(A.created)?A.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(A.modified)?A.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(A){let t=A.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(A){let t=A.parent.path.replace(/\/+$/,""),e=A.name,i=`${t}/${$o}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(A,s);let n=this.app.vault.getAbstractFileByPath(s),o=new Set;for(let c of this.app.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let g=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof g=="string"&&g&&o.add(g)}let a=[],r=[],l=await this.createFolderNote(t,e,T,r,o);return n instanceof It.TFolder&&await this.buildNotesFromArchive(n,t,l,r,o,a),a.length&&new It.Notice(`Stashpad: ${a.length} attachment name collision(s) renamed on import \u2014 check ![[links]] in the imported notes.`),{kind:"folder",folder:t,archivePath:s,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(A,t,e,i,s){let n=mt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=xt(t)||t,r=await this.uniquePath(A,Mt(a,n));return await this.createNote(r,re(o,`${t} +`)),i.push(r),n}async mergeReservedFolder(A,t,e){await this.ensureFolder(t);for(let i of[...A.children])if(i instanceof It.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof It.TFile){let s=`${t}/${i.name}`;await this.app.vault.adapter.exists(s)&&(s=await this.uniquePath(t,i.name),e.push(`${i.name} \u2192 ${s.split("/").pop()}`)),await this.app.fileManager.renameFile(i,s)}}async buildNotesFromArchive(A,t,e,i,s,n){for(let o of[...A.children])if(o instanceof It.TFolder)if(Fs.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let a=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,a,i,s,n)}else if(o instanceof It.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:r,body:l}=Dt(a),c={};for(let[f,C]of Object.entries(r))se.includes(f)||(c[f]=C);let g=typeof r.id=="string"&&r.id?r.id:null,p=g&&!s.has(g)?g:mt();s.add(p),c.id=p,c.parent=e;let d=this.preservedTimes(r,o);c.created=d.created,d.modified&&(c.modified=d.modified),c.attachments=Array.isArray(r.attachments)?r.attachments:[];let I=xt(l)||o.basename,u=await this.uniquePath(t,Mt(I,c.id));await this.createNote(u,re(c,l)),i.push(u)}else{if(Xo.has(o.extension))continue;{let a=mt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[Ot(o.path)]},l=`${o.basename} ![[${o.path}]] -`,c=Nt(o.basename)||o.basename,g=await this.uniquePath(t,xt(c,a));await this.createNote(g,re(r,l)),i.push(g)}}}recordNotePaths(A){return A.kind==="folder"?A.notePaths:[A.notePath]}announce(A,t=[]){let e=A[0]?.folder??"",i=A.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(A,t))};this.plugin.notifications.show({message:`Imported ${i} file${i===1?"":"s"}${s} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:A.flatMap(a=>this.recordNotePaths(a)),actions:[{label:"Undo import",onClick:()=>void o()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${i} file${i===1?"":"s"}`,undo:async()=>{await o()},redo:async()=>{}})}async undo(A,t=[]){for(let e of A)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof pt.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof pt.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 pt.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof pt.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 pt.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof pt.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof pt.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 pt.Notice(`Undid import of ${A.length} file(s).`)}pickFilesInto(A){let t=document.createElement("input");t.type="file",t.multiple=!0,t.style.display="none",t.onchange=async()=>{let e=Array.from(t.files??[]);if(t.remove(),e.length===0)return;let i=[];for(let n of e)try{let o=await n.arrayBuffer(),a=await this.uniquePath(A,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let r=this.app.vault.getAbstractFileByPath(a);r instanceof pt.TFile&&i.push(r)}catch(o){console.warn("[Stashpad] file-picker write failed",n.name,o)}if(i.length===0)return;await this.plugin.importLog.load();let s=[];for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),i=[];for(let n of e)await this.isStillImportable(n)&&i.push(n);if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] loose-file import failed",n.path,o)}return s}async importLooseFoldersIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof pt.TFolder))return 0;let i=e.children.filter(n=>n instanceof pt.TFolder&&!ws.has(n.name));if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i){let o=n.path;try{let a=await this.importFolder(n);a&&a.kind==="folder"&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:null,sourcePath:o,notePaths:a.notePaths}))}catch(a){console.warn("[Stashpad] loose-folder import failed",o,a)}}return s}pendingEncryptedPaths(){for(let A of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(A)instanceof pt.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 pt.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&&Lt(n))return this.pendingEncryptedStashes.add(A.path),!1;let o=await Re(this.app,n,{...s,secretId:_e(A.basename)});if(!o)return!1;let a=await _t(this.app,o,t,e);if(a.colorAliases)for(let[r,l]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,r,l)}catch{}try{await this.app.fileManager.trashFile(A)}catch{}this.pendingEncryptedStashes.delete(A.path);try{await this.plugin.newLog().append({type:"stash_import",id:M,payload:{from:A.path,into:t,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,loose:!0}})}catch{}return!0}catch(n){return console.warn("[Stashpad] loose .stash import failed",A.path,n),!1}}async importLooseStashesIn(A,t={}){let e=A.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===ae);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 Ft(this.app,A,t,e,i).open()})}dupChoice(A){return new Promise(t=>{new ri(this.app,A,t).open()})}async ensureFolder(A){let t=this.app.vault.adapter,e=A.split("/").filter(Boolean),i="";for(let s of e){i=i?`${i}/${s}`:s;try{await t.exists(i)||await t.mkdir(i)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(A,t){let e=this.app.vault.adapter,i=t.lastIndexOf("."),s=i>0?t.slice(0,i):t,n=i>0?t.slice(i):"",o=`${A}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${A}/${s}-${a}${n}`;return o}};Ve.DEBOUNCE_MS=900,Ve.BATCH_CONFIRM_AT=8;var vs=Ve;var Fs=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 Ss=class Ss{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()},Ss.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}};Ss.SAVE_DEBOUNCE_MS=8e3;var ks=Ss;var kn="stashpad:unghost-after-reload",Ds=class extends $.Plugin{constructor(){super(...arguments);this.settings={...ce};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.suppressComposerAutofocusUntil=0;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this.noteClipboard=null;this.noteClipboardNotice=null;this._renderCacheStore=null;this.knownStashpadFolders=new Set;this.suppressedFolderDeletes=new Set;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.reHomePending=new Set;this.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.writeChain=Promise.resolve()}get notifications(){return this._notifications||(this._notifications=new Ji(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new ys(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new vs(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new Fs(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 ks(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 Qs(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),i=async()=>{let a=e.split("/").filter(Boolean),r="";for(let l of a)r=r?`${r}/${l}`:l,await t.exists(r)||await t.mkdir(r)},s=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(s)&&!await t.exists(n))try{await i();let a=await t.read(s);await t.write(n,a),console.debug("[Stashpad] migrated data.json \u2192",n)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let o=".stashpad";if(await t.exists(o))try{await i();let a=await t.list(o);for(let r of a.files){let l=r.replace(/^.*\//,""),c=this.pluginPrivatePath(l);if(!await t.exists(c))try{let g=await t.read(r);await t.write(c,g),console.debug("[Stashpad] migrated",r,"\u2192",c)}catch(g){console.warn(`Stashpad: failed to migrate ${r}`,g)}}}catch(a){console.warn("Stashpad: .stashpad migration scan failed",a)}}async loadData(){let t=this.app.vault.adapter,e=this.pluginPrivatePath("data.json");if(!await t.exists(e))return null;try{return JSON.parse(await t.read(e))}catch(i){return console.warn("Stashpad: data.json parse failed",i),null}}async saveData(t){let e=this.app.vault.adapter,i=this.pluginPrivatePath();if(!await e.exists(i)){let s=i.split("/").filter(Boolean),n="";for(let o of s)n=n?`${n}/${o}`:o,await e.exists(n)||await e.mkdir(n)}await e.write(this.pluginPrivatePath("data.json"),JSON.stringify(t,null,2))}async createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let l of s)n=n?`${n}/${l}`:l,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let l=this.app.vault.getAbstractFileByPath(o);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=M),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),r=["---",`id: ${M}`,"parent: null",`created: ${a}`,"---","Home"].join(` -`);await this.app.vault.create(o,r);try{await this.seedLocalAuthorStub(e)}catch{}try{await this.seedKnownAuthorsInFolder(e)}catch{}}collectColorsInFolder(t){let e=new Map,i=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==i&&!o.startsWith(i+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=typeof a?.color=="string"?a.color.trim():"";if(!r||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(r))continue;let l=r.toLowerCase();e.set(l,(e.get(l)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let r of this.app.vault.getMarkdownFiles()){let l=r.parent?.path?.replace(/\/+$/,"")??"";if(l!==s&&!l.startsWith(s+"/"))continue;let c=this.app.metadataCache.getFileCache(r)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(r,p=>{i?p.color=i:delete p.color}),o++}catch(p){console.warn(`Stashpad: recolor failed for ${r.path}`,p)}}let a=this.settings.colorAliases?.[s];if(a){let r=a[n];r&&(delete a[n],i&&(a[i.toLowerCase()]=r),Object.keys(a).length===0&&delete this.settings.colorAliases[s],await this.saveSettings())}return o}getColorAlias(t,e){let i=t.replace(/\/+$/,""),s=this.settings.colorAliases?.[i];if(!s)return;let n=s[e.toLowerCase()];return n&&n.trim()?n:void 0}async setColorAlias(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[s]||(this.settings.colorAliases[s]={});let o=this.settings.colorAliases[s],a=i.trim();a?o[n]=a:delete o[n],Object.keys(o).length===0&&delete this.settings.colorAliases[s],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let i=t.trim().replace(/^\/+|\/+$/g,"");if(!i)return;let s=Date.now();for(;Date.now()-s<e;){if(this.discoverStashpadFolders().includes(i))return;await new Promise(n=>setTimeout(n,80))}}discoverStashpadFolders(){let t=new Set;for(let i of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(i)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let n=i.parent?.path?.replace(/\/+$/,"")??"";n&&t.add(n)}let e=[...t].sort();return this.knownStashpadFolders=new Set(e),e}closeStashpadTabsFor(t){let e=0;for(let i of this.app.workspace.getLeavesOfType(ct)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(a=>a!==t&&!a.startsWith(t+"/")),s=(e.folderPanelPinned?.length??0)+(e.folderPanelDownranked?.length??0)+(e.folderPanelHidden?.length??0);e.folderPanelPinned=i(e.folderPanelPinned),e.folderPanelDownranked=i(e.folderPanelDownranked),e.folderPanelHidden=i(e.folderPanelHidden),e.folderPanelPinned.length+e.folderPanelDownranked.length+e.folderPanelHidden.length!==s&&await this.saveSettings()}async deleteStashpadFolderWithUndo(t){let e=t.path.replace(/\/+$/,""),i=t.name,s=this.app.vault.adapter,n=".trash";try{await s.exists(n)||await s.mkdir(n)}catch(l){console.warn("[Stashpad] couldn't ensure .trash",l)}let o=`${n}/${i}`;for(let l=1;await s.exists(o);l++)o=`${n}/${i} (${l})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let a=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(l){console.warn("[Stashpad] folder delete failed",l),this.suppressedFolderDeletes.delete(e),new $.Notice("Delete failed (see console).");return}let r=a>0?`Deleted \u201C${i}\u201D \u2014 closed ${a} open tab${a===1?"":"s"}.`:`Deleted \u201C${i}\u201D.`;this.notifications.show({message:r,kind:"warning",category:"delete",duration:0,folder:e,actions:[{label:"Undo",onClick:async()=>{try{if(await s.exists(e)){new $.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 $.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(l){console.warn("[Stashpad] folder undo failed",l),new $.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(l=>(l??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(l=>s.has(l)?!1:e.size>0?e.has(l):!i.has(l)),a=(t||"").trim().replace(/\/+$/,""),r=o.filter(l=>l!==a);return a&&r.unshift(a),r}async maybeSweepFolder(t){let e=(t||"").trim().replace(/\/+$/,"");!e||this.sweptFolders.has(e)||(this.sweptFolders.add(e),setTimeout(()=>{this.runSweep(e,{silent:!0})},3e3))}async runIntegrityCheckOnFolder(t){let e=(t||"").trim().replace(/\/+$/,"");e&&await this.runSweep(e,{silent:!1})}async runSweep(t,e){try{let i=this.newLog(),s={},n=this.app.vault.getMarkdownFiles().filter(l=>l.path===t||l.path.startsWith(t+"/"));for(let l of n){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id.trim():"";if(!g)continue;let p=c&&"parent"in c?c.parent??null:null;s[g]={parent:p,path:l.path}}let o=await i.readState(),a=l=>l===t||l.startsWith(t+"/");if(!e.silent){for(let[l,c]of Object.entries(s)){let g=o[l];g?g.parent!==c.parent?await i.append({type:"parent_change",id:l,payload:{from:g.parent,to:c.parent}}):g.path!==c.path&&await i.append({type:"rename",id:l,payload:{from:g.path,to:c.path}}):await i.append({type:"create",id:l,payload:{path:c.path,parent:c.parent}})}for(let[l,c]of Object.entries(o))!s[l]&&a(c.path)&&await i.append({type:"missing",id:l,payload:{lastPath:c.path}})}let r={};for(let[l,c]of Object.entries(o))a(c.path)||(r[l]=c);for(let[l,c]of Object.entries(s))r[l]=c;await i.writeState(r)}catch(i){console.warn("Stashpad: integrity sweep failed",i)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new Es,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),bt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new zi(this.app,()=>this.settings.encryption??mi(),async d=>{this.settings.encryption=d,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.tryAutoUnlock(),this.settingTab=new ts(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),this.registerEvent(this.app.vault.on("delete",d=>this.renderCacheStore.evict(d.path))),this.registerEvent(this.app.vault.on("rename",(d,I)=>this.renderCacheStore.evict(I))),await this.authorRegistry.load();{let d=(this.settings.authorId??"").trim();d&&this.authorRegistry.record({id:d,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{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(ct,d=>new us(d,this)),this.registerView(fe,d=>new is(d,this)),this.registerView(ie,d=>new Ti(d,this)),this.registerView(Se,d=>new Cs(d,this)),this.registerView(ue,d=>new ms(d,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",d=>{d&&d.view.getViewType()===ct&&(this.lastActiveStashpadLeaf=d,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(fe).length===0&&setTimeout(()=>{ss(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let d=jt(),I=!!d&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===d,u=!!I&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",u),document.body.classList.toggle("stashpad-active",!!I)};this.register(So(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=d=>{try{let I=Array.from(document.querySelectorAll("style")).filter(u=>(u.textContent??"").includes(".stashpad-"));for(let u of I){let f=u.id||"",C=f?`style[data-stashpad-source="${f}"]`:null;if(C&&d.head.querySelector(C))continue;let m=d.createElement("style");f?m.setAttribute("data-stashpad-source",f):m.setAttribute("data-stashpad-source","anon"),m.textContent=u.textContent??"",d.head.appendChild(m)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",d=>{let I=d?.doc??d?.win?.document??null;I&&e(I)})),this.registerEvent(this.app.workspace.on("file-menu",(d,I)=>{if(!(I instanceof $.TFolder))return;let u=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(u)&&d.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(u))})})),setTimeout(()=>{try{let d=this.app.workspace;typeof d.iterateAllLeaves=="function"&&d.iterateAllLeaves(I=>{let u=I?.view?.containerEl?.ownerDocument;u&&u!==document&&e(u)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let i=window.visualViewport,s=()=>{let d=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=d&&d.isConnected?d.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${I}px`);let u=0;i&&(u=Math.max(0,window.innerHeight-i.height-i.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${u}px`),document.body.classList.toggle("stashpad-keyboard-open",u>100)};s(),i&&(i.addEventListener("resize",s),i.addEventListener("scroll",s),this.register(()=>{i.removeEventListener("resize",s),i.removeEventListener("scroll",s)})),window.addEventListener("resize",s),this.register(()=>window.removeEventListener("resize",s)),requestAnimationFrame(s),setTimeout(s,250),setTimeout(s,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",d=>{d.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{Ui(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Bs(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{ss(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 $.Notice("Encryption isn't set up.");return}this.encryption.lock(),new $.Notice("Encryption locked.")}});let o=d=>{let I=jt();I&&typeof I[d]=="function"&&I[d]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>o("toggleSplit")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>o("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-lock-selection",name:"Encrypt (lock) selection (notes + children)",callback:()=>o("cmdLockSelection")}),this.addCommand({id:"stashpad-unlock-all",name:"Decrypt (unlock) locked notes in view",callback:()=>o("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:()=>o("cmdCopyNotes")}),this.addCommand({id:"stashpad-cut-notes",name:"Cut notes (paste in list to move, in composer to extract text)",callback:()=>o("cmdCutNotes")}),this.addCommand({id:"stashpad-paste-notes",name:"Paste notes (from the note clipboard)",callback:()=>o("cmdPasteNotes")}),this.addCommand({id:"stashpad-move-to-archive",name:"Move selection to archive (encrypt)",callback:()=>o("cmdMoveToArchive")}),this.addCommand({id:"stashpad-encrypt-delete",name:"Encrypt & delete selection (to encrypted trash)",callback:()=>o("cmdEncryptDelete")}),this.addCommand({id:"stashpad-restore-trash",name:"Open encrypted trash (restore deleted)\u2026",callback:()=>this.openEncryptedTrash()}),this.addCommand({id:"stashpad-encrypt-existing-trash",name:"Encrypt existing Obsidian trash (backfill .trash into encrypted trash)",callback:()=>void this.encryptExistingTrash()}),this.addCommand({id:"stashpad-close-duplicate-tabs",name:"Close duplicate & orphaned Stashpad tabs (tidy up)",callback:()=>void this.closeDuplicateStashpadTabs()}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>o("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>o("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>o("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>o("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>o("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>o("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>o("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>o("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>o("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>o("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>o("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>o("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>o("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>o("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>o("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>o("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>o("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>o("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>o("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>o("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>o("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>o("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>o("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>o("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>o("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>o("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>o("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>o("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>o("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>o("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new $.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let d=bt.report();console.log(d);try{await navigator.clipboard.writeText(d)}catch{}new $.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{bt.reset(),new $.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>o("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>o("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>o("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:d}=await Promise.resolve().then(()=>(Ht(),Ai));new d(this.app,this.importLog.recent()).open()}}),this.addCommand({id:"stashpad-import-files",name:"Import file(s) into Stashpad\u2026",callback:()=>this.openImportPicker()}),this.addCommand({id:"stashpad-import-loose-files",name:"Import loose files & folders in this folder (scan for moved-in / unprocessed items)",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderFrontmatterBackfill(I),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>o("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>o("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void Ui(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void Bs(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void ss(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:d=>{let I=this.app.workspace.getActiveFile(),u=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return d||u&&I&&this.revealNoteInStashpad(I),u}});let a=Object.keys(li);for(let d of a){let I=li[d];this.addCommand({id:`stashpad-open-panels-${d}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await Ui(this.app),this.app.workspace.getLeavesOfType(ie)[0]?.view?.setActivePanel?.(d)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>o("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>o("cmdTogglePin")}),this.addCommand({id:"stashpad-open-tiny",name:"Open Stashpad in tiny window",callback:()=>void this.openTinyWindow()}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>o("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>o("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>o("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>o("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>o("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Stashpad: open / switch / create folder\u2026",callback:()=>this.openFolderPicker()}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:d=>{let I=jt(),u=I&&I.noteFolder;return u?(d||(new $.Notice(`Running integrity check on "${u}"\u2026`),this.runIntegrityCheckOnFolder(u).then(()=>{new $.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 $.Notice("Stashpad: rebuilding author registry\u2026");try{let d=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${d.total} author(s) \u2014 ${d.fromStubs} from stubs, ${d.fromNotes} from note links.`,kind:"success",category:"system"})}catch(d){new $.Notice(`Author registry rebuild failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new $.Notice("Stashpad: restoring author stubs\u2026");try{let d=await this.restoreMissingAuthorStubs();this.notifications.show({message:d.created>0?`Restored ${d.created} author stub(s) across ${d.folders} folder(s).`:`No missing author stubs \u2014 all present across ${d.folders} folder(s).`,kind:"success",category:"system"})}catch(d){new $.Notice(`Restore author stubs failed: ${d.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 $.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:d,fmChecked:I,fmWritten:u,slugsRenamed:f,authors:C,imported:m,attachmentsLinked:E}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${d.length} folder${d.length===1?"":"s"}`),m>0&&w.push(`imported ${m} loose file${m===1?"":"s"}`),E>0&&w.push(`linked attachments on ${E} note${E===1?"":"s"}`),u>0&&w.push(`updated ${u} note${u===1?"":"s"}' metadata`),f>0&&w.push(`renamed ${f} note${f===1?"":"s"}`),C>0&&w.push(`${C} author${C===1?"":"s"} in registry`),w.push(`(checked ${I} total)`),new $.Notice(`Stashpad: ${w.join(" \xB7 ")}`)}catch(d){new $.Notice(`Stashpad: rebootstrap failed (${d.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:d=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(d||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ht(),Ai)).then(({NotificationHistoryModal:d,LogModal:I})=>{new d(this.app,this.notifications,async()=>{let u=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await u.exists(f)){new $.Notice("No log yet \u2014 make some changes first.");return}let C=await u.read(f);new I(this.app,C,f).open()},this.settings.authorId||null,u=>this.lookupNoteAuthorIds(u)).open()})}});let r=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let d of r){let I=`stashpad-toggle-${String(d.key).replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${d.label}`,callback:async()=>{let u=!this.settings[d.key];this.settings[d.key]=u,await this.saveSettings(),new $.Notice(`${d.label}: ${u?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{d?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let d of ji)this.addCommand({id:`stashpad-open-settings-${d.id}`,name:`Open Stashpad settings: ${d.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let l=()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{document.getElementById("stashpad-jd-index-section")?.scrollIntoView({behavior:"smooth",block:"start"})},100))};this.addCommand({id:"stashpad-preview-jd-index",name:"Preview JD index (overwrites home note body)",callback:async()=>{try{let{buildJdIndexPreview:d}=await Promise.resolve().then(()=>(di(),Gi)),I=await d(this.app,this,this.settings);if(I.error==="no-dest"){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(I.error==="no-home"){new $.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:u}=await Promise.resolve().then(()=>(di(),Gi));u(this.app,I)}catch(d){console.error("[stashpad] preview failed",d),new $.Notice(`Preview failed: ${d?.message??d}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:d,scanForJdNotes:I,JdBuildConfirmModal:u}=await Promise.resolve().then(()=>(di(),Gi));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}let C=I(this.app,this,this.settings);new u(this.app,this,this.settings,C.indexed.length,async()=>{try{let E=await d(this.app,this,this.settings);if(E.error==="no-dest"){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(E.error==="dest-not-stashpad"){new $.Notice(`"${E.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),l();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new $.Notice(`Index built: ${E.created} created, ${E.updated} updated, ${E.skipped} skipped \u2192 ${E.destFolder}`,6e3)}catch(E){console.error("[stashpad] build failed",E),new $.Notice(`Build failed: ${E?.message??E}`,8e3)}}).open()}catch(d){console.error("[stashpad] build failed",d),new $.Notice(`Build failed: ${d?.message??d}`,8e3)}}});let c=d=>{if(d.extension!==ae)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),u=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=d.parent?.path||"",C=f.split("/").pop()??"";if(I&&C===I){if(u&&f.endsWith(`/${u}`))return;let m=f.slice(0,f.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(d,m);return}this.settings.autoImport&&this.importService.isArmed()&&(be(d.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(d,f))};this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile&&c(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile&&c(d)}));let g=d=>{if(d.extension!=="md")return;let I=d.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(d)},800)},p=d=>{if(d.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let u=d.parent?.path?.replace(/\/+$/,"")??"";if((u.split("/").pop()??"")!==I)return;let C=u.slice(0,u.length-I.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(d,C)},200)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("delete",d=>{if(!(d instanceof $.TFolder))return;let I=d.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof $.TFile&&this.maybeReHomeOnCrossFolderMove(d,I)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof $.TFile&&this.maybeArchiveOnMoveIn(d,I)})),this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile?this.importService.enqueue(d):d instanceof $.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile?this.importService.enqueue(d):d instanceof $.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof $.TFile&&this.maybeAdoptAuthorRename(d,I)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(kn,"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 $.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(kn)==="1"}catch{}if(t){try{window.localStorage?.removeItem(kn)}catch{}for(let e of this.app.workspace.getLeavesOfType(ct))try{let i=e;i.isDeferred&&typeof i.loadIfDeferred=="function"&&await i.loadIfDeferred()}catch(i){console.warn("[Stashpad] un-ghost leaf failed",i)}}}isSemverGreater(t,e){let i=t.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0),n=Math.max(i.length,s.length);for(let o=0;o<n;o++){let a=i[o]??0,r=s[o]??0;if(a!==r)return a>r}return!1}parseAuthorFilePath(t){let e=t.match(/\/_authors\/([^/]+?)-([a-z0-9]{4,12})\.md$/i);return e?{name:e[1].replace(/-/g," "),id:e[2]}:null}authorNameToSafe(t){return t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author"}async syncAuthorFilesToName(){let t=(this.settings.authorId??"").trim(),e=(this.settings.authorName??"").trim();if(!t||!e)return;let i=this.authorNameToSafe(e);for(let s of this.discoverStashpadFolders()){let n=`${s}/_authors`;if(await this.app.vault.adapter.exists(n))for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(n+"/"))continue;let a=this.parseAuthorFilePath(o.path);if(!a||a.id!==t)continue;let r=`${n}/${i}-${t}.md`,l=o;if(o.path!==r)try{this.authorRenameInFlight.add(o.path),this.authorRenameInFlight.add(r),await this.app.fileManager.renameFile(o,r);let c=this.app.vault.getAbstractFileByPath(r);c&&(l=c)}catch(c){console.warn("[Stashpad] author file rename failed",c);continue}try{await this.refreshAuthorStub(l)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,i?a.role=i:delete a.role,s?a.department=s:delete a.department})}catch(n){console.warn("[Stashpad] refreshAuthorStub failed",n)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let i=this.parseAuthorFilePath(t.path);if(!i)return;let s=(this.settings.authorId??"").trim();if(!s||i.id!==s)return;let n=i.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let i=this.app.vault.adapter,s=t.name,n=s.lastIndexOf("."),o=n>0?s.slice(0,n):s,a=n>0?s.slice(n):"",r=0;for(;await i.exists(`${e}/${s}`);)r+=1,s=`${o}-${r}${a}`;let l=`${e}/${s}`;await this.app.fileManager.renameFile(t,l);let c=this.app.vault.getAbstractFileByPath(l);c instanceof $.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(c)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[l]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",a=!i,r=!n,l=!o;if(!a&&!r&&!l)return;let{newId:c}=await Promise.resolve().then(()=>(Kt(),Mi)),g,p=!1,d=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(g=c(),f.id=g)),r){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=M,p=!0)}l&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),d=!0))}),!g&&!p&&!d)return;let I=this.newLog(),u=g||i;u&&await I.append({type:"parent_change",id:u,payload:{from:null,to:M,reason:"orphan_auto_fix",path:t.path,addedId:!!g,addedParent:p,addedCreated:d}}),new $.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===M||this.app.vault.getMarkdownFiles().some(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(a)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,a=>{let r=typeof a.parent=="string"?a.parent.trim():"";r&&r!==M&&(a.parent=M)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:M,reason:"rehome_cross_folder_move",path:t.path}}),new $.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(Lt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await Re(this.app,i);if(!s)return;let n=jt(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let l of n.collectExistingIds())o.add(l);else for(let l of this.app.vault.getMarkdownFiles()){if(!l.path.startsWith(e+"/"))continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter?.id;typeof c=="string"&&o.add(c)}let a=await _t(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:M,payload:{from:t.path,into:e,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let r=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&r.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&r.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:r.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed +`,c=xt(o.basename)||o.basename,g=await this.uniquePath(t,Mt(c,a));await this.createNote(g,re(r,l)),i.push(g)}}}recordNotePaths(A){return A.kind==="folder"?A.notePaths:[A.notePath]}announce(A,t=[]){let e=A[0]?.folder??"",i=A.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(A,t))};this.plugin.notifications.show({message:`Imported ${i} file${i===1?"":"s"}${s} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:A.flatMap(a=>this.recordNotePaths(a)),actions:[{label:"Undo import",onClick:()=>void o()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${i} file${i===1?"":"s"}`,undo:async()=>{await o()},redo:async()=>{}})}async undo(A,t=[]){for(let e of A)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else if(e.kind==="file"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else{for(let s of e.notePaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof It.TFolder){let s=await this.uniquePath(e.folder,e.originalName);this.suppress(s),await this.app.fileManager.renameFile(i,s)}}}catch(i){console.warn("[Stashpad] import undo failed",e,i)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(i){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,i)}new It.Notice(`Undid import of ${A.length} file(s).`)}pickFilesInto(A){let t=document.createElement("input");t.type="file",t.multiple=!0,t.style.display="none",t.onchange=async()=>{let e=Array.from(t.files??[]);if(t.remove(),e.length===0)return;let i=[];for(let n of e)try{let o=await n.arrayBuffer(),a=await this.uniquePath(A,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let r=this.app.vault.getAbstractFileByPath(a);r instanceof It.TFile&&i.push(r)}catch(o){console.warn("[Stashpad] file-picker write failed",n.name,o)}if(i.length===0)return;await this.plugin.importLog.load();let s=[];for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),i=[];for(let n of e)await this.isStillImportable(n)&&i.push(n);if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] loose-file import failed",n.path,o)}return s}async importLooseFoldersIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof It.TFolder))return 0;let i=e.children.filter(n=>n instanceof It.TFolder&&!Fs.has(n.name));if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i){let o=n.path;try{let a=await this.importFolder(n);a&&a.kind==="folder"&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:null,sourcePath:o,notePaths:a.notePaths}))}catch(a){console.warn("[Stashpad] loose-folder import failed",o,a)}}return s}pendingEncryptedPaths(){for(let A of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(A)instanceof It.TFile||this.pendingEncryptedStashes.delete(A);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(A){this.pendingEncryptedStashes.delete(A)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(A){this.encryptedNotifySnoozeUntil=A===1/0?Number.MAX_SAFE_INTEGER:Date.now()+A}parkEncrypted(A){return this.pendingEncryptedStashes.has(A)?!1:(this.pendingEncryptedStashes.add(A),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let A=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof It.TFile))continue;let s=i.parent?.path?.replace(/\/+$/,"")??"";if(await this.importOneStash(i,s,this.liveRootIds(s),!1,{allowLater:!0,onLater:()=>{t=!0,this.snoozeEncryptedNotify(60*60*1e3)}})&&A++,t)break}return{imported:A,rescheduled:t}}liveRootIds(A){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==A)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(A,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(A));if(i&&Lt(n))return this.pendingEncryptedStashes.add(A.path),!1;let o=await Le(this.app,n,{...s,secretId:ti(A.basename)});if(!o)return!1;let a=await zt(this.app,o,t,e);if(a.colorAliases)for(let[r,l]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,r,l)}catch{}try{await this.app.fileManager.trashFile(A)}catch{}this.pendingEncryptedStashes.delete(A.path);try{await this.plugin.newLog().append({type:"stash_import",id:T,payload:{from:A.path,into:t,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,loose:!0}})}catch{}return!0}catch(n){return console.warn("[Stashpad] loose .stash import failed",A.path,n),!1}}async importLooseStashesIn(A,t={}){let e=A.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===ae);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 Ft(this.app,A,t,e,i).open()})}dupChoice(A){return new Promise(t=>{new li(this.app,A,t).open()})}async ensureFolder(A){let t=this.app.vault.adapter,e=A.split("/").filter(Boolean),i="";for(let s of e){i=i?`${i}/${s}`:s;try{await t.exists(i)||await t.mkdir(i)}catch(n){if(!/already exists/i.test(n.message))throw n}}}async uniquePath(A,t){let e=this.app.vault.adapter,i=t.lastIndexOf("."),s=i>0?t.slice(0,i):t,n=i>0?t.slice(i):"",o=`${A}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${A}/${s}-${a}${n}`;return o}};$e.DEBOUNCE_MS=900,$e.BATCH_CONFIRM_AT=8;var ks=$e;var Ss=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 bs=class bs{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()},bs.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}};bs.SAVE_DEBOUNCE_MS=8e3;var Ds=bs;var Dn="stashpad:unghost-after-reload",Ns=class extends $.Plugin{constructor(){super(...arguments);this.settings={...ce};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.suppressComposerAutofocusUntil=0;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this.noteClipboard=null;this.noteClipboardNotice=null;this._renderCacheStore=null;this.knownStashpadFolders=new Set;this.suppressedFolderDeletes=new Set;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.reHomePending=new Set;this.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.writeChain=Promise.resolve()}get notifications(){return this._notifications||(this._notifications=new qi(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new vs(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new ks(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new Ss(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 Ds(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 ys(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),i=async()=>{let a=e.split("/").filter(Boolean),r="";for(let l of a)r=r?`${r}/${l}`:l,await t.exists(r)||await t.mkdir(r)},s=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,n=this.pluginPrivatePath("data.json");if(await t.exists(s)&&!await t.exists(n))try{await i();let a=await t.read(s);await t.write(n,a),console.debug("[Stashpad] migrated data.json \u2192",n)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let o=".stashpad";if(await t.exists(o))try{await i();let a=await t.list(o);for(let r of a.files){let l=r.replace(/^.*\//,""),c=this.pluginPrivatePath(l);if(!await t.exists(c))try{let g=await t.read(r);await t.write(c,g),console.debug("[Stashpad] migrated",r,"\u2192",c)}catch(g){console.warn(`Stashpad: failed to migrate ${r}`,g)}}}catch(a){console.warn("Stashpad: .stashpad migration scan failed",a)}}async loadData(){let t=this.app.vault.adapter,e=this.pluginPrivatePath("data.json");if(!await t.exists(e))return null;try{return JSON.parse(await t.read(e))}catch(i){return console.warn("Stashpad: data.json parse failed",i),null}}async saveData(t){let e=this.app.vault.adapter,i=this.pluginPrivatePath();if(!await e.exists(i)){let s=i.split("/").filter(Boolean),n="";for(let o of s)n=n?`${n}/${o}`:o,await e.exists(n)||await e.mkdir(n)}await e.write(this.pluginPrivatePath("data.json"),JSON.stringify(t,null,2))}async createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let l of s)n=n?`${n}/${l}`:l,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let l=this.app.vault.getAbstractFileByPath(o);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=T),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),r=["---",`id: ${T}`,"parent: null",`created: ${a}`,"---","Home"].join(` +`);await this.app.vault.create(o,r);try{await this.seedLocalAuthorStub(e)}catch{}try{await this.seedKnownAuthorsInFolder(e)}catch{}}collectColorsInFolder(t){let e=new Map,i=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==i&&!o.startsWith(i+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=typeof a?.color=="string"?a.color.trim():"";if(!r||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(r))continue;let l=r.toLowerCase();e.set(l,(e.get(l)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let r of this.app.vault.getMarkdownFiles()){let l=r.parent?.path?.replace(/\/+$/,"")??"";if(l!==s&&!l.startsWith(s+"/"))continue;let c=this.app.metadataCache.getFileCache(r)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(r,p=>{i?p.color=i:delete p.color}),o++}catch(p){console.warn(`Stashpad: recolor failed for ${r.path}`,p)}}let a=this.settings.colorAliases?.[s];if(a){let r=a[n];r&&(delete a[n],i&&(a[i.toLowerCase()]=r),Object.keys(a).length===0&&delete this.settings.colorAliases[s],await this.saveSettings())}return o}getColorAlias(t,e){let i=t.replace(/\/+$/,""),s=this.settings.colorAliases?.[i];if(!s)return;let n=s[e.toLowerCase()];return n&&n.trim()?n:void 0}async setColorAlias(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[s]||(this.settings.colorAliases[s]={});let o=this.settings.colorAliases[s],a=i.trim();a?o[n]=a:delete o[n],Object.keys(o).length===0&&delete this.settings.colorAliases[s],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let i=t.trim().replace(/^\/+|\/+$/g,"");if(!i)return;let s=Date.now();for(;Date.now()-s<e;){if(this.discoverStashpadFolders().includes(i))return;await new Promise(n=>setTimeout(n,80))}}discoverStashpadFolders(){let t=new Set;for(let i of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(i)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let n=i.parent?.path?.replace(/\/+$/,"")??"";n&&t.add(n)}let e=[...t].sort();return this.knownStashpadFolders=new Set(e),e}closeStashpadTabsFor(t){let e=0;for(let i of this.app.workspace.getLeavesOfType(ct)){let s=i.view?.noteFolder??"";s||(s=((i.getViewState?.()?.state??{}).folderOverride??"")||this.settings.folder||"Stashpad"),s=(s||"").replace(/\/+$/,""),(s===t||s.startsWith(t+"/"))&&(i.detach(),e++)}return e}async prunePlacementFor(t){let e=this.settings,i=o=>(o??[]).filter(a=>a!==t&&!a.startsWith(t+"/")),s=(e.folderPanelPinned?.length??0)+(e.folderPanelDownranked?.length??0)+(e.folderPanelHidden?.length??0);e.folderPanelPinned=i(e.folderPanelPinned),e.folderPanelDownranked=i(e.folderPanelDownranked),e.folderPanelHidden=i(e.folderPanelHidden),e.folderPanelPinned.length+e.folderPanelDownranked.length+e.folderPanelHidden.length!==s&&await this.saveSettings()}async deleteStashpadFolderWithUndo(t){let e=t.path.replace(/\/+$/,""),i=t.name,s=this.app.vault.adapter,n=".trash";try{await s.exists(n)||await s.mkdir(n)}catch(l){console.warn("[Stashpad] couldn't ensure .trash",l)}let o=`${n}/${i}`;for(let l=1;await s.exists(o);l++)o=`${n}/${i} (${l})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let a=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(l){console.warn("[Stashpad] folder delete failed",l),this.suppressedFolderDeletes.delete(e),new $.Notice("Delete failed (see console).");return}let r=a>0?`Deleted \u201C${i}\u201D \u2014 closed ${a} open tab${a===1?"":"s"}.`:`Deleted \u201C${i}\u201D.`;this.notifications.show({message:r,kind:"warning",category:"delete",duration:0,folder:e,actions:[{label:"Undo",onClick:async()=>{try{if(await s.exists(e)){new $.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 $.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(l){console.warn("[Stashpad] folder undo failed",l),new $.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(l=>(l??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(l=>s.has(l)?!1:e.size>0?e.has(l):!i.has(l)),a=(t||"").trim().replace(/\/+$/,""),r=o.filter(l=>l!==a);return a&&r.unshift(a),r}async maybeSweepFolder(t){let e=(t||"").trim().replace(/\/+$/,"");!e||this.sweptFolders.has(e)||(this.sweptFolders.add(e),setTimeout(()=>{this.runSweep(e,{silent:!0})},3e3))}async runIntegrityCheckOnFolder(t){let e=(t||"").trim().replace(/\/+$/,"");e&&await this.runSweep(e,{silent:!1})}async runSweep(t,e){try{let i=this.newLog(),s={},n=this.app.vault.getMarkdownFiles().filter(l=>l.path===t||l.path.startsWith(t+"/"));for(let l of n){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id.trim():"";if(!g)continue;let p=c&&"parent"in c?c.parent??null:null;s[g]={parent:p,path:l.path}}let o=await i.readState(),a=l=>l===t||l.startsWith(t+"/");if(!e.silent){for(let[l,c]of Object.entries(s)){let g=o[l];g?g.parent!==c.parent?await i.append({type:"parent_change",id:l,payload:{from:g.parent,to:c.parent}}):g.path!==c.path&&await i.append({type:"rename",id:l,payload:{from:g.path,to:c.path}}):await i.append({type:"create",id:l,payload:{path:c.path,parent:c.parent}})}for(let[l,c]of Object.entries(o))!s[l]&&a(c.path)&&await i.append({type:"missing",id:l,payload:{lastPath:c.path}})}let r={};for(let[l,c]of Object.entries(o))a(c.path)||(r[l]=c);for(let[l,c]of Object.entries(s))r[l]=c;await i.writeState(r)}catch(i){console.warn("Stashpad: integrity sweep failed",i)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new ws,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),Nt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new Vi(this.app,()=>this.settings.encryption??Qi(),async d=>{this.settings.encryption=d,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.tryAutoUnlock(),this.settingTab=new is(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),this.registerEvent(this.app.vault.on("delete",d=>this.renderCacheStore.evict(d.path))),this.registerEvent(this.app.vault.on("rename",(d,I)=>this.renderCacheStore.evict(I))),await this.authorRegistry.load();{let d=(this.settings.authorId??"").trim();d&&this.authorRegistry.record({id:d,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{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(ct,d=>new Cs(d,this)),this.registerView(fe,d=>new ns(d,this)),this.registerView(ie,d=>new Ui(d,this)),this.registerView(be,d=>new Bs(d,this)),this.registerView(ue,d=>new Qs(d,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",d=>{d&&d.view.getViewType()===ct&&(this.lastActiveStashpadLeaf=d,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(fe).length===0&&setTimeout(()=>{os(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let d=jt(),I=!!d&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===d,u=!!I&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",u),document.body.classList.toggle("stashpad-active",!!I)};this.register(So(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=d=>{try{let I=Array.from(document.querySelectorAll("style")).filter(u=>(u.textContent??"").includes(".stashpad-"));for(let u of I){let f=u.id||"",C=f?`style[data-stashpad-source="${f}"]`:null;if(C&&d.head.querySelector(C))continue;let m=d.createElement("style");f?m.setAttribute("data-stashpad-source",f):m.setAttribute("data-stashpad-source","anon"),m.textContent=u.textContent??"",d.head.appendChild(m)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",d=>{let I=d?.doc??d?.win?.document??null;I&&e(I)})),this.registerEvent(this.app.workspace.on("file-menu",(d,I)=>{if(!(I instanceof $.TFolder))return;let u=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(u)&&d.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(u))})})),setTimeout(()=>{try{let d=this.app.workspace;typeof d.iterateAllLeaves=="function"&&d.iterateAllLeaves(I=>{let u=I?.view?.containerEl?.ownerDocument;u&&u!==document&&e(u)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let i=window.visualViewport,s=()=>{let d=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=d&&d.isConnected?d.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${I}px`);let u=0;i&&(u=Math.max(0,window.innerHeight-i.height-i.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${u}px`),document.body.classList.toggle("stashpad-keyboard-open",u>100)};s(),i&&(i.addEventListener("resize",s),i.addEventListener("scroll",s),this.register(()=>{i.removeEventListener("resize",s),i.removeEventListener("scroll",s)})),window.addEventListener("resize",s),this.register(()=>window.removeEventListener("resize",s)),requestAnimationFrame(s),setTimeout(s,250),setTimeout(s,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",d=>{d.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{Pi(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Es(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{os(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 $.Notice("Encryption isn't set up.");return}this.encryption.lock(),new $.Notice("Encryption locked.")}});let o=d=>{let I=jt();I&&typeof I[d]=="function"&&I[d]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>o("toggleSplit")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>o("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-lock-selection",name:"Encrypt (lock) selection (notes + children)",callback:()=>o("cmdLockSelection")}),this.addCommand({id:"stashpad-unlock-all",name:"Decrypt (unlock) locked notes in view",callback:()=>o("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:()=>o("cmdCopyNotes")}),this.addCommand({id:"stashpad-cut-notes",name:"Cut notes (paste in list to move, in composer to extract text)",callback:()=>o("cmdCutNotes")}),this.addCommand({id:"stashpad-paste-notes",name:"Paste notes (from the note clipboard)",callback:()=>o("cmdPasteNotes")}),this.addCommand({id:"stashpad-move-to-archive",name:"Move selection to archive (encrypt)",callback:()=>o("cmdMoveToArchive")}),this.addCommand({id:"stashpad-encrypt-delete",name:"Encrypt & delete selection (to encrypted trash)",callback:()=>o("cmdEncryptDelete")}),this.addCommand({id:"stashpad-restore-trash",name:"Open encrypted trash (restore deleted)\u2026",callback:()=>this.openEncryptedTrash()}),this.addCommand({id:"stashpad-encrypt-existing-trash",name:"Encrypt existing Obsidian trash (backfill .trash into encrypted trash)",callback:()=>void this.encryptExistingTrash()}),this.addCommand({id:"stashpad-close-duplicate-tabs",name:"Close duplicate & orphaned Stashpad tabs (tidy up)",callback:()=>void this.closeDuplicateStashpadTabs()}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>o("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>o("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>o("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>o("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>o("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>o("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>o("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>o("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>o("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>o("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>o("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>o("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>o("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>o("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>o("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>o("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>o("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>o("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>o("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>o("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>o("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>o("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>o("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>o("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>o("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>o("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>o("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>o("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>o("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>o("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new $.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let d=Nt.report();console.log(d);try{await navigator.clipboard.writeText(d)}catch{}new $.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{Nt.reset(),new $.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>o("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>o("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>o("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:d}=await Promise.resolve().then(()=>(Tt(),ci));new d(this.app,this.importLog.recent()).open()}}),this.addCommand({id:"stashpad-import-files",name:"Import file(s) into Stashpad\u2026",callback:()=>this.openImportPicker()}),this.addCommand({id:"stashpad-import-loose-files",name:"Import loose files & folders in this folder (scan for moved-in / unprocessed items)",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:d=>{let I=this.importService.defaultDestination();return d?!!I:(I&&this.runFolderFrontmatterBackfill(I),!0)}}),this.addCommand({id:"stashpad-select-all",name:"Select all visible notes",callback:()=>o("cmdSelectAll")}),this.addCommand({id:"stashpad-copy-codeblock",name:"Copy code from codeblock",callback:()=>o("cmdCopyCodeBlock")}),this.addCommand({id:"stashpad-open-panels",name:"Open Stashpad panels (sidebar)",callback:()=>void Pi(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void Es(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void os(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:d=>{let I=this.app.workspace.getActiveFile(),u=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return d||u&&I&&this.revealNoteInStashpad(I),u}});let a=Object.keys(di);for(let d of a){let I=di[d];this.addCommand({id:`stashpad-open-panels-${d}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await Pi(this.app),this.app.workspace.getLeavesOfType(ie)[0]?.view?.setActivePanel?.(d)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>o("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>o("cmdTogglePin")}),this.addCommand({id:"stashpad-open-tiny",name:"Open Stashpad in tiny window",callback:()=>void this.openTinyWindow()}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>o("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>o("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>o("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>o("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>o("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Stashpad: open / switch / create folder\u2026",callback:()=>this.openFolderPicker()}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:d=>{let I=jt(),u=I&&I.noteFolder;return u?(d||(new $.Notice(`Running integrity check on "${u}"\u2026`),this.runIntegrityCheckOnFolder(u).then(()=>{new $.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 $.Notice("Stashpad: rebuilding author registry\u2026");try{let d=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${d.total} author(s) \u2014 ${d.fromStubs} from stubs, ${d.fromNotes} from note links.`,kind:"success",category:"system"})}catch(d){new $.Notice(`Author registry rebuild failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new $.Notice("Stashpad: restoring author stubs\u2026");try{let d=await this.restoreMissingAuthorStubs();this.notifications.show({message:d.created>0?`Restored ${d.created} author stub(s) across ${d.folders} folder(s).`:`No missing author stubs \u2014 all present across ${d.folders} folder(s).`,kind:"success",category:"system"})}catch(d){new $.Notice(`Restore author stubs failed: ${d.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 $.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:d,fmChecked:I,fmWritten:u,slugsRenamed:f,authors:C,imported:m,attachmentsLinked:E}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${d.length} folder${d.length===1?"":"s"}`),m>0&&w.push(`imported ${m} loose file${m===1?"":"s"}`),E>0&&w.push(`linked attachments on ${E} note${E===1?"":"s"}`),u>0&&w.push(`updated ${u} note${u===1?"":"s"}' metadata`),f>0&&w.push(`renamed ${f} note${f===1?"":"s"}`),C>0&&w.push(`${C} author${C===1?"":"s"} in registry`),w.push(`(checked ${I} total)`),new $.Notice(`Stashpad: ${w.join(" \xB7 ")}`)}catch(d){new $.Notice(`Stashpad: rebootstrap failed (${d.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:d=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(d||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Tt(),ci)).then(({NotificationHistoryModal:d,LogModal:I})=>{new d(this.app,this.notifications,async()=>{let u=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await u.exists(f)){new $.Notice("No log yet \u2014 make some changes first.");return}let C=await u.read(f);new I(this.app,C,f).open()},this.settings.authorId||null,u=>this.lookupNoteAuthorIds(u)).open()})}});let r=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let d of r){let I=`stashpad-toggle-${String(d.key).replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${d.label}`,callback:async()=>{let u=!this.settings[d.key];this.settings[d.key]=u,await this.saveSettings(),new $.Notice(`${d.label}: ${u?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{d?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let d of es)this.addCommand({id:`stashpad-open-settings-${d.id}`,name:`Open Stashpad settings: ${d.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let l=()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{document.getElementById("stashpad-jd-index-section")?.scrollIntoView({behavior:"smooth",block:"start"})},100))};this.addCommand({id:"stashpad-preview-jd-index",name:"Preview JD index (overwrites home note body)",callback:async()=>{try{let{buildJdIndexPreview:d}=await Promise.resolve().then(()=>(gi(),Li)),I=await d(this.app,this,this.settings);if(I.error==="no-dest"){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(I.error==="no-home"){new $.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:u}=await Promise.resolve().then(()=>(gi(),Li));u(this.app,I)}catch(d){console.error("[stashpad] preview failed",d),new $.Notice(`Preview failed: ${d?.message??d}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:d,scanForJdNotes:I,JdBuildConfirmModal:u}=await Promise.resolve().then(()=>(gi(),Li));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}let C=I(this.app,this,this.settings);new u(this.app,this,this.settings,C.indexed.length,async()=>{try{let E=await d(this.app,this,this.settings);if(E.error==="no-dest"){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(E.error==="dest-not-stashpad"){new $.Notice(`"${E.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),l();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new $.Notice(`Index built: ${E.created} created, ${E.updated} updated, ${E.skipped} skipped \u2192 ${E.destFolder}`,6e3)}catch(E){console.error("[stashpad] build failed",E),new $.Notice(`Build failed: ${E?.message??E}`,8e3)}}).open()}catch(d){console.error("[stashpad] build failed",d),new $.Notice(`Build failed: ${d?.message??d}`,8e3)}}});let c=d=>{if(d.extension!==ae)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),u=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=d.parent?.path||"",C=f.split("/").pop()??"";if(I&&C===I){if(u&&f.endsWith(`/${u}`))return;let m=f.slice(0,f.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(d,m);return}this.settings.autoImport&&this.importService.isArmed()&&(xe(d.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(d,f))};this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile&&c(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile&&c(d)}));let g=d=>{if(d.extension!=="md")return;let I=d.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(d)},800)},p=d=>{if(d.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let u=d.parent?.path?.replace(/\/+$/,"")??"";if((u.split("/").pop()??"")!==I)return;let C=u.slice(0,u.length-I.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(d,C)},200)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile&&(g(d),p(d))})),this.registerEvent(this.app.vault.on("delete",d=>{if(!(d instanceof $.TFolder))return;let I=d.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof $.TFile&&this.maybeReHomeOnCrossFolderMove(d,I)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof $.TFile&&this.maybeArchiveOnMoveIn(d,I)})),this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile?this.importService.enqueue(d):d instanceof $.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile?this.importService.enqueue(d):d instanceof $.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",(d,I)=>{d instanceof $.TFile&&this.maybeAdoptAuthorRename(d,I)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(Dn,"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 $.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(Dn)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Dn)}catch{}for(let e of this.app.workspace.getLeavesOfType(ct))try{let i=e;i.isDeferred&&typeof i.loadIfDeferred=="function"&&await i.loadIfDeferred()}catch(i){console.warn("[Stashpad] un-ghost leaf failed",i)}}}isSemverGreater(t,e){let i=t.split(".").map(o=>parseInt(o,10)||0),s=e.split(".").map(o=>parseInt(o,10)||0),n=Math.max(i.length,s.length);for(let o=0;o<n;o++){let a=i[o]??0,r=s[o]??0;if(a!==r)return a>r}return!1}parseAuthorFilePath(t){let e=t.match(/\/_authors\/([^/]+?)-([a-z0-9]{4,12})\.md$/i);return e?{name:e[1].replace(/-/g," "),id:e[2]}:null}authorNameToSafe(t){return t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author"}async syncAuthorFilesToName(){let t=(this.settings.authorId??"").trim(),e=(this.settings.authorName??"").trim();if(!t||!e)return;let i=this.authorNameToSafe(e);for(let s of this.discoverStashpadFolders()){let n=`${s}/_authors`;if(await this.app.vault.adapter.exists(n))for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(n+"/"))continue;let a=this.parseAuthorFilePath(o.path);if(!a||a.id!==t)continue;let r=`${n}/${i}-${t}.md`,l=o;if(o.path!==r)try{this.authorRenameInFlight.add(o.path),this.authorRenameInFlight.add(r),await this.app.fileManager.renameFile(o,r);let c=this.app.vault.getAbstractFileByPath(r);c&&(l=c)}catch(c){console.warn("[Stashpad] author file rename failed",c);continue}try{await this.refreshAuthorStub(l)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,i?a.role=i:delete a.role,s?a.department=s:delete a.department})}catch(n){console.warn("[Stashpad] refreshAuthorStub failed",n)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let i=this.parseAuthorFilePath(t.path);if(!i)return;let s=(this.settings.authorId??"").trim();if(!s||i.id!==s)return;let n=i.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let i=this.app.vault.adapter,s=t.name,n=s.lastIndexOf("."),o=n>0?s.slice(0,n):s,a=n>0?s.slice(n):"",r=0;for(;await i.exists(`${e}/${s}`);)r+=1,s=`${o}-${r}${a}`;let l=`${e}/${s}`;await this.app.fileManager.renameFile(t,l);let c=this.app.vault.getAbstractFileByPath(l);c instanceof $.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(c)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[l]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",a=!i,r=!n,l=!o;if(!a&&!r&&!l)return;let{newId:c}=await Promise.resolve().then(()=>(Kt(),Ti)),g,p=!1,d=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(g=c(),f.id=g)),r){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=T,p=!0)}l&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),d=!0))}),!g&&!p&&!d)return;let I=this.newLog(),u=g||i;u&&await I.append({type:"parent_change",id:u,payload:{from:null,to:T,reason:"orphan_auto_fix",path:t.path,addedId:!!g,addedParent:p,addedCreated:d}}),new $.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===T||this.app.vault.getMarkdownFiles().some(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(a)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,a=>{let r=typeof a.parent=="string"?a.parent.trim():"";r&&r!==T&&(a.parent=T)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:T,reason:"rehome_cross_folder_move",path:t.path}}),new $.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(Lt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await Le(this.app,i);if(!s)return;let n=jt(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let l of n.collectExistingIds())o.add(l);else for(let l of this.app.vault.getMarkdownFiles()){if(!l.path.startsWith(e+"/"))continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter?.id;typeof c=="string"&&o.add(c)}let a=await zt(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:T,payload:{from:t.path,into:e,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let r=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&r.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&r.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:r.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed File: \`${t.name}\` Error: ${i.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:qi(this.app,t.path,$.Platform.isMobile)}),console.error(i)}}lookupNoteAuthorIds(t){let e=new Set,i=s=>{if(typeof s!="string")return null;let n=s.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;if(n?.id!==t)continue;let o=i(n?.author);o&&e.add(o);let a=n?.contributors;if(Array.isArray(a))for(let r of a){let l=i(r);l&&e.add(l)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let d of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(d)?.frontmatter?.id!==t)continue;let u=d.parent?.path;u&&e.add(u)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async d=>{if(d&&!await this.app.vault.adapter.exists(d))try{await this.app.vault.createFolder(d)}catch(I){let u=I?.message??"";if(!/already exists/i.test(u))throw I}},a=0,r=0,l=0,c=0;for(let d of e)try{if(i&&await o(`${d}/${i}`),s&&await o(`${d}/${s}`),this.settings.autoImport)try{let u=await this.importService.importLooseInto(d);c+=u.files+u.folders+u.stashes}catch(u){console.warn("Stashpad: loose sweep failed",d,u)}let I=await Ke(this.app,d);a+=I.checked,r+=I.written,l+=await this.rebootstrapFolderSlugs(d),n.push(d)}catch(I){console.warn(`Stashpad: rebootstrap skipped ${d}`,I)}let g=0;try{g=(await this.rebuildAuthorRegistry()).total}catch(d){console.warn("Stashpad: rebootstrap author-registry rebuild failed",d)}let p=0;try{p=await this.convertAttachmentsToLinks()}catch(d){console.warn("Stashpad: attachment-link conversion failed",d)}return{touched:n,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:g,imported:c,attachmentsLinked:p}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Yt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let r=we(a.basename);if(!(!r||r===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==r))try{let c=await this.app.vault.cachedRead(a),g=c.startsWith("---")?c.slice(c.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):c,p=Nt(g,s),d=xt(p,r);if(a.name===d)continue;let I=a.parent?`${a.parent.path}/${d}`:d;if(this.app.vault.getAbstractFileByPath(I))continue;await this.app.fileManager.renameFile(a,I),n+=1}catch(c){console.warn(`Stashpad: slug rebootstrap skipped ${a.path}`,c)}}return n}onStashpadSelectionChange(t){return this.stashpadSelectionListeners.add(t),()=>this.stashpadSelectionListeners.delete(t)}notifyStashpadSelectionChanged(){for(let t of this.stashpadSelectionListeners)try{t()}catch(e){console.warn("[Stashpad] selection listener failed",e)}}onStashpadContentChange(t){return this.stashpadContentListeners.add(t),()=>this.stashpadContentListeners.delete(t)}notifyStashpadContentChanged(){for(let t of this.stashpadContentListeners)try{t()}catch(e){console.warn("[Stashpad] content listener failed",e)}}getActiveStashpadSelection(){let e=this.lastActiveStashpadLeaf?.view;if(!e||e.getViewType?.()!==ct)return null;let i=e.noteFolder??"";if(!i)return null;let s=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=s[e.cursorIdx]),!n&&e.selection?.size>0){let o=e.firstSelectedId??[...e.selection][0];n=s.find(a=>a.id===o)}return n?.file?{folder:i,id:n.id,file:n.file}:null}fileForPin(t,e){let i=t.replace(/\/+$/,"");for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===i&&this.app.metadataCache.getFileCache(s)?.frontmatter?.id===e)return s;return null}async pinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned!==!0&&(await this.app.fileManager.processFrontMatter(e,i=>{i.pinned=!0,i.pinnedAt=Date.now()}),this.refreshPanelsView())}async unpinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0&&(await this.app.fileManager.processFrontMatter(e,i=>{delete i.pinned,delete i.pinnedAt}),this.refreshPanelsView())}isPinned(t){let e=this.fileForPin(t.folder,t.id);return e?this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0:!1}listPinnedNotes(){let t=new Set(this.discoverStashpadFolders()),e=[];for(let i of this.app.vault.getMarkdownFiles()){let s=i.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(s))continue;let n=this.app.metadataCache.getFileCache(i)?.frontmatter;if(!n||n.pinned!==!0||typeof n.id!="string"||!n.id)continue;let o=typeof n.pinnedAt=="number"?n.pinnedAt:0;e.push({folder:s,id:n.id,pinnedAt:o,file:i})}return e.sort((i,s)=>i.pinnedAt-s.pinnedAt||i.file.path.localeCompare(s.file.path)),e}async migratePinnedNotesToFrontmatter(){let t=this.settings.pinnedNotes??[];if(t.length===0)return;let e=Date.now()-t.length*1e3;for(let i of t){let s=this.fileForPin(i.folder,i.id);if(!s){e+=1e3;continue}try{if(this.app.metadataCache.getFileCache(s)?.frontmatter?.pinned!==!0){let n=e;await this.app.fileManager.processFrontMatter(s,o=>{o.pinned=!0,o.pinnedAt=n})}}catch(n){console.warn("[Stashpad] pin migration failed for",i,n)}e+=1e3}this.settings.pinnedNotes=[],await this.saveSettings(),this.refreshPanelsView()}refreshPanelsView(){let t=this.app.workspace.getLeavesOfType(ie);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(ct)){let e=t.view;e&&typeof e.render=="function"&&e.render()}}openFolderPicker(){let t=I=>{let f=I.getViewState().state?.folderOverride;return typeof f=="string"&&f.trim()?f.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(ct),i=this.discoverStashpadFolders(),s=jt(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let I of this.app.vault.getAllLoadedFiles())if(I.children){let u=I.path;u&&u!=="/"&&!u.startsWith(".")&&o.add(u)}let a=I=>{let u=I.split("/").filter(Boolean).pop()??"";return u?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(C=>(C??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(u):!1},r=new Set,l=[],c=[],g=new Set;for(let I of e){let u=t(I);if(g.has(u))continue;g.add(u),r.add(u);let f=u.split("/").pop()||u;l.push({kind:"reveal",folder:u,label:`Reveal "${f}" tab`,leaf:I,icon:this.isArchiveFolder(u)?"archive":"layout-grid"}),c.push({kind:"open-anyway",folder:u,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let I of i.filter(u=>!r.has(u))){let u=I.split("/").pop()||I;l.push({kind:"open",folder:I,label:`Open "${u}" in new tab`,icon:this.isArchiveFolder(I)?"archive":"layout-template"})}let p=this,d=new class extends $.SuggestModal{getSuggestions(I){let u=I.trim().toLowerCase(),f=u?u.split(/\s+/).filter(Boolean):[],C=y=>{if(!f.length)return!0;let v=y.toLowerCase();for(let S of f)if(!v.includes(S))return!1;return!0},m=u?l.filter(y=>{let v="folder"in y?y.folder:"";return C(y.label)||C(v)}):l.slice();if(u&&s&&n)for(let y of i){if(y.toLowerCase()===n.toLowerCase())continue;let v=y.split("/").pop()??y,S=`${y} ${v}`;C(S)&&m.push({kind:"switch-current",folder:y,label:`Switch this tab to "${v}"`,icon:"folder-input"})}let E=I.trim().replace(/^\/+|\/+$/g,"");if(E&&!a(E)){let y=Array.from(o).find(S=>S.toLowerCase()===E.toLowerCase()),v=i.some(S=>S.toLowerCase()===E.toLowerCase());if(y&&!v)m.push({kind:"convert",folder:y,label:`Convert \u201C${wi(y)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!y){let S=wi(E);m.push({kind:"create",folder:E,label:`+ Create new Stashpad \u201C${S}\u201D`,icon:"folder-plus"})}}let w=c.filter(y=>C(y.label)||C("folder"in y?y.folder:""));return m.push(...w),p.encryption?.isConfigured?.()&&C("trash deleted encrypted")&&m.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),m}renderSuggestion(I,u){u.addClass("stashpad-suggest-item"),u.addClass("stashpad-ribbon-suggest-item"),I.kind==="create"&&u.addClass("stashpad-suggest-create");let f=u.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,$.setIcon)(f,I.icon);let C=u.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:I.label}),"folder"in I&&I.folder&&I.label!==I.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:I.folder})}async onChooseSuggestion(I){if(I.kind==="trash"){p.openEncryptedTrash();return}if(I.kind==="reveal"){p.app.workspace.revealLeaf(I.leaf);return}if(I.kind==="open"||I.kind==="open-anyway"){await p.activateViewForFolder(I.folder);return}if(I.kind==="switch-current"){let u=s;u&&typeof u.setFolderOverride=="function"&&(await u.setFolderOverride(I.folder),p.app.workspace.revealLeaf(u.leaf));return}if(I.kind==="create"){try{let u=wi(I.folder);await p.app.vault.adapter.exists(u)||await p.app.vault.createFolder(u),await p.activateViewForFolder(u)}catch(u){new $.Notice(`Stashpad: couldn't create folder (${u.message})`)}return}if(I.kind==="convert"){let{ConfirmModal:u}=await Promise.resolve().then(()=>(Ht(),Ai)),f=I.folder,C=[`\u201C${f}\u201D already exists as a regular vault folder.`,"Converting will add a Home note + _imports / _exports subfolders inside it.","Existing files are NOT touched."];new u(p.app,"Convert into a Stashpad?",C.join(` -`),"Convert",async m=>{if(m)try{await p.activateViewForFolder(f)}catch(E){new $.Notice(`Stashpad: couldn't convert folder (${E.message})`)}}).open();return}}}(this.app);d.setPlaceholder(s?"Open, switch this tab, or create a Stashpad folder \u2014 type to filter\u2026":"Open or create a Stashpad folder \u2014 type to filter\u2026"),d.open()}async openTinyWindow(){let t=jt(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new $.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:ct,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(ct);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:ct,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(ct),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 Bs(this.app);let t=this.app.workspace.getLeavesOfType(ue)[0];t&&this.app.workspace.setActiveLeaf(t,{focus:!0})}async reconcileLockedRegistry(){let t=this.settings.lockedSubtrees??[],e=[];for(let n of t){let o=(n.folder??"").replace(/\/+$/,"");if(!(o==="_deleted"||o.startsWith("_deleted/")))try{await this.app.vault.adapter.exists(n.blob)&&e.push(n)}catch{e.push(n)}}let i=e.length!==t.length,s=new Set(e.map(n=>n.blob));for(let n of this.app.vault.getFiles()){if(n.extension!=="stashenc"||s.has(n.path))continue;let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o==="_deleted"||o.startsWith("_deleted/"))continue;let a=await fo(this.app,n.path);a&&(e.push({folder:o,blob:n.path,parentId:a.parentId,title:a.title,count:a.count,created:a.created,rootId:a.rootId,prevSibling:a.prevSibling}),i=!0)}i&&(this.settings.lockedSubtrees=e,await this.saveSettings(),this.refreshAllStashpadViews?.())}lockedSubtreesFor(t,e){let i=t.replace(/\/+$/,""),s=[],n=new Set;for(let o of this.settings.lockedSubtrees??[])(o.folder??"").replace(/\/+$/,"")===i&&(o.parentId??M)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??M,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let a=o.parent?.path?.replace(/\/+$/,"")??"";a!==i||a==="_deleted"||a.startsWith("_deleted/")||e===M&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:M,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new $t(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 $.Notice("Set up encryption first (Settings \u2192 Encryption)."),!1)}async lockNoteSubtree(t,e,i=null,s={}){if(!await this.ensureEncryptionUnlocked())return null;let n=this.encryption.getSessionKey();if(!n)return null;try{let o=this.settings.hideLockedTitles??!1,a=await Bo(this.app,t,e,n,i,o,s.blobFolder),r=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(l=>l.blob!==a.blobPath),{folder:r,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 $.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:Oi(this.app,t.path,$.Platform.isMobile)}),console.error(i)}}lookupNoteAuthorIds(t){let e=new Set,i=s=>{if(typeof s!="string")return null;let n=s.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;if(n?.id!==t)continue;let o=i(n?.author);o&&e.add(o);let a=n?.contributors;if(Array.isArray(a))for(let r of a){let l=i(r);l&&e.add(l)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let d of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(d)?.frontmatter?.id!==t)continue;let u=d.parent?.path;u&&e.add(u)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async d=>{if(d&&!await this.app.vault.adapter.exists(d))try{await this.app.vault.createFolder(d)}catch(I){let u=I?.message??"";if(!/already exists/i.test(u))throw I}},a=0,r=0,l=0,c=0;for(let d of e)try{if(i&&await o(`${d}/${i}`),s&&await o(`${d}/${s}`),this.settings.autoImport)try{let u=await this.importService.importLooseInto(d);c+=u.files+u.folders+u.stashes}catch(u){console.warn("Stashpad: loose sweep failed",d,u)}let I=await ze(this.app,d);a+=I.checked,r+=I.written,l+=await this.rebootstrapFolderSlugs(d),n.push(d)}catch(I){console.warn(`Stashpad: rebootstrap skipped ${d}`,I)}let g=0;try{g=(await this.rebuildAuthorRegistry()).total}catch(d){console.warn("Stashpad: rebootstrap author-registry rebuild failed",d)}let p=0;try{p=await this.convertAttachmentsToLinks()}catch(d){console.warn("Stashpad: attachment-link conversion failed",d)}return{touched:n,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:g,imported:c,attachmentsLinked:p}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Yt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let r=we(a.basename);if(!(!r||r===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==r))try{let c=await this.app.vault.cachedRead(a),g=c.startsWith("---")?c.slice(c.indexOf(` +---`,3)+4).replace(/^\r?\n/,""):c,p=xt(g,s),d=Mt(p,r);if(a.name===d)continue;let I=a.parent?`${a.parent.path}/${d}`:d;if(this.app.vault.getAbstractFileByPath(I))continue;await this.app.fileManager.renameFile(a,I),n+=1}catch(c){console.warn(`Stashpad: slug rebootstrap skipped ${a.path}`,c)}}return n}onStashpadSelectionChange(t){return this.stashpadSelectionListeners.add(t),()=>this.stashpadSelectionListeners.delete(t)}notifyStashpadSelectionChanged(){for(let t of this.stashpadSelectionListeners)try{t()}catch(e){console.warn("[Stashpad] selection listener failed",e)}}onStashpadContentChange(t){return this.stashpadContentListeners.add(t),()=>this.stashpadContentListeners.delete(t)}notifyStashpadContentChanged(){for(let t of this.stashpadContentListeners)try{t()}catch(e){console.warn("[Stashpad] content listener failed",e)}}getActiveStashpadSelection(){let e=this.lastActiveStashpadLeaf?.view;if(!e||e.getViewType?.()!==ct)return null;let i=e.noteFolder??"";if(!i)return null;let s=e.currentChildren??[],n;if(typeof e.cursorIdx=="number"&&e.cursorIdx>=0&&(n=s[e.cursorIdx]),!n&&e.selection?.size>0){let o=e.firstSelectedId??[...e.selection][0];n=s.find(a=>a.id===o)}return n?.file?{folder:i,id:n.id,file:n.file}:null}fileForPin(t,e){let i=t.replace(/\/+$/,"");for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===i&&this.app.metadataCache.getFileCache(s)?.frontmatter?.id===e)return s;return null}async pinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned!==!0&&(await this.app.fileManager.processFrontMatter(e,i=>{i.pinned=!0,i.pinnedAt=Date.now()}),this.refreshPanelsView())}async unpinNote(t){let e=this.fileForPin(t.folder,t.id);e&&this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0&&(await this.app.fileManager.processFrontMatter(e,i=>{delete i.pinned,delete i.pinnedAt}),this.refreshPanelsView())}isPinned(t){let e=this.fileForPin(t.folder,t.id);return e?this.app.metadataCache.getFileCache(e)?.frontmatter?.pinned===!0:!1}listPinnedNotes(){let t=new Set(this.discoverStashpadFolders()),e=[];for(let i of this.app.vault.getMarkdownFiles()){let s=i.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(s))continue;let n=this.app.metadataCache.getFileCache(i)?.frontmatter;if(!n||n.pinned!==!0||typeof n.id!="string"||!n.id)continue;let o=typeof n.pinnedAt=="number"?n.pinnedAt:0;e.push({folder:s,id:n.id,pinnedAt:o,file:i})}return e.sort((i,s)=>i.pinnedAt-s.pinnedAt||i.file.path.localeCompare(s.file.path)),e}async migratePinnedNotesToFrontmatter(){let t=this.settings.pinnedNotes??[];if(t.length===0)return;let e=Date.now()-t.length*1e3;for(let i of t){let s=this.fileForPin(i.folder,i.id);if(!s){e+=1e3;continue}try{if(this.app.metadataCache.getFileCache(s)?.frontmatter?.pinned!==!0){let n=e;await this.app.fileManager.processFrontMatter(s,o=>{o.pinned=!0,o.pinnedAt=n})}}catch(n){console.warn("[Stashpad] pin migration failed for",i,n)}e+=1e3}this.settings.pinnedNotes=[],await this.saveSettings(),this.refreshPanelsView()}refreshPanelsView(){let t=this.app.workspace.getLeavesOfType(ie);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(ct)){let e=t.view;e&&typeof e.render=="function"&&e.render()}}openFolderPicker(){let t=I=>{let f=I.getViewState().state?.folderOverride;return typeof f=="string"&&f.trim()?f.trim().replace(/^\/+|\/+$/g,""):(this.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")},e=this.app.workspace.getLeavesOfType(ct),i=this.discoverStashpadFolders(),s=jt(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let I of this.app.vault.getAllLoadedFiles())if(I.children){let u=I.path;u&&u!=="/"&&!u.startsWith(".")&&o.add(u)}let a=I=>{let u=I.split("/").filter(Boolean).pop()??"";return u?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(C=>(C??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(u):!1},r=new Set,l=[],c=[],g=new Set;for(let I of e){let u=t(I);if(g.has(u))continue;g.add(u),r.add(u);let f=u.split("/").pop()||u;l.push({kind:"reveal",folder:u,label:`Reveal "${f}" tab`,leaf:I,icon:this.isArchiveFolder(u)?"archive":"layout-grid"}),c.push({kind:"open-anyway",folder:u,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let I of i.filter(u=>!r.has(u))){let u=I.split("/").pop()||I;l.push({kind:"open",folder:I,label:`Open "${u}" in new tab`,icon:this.isArchiveFolder(I)?"archive":"layout-template"})}let p=this,d=new class extends $.SuggestModal{getSuggestions(I){let u=I.trim().toLowerCase(),f=u?u.split(/\s+/).filter(Boolean):[],C=y=>{if(!f.length)return!0;let v=y.toLowerCase();for(let S of f)if(!v.includes(S))return!1;return!0},m=u?l.filter(y=>{let v="folder"in y?y.folder:"";return C(y.label)||C(v)}):l.slice();if(u&&s&&n)for(let y of i){if(y.toLowerCase()===n.toLowerCase())continue;let v=y.split("/").pop()??y,S=`${y} ${v}`;C(S)&&m.push({kind:"switch-current",folder:y,label:`Switch this tab to "${v}"`,icon:"folder-input"})}let E=I.trim().replace(/^\/+|\/+$/g,"");if(E&&!a(E)){let y=Array.from(o).find(S=>S.toLowerCase()===E.toLowerCase()),v=i.some(S=>S.toLowerCase()===E.toLowerCase());if(y&&!v)m.push({kind:"convert",folder:y,label:`Convert \u201C${vi(y)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!y){let S=vi(E);m.push({kind:"create",folder:E,label:`+ Create new Stashpad \u201C${S}\u201D`,icon:"folder-plus"})}}let w=c.filter(y=>C(y.label)||C("folder"in y?y.folder:""));return m.push(...w),p.encryption?.isConfigured?.()&&C("trash deleted encrypted")&&m.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),m}renderSuggestion(I,u){u.addClass("stashpad-suggest-item"),u.addClass("stashpad-ribbon-suggest-item"),I.kind==="create"&&u.addClass("stashpad-suggest-create");let f=u.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,$.setIcon)(f,I.icon);let C=u.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:I.label}),"folder"in I&&I.folder&&I.label!==I.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:I.folder})}async onChooseSuggestion(I){if(I.kind==="trash"){p.openEncryptedTrash();return}if(I.kind==="reveal"){p.app.workspace.revealLeaf(I.leaf);return}if(I.kind==="open"||I.kind==="open-anyway"){await p.activateViewForFolder(I.folder);return}if(I.kind==="switch-current"){let u=s;u&&typeof u.setFolderOverride=="function"&&(await u.setFolderOverride(I.folder),p.app.workspace.revealLeaf(u.leaf));return}if(I.kind==="create"){try{let u=vi(I.folder);await p.app.vault.adapter.exists(u)||await p.app.vault.createFolder(u),await p.activateViewForFolder(u)}catch(u){new $.Notice(`Stashpad: couldn't create folder (${u.message})`)}return}if(I.kind==="convert"){let{ConfirmModal:u}=await Promise.resolve().then(()=>(Tt(),ci)),f=I.folder,C=[`\u201C${f}\u201D already exists as a regular vault folder.`,"Converting will add a Home note + _imports / _exports subfolders inside it.","Existing files are NOT touched."];new u(p.app,"Convert into a Stashpad?",C.join(` +`),"Convert",async m=>{if(m)try{await p.activateViewForFolder(f)}catch(E){new $.Notice(`Stashpad: couldn't convert folder (${E.message})`)}}).open();return}}}(this.app);d.setPlaceholder(s?"Open, switch this tab, or create a Stashpad folder \u2014 type to filter\u2026":"Open or create a Stashpad folder \u2014 type to filter\u2026"),d.open()}async openTinyWindow(){let t=jt(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new $.Notice("Stashpad: couldn't open popout window on this build.");return}await n.setViewState({type:ct,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(ct);if(s.length>0){e.revealLeaf(s[0]);return}}let i=e.getLeaf("tab");await i.setViewState({type:ct,active:!0}),e.revealLeaf(i)}async focusLastStashpadTab(){let t=this.app.workspace,e=t.getLeavesOfType(ct),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 Es(this.app);let t=this.app.workspace.getLeavesOfType(ue)[0];t&&this.app.workspace.setActiveLeaf(t,{focus:!0})}async reconcileLockedRegistry(){let t=this.settings.lockedSubtrees??[],e=[];for(let n of t){let o=(n.folder??"").replace(/\/+$/,"");if(!(o==="_deleted"||o.startsWith("_deleted/")))try{await this.app.vault.adapter.exists(n.blob)&&e.push(n)}catch{e.push(n)}}let i=e.length!==t.length,s=new Set(e.map(n=>n.blob));for(let n of this.app.vault.getFiles()){if(n.extension!=="stashenc"||s.has(n.path))continue;let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o==="_deleted"||o.startsWith("_deleted/"))continue;let a=await Co(this.app,n.path);a&&(e.push({folder:o,blob:n.path,parentId:a.parentId,title:a.title,count:a.count,created:a.created,rootId:a.rootId,prevSibling:a.prevSibling}),i=!0)}i&&(this.settings.lockedSubtrees=e,await this.saveSettings(),this.refreshAllStashpadViews?.())}lockedSubtreesFor(t,e){let i=t.replace(/\/+$/,""),s=[],n=new Set;for(let o of this.settings.lockedSubtrees??[])(o.folder??"").replace(/\/+$/,"")===i&&(o.parentId??T)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??T,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let a=o.parent?.path?.replace(/\/+$/,"")??"";a!==i||a==="_deleted"||a.startsWith("_deleted/")||e===T&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:T,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new Xt(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 $.Notice("Set up encryption first (Settings \u2192 Encryption)."),!1)}async lockNoteSubtree(t,e,i=null,s={}){if(!await this.ensureEncryptionUnlocked())return null;let n=this.encryption.getSessionKey();if(!n)return null;try{let o=this.settings.hideLockedTitles??!1,a=await Bo(this.app,t,e,n,i,o,s.blobFolder),r=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(l=>l.blob!==a.blobPath),{folder:r,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 $.Notice(`\u26A0\uFE0F Locked, but ${a.unpurged.length} file${a.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): ${a.unpurged.join(` -`)}`,0):s.silent||this.notifications.show({message:`Locked ${a.title?`\u201C${a.title}\u201D`:"a note"} (${a.noteCount} note${a.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),a}catch(o){return console.warn("[Stashpad] lock failed",o),new $.Notice(`Couldn't lock: ${o.message}`),null}}async unlockBundleAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,""),n=new Set;for(let o of this.app.vault.getMarkdownFiles())if((o.parent?.path?.replace(/\/+$/,"")??"")===s)try{let a=Mt(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}try{let o=await Qo(this.app,t,i,n,e.destFolder);return this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(a=>a.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${o.notesWritten} note${o.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:s}),!0}catch(o){return console.warn("[Stashpad] unlock failed",o),new $.Notice(`Couldn't unlock: ${o.message}`),!1}}async lockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=[];for(let c of this.app.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let g;try{g=Mt(await this.app.vault.read(c)).fm}catch{continue}let p=g.id;typeof p!="string"||p===M||(typeof g.parent=="string"?g.parent:M)!==M||i.push(p)}let s=new Set((this.settings.lockedSubtrees??[]).map(c=>c.rootId).filter(c=>!!c)),n=i.filter(c=>!s.has(c));if(n.length===0)return new $.Notice("Nothing to lock in this folder."),0;let a=(await new qe(this.app).load(e))[M]??[],r=n.length>3?new $.Notice("",0):null,l=0;for(let c=0;c<n.length;c++){let g=n[c];r?.setMessage(`\u{1F512} Encrypting ${c+1}/${n.length}\u2026`);let p=a.indexOf(g),d=p>0?a[p-1]:null;await this.lockNoteSubtree(e,g,d,{silent:!0})&&l++}return r?.hide(),l>0&&this.notifications.show({message:`Locked ${l} note${l===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),l}async unlockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>o.extension==="stashenc"&&(o.parent?.path?.replace(/\/+$/,"")??"")===e).map(o=>o.path);if(i.length===0)return new $.Notice("No locked notes in this folder."),0;let s=i.length>3?new $.Notice("",0):null,n=0;for(let o=0;o<i.length;o++){s?.setMessage(`\u{1F513} Decrypting ${o+1}/${i.length}\u2026`);try{await this.unlockBundleAt(i[o],{silent:!0})&&n++}catch(a){console.warn("[Stashpad] folder unlock skipped",i[o],a)}}return s?.hide(),n>0&&this.notifications.show({message:`Unlocked ${n} note${n===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),n}async unlockAllInVault(){if(!await this.ensureEncryptionUnlocked())return 0;let t=this.app.vault.getFiles().filter(n=>n.extension==="stashenc"&&(n.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(n=>n.path);if(t.length===0)return new $.Notice("No locked notes anywhere in the vault."),0;let e=t.length>3?new $.Notice("",0):null,i=0;for(let n=0;n<t.length;n++){e?.setMessage(`\u{1F513} Decrypting ${n+1}/${t.length}\u2026`);try{await this.unlockBundleAt(t[n],{silent:!0})&&i++}catch(o){console.warn("[Stashpad] vault unlock skipped",t[n],o)}}e?.hide();let s=t[0].replace(/\/[^/]*$/,"");return i>0&&this.notifications.show({message:`Unlocked ${i} note${i===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:s}),i}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),n=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),o=await Eo(this.app,t,e,i,s,n);return o.unpurged.length>0&&new $.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${o.unpurged.length} file${o.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): +`)}`,0):s.silent||this.notifications.show({message:`Locked ${a.title?`\u201C${a.title}\u201D`:"a note"} (${a.noteCount} note${a.noteCount===1?"":"s"}).`,kind:"success",category:"system",folder:t}),a}catch(o){return console.warn("[Stashpad] lock failed",o),new $.Notice(`Couldn't lock: ${o.message}`),null}}async unlockBundleAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,""),n=new Set;for(let o of this.app.vault.getMarkdownFiles())if((o.parent?.path?.replace(/\/+$/,"")??"")===s)try{let a=Dt(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}try{let o=await Qo(this.app,t,i,n,e.destFolder);return this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(a=>a.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${o.notesWritten} note${o.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:s}),!0}catch(o){return console.warn("[Stashpad] unlock failed",o),new $.Notice(`Couldn't unlock: ${o.message}`),!1}}async lockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=[];for(let c of this.app.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let g;try{g=Dt(await this.app.vault.read(c)).fm}catch{continue}let p=g.id;typeof p!="string"||p===T||(typeof g.parent=="string"?g.parent:T)!==T||i.push(p)}let s=new Set((this.settings.lockedSubtrees??[]).map(c=>c.rootId).filter(c=>!!c)),n=i.filter(c=>!s.has(c));if(n.length===0)return new $.Notice("Nothing to lock in this folder."),0;let a=(await new Ke(this.app).load(e))[T]??[],r=n.length>3?new $.Notice("",0):null,l=0;for(let c=0;c<n.length;c++){let g=n[c];r?.setMessage(`\u{1F512} Encrypting ${c+1}/${n.length}\u2026`);let p=a.indexOf(g),d=p>0?a[p-1]:null;await this.lockNoteSubtree(e,g,d,{silent:!0})&&l++}return r?.hide(),l>0&&this.notifications.show({message:`Locked ${l} note${l===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),l}async unlockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>o.extension==="stashenc"&&(o.parent?.path?.replace(/\/+$/,"")??"")===e).map(o=>o.path);if(i.length===0)return new $.Notice("No locked notes in this folder."),0;let s=i.length>3?new $.Notice("",0):null,n=0;for(let o=0;o<i.length;o++){s?.setMessage(`\u{1F513} Decrypting ${o+1}/${i.length}\u2026`);try{await this.unlockBundleAt(i[o],{silent:!0})&&n++}catch(a){console.warn("[Stashpad] folder unlock skipped",i[o],a)}}return s?.hide(),n>0&&this.notifications.show({message:`Unlocked ${n} note${n===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),n}async unlockAllInVault(){if(!await this.ensureEncryptionUnlocked())return 0;let t=this.app.vault.getFiles().filter(n=>n.extension==="stashenc"&&(n.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(n=>n.path);if(t.length===0)return new $.Notice("No locked notes anywhere in the vault."),0;let e=t.length>3?new $.Notice("",0):null,i=0;for(let n=0;n<t.length;n++){e?.setMessage(`\u{1F513} Decrypting ${n+1}/${t.length}\u2026`);try{await this.unlockBundleAt(t[n],{silent:!0})&&i++}catch(o){console.warn("[Stashpad] vault unlock skipped",t[n],o)}}e?.hide();let s=t[0].replace(/\/[^/]*$/,"");return i>0&&this.notifications.show({message:`Unlocked ${i} note${i===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:s}),i}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),n=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),o=await Eo(this.app,t,e,i,s,n);return o.unpurged.length>0&&new $.Notice(`\u26A0\uFE0F Sent to encrypted trash, but ${o.unpurged.length} file${o.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the delete): ${o.unpurged.join(` -`)}`,0),o.blobPath}catch(s){return console.warn("[Stashpad] encrypt-delete failed",s),new $.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 Xi(this.app,t);if(s?.kind==="rawtrash")try{let n=await vo(this.app,t,i);return e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Jt}/).`,kind:"success",category:"system",folder:""}),!0}catch(n){return console.warn("[Stashpad] trash-backfill restore failed",n),new $.Notice(`Couldn't restore: ${n.message}`,0),!1}try{let n=await dn(this.app,t,s,i),o=new Set;for(let r of this.app.vault.getMarkdownFiles())if((r.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let l=Mt(await this.app.vault.read(r)).fm.id;typeof l=="string"&&o.add(l)}catch{}let a=await yo(this.app,t,i,o);return e.silent||this.notifications.show({message:`Restored ${a.notesWritten} note${a.notesWritten===1?"":"s"} to \u201C${a.restoredTo.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:a.restoredTo}),!0}catch(n){return console.warn("[Stashpad] restore-from-trash failed",n),new $.Notice(`Couldn't restore: ${n.message}`,0),!1}}async listDeletedTrash(){let t=await Fo(this.app),e=[];for(let i of t)e.push({blob:i,meta:await Xi(this.app,i)});return e}async restoreAllTrash(){if(!await this.ensureEncryptionUnlocked())return 0;let t=await this.listDeletedTrash();if(t.length===0)return new $.Notice("Nothing to restore."),0;let e=t.length>3?new $.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 wo(this.app,t,new Date().toISOString(),e);return i?(i.unpurged.length>0?new $.Notice(`\u26A0\uFE0F Encrypted the trash, but ${i.unpurged.length} file${i.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed): +`)}`,0),o.blobPath}catch(s){return console.warn("[Stashpad] encrypt-delete failed",s),new $.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 _i(this.app,t);if(s?.kind==="rawtrash")try{let n=await vo(this.app,t,i);return e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Jt}/).`,kind:"success",category:"system",folder:""}),!0}catch(n){return console.warn("[Stashpad] trash-backfill restore failed",n),new $.Notice(`Couldn't restore: ${n.message}`,0),!1}try{let n=await gn(this.app,t,s,i),o=new Set;for(let r of this.app.vault.getMarkdownFiles())if((r.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let l=Dt(await this.app.vault.read(r)).fm.id;typeof l=="string"&&o.add(l)}catch{}let a=await yo(this.app,t,i,o);return e.silent||this.notifications.show({message:`Restored ${a.notesWritten} note${a.notesWritten===1?"":"s"} to \u201C${a.restoredTo.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:a.restoredTo}),!0}catch(n){return console.warn("[Stashpad] restore-from-trash failed",n),new $.Notice(`Couldn't restore: ${n.message}`,0),!1}}async listDeletedTrash(){let t=await Fo(this.app),e=[];for(let i of t)e.push({blob:i,meta:await _i(this.app,i)});return e}async restoreAllTrash(){if(!await this.ensureEncryptionUnlocked())return 0;let t=await this.listDeletedTrash();if(t.length===0)return new $.Notice("Nothing to restore."),0;let e=t.length>3?new $.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 wo(this.app,t,new Date().toISOString(),e);return i?(i.unpurged.length>0?new $.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 ${Jt}/.`,kind:"success",category:"system",folder:""}),!0):(new $.Notice(`Obsidian's vault trash (${Jt}/) 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 $.Notice(`Couldn't encrypt the existing trash: ${e.message}`,0),!1}}openEncryptedTrash(t){if(!this.encryption.isConfigured()){new $.Notice("Set up encryption first (Settings \u2192 Encryption).");return}Wo(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new $.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=await this.listDeletedTrash();if(t.length===0){new $.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 fs(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,""),s=[];for(let l of e){let c=this.app.vault.getAbstractFileByPath(l);if(!(c instanceof $.TFile)||(c.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let g;try{g=Mt(await this.app.vault.read(c)).fm}catch{continue}let p=typeof g.id=="string"?g.id:null;!p||p===M||s.push({id:p,parent:typeof g.parent=="string"?g.parent:null})}if(s.length===0)return;let n=new Set(s.map(l=>l.id)),o=new Set((this.settings.lockedSubtrees??[]).map(l=>l.rootId).filter(l=>!!l)),a=s.filter(l=>!o.has(l.id)&&!(l.parent&&n.has(l.parent)));if(a.length===0)return;if(!await this.ensureEncryptionUnlocked()){new $.Notice(`\u26A0\uFE0F Archive folder "${i.split("/").pop()}": ${a.length} arriving note${a.length===1?"":"s"} NOT encrypted (vault is locked). Unlock encryption and lock them manually.`,0);return}let r=0;for(let l of a)await this.lockNoteSubtree(i,l.id,null,{silent:!0})&&r++;r>0&&this.notifications.show({message:`Archived (encrypted) ${r} note${r===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:ct,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(ct),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 $.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(ct),e=this.app.workspace.activeLeaf;for(let I of t)try{await I.loadIfDeferred?.()}catch{}let i=I=>I.getViewState()?.state??{},s=I=>{let u=i(I);return(I.isDeferred?u.folderOverride??"":I.view?.noteFolder??u.folderOverride??"").replace(/\/+$/,"")},n=I=>{let u=i(I);return(I.isDeferred?u.focusId:I.view?.focusId??u.focusId)||M},o=I=>{let u=I.view;return!!u&&u.getViewType?.()===ct&&typeof u.navigateTo=="function"&&typeof u.noteFolder=="string"},a=new Map;for(let I of this.app.vault.getMarkdownFiles()){let u=(I.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(I)?.frontmatter?.id;typeof f=="string"&&f&&(a.get(u)??a.set(u,new Set).get(u)).add(f)}let r=0,l=[];for(let I of t){let u=s(I),f=n(I);if(u&&f&&f!==M){let C=!I.isDeferred&&!!I.view?.tree?.get?.(f),m=a.get(u)?.has(f)??!1;if(!C&&!m){I.detach(),r++;continue}}l.push(I)}let c=new Map;for(let I of l){let u=s(I);if(!u)continue;let f=u+" "+n(I);(c.get(f)??c.set(f,[]).get(f)).push(I)}let g=0;for(let I of c.values()){if(I.length<=1)continue;I.sort((f,C)=>{let m=E=>E===e?2:E.isDeferred?0:1;return m(C)-m(f)});let u=null;for(let f of I){try{await f.loadIfDeferred?.()}catch{}if(o(f)){u=f;break}}u||(u=I[0]);for(let f of I)f!==u&&(f.detach(),g++)}let p=this.app.workspace.getLeavesOfType(ct).length,d=document.createDocumentFragment();return d.createEl("div",{text:g+r>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),d.createEl("div",{text:`\u2022 ${g} duplicate tab${g===1?"":"s"} closed`}),d.createEl("div",{text:`\u2022 ${r} orphaned tab${r===1?"":"s"} pruned (note no longer exists)`}),d.createEl("div",{text:`\u2022 ${p} Stashpad tab${p===1?"":"s"} remaining`}),new $.Notice(d,7e3),g+r}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(ct).find(o=>(o.view?.noteFolder??"").replace(/\/+$/,"")===s)?.view??this.lastActiveStashpadLeaf?.view;if(n&&typeof n.navigateTo=="function"&&(!n.tree||typeof n.tree.get!="function"||!!n.tree.get(e))){n.navigateTo(e);return}i>0?window.setTimeout(()=>this.navigateWhenReady(t,e,i-1),90):n&&typeof n.navigateTo=="function"&&n.navigateTo(e)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,i=this.discoverStashpadFolders(),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(I=>typeof I=="string"):[],l=a.includes(e),c=r.some(I=>I.includes(e));if(!l&&!c)continue;let g=n.parent?.path??"",p=i.find(I=>g===I||g.startsWith(I+"/"));if(!p)continue;s.has(p)||s.set(p,{authored:0,contributed:0});let d=s.get(p);l&&d.authored++,c&&d.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return ne(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(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return!1;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),r=`${s}/${a}-${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:o?.role,department:o?.department},new Date().toISOString())),!0)}catch(l){return console.warn("[Stashpad] ensureAuthorStubFor failed",r,l),!1}}async seedKnownAuthorsInFolder(t){let e=0;for(let i of this.collectKnownAuthors())await this.ensureAuthorStubFor(t,i.id,i.name)&&e++;return e}async checkDueReminders(){let t=Date.now(),e=new Set(this.settings.notifiedDueKeys??[]),i=(this.settings.authorId??"").trim(),s=[];for(let o of this.app.vault.getMarkdownFiles()){if(o.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!a||a.due==null)continue;let r=typeof a.id=="string"?a.id:"";if(!r)continue;let l=String(a.due),c=typeof a.due=="number"?a.due:Date.parse(l);if(!Number.isFinite(c)||c>t)continue;let g=me(a);if(g.length>0&&!(i&&g.some(d=>d.id===i)))continue;let p=`${r}@${l}`;e.has(p)||s.push({id:r,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:c,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 r=Mt(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(l=>l.trim()).find(l=>l.length>0);if(r)return r.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(s.length<=3)for(let o of s){let a=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${a}\u201D (${Wt(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 $.Notice("No authors or Stashpad folders to sync.");return}let i=e.length*t.length>8?new $.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,r=((Array.isArray(o?.aliases)?o.aliases.find(l=>typeof l=="string")??"":typeof o?.aliases=="string"?o.aliases:"")||(typeof o?.name=="string"?o.name:"")||n.name).trim();t.has(n.id)||t.set(n.id,r),this.authorRegistry.record({id:n.id,name:r})}return[...t.entries()].map(([s,n])=>({id:s,name:n}))}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,i=0;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=[];if(typeof o.author=="string"&&a.push(o.author),Array.isArray(o.contributors))for(let r of o.contributors)typeof r=="string"&&a.push(r);for(let r of a){let l=this.parseAuthorRef(r);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),i++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter,g=((Array.isArray(l?.aliases)?l.aliases.find(u=>typeof u=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||r.name).trim(),p=typeof l?.role=="string"?l.role:void 0,d=typeof l?.department=="string"?l.department:void 0,I=e.get(r.id);I||s++,e.set(r.id,{id:r.id,name:g||I?.name,role:p??I?.role,department:d??I?.department,fromStub:!0})}}return await this.authorRegistry.load(),this.authorRegistry.replaceAll([...e.values()]),await this.authorRegistry.save(),{total:e.size,fromStubs:s,fromNotes:i}}buildAuthorStub(t,e){let i=a=>a.replace(/[\r\n]+/g," ").trim(),s=a=>i(a).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=i(t.name),o=["---",`authorId: ${t.id}`,"aliases:",` - "${s(t.name)}"`];return t.role&&o.push(`role: "${s(t.role)}"`),t.department&&o.push(`department: "${s(t.department)}"`),o.push(`created: ${e}`,"---",`# ${n}`),o.join(` -`)}async restoreMissingAuthorStubs(){await this.authorRegistry.load();let t=this.authorRegistry.all().filter(n=>n.id&&n.name),e=this.discoverStashpadFolders(),i=this.app.vault.getMarkdownFiles(),s=0;for(let n of e){let o=`${n}/_authors`,a=new Set;for(let r of i){if(!r.path.startsWith(o+"/"))continue;let l=this.parseAuthorFilePath(r.path)?.id;l&&a.add(l)}for(let r of t){if(a.has(r.id))continue;let l=this.authorNameToSafe(r.name),c=`${o}/${l}-${r.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(c))continue;await this.app.vault.create(c,this.buildAuthorStub(r,r.firstSeen??new Date().toISOString())),s++}catch(g){console.warn("[Stashpad] restore author stub failed",c,g)}}}return{created:s,folders:e.length}}async convertAttachmentsToLinks(){let t=0,e=i=>/^\[\[.*\]\]$/.test(i.trim());for(let i of this.discoverStashpadFolders()){let s=i.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==s&&!o.startsWith(s+"/")||be(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let r=a.attachments,l=Array.isArray(r),c=typeof r=="string"&&r.trim().length>0;if(!(!l&&!c||!(c?!e(r):r.some(p=>typeof p=="string"&&p.trim()&&!e(p)))))try{await this.app.fileManager.processFrontMatter(n,p=>{Array.isArray(p.attachments)?p.attachments=p.attachments.map(d=>typeof d=="string"&&d.trim()?Ot(d):d):typeof p.attachments=="string"&&p.attachments.trim()&&(p.attachments=[Ot(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 $.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 Sn(this.app,e,t,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(l){this.notifications.show({message:`Stashpad: import failed in \`${e}\` +`)}`,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 ${Jt}/.`,kind:"success",category:"system",folder:""}),!0):(new $.Notice(`Obsidian's vault trash (${Jt}/) 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 $.Notice(`Couldn't encrypt the existing trash: ${e.message}`,0),!1}}openEncryptedTrash(t){if(!this.encryption.isConfigured()){new $.Notice("Set up encryption first (Settings \u2192 Encryption).");return}Wo(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new $.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=await this.listDeletedTrash();if(t.length===0){new $.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 ms(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)}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 $.Notice(`"${o.split("/").pop()}" auto-encrypts notes moved in, so cross-folder paste is disabled there. Use the "Move to archive" command \u2014 it checks the encryption key first.`),null;let a=[],r=[],l=[],c=[];for(let M of e){let F=await Se(this.app,t,M);if(F){l.push(F.rootNote.id),a.push({id:F.rootNote.id,file:F.rootNote.file}),c.push(F.rootNote.file);for(let N of F.descendants)r.push({id:N.id,file:N.file}),c.push(N.file)}}if(!a.length)return null;let g=a.length+r.length,p=[],d=[];n==="cut"&&(p=await this.exclusiveAttachmentsOf(c),d=await this.snapshotPaths([...c.map(M=>M.path),...p.map(M=>M.path)]));let I=await ke(this.app,{rootNotes:a,allDescendants:r,sourceFolder:t}),u=await this.idsInFolder(o),f=new Set(this.filesUnder(o)),C=await zt(this.app,I,o,u,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),m=this.filesUnder(o).filter(M=>!f.has(M)),E=await this.snapshotPaths(m),w=l.map(M=>C.idRemap[M]).filter(M=>!!M);if(n==="cut"){for(let M of c)try{await this.app.fileManager.trashFile(M)}catch(F){console.warn("[Stashpad] cross-folder move: couldn't trash source note",M.path,F)}for(let M of p)try{await this.app.fileManager.trashFile(M)}catch(F){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",M.path,F)}}let y=async()=>{for(let M of[...m].reverse()){let F=this.app.vault.getAbstractFileByPath(M);if(F)try{await this.app.fileManager.trashFile(F)}catch{}}};return{rootIds:w,noteCount:g,undo:n==="cut"?async()=>{await y(),await this.restoreSnapshot(d)}:async()=>{await y()},redo:n==="cut"?async()=>{await this.restoreSnapshot(E);for(let M of d){let F=this.app.vault.getAbstractFileByPath(M.path);if(F)try{await this.app.fileManager.trashFile(F)}catch{}}}:async()=>{await this.restoreSnapshot(E)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let a=await Se(this.app,t,o);a&&i.push(a.rootNote.file,...a.descendants.map(r=>r.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i),n=[];for(let o of[...i,...s])try{await this.app.fileManager.trashFile(o),n.push(o)}catch(a){console.warn("[Stashpad] trashSubtrees: couldn't trash",o.path,a)}return n}async exclusiveAttachmentsOf(t){let e=new Set(t.map(n=>n.path)),i=new Map;for(let n of t)for(let o of await Xi(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 Se(this.app,t,n);o&&i.push(o.rootNote.file,...o.descendants.map(a=>a.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i);return[...i.map(n=>n.path),...s.map(n=>n.path)]}async orderedSubtreeNodes(t,e){let i=[],s=new Set,n=o=>{let a=this.app.metadataCache.getFileCache(o)?.frontmatter?.position;return typeof a=="number"?a:Number.MAX_SAFE_INTEGER};for(let o of e){let a=await Se(this.app,t,o);if(!a)continue;let r=new Map;for(let c of a.descendants){if(!c.parent)continue;let g=r.get(c.parent)??[];g.push({id:c.id,file:c.file,created:c.created}),r.set(c.parent,g)}for(let c of r.values())c.sort((g,p)=>n(g.file)-n(p.file)||g.created.localeCompare(p.created));let l=(c,g)=>{if(!s.has(c.id)){s.add(c.id),i.push({file:c.file,created:c.created,depth:g});for(let p of r.get(c.id)??[])l(p,g+1)}};l({id:a.rootNote.id,file:a.rootNote.file,created:a.rootNote.created},0)}return i}filesUnder(t){let e=t.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(i=>i.path.startsWith(e)).map(i=>i.path)}async snapshotPaths(t){let e=[];for(let i of t){let s=this.app.vault.getAbstractFileByPath(i);if(!s)continue;let n=!i.toLowerCase().endsWith(".md");try{n?e.push({path:i,binary:n,data:await this.app.vault.readBinary(s)}):e.push({path:i,binary:n,text:await this.app.vault.read(s)})}catch(o){console.warn("[Stashpad] snapshotPaths: couldn't read",i,o)}}return e}async restoreSnapshot(t){for(let e of t){let i=e.path.split("/").slice(0,-1).join("/");await this.ensureVaultFolder(i);let s=this.app.vault.getAbstractFileByPath(e.path);try{e.binary?s?await this.app.vault.adapter.writeBinary(e.path,e.data):await this.app.vault.createBinary(e.path,e.data):s?await this.app.vault.modify(s,e.text??""):await this.app.vault.create(e.path,e.text??"")}catch(n){console.warn("[Stashpad] restoreSnapshot: couldn't write",e.path,n)}}}async ensureVaultFolder(t){if(!t)return;let e="";for(let i of t.split("/"))if(e=e?`${e}/${i}`:i,!await this.app.vault.adapter.exists(e))try{await this.app.vault.createFolder(e)}catch{}}refreshOpenViewsForFolder(t){let e=t.replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(ct)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,""),s=[];for(let l of e){let c=this.app.vault.getAbstractFileByPath(l);if(!(c instanceof $.TFile)||(c.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let g;try{g=Dt(await this.app.vault.read(c)).fm}catch{continue}let p=typeof g.id=="string"?g.id:null;!p||p===T||s.push({id:p,parent:typeof g.parent=="string"?g.parent:null})}if(s.length===0)return;let n=new Set(s.map(l=>l.id)),o=new Set((this.settings.lockedSubtrees??[]).map(l=>l.rootId).filter(l=>!!l)),a=s.filter(l=>!o.has(l.id)&&!(l.parent&&n.has(l.parent)));if(a.length===0)return;if(!await this.ensureEncryptionUnlocked()){new $.Notice(`\u26A0\uFE0F Archive folder "${i.split("/").pop()}": ${a.length} arriving note${a.length===1?"":"s"} NOT encrypted (vault is locked). Unlock encryption and lock them manually.`,0);return}let r=0;for(let l of a)await this.lockNoteSubtree(i,l.id,null,{silent:!0})&&r++;r>0&&this.notifications.show({message:`Archived (encrypted) ${r} note${r===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:ct,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(ct),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 $.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(ct),e=this.app.workspace.activeLeaf;for(let I of t)try{await I.loadIfDeferred?.()}catch{}let i=I=>I.getViewState()?.state??{},s=I=>{let u=i(I);return(I.isDeferred?u.folderOverride??"":I.view?.noteFolder??u.folderOverride??"").replace(/\/+$/,"")},n=I=>{let u=i(I);return(I.isDeferred?u.focusId:I.view?.focusId??u.focusId)||T},o=I=>{let u=I.view;return!!u&&u.getViewType?.()===ct&&typeof u.navigateTo=="function"&&typeof u.noteFolder=="string"},a=new Map;for(let I of this.app.vault.getMarkdownFiles()){let u=(I.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(I)?.frontmatter?.id;typeof f=="string"&&f&&(a.get(u)??a.set(u,new Set).get(u)).add(f)}let r=0,l=[];for(let I of t){let u=s(I),f=n(I);if(u&&f&&f!==T){let C=!I.isDeferred&&!!I.view?.tree?.get?.(f),m=a.get(u)?.has(f)??!1;if(!C&&!m){I.detach(),r++;continue}}l.push(I)}let c=new Map;for(let I of l){let u=s(I);if(!u)continue;let f=u+" "+n(I);(c.get(f)??c.set(f,[]).get(f)).push(I)}let g=0;for(let I of c.values()){if(I.length<=1)continue;I.sort((f,C)=>{let m=E=>E===e?2:E.isDeferred?0:1;return m(C)-m(f)});let u=null;for(let f of I){try{await f.loadIfDeferred?.()}catch{}if(o(f)){u=f;break}}u||(u=I[0]);for(let f of I)f!==u&&(f.detach(),g++)}let p=this.app.workspace.getLeavesOfType(ct).length,d=document.createDocumentFragment();return d.createEl("div",{text:g+r>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),d.createEl("div",{text:`\u2022 ${g} duplicate tab${g===1?"":"s"} closed`}),d.createEl("div",{text:`\u2022 ${r} orphaned tab${r===1?"":"s"} pruned (note no longer exists)`}),d.createEl("div",{text:`\u2022 ${p} Stashpad tab${p===1?"":"s"} remaining`}),new $.Notice(d,7e3),g+r}navigateWhenReady(t,e,i=15){let s=t.replace(/\/+$/,""),n=this.app.workspace.getLeavesOfType(ct).find(o=>(o.view?.noteFolder??"").replace(/\/+$/,"")===s)?.view??this.lastActiveStashpadLeaf?.view;if(n&&typeof n.navigateTo=="function"&&(!n.tree||typeof n.tree.get!="function"||!!n.tree.get(e))){n.navigateTo(e);return}i>0?window.setTimeout(()=>this.navigateWhenReady(t,e,i-1),90):n&&typeof n.navigateTo=="function"&&n.navigateTo(e)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,i=this.discoverStashpadFolders(),s=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(I=>typeof I=="string"):[],l=a.includes(e),c=r.some(I=>I.includes(e));if(!l&&!c)continue;let g=n.parent?.path??"",p=i.find(I=>g===I||g.startsWith(I+"/"));if(!p)continue;s.has(p)||s.set(p,{authored:0,contributed:0});let d=s.get(p);l&&d.authored++,c&&d.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return ne(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(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return!1;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),r=`${s}/${a}-${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:o?.role,department:o?.department},new Date().toISOString())),!0)}catch(l){return console.warn("[Stashpad] ensureAuthorStubFor failed",r,l),!1}}async seedKnownAuthorsInFolder(t){let e=0;for(let i of this.collectKnownAuthors())await this.ensureAuthorStubFor(t,i.id,i.name)&&e++;return e}async checkDueReminders(){let t=Date.now(),e=new Set(this.settings.notifiedDueKeys??[]),i=(this.settings.authorId??"").trim(),s=[];for(let o of this.app.vault.getMarkdownFiles()){if(o.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!a||a.due==null)continue;let r=typeof a.id=="string"?a.id:"";if(!r)continue;let l=String(a.due),c=typeof a.due=="number"?a.due:Date.parse(l);if(!Number.isFinite(c)||c>t)continue;let g=me(a);if(g.length>0&&!(i&&g.some(d=>d.id===i)))continue;let p=`${r}@${l}`;e.has(p)||s.push({id:r,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:c,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 r=Dt(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(l=>l.trim()).find(l=>l.length>0);if(r)return r.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(s.length<=3)for(let o of s){let a=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${a}\u201D (${$t(o.dueMs,this.settings)})`,kind:"warning",category:"reminder",duration:0,folder:o.folder,affectedIds:[o.id],actions:[{label:"Open",onClick:()=>void this.revealNoteByRef(o.folder,o.id)}]})}else this.notifications.show({message:`\u23F0 ${s.length} tasks are due \u2014 open the Tasks panel to review.`,kind:"warning",category:"reminder",duration:0,folder:""})}async syncAuthorsAcrossFolders(){await this.rebuildAuthorRegistry();let t=this.collectKnownAuthors(),e=this.discoverStashpadFolders();if(!t.length||!e.length){new $.Notice("No authors or Stashpad folders to sync.");return}let i=e.length*t.length>8?new $.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,r=((Array.isArray(o?.aliases)?o.aliases.find(l=>typeof l=="string")??"":typeof o?.aliases=="string"?o.aliases:"")||(typeof o?.name=="string"?o.name:"")||n.name).trim();t.has(n.id)||t.set(n.id,r),this.authorRegistry.record({id:n.id,name:r})}return[...t.entries()].map(([s,n])=>({id:s,name:n}))}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,i=0;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=[];if(typeof o.author=="string"&&a.push(o.author),Array.isArray(o.contributors))for(let r of o.contributors)typeof r=="string"&&a.push(r);for(let r of a){let l=this.parseAuthorRef(r);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),i++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter,g=((Array.isArray(l?.aliases)?l.aliases.find(u=>typeof u=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||r.name).trim(),p=typeof l?.role=="string"?l.role:void 0,d=typeof l?.department=="string"?l.department:void 0,I=e.get(r.id);I||s++,e.set(r.id,{id:r.id,name:g||I?.name,role:p??I?.role,department:d??I?.department,fromStub:!0})}}return await this.authorRegistry.load(),this.authorRegistry.replaceAll([...e.values()]),await this.authorRegistry.save(),{total:e.size,fromStubs:s,fromNotes:i}}buildAuthorStub(t,e){let i=a=>a.replace(/[\r\n]+/g," ").trim(),s=a=>i(a).replace(/\\/g,"\\\\").replace(/"/g,'\\"'),n=i(t.name),o=["---",`authorId: ${t.id}`,"aliases:",` - "${s(t.name)}"`];return t.role&&o.push(`role: "${s(t.role)}"`),t.department&&o.push(`department: "${s(t.department)}"`),o.push(`created: ${e}`,"---",`# ${n}`),o.join(` +`)}async restoreMissingAuthorStubs(){await this.authorRegistry.load();let t=this.authorRegistry.all().filter(n=>n.id&&n.name),e=this.discoverStashpadFolders(),i=this.app.vault.getMarkdownFiles(),s=0;for(let n of e){let o=`${n}/_authors`,a=new Set;for(let r of i){if(!r.path.startsWith(o+"/"))continue;let l=this.parseAuthorFilePath(r.path)?.id;l&&a.add(l)}for(let r of t){if(a.has(r.id))continue;let l=this.authorNameToSafe(r.name),c=`${o}/${l}-${r.id}.md`;try{if(await this.ensureFolderPath(o),await this.app.vault.adapter.exists(c))continue;await this.app.vault.create(c,this.buildAuthorStub(r,r.firstSeen??new Date().toISOString())),s++}catch(g){console.warn("[Stashpad] restore author stub failed",c,g)}}}return{created:s,folders:e.length}}async convertAttachmentsToLinks(){let t=0,e=i=>/^\[\[.*\]\]$/.test(i.trim());for(let i of this.discoverStashpadFolders()){let s=i.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==s&&!o.startsWith(s+"/")||xe(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let r=a.attachments,l=Array.isArray(r),c=typeof r=="string"&&r.trim().length>0;if(!(!l&&!c||!(c?!e(r):r.some(p=>typeof p=="string"&&p.trim()&&!e(p)))))try{await this.app.fileManager.processFrontMatter(n,p=>{Array.isArray(p.attachments)?p.attachments=p.attachments.map(d=>typeof d=="string"&&d.trim()?Ot(d):d):typeof p.attachments=="string"&&p.attachments.trim()&&(p.attachments=[Ot(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 $.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 bn(this.app,e,t,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(l){this.notifications.show({message:`Stashpad: import failed in \`${e}\` Error: ${l.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,l);return}let o=i+s+n,a=this.lastActiveStashpadLeaf?.view;o>0&&a?.noteFolder===t&&a?.tree&&(a.tree.rebuild(t),a.render?.());let r;if(o===0)r=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let l=[];i&&l.push(`${i} loose file${i===1?"":"s"}`),s&&l.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&l.push(`${n} .stash bundle${n===1?"":"s"}`),r=`Imported ${l.join(" + ")} in \`${e}\`.`}this.notifications.show({message:r,kind:o>0?"success":"info",category:"import",folder:t})}refreshViewIfShowing(t){let e=this.lastActiveStashpadLeaf?.view;e?.noteFolder===t&&e?.tree&&(e.tree.rebuild(t),e.render?.())}async runFolderSlugPass(t){let e=t.split("/").pop()||t,i=0;try{i=await this.rebootstrapFolderSlugs(t)}catch(s){this.notifications.show({message:`Stashpad: slug pass failed in \`${e}\` -${s.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderSlugPass failed",t,s);return}this.refreshViewIfShowing(t),this.notifications.show({message:i>0?`Renamed ${i} stale filename${i===1?"":"s"} in \`${e}\`.`:`No stale filenames in \`${e}\` \u2014 all slugs match their notes.`,kind:i>0?"success":"info",category:"system",folder:t})}async runFolderFrontmatterBackfill(t){let e=t.split("/").pop()||t,i=0,s=0;try{let n=await Ke(this.app,t);i=n.written,s=n.checked}catch(n){this.notifications.show({message:`Stashpad: frontmatter backfill failed in \`${e}\` -${n.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderFrontmatterBackfill failed",t,n);return}this.notifications.show({message:i>0?`Backfilled recovery links on ${i} note${i===1?"":"s"} in \`${e}\` (${s} checked).`:`Recovery links already up to date in \`${e}\` (${s} checked).`,kind:i>0?"success":"info",category:"system",folder:t})}async runAutoImportSweep(){if(!this.settings.autoImport||!this.importService.isArmed()||this.autoSweepInProgress)return;this.autoSweepInProgress=!0;let t=0,e=0,i=0;try{for(let n of this.discoverStashpadFolders())try{let o=await this.importService.importLooseInto(n,{auto:!0});t+=o.files,e+=o.folders,i+=o.stashes}catch(o){console.warn("[Stashpad] auto-import sweep failed",n,o)}}finally{this.autoSweepInProgress=!1}if(t+e+i>0){let n=this.lastActiveStashpadLeaf?.view;n?.tree&&n?.noteFolder&&(n.tree.rebuild(n.noteFolder),n.render?.());let o=[];t&&o.push(`${t} file${t===1?"":"s"}`),e&&o.push(`${e} folder${e===1?"":"s"}`),i&&o.push(`${i} .stash bundle${i===1?"":"s"}`),this.notifications.show({message:`Auto-imported ${o.join(" + ")} (background sweep).`,kind:"success",category:"import"})}this.notifyPendingEncrypted()}notifyPendingEncrypted(){let t=this.importService.pendingEncryptedPaths();if(t.length===0||!this.importService.shouldNotifyEncrypted())return;this.importService.snoozeEncryptedNotify(60*60*1e3);let e=t.length;this.notifications.show({message:`${e} encrypted .stash bundle${e===1?"":"s"} waiting to import. Import ${e===1?"it":"them"} with the password?`,kind:"info",category:"import",duration:0,actions:[{label:"Import now",onClick:()=>void this.importPendingEncryptedNow()},{label:"Remind me later",onClick:()=>this.importService.snoozeEncryptedNotify(60*60*1e3)},{label:"Not now (until next launch)",onClick:()=>this.importService.snoozeEncryptedNotify(1/0)}]})}async importPendingEncryptedNow(){let{imported:t,rescheduled:e}=await this.importService.importPendingEncrypted();if(t>0){let i=this.lastActiveStashpadLeaf?.view;i?.tree&&i?.noteFolder&&(i.tree.rebuild(i.noteFolder),i.render?.()),this.notifications.show({message:`Imported ${t} encrypted .stash bundle${t===1?"":"s"}.`,kind:"success",category:"import"})}}async seedLocalAuthorStub(t){let e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();if(!e||!i)return!1;let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(r=>r.path.startsWith(s+"/")&&this.parseAuthorFilePath(r.path)?.id===e))return!1;let o=this.authorNameToSafe(i),a=`${s}/${o}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(a)?!1:(await this.app.vault.create(a,this.buildAuthorStub({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment},new Date().toISOString())),this.authorRegistry.record({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment}),!0)}catch(r){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,r),!1}}async seedLocalAuthorStubsEverywhere(){if(!(this.settings.authorName??"").trim())return 0;let e=0;for(let i of this.discoverStashpadFolders())await this.seedLocalAuthorStub(i)&&e++;return e}async ensureFolderPath(t){let e=this.app.vault.adapter,i=t.split("/").filter(Boolean),s="";for(let n of i){s=s?`${s}/${n}`:n;try{await e.exists(s)||await e.mkdir(s)}catch(o){if(!/already exists/i.test(o.message))throw o}}}async loadSettings(){let t=await this.loadData()??{};typeof t?.confirmMultiDelete=="boolean"&&(typeof t.confirmBulkDelete!="boolean"&&(t.confirmBulkDelete=t.confirmMultiDelete),typeof t.confirmAttachmentDelete!="boolean"&&(t.confirmAttachmentDelete=t.confirmMultiDelete),delete t.confirmMultiDelete),typeof t?.jdIndexDestFolder=="string"&&typeof t?.jdIndexStashpadFolder!="string"&&(t.jdIndexStashpadFolder=t.jdIndexDestFolder),this.settings={...ce,...t,shortcuts:{...ce.shortcuts,...t?.shortcuts??{}},mod:{...ce.mod,...t?.mod??{}},bindings:mr(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:Br(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Yt]},un(this.settings),this.notifications.loadMutedFromList(this.settings.mutedNotificationCategories),this.notifications.setHistoryLimit(this.settings.notificationHistoryLimit),this.notifications.setDefaultAuthorId(this.settings.authorId),this.attachNotificationPersistence()}notificationsPath(){return this.pluginPrivatePath("notifications.json")}async attachNotificationPersistence(){if(this.notifPersistenceWired)return;this.notifPersistenceWired=!0;let t=this.app.vault.adapter,e=this.notificationsPath();try{if(await t.exists(e)){let i=await t.read(e),s=JSON.parse(i);Array.isArray(s)&&this.notifications.loadHistory(s)}}catch(i){console.warn("[Stashpad] failed to load notification history",i)}this.notifications.onChange(()=>{this.notifSaveTimer!=null&&window.clearTimeout(this.notifSaveTimer),this.notifSaveTimer=window.setTimeout(()=>{this.notifSaveTimer=null,this.persistNotificationHistory()},1e3)})}async persistNotificationHistory(){try{let t=this.notifications.recent().slice().reverse(),e=this.notificationsPath(),i=e.replace(/\/[^/]+$/,""),s=this.app.vault.adapter;i&&!await s.exists(i)&&await s.mkdir(i),await s.write(e,JSON.stringify(t))}catch(t){console.warn("[Stashpad] failed to save notification history",t)}}readLastCursorFile(){try{let t=window.localStorage.getItem(this.LAST_CURSOR_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastCursor(t){let i=this.readLastCursorFile()[t]??{};return new Map(Object.entries(i))}saveLastCursor(t,e,i){try{let s=this.readLastCursorFile();s[t]||(s[t]={}),s[t][e]=i,window.localStorage.setItem(this.LAST_CURSOR_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-cursor",s)}}readLastSelectionFile(){try{let t=window.localStorage.getItem(this.LAST_SELECTION_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastSelection(t){let i=this.readLastSelectionFile()[t]??{},s=new Map;for(let[n,o]of Object.entries(i))Array.isArray(o)&&s.set(n,o.filter(a=>typeof a=="string"));return s}saveLastSelection(t,e,i){try{let s=this.readLastSelectionFile();s[t]||(s[t]={}),i.length?s[t][e]=i:delete s[t][e],window.localStorage.setItem(this.LAST_SELECTION_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-selection",s)}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),un(this.settings),bt.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 $.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let g of i){let p=this.app.metadataCache.getFileCache(g)?.frontmatter,d=typeof p?.id=="string"?p.id.trim():"";d&&e.add(d)}let{newId:s}=await Promise.resolve().then(()=>(Kt(),Mi)),n=()=>{for(let g=0;g<100;g++){let p=s();if(!e.has(p))return e.add(p),p}for(let g=8;g<=16;g+=2){let p=s(g);if(!e.has(p))return e.add(p),p}throw new Error("Could not generate a unique id")},o=[];for(let g of i){let p=g.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(p))continue;let d=this.app.metadataCache.getFileCache(g)?.frontmatter,I=typeof d?.id=="string"?d.id.trim():"",u=d?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof d?.created=="string"&&d.created.trim()!=="",m=!I,E=!f,w=!C;!m&&!E&&!w||o.push({file:g,addId:m,addParent:E,addCreated:w})}if(o.length===0){new $.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,r=0,l=this.newLog();for(let g of o)try{let p;await this.app.fileManager.processFrontMatter(g.file,u=>{if(g.addId&&(typeof u.id=="string"&&u.id.trim()||(p=n(),u.id=p)),g.addParent){let f=u.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(u.parent=M)}g.addCreated&&(typeof u.created=="string"&&u.created.trim()||(u.created=new Date(g.file.stat.ctime).toISOString()))});let d=this.app.metadataCache.getFileCache(g.file)?.frontmatter,I=p??d?.id??"";I&&await l.append({type:"parent_change",id:I,payload:{from:null,to:M,reason:"orphan_fix",path:g.file.path,addedId:g.addId,addedParent:g.addParent,addedCreated:g.addCreated}}),a++}catch(p){console.warn("Stashpad: orphan fix failed for",g.file.path,p),r++}let c=r?` (${r} failed \u2014 see console)`:"";new $.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Kt(),Mi)),i=new Set;for(let l of this.app.vault.getMarkdownFiles()){if(l.path===t.path)continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id.trim():"";g&&i.add(g)}let s=()=>{for(let l=0;l<50;l++){let c=e();if(!i.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!i.has(c))return c}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||i.has(c)?(l.id=s(),n.push("id")):o.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?o.push("parent"):(l.parent=M,n.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?o.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(l){new $.Notice(`Adopt failed: ${l.message}`);return}let a=!1;try{let l=this.app.metadataCache.getFileCache(t)?.frontmatter,c=typeof l?.id=="string"?l.id.trim():"";if(c&&t.basename&&!t.basename.endsWith(`-${c}`)){let g=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(g)||(await this.app.fileManager.renameFile(t,g),a=!0)}}catch(l){console.warn("Stashpad: adopt rename failed",l)}if(n.length===0&&!a){new $.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let r=[];n.length&&r.push(`added: ${n.join(", ")}`),a&&r.push("renamed with id"),new $.Notice(`Adopted into Stashpad \u2014 ${r.join("; ")}.`);try{let l=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,g=c?.id??"";g&&await l.append({type:"create",id:g,payload:{path:t.path,parent:c?.parent??M,source:"adopt",added:n}})}catch{}}};function mr(h,A,t){let e=In();for(let i of Le){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(h&&typeof h=="object")for(let i of Le){let s=h[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of Le){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 Br(h){let A={};if(!h||typeof h!="object")return A;for(let[t,e]of Object.entries(h))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var Sn=class extends $.SuggestModal{constructor(t,e,i,s){super(t);this.def=e;this.folders=i;this.onPick=s;this.setPlaceholder("Choose a Stashpad folder to import into\u2026")}getSuggestions(t){let e=t.toLowerCase();return[this.def,...this.folders.filter(s=>s!==this.def)].filter(s=>s.toLowerCase().includes(e)).map(s=>({label:s,folder:s,current:s===this.def}))}renderSuggestion(t,e){e.createDiv({text:t.label}),t.current&&(e.createDiv({cls:"stashpad-suggest-note",text:"current"}),e.addClass("is-pinned-import-target"))}onChooseSuggestion(t){this.onPick(t.folder)}}; +${s.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderSlugPass failed",t,s);return}this.refreshViewIfShowing(t),this.notifications.show({message:i>0?`Renamed ${i} stale filename${i===1?"":"s"} in \`${e}\`.`:`No stale filenames in \`${e}\` \u2014 all slugs match their notes.`,kind:i>0?"success":"info",category:"system",folder:t})}async runFolderFrontmatterBackfill(t){let e=t.split("/").pop()||t,i=0,s=0;try{let n=await ze(this.app,t);i=n.written,s=n.checked}catch(n){this.notifications.show({message:`Stashpad: frontmatter backfill failed in \`${e}\` +${n.message}`,kind:"error",category:"system",folder:t}),console.error("[Stashpad] runFolderFrontmatterBackfill failed",t,n);return}this.notifications.show({message:i>0?`Backfilled recovery links on ${i} note${i===1?"":"s"} in \`${e}\` (${s} checked).`:`Recovery links already up to date in \`${e}\` (${s} checked).`,kind:i>0?"success":"info",category:"system",folder:t})}async runAutoImportSweep(){if(!this.settings.autoImport||!this.importService.isArmed()||this.autoSweepInProgress)return;this.autoSweepInProgress=!0;let t=0,e=0,i=0;try{for(let n of this.discoverStashpadFolders())try{let o=await this.importService.importLooseInto(n,{auto:!0});t+=o.files,e+=o.folders,i+=o.stashes}catch(o){console.warn("[Stashpad] auto-import sweep failed",n,o)}}finally{this.autoSweepInProgress=!1}if(t+e+i>0){let n=this.lastActiveStashpadLeaf?.view;n?.tree&&n?.noteFolder&&(n.tree.rebuild(n.noteFolder),n.render?.());let o=[];t&&o.push(`${t} file${t===1?"":"s"}`),e&&o.push(`${e} folder${e===1?"":"s"}`),i&&o.push(`${i} .stash bundle${i===1?"":"s"}`),this.notifications.show({message:`Auto-imported ${o.join(" + ")} (background sweep).`,kind:"success",category:"import"})}this.notifyPendingEncrypted()}notifyPendingEncrypted(){let t=this.importService.pendingEncryptedPaths();if(t.length===0||!this.importService.shouldNotifyEncrypted())return;this.importService.snoozeEncryptedNotify(60*60*1e3);let e=t.length;this.notifications.show({message:`${e} encrypted .stash bundle${e===1?"":"s"} waiting to import. Import ${e===1?"it":"them"} with the password?`,kind:"info",category:"import",duration:0,actions:[{label:"Import now",onClick:()=>void this.importPendingEncryptedNow()},{label:"Remind me later",onClick:()=>this.importService.snoozeEncryptedNotify(60*60*1e3)},{label:"Not now (until next launch)",onClick:()=>this.importService.snoozeEncryptedNotify(1/0)}]})}async importPendingEncryptedNow(){let{imported:t,rescheduled:e}=await this.importService.importPendingEncrypted();if(t>0){let i=this.lastActiveStashpadLeaf?.view;i?.tree&&i?.noteFolder&&(i.tree.rebuild(i.noteFolder),i.render?.()),this.notifications.show({message:`Imported ${t} encrypted .stash bundle${t===1?"":"s"}.`,kind:"success",category:"import"})}}async seedLocalAuthorStub(t){let e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();if(!e||!i)return!1;let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(r=>r.path.startsWith(s+"/")&&this.parseAuthorFilePath(r.path)?.id===e))return!1;let o=this.authorNameToSafe(i),a=`${s}/${o}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(a)?!1:(await this.app.vault.create(a,this.buildAuthorStub({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment},new Date().toISOString())),this.authorRegistry.record({id:e,name:i,role:this.settings.authorRole,department:this.settings.authorDepartment}),!0)}catch(r){return console.warn("[Stashpad] seedLocalAuthorStub failed",a,r),!1}}async seedLocalAuthorStubsEverywhere(){if(!(this.settings.authorName??"").trim())return 0;let e=0;for(let i of this.discoverStashpadFolders())await this.seedLocalAuthorStub(i)&&e++;return e}async ensureFolderPath(t){let e=this.app.vault.adapter,i=t.split("/").filter(Boolean),s="";for(let n of i){s=s?`${s}/${n}`:n;try{await e.exists(s)||await e.mkdir(s)}catch(o){if(!/already exists/i.test(o.message))throw o}}}async loadSettings(){let t=await this.loadData()??{};typeof t?.confirmMultiDelete=="boolean"&&(typeof t.confirmBulkDelete!="boolean"&&(t.confirmBulkDelete=t.confirmMultiDelete),typeof t.confirmAttachmentDelete!="boolean"&&(t.confirmAttachmentDelete=t.confirmMultiDelete),delete t.confirmMultiDelete),typeof t?.jdIndexDestFolder=="string"&&typeof t?.jdIndexStashpadFolder!="string"&&(t.jdIndexStashpadFolder=t.jdIndexDestFolder),this.settings={...ce,...t,shortcuts:{...ce.shortcuts,...t?.shortcuts??{}},mod:{...ce.mod,...t?.mod??{}},bindings:mr(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:Br(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Yt]},Cn(this.settings),this.notifications.loadMutedFromList(this.settings.mutedNotificationCategories),this.notifications.setHistoryLimit(this.settings.notificationHistoryLimit),this.notifications.setDefaultAuthorId(this.settings.authorId),this.attachNotificationPersistence()}notificationsPath(){return this.pluginPrivatePath("notifications.json")}async attachNotificationPersistence(){if(this.notifPersistenceWired)return;this.notifPersistenceWired=!0;let t=this.app.vault.adapter,e=this.notificationsPath();try{if(await t.exists(e)){let i=await t.read(e),s=JSON.parse(i);Array.isArray(s)&&this.notifications.loadHistory(s)}}catch(i){console.warn("[Stashpad] failed to load notification history",i)}this.notifications.onChange(()=>{this.notifSaveTimer!=null&&window.clearTimeout(this.notifSaveTimer),this.notifSaveTimer=window.setTimeout(()=>{this.notifSaveTimer=null,this.persistNotificationHistory()},1e3)})}async persistNotificationHistory(){try{let t=this.notifications.recent().slice().reverse(),e=this.notificationsPath(),i=e.replace(/\/[^/]+$/,""),s=this.app.vault.adapter;i&&!await s.exists(i)&&await s.mkdir(i),await s.write(e,JSON.stringify(t))}catch(t){console.warn("[Stashpad] failed to save notification history",t)}}readLastCursorFile(){try{let t=window.localStorage.getItem(this.LAST_CURSOR_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastCursor(t){let i=this.readLastCursorFile()[t]??{};return new Map(Object.entries(i))}saveLastCursor(t,e,i){try{let s=this.readLastCursorFile();s[t]||(s[t]={}),s[t][e]=i,window.localStorage.setItem(this.LAST_CURSOR_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-cursor",s)}}readLastSelectionFile(){try{let t=window.localStorage.getItem(this.LAST_SELECTION_LS_KEY);if(!t)return{};let e=JSON.parse(t);return e&&typeof e=="object"?e:{}}catch{return{}}}loadLastSelection(t){let i=this.readLastSelectionFile()[t]??{},s=new Map;for(let[n,o]of Object.entries(i))Array.isArray(o)&&s.set(n,o.filter(a=>typeof a=="string"));return s}saveLastSelection(t,e,i){try{let s=this.readLastSelectionFile();s[t]||(s[t]={}),i.length?s[t][e]=i:delete s[t][e],window.localStorage.setItem(this.LAST_SELECTION_LS_KEY,JSON.stringify(s))}catch(s){console.warn("[Stashpad] failed to save last-selection",s)}}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),Cn(this.settings),Nt.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 $.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let g of i){let p=this.app.metadataCache.getFileCache(g)?.frontmatter,d=typeof p?.id=="string"?p.id.trim():"";d&&e.add(d)}let{newId:s}=await Promise.resolve().then(()=>(Kt(),Ti)),n=()=>{for(let g=0;g<100;g++){let p=s();if(!e.has(p))return e.add(p),p}for(let g=8;g<=16;g+=2){let p=s(g);if(!e.has(p))return e.add(p),p}throw new Error("Could not generate a unique id")},o=[];for(let g of i){let p=g.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(p))continue;let d=this.app.metadataCache.getFileCache(g)?.frontmatter,I=typeof d?.id=="string"?d.id.trim():"",u=d?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof d?.created=="string"&&d.created.trim()!=="",m=!I,E=!f,w=!C;!m&&!E&&!w||o.push({file:g,addId:m,addParent:E,addCreated:w})}if(o.length===0){new $.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,r=0,l=this.newLog();for(let g of o)try{let p;await this.app.fileManager.processFrontMatter(g.file,u=>{if(g.addId&&(typeof u.id=="string"&&u.id.trim()||(p=n(),u.id=p)),g.addParent){let f=u.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(u.parent=T)}g.addCreated&&(typeof u.created=="string"&&u.created.trim()||(u.created=new Date(g.file.stat.ctime).toISOString()))});let d=this.app.metadataCache.getFileCache(g.file)?.frontmatter,I=p??d?.id??"";I&&await l.append({type:"parent_change",id:I,payload:{from:null,to:T,reason:"orphan_fix",path:g.file.path,addedId:g.addId,addedParent:g.addParent,addedCreated:g.addCreated}}),a++}catch(p){console.warn("Stashpad: orphan fix failed for",g.file.path,p),r++}let c=r?` (${r} failed \u2014 see console)`:"";new $.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Kt(),Ti)),i=new Set;for(let l of this.app.vault.getMarkdownFiles()){if(l.path===t.path)continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter,g=typeof c?.id=="string"?c.id.trim():"";g&&i.add(g)}let s=()=>{for(let l=0;l<50;l++){let c=e();if(!i.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!i.has(c))return c}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||i.has(c)?(l.id=s(),n.push("id")):o.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?o.push("parent"):(l.parent=T,n.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?o.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(l){new $.Notice(`Adopt failed: ${l.message}`);return}let a=!1;try{let l=this.app.metadataCache.getFileCache(t)?.frontmatter,c=typeof l?.id=="string"?l.id.trim():"";if(c&&t.basename&&!t.basename.endsWith(`-${c}`)){let g=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(g)||(await this.app.fileManager.renameFile(t,g),a=!0)}}catch(l){console.warn("Stashpad: adopt rename failed",l)}if(n.length===0&&!a){new $.Notice(`Already a Stashpad note (${o.join(", ")} present).`);return}let r=[];n.length&&r.push(`added: ${n.join(", ")}`),a&&r.push("renamed with id"),new $.Notice(`Adopted into Stashpad \u2014 ${r.join("; ")}.`);try{let l=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,g=c?.id??"";g&&await l.append({type:"create",id:g,payload:{path:t.path,parent:c?.parent??T,source:"adopt",added:n}})}catch{}}};function mr(h,A,t){let e=fn();for(let i of qe){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(h&&typeof h=="object")for(let i of qe){let s=h[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of qe){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 Br(h){let A={};if(!h||typeof h!="object")return A;for(let[t,e]of Object.entries(h))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var bn=class extends $.SuggestModal{constructor(t,e,i,s){super(t);this.def=e;this.folders=i;this.onPick=s;this.setPlaceholder("Choose a Stashpad folder to import into\u2026")}getSuggestions(t){let e=t.toLowerCase();return[this.def,...this.folders.filter(s=>s!==this.def)].filter(s=>s.toLowerCase().includes(e)).map(s=>({label:s,folder:s,current:s===this.def}))}renderSuggestion(t,e){e.createDiv({text:t.label}),t.current&&(e.createDiv({cls:"stashpad-suggest-note",text:"current"}),e.addClass("is-pinned-import-target"))}onChooseSuggestion(t){this.onPick(t.folder)}}; /*! Bundled license information: jszip/dist/jszip.min.js: diff --git a/manifest.json b/manifest.json index e3a2b00..445aaff 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.99.20", + "version": "0.99.23", "minAppVersion": "1.7.0", "description": "Chat-style nested-notes view: rapid capture, outliner navigation, in-place editing.", "author": "Human", diff --git a/package.json b/package.json index 4448bef..57f3f0b 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.99.20", + "version": "0.99.23", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.99.23.md b/release-notes/0.99.23.md new file mode 100644 index 0000000..7073d3b --- /dev/null +++ b/release-notes/0.99.23.md @@ -0,0 +1,37 @@ +# 0.99.23 — Cross-folder note paste + +Cut or copy notes in one Stashpad folder and paste them into another. Previously +the clipboard worked only within a single folder; a different-folder paste was +refused. + +## Paste across folders + +- **Cut → move, copy → clone.** Pasting in the list of a different folder now + moves the notes there (cut) or drops a fresh duplicate (copy). The whole + subtree comes along — the note and all of its children. +- **Attachments travel with the notes.** A moved or copied subtree carries its + referenced attachments into the destination folder's `_attachments`, so the + result is self-contained — no links pointing back at the original folder. + On a move, the source's now-unused attachments are cleaned up; attachments + shared with other notes are left in place. +- **Copies get new identities; moves keep theirs.** A copy is a true duplicate + (fresh ids), so it's independent of the original. A move preserves each note's + id. Pasted roots land where your cursor is. +- **Archive folders are protected.** An auto-encrypting archive folder is + declined as a cross-folder paste target (its key might not be on this device), + with a pointer to the explicit "Move to archive" command. Archive folders also + stay out of cross-folder search, so they don't surface as targets. + +## Undo / redo + +- **Every cross-folder paste is undoable and redoable.** Undo a move and the + notes (and their attachments) return to the source folder; undo a copy and the + duplicate is removed. Redo replays it. The same applies to pasting a cut into a + note's composer. + +## Composer paste + +- Pasting a cross-folder cut into a note's **composer** drops the full subtree in + as an indented bullet outline — the note plus its children, nested by depth and + ordered to match the list — then removes the originals (undoable). +</content> diff --git a/src/encryption-ops.ts b/src/encryption-ops.ts index 39bea25..4f24702 100644 --- a/src/encryption-ops.ts +++ b/src/encryption-ops.ts @@ -37,7 +37,7 @@ interface SubtreeNode { id: StashpadId; file: TFile; parent: StashpadId | null; /** Collect a note + all its descendants within `folder` by walking frontmatter * `parent` links. Returns the root note and the rest, plus the root's parent. */ -async function collectSubtree(app: App, folder: string, rootId: StashpadId): Promise<{ +export async function collectSubtree(app: App, folder: string, rootId: StashpadId): Promise<{ rootNote: SubtreeNode; descendants: SubtreeNode[]; parentId: StashpadId | null; } | null> { const cleaned = folder.replace(/\/+$/, ""); diff --git a/src/main.ts b/src/main.ts index b51f547..b7f4798 100644 --- a/src/main.ts +++ b/src/main.ts @@ -7,7 +7,7 @@ import { STASHPAD_TRASH_VIEW_TYPE } from "./types"; import { StashpadPanelsView, openStashpadPanelsView, PANEL_REGISTRY, type PanelId } from "./panels-view"; import { StashpadFolderPanelView, openFolderPanelView } from "./folder-panel-view"; import { EncryptionService, defaultEncryptionConfig } from "./encryption-service"; -import { lockSubtree, unlockBundle, readLockedMeta, type LockResult, deleteEncryptSubtree, restoreDeleted, listDeletedBlobs, readDeletedMeta, deletedRestoreDest, backfillTrashEncrypt, restoreRawTrash, OBSIDIAN_TRASH_DIR, type DeletedMeta } from "./encryption-ops"; +import { lockSubtree, unlockBundle, readLockedMeta, type LockResult, deleteEncryptSubtree, restoreDeleted, listDeletedBlobs, readDeletedMeta, deletedRestoreDest, backfillTrashEncrypt, restoreRawTrash, OBSIDIAN_TRASH_DIR, type DeletedMeta, collectSubtree } from "./encryption-ops"; import { EncryptionPasswordModal } from "./modals"; import { DEFAULT_SETTINGS, StashpadSettings, StashpadSettingTab, setSettings, SETTINGS_TABS, @@ -15,7 +15,7 @@ import { } from "./settings"; import { DEFAULT_STOPWORDS, bodyToSlug, buildFilename, parseIdFromFilename } from "./slug-service"; import { getActiveView, onActiveViewChange } from "./active-view"; -import { importStashZip, STASH_EXT, splitFrontmatter } from "./stash-package"; +import { importStashZip, buildStashZip, resolveNoteAttachmentFiles, STASH_EXT, splitFrontmatter } from "./stash-package"; import { formatDateTime } from "./format"; import { resolveStashBytes, isEncryptedStash } from "./stash-crypto"; import { StashpadLog } from "./log"; @@ -34,6 +34,9 @@ import { RenderCacheStore } from "./render-cache-store"; * the next load knows to un-ghost the deferred Stashpad tabs. */ const UNGHOST_FLAG = "stashpad:unghost-after-reload"; +/** A captured file's content, for snapshot-backed undo/redo of file operations. */ +interface FileSnapshot { path: string; binary: boolean; text?: string; data?: ArrayBuffer; } + export default class StashpadPlugin extends Plugin { settings: StashpadSettings = { ...DEFAULT_SETTINGS }; private undoStacks = new Map<string, UndoStack>(); @@ -3290,6 +3293,252 @@ export default class StashpadPlugin extends Plugin { return (this.settings.archiveFolders ?? []).includes(cleaned); } + /** Ids of the markdown notes living directly in `folder` (read from DISK — the + * metadata cache can lag and an under-read here would miss a real id collision + * on import). */ + async idsInFolder(folder: string): Promise<Set<StashpadId>> { + const cleaned = folder.replace(/\/+$/, ""); + const out = new Set<StashpadId>(); + for (const f of this.app.vault.getMarkdownFiles()) { + if ((f.parent?.path?.replace(/\/+$/, "") ?? "") !== cleaned) continue; + try { const id = splitFrontmatter(await this.app.vault.read(f)).fm.id; if (typeof id === "string") out.add(id); } catch { /* skip unreadable */ } + } + return out; + } + + /** Cross-folder note paste engine (cut = move, copy = clone). Routes the source + * subtree(s) through the `.stash` bundle path so ATTACHMENTS travel into the + * destination's `_attachments` folder, then (for a cut) trashes the source + * notes and their EXCLUSIVE attachments. Refuses an archive / auto-encrypting + * destination — a missing on-device key could strand the move — so that path + * is left to the explicit "Move to archive" command (which checks the key + * first). Returns the destination root ids, total note count, and reversible + * `undo` / `redo` closures (file-level — the caller adds tree rebuild + render). + * Undo is snapshot-backed: we capture the created destination files and (for a + * cut) the source files BEFORE trashing them, so undo fully restores either + * direction. Null on refusal / no-op. */ + async crossFolderPaste( + srcFolder: string, rootIds: StashpadId[], destFolder: string, + destParent: StashpadId, mode: "cut" | "copy", + ): Promise<{ rootIds: StashpadId[]; noteCount: number; undo: () => Promise<void>; redo: () => Promise<void> } | null> { + const cleanDest = destFolder.replace(/\/+$/, ""); + if (this.isArchiveFolder(cleanDest)) { + new Notice(`"${cleanDest.split("/").pop()}" auto-encrypts notes moved in, so cross-folder paste is disabled there. Use the "Move to archive" command — it checks the encryption key first.`); + return null; + } + // Gather source subtree(s) from DISK (authoritative; the source folder's view + // may be closed, so we can't rely on an in-memory tree). + const rootNotes: { id: StashpadId; file: TFile }[] = []; + const allDescendants: { id: StashpadId; file: TFile }[] = []; + const srcRootOldIds: StashpadId[] = []; + const srcNoteFiles: TFile[] = []; + for (const rid of rootIds) { + const sub = await collectSubtree(this.app, srcFolder, rid); + if (!sub) continue; + srcRootOldIds.push(sub.rootNote.id); + rootNotes.push({ id: sub.rootNote.id, file: sub.rootNote.file }); + srcNoteFiles.push(sub.rootNote.file); + for (const d of sub.descendants) { allDescendants.push({ id: d.id, file: d.file }); srcNoteFiles.push(d.file); } + } + if (!rootNotes.length) return null; + const noteCount = rootNotes.length + allDescendants.length; + + // For a CUT, snapshot the source (notes + EXCLUSIVE attachments) BEFORE we + // touch anything, so undo can recreate it byte-for-byte. + let srcExclusiveAtts: TFile[] = []; + let srcSnapshot: FileSnapshot[] = []; + if (mode === "cut") { + srcExclusiveAtts = await this.exclusiveAttachmentsOf(srcNoteFiles); + srcSnapshot = await this.snapshotPaths([...srcNoteFiles.map((f) => f.path), ...srcExclusiveAtts.map((f) => f.path)]); + } + + // Bundle the subtree (collects referenced attachments) → import into dest + // (writes attachments into dest/_attachments). Copy → fresh ids; cut → keep + // ids so the moved notes retain their identity. Roots reparent to the paste + // target. dedupeExisting:false on purpose — the vault-wide reuse would route + // the pasted note's attachment link back to the SOURCE folder's copy (and for + // a cut, that copy then gets trashed → a dangling link). We want the + // attachment physically in THIS folder's _attachments so the subtree is + // self-contained. (An identical file already in dest's _attachments is still + // reused — only the cross-folder reuse is dropped.) + const zip = await buildStashZip(this.app, { rootNotes, allDescendants, sourceFolder: srcFolder }); + const destExistingIds = await this.idsInFolder(cleanDest); + const beforePaths = new Set(this.filesUnder(cleanDest)); + const summary = await importStashZip(this.app, zip, cleanDest, destExistingIds, { + dedupeExisting: false, + forceNewIds: mode === "copy", + reparentRootsTo: destParent, + }); + const createdPaths = this.filesUnder(cleanDest).filter((p) => !beforePaths.has(p)); + const destSnapshot = await this.snapshotPaths(createdPaths); + const newRootIds = srcRootOldIds.map((old) => summary.idRemap[old]).filter((x): x is StashpadId => !!x); + + // CUT: the notes + attachments now live in dest, so trash the source subtree. + if (mode === "cut") { + for (const f of srcNoteFiles) { try { await this.app.fileManager.trashFile(f); } catch (e) { console.warn("[Stashpad] cross-folder move: couldn't trash source note", f.path, e); } } + for (const f of srcExclusiveAtts) { try { await this.app.fileManager.trashFile(f); } catch (e) { console.warn("[Stashpad] cross-folder move: couldn't trash source attachment", f.path, e); } } + } + + const removeCreated = async () => { + for (const p of [...createdPaths].reverse()) { + const f = this.app.vault.getAbstractFileByPath(p); + if (f) { try { await this.app.fileManager.trashFile(f as TFile); } catch { /* already gone */ } } + } + }; + const undo = mode === "cut" + ? async () => { await removeCreated(); await this.restoreSnapshot(srcSnapshot); } + : async () => { await removeCreated(); }; + const redo = mode === "cut" + ? async () => { await this.restoreSnapshot(destSnapshot); for (const s of srcSnapshot) { const f = this.app.vault.getAbstractFileByPath(s.path); if (f) { try { await this.app.fileManager.trashFile(f as TFile); } catch { /* gone */ } } } } + : async () => { await this.restoreSnapshot(destSnapshot); }; + + return { rootIds: newRootIds, noteCount, undo, redo }; + } + + /** Trash (recoverable) the given subtrees in `folder`: every note file plus the + * attachments referenced ONLY by those subtrees — shared attachments stay put. + * Returns the files it trashed (for the caller's undo snapshot). */ + async trashSubtrees(folder: string, rootIds: StashpadId[]): Promise<TFile[]> { + const files: TFile[] = []; + for (const rid of rootIds) { + const sub = await collectSubtree(this.app, folder, rid); + if (!sub) continue; + files.push(sub.rootNote.file, ...sub.descendants.map((d) => d.file)); + } + if (!files.length) return []; + const exclusiveAtts = await this.exclusiveAttachmentsOf(files); + const trashed: TFile[] = []; + for (const f of [...files, ...exclusiveAtts]) { + try { await this.app.fileManager.trashFile(f); trashed.push(f); } + catch (e) { console.warn("[Stashpad] trashSubtrees: couldn't trash", f.path, e); } + } + return trashed; + } + + /** Attachments referenced ONLY by `noteFiles` (not by any note outside the set). + * Exclusivity is read from the live resolvedLinks graph — call while the notes + * are still present. */ + async exclusiveAttachmentsOf(noteFiles: TFile[]): Promise<TFile[]> { + const subtreePaths = new Set(noteFiles.map((f) => f.path)); + const subtreeAtts = new Map<string, TFile>(); + for (const f of noteFiles) for (const af of await resolveNoteAttachmentFiles(this.app, f)) subtreeAtts.set(af.path, af); + const resolved = this.app.metadataCache.resolvedLinks ?? {}; + for (const notePath of Object.keys(resolved)) { + if (subtreePaths.has(notePath)) continue; + for (const target of Object.keys(resolved[notePath] ?? {})) subtreeAtts.delete(target); // referenced elsewhere → not exclusive + } + return [...subtreeAtts.values()]; + } + + /** Paths of every file (notes + their exclusive attachments) in the given + * subtrees — for an undo snapshot taken before trashing. */ + async subtreeFilePaths(folder: string, rootIds: StashpadId[]): Promise<string[]> { + const files: TFile[] = []; + for (const rid of rootIds) { + const sub = await collectSubtree(this.app, folder, rid); + if (!sub) continue; + files.push(sub.rootNote.file, ...sub.descendants.map((d) => d.file)); + } + if (!files.length) return []; + const atts = await this.exclusiveAttachmentsOf(files); + return [...files.map((f) => f.path), ...atts.map((f) => f.path)]; + } + + /** Pre-ordered (parent → children, depth-tagged) nodes of the given subtrees, + * read from disk — for building the indented outline of a CROSS-folder cut + * pasted into a composer (the source folder's tree isn't loaded in the + * destination view). Siblings are ordered by `position` frontmatter (then + * `created`) to match the list's visual order. */ + async orderedSubtreeNodes(folder: string, rootIds: StashpadId[]): Promise<Array<{ file: TFile; created: string; depth: number }>> { + const out: Array<{ file: TFile; created: string; depth: number }> = []; + const seen = new Set<StashpadId>(); + const posOf = (f: TFile): number => { const v = (this.app.metadataCache.getFileCache(f)?.frontmatter as Record<string, unknown> | undefined)?.position; return typeof v === "number" ? v : Number.MAX_SAFE_INTEGER; }; + type N = { id: StashpadId; file: TFile; created: string }; + for (const rid of rootIds) { + const sub = await collectSubtree(this.app, folder, rid); + if (!sub) continue; + const childrenOf = new Map<StashpadId, N[]>(); + for (const d of sub.descendants) { + if (!d.parent) continue; + const arr = childrenOf.get(d.parent as StashpadId) ?? []; + arr.push({ id: d.id, file: d.file, created: d.created }); + childrenOf.set(d.parent as StashpadId, arr); + } + for (const arr of childrenOf.values()) arr.sort((a, b) => (posOf(a.file) - posOf(b.file)) || a.created.localeCompare(b.created)); + const walk = (node: N, depth: number): void => { + if (seen.has(node.id)) return; // cycle / overlap guard + seen.add(node.id); + out.push({ file: node.file, created: node.created, depth }); + for (const c of childrenOf.get(node.id) ?? []) walk(c, depth + 1); + }; + walk({ id: sub.rootNote.id, file: sub.rootNote.file, created: sub.rootNote.created }, 0); + } + return out; + } + + /** All file paths under `folder` (notes directly in it + its `_attachments`). */ + filesUnder(folder: string): string[] { + const prefix = folder.replace(/\/+$/, "") + "/"; + return this.app.vault.getFiles().filter((f) => f.path.startsWith(prefix)).map((f) => f.path); + } + + /** Capture content for a set of paths (text for `.md`, binary otherwise) so an + * undo/redo can recreate them exactly. Missing paths are skipped. */ + async snapshotPaths(paths: string[]): Promise<FileSnapshot[]> { + const out: FileSnapshot[] = []; + for (const path of paths) { + const f = this.app.vault.getAbstractFileByPath(path) as TFile | null; + if (!f) continue; + const binary = !path.toLowerCase().endsWith(".md"); + try { + if (binary) out.push({ path, binary, data: await this.app.vault.readBinary(f) }); + else out.push({ path, binary, text: await this.app.vault.read(f) }); + } catch (e) { console.warn("[Stashpad] snapshotPaths: couldn't read", path, e); } + } + return out; + } + + /** Recreate files from a snapshot (parents are created as needed). Overwrites an + * existing file at the same path. */ + async restoreSnapshot(snaps: FileSnapshot[]): Promise<void> { + for (const s of snaps) { + const dir = s.path.split("/").slice(0, -1).join("/"); + await this.ensureVaultFolder(dir); + const existing = this.app.vault.getAbstractFileByPath(s.path) as TFile | null; + try { + if (s.binary) { + if (existing) await this.app.vault.adapter.writeBinary(s.path, s.data as ArrayBuffer); + else await this.app.vault.createBinary(s.path, s.data as ArrayBuffer); + } else { + if (existing) await this.app.vault.modify(existing, s.text ?? ""); + else await this.app.vault.create(s.path, s.text ?? ""); + } + } catch (e) { console.warn("[Stashpad] restoreSnapshot: couldn't write", s.path, e); } + } + } + + /** Ensure a (possibly nested) vault folder exists. */ + async ensureVaultFolder(dir: string): Promise<void> { + if (!dir) return; + let acc = ""; + for (const seg of dir.split("/")) { + acc = acc ? `${acc}/${seg}` : seg; + if (!(await this.app.vault.adapter.exists(acc))) { try { await this.app.vault.createFolder(acc); } catch { /* race / exists */ } } + } + } + + /** Rebuild + re-render every open Stashpad view showing `folder` — after an + * out-of-band change to its files (e.g. a cross-folder move that removed notes + * from the source folder, whose view isn't the one that ran the command). */ + refreshOpenViewsForFolder(folder: string): void { + const cleaned = folder.replace(/\/+$/, ""); + for (const leaf of this.app.workspace.getLeavesOfType(STASHPAD_VIEW_TYPE)) { + const v = leaf.view as any; + if ((v?.noteFolder?.replace(/\/+$/, "") ?? "") !== cleaned) continue; + try { v.tree?.rebuild?.(folder); v.render?.(); } catch (e) { console.warn("[Stashpad] refresh view failed", e); } + } + } + /** Batches arrivals per archive folder: each move-in (re)arms a settle timer so * a multi-file move (a whole subtree dragged in) is swept ONCE, after the * re-home debounce (900ms) and metadata indexing have settled. */ diff --git a/src/stash-package.ts b/src/stash-package.ts index 5cdcdd3..042e4d4 100644 --- a/src/stash-package.ts +++ b/src/stash-package.ts @@ -53,6 +53,9 @@ export interface ImportSummary { /** Hex→name aliases from the manifest, for the caller to merge into the * destination folder's color aliases (importStashZip has no settings access). */ colorAliases?: Record<string, string>; + /** Old id → new id mapping applied on import (identity for kept ids). Lets a + * caller (e.g. cross-folder paste) locate the written roots by their source id. */ + idRemap: Record<string, string>; } interface ParsedNote { @@ -118,7 +121,7 @@ export async function importStashZip( buf: ArrayBuffer | Uint8Array, destFolder: string, existingIds: Set<StashpadId>, - opts: { dedupeExisting?: boolean } = {}, + opts: { dedupeExisting?: boolean; forceNewIds?: boolean; reparentRootsTo?: StashpadId | null } = {}, ): Promise<ImportSummary> { const zip = await JSZip.loadAsync(buf as any); const manifestFile = zip.file("manifest.json"); @@ -152,7 +155,9 @@ export async function importStashZip( for (const p of parsed) { const oldId = p.fm.id as string | undefined; if (!oldId) continue; - if (existingIds.has(oldId) || idRemap.has(oldId) /* dup within zip */) { + if (opts.forceNewIds) { + idRemap.set(oldId, newId(6)); // cross-folder COPY → a fresh identity (not a same-id twin) + } else if (existingIds.has(oldId) || idRemap.has(oldId) /* dup within zip */) { idRemap.set(oldId, `${oldId}-${newId(4)}-Imported`); collisionsRenamed++; } else { @@ -225,13 +230,18 @@ export async function importStashZip( const oldParent = (p.fm.parent ?? null) as string | null; let newParent: string | null = oldParent; - if (oldParent && oldParent !== ROOT_ID && idRemap.has(oldParent)) { - newParent = idRemap.get(oldParent)!; - } else if (oldParent && oldParent !== ROOT_ID && !idRemap.has(oldParent)) { + if (!oldParent || oldParent === ROOT_ID) { + // Top-level in the source → a bundle root. Honor reparentRootsTo (cross- + // folder paste nests the pasted root where the cursor was); otherwise keep + // it at ROOT as before. + newParent = opts.reparentRootsTo ?? oldParent ?? ROOT_ID; + } else if (idRemap.has(oldParent)) { + newParent = idRemap.get(oldParent)!; // internal edge — remap to the moved parent + } else { // Parent isn't in this bundle. If it already EXISTS in the destination // (e.g. UNLOCK: the locked subtree's parent stayed in the vault), keep the - // link so nesting is restored; otherwise pin to ROOT for safety. - newParent = existingIds.has(oldParent) ? oldParent : ROOT_ID; + // link so nesting is restored; otherwise it's a bundle root → reparent/ROOT. + newParent = existingIds.has(oldParent) ? oldParent : (opts.reparentRootsTo ?? ROOT_ID); } // Rewrite body: ![[basename]] -> ![[<routed path>]] (the _attachments copy, @@ -280,7 +290,7 @@ export async function importStashZip( if (Object.keys(clean).length) colorAliases = clean; } - return { notesWritten, attachmentsWritten, collisionsRenamed, warnings, colorAliases }; + return { notesWritten, attachmentsWritten, collisionsRenamed, warnings, colorAliases, idRemap: Object.fromEntries(idRemap) }; } // ---------------- Helpers ---------------- diff --git a/src/view.ts b/src/view.ts index 662ca9a..f284c57 100644 --- a/src/view.ts +++ b/src/view.ts @@ -6998,7 +6998,40 @@ export class StashpadView extends ItemView { async cmdPasteNotes(): Promise<void> { const clip = this.plugin.noteClipboard; if (!clip) { new Notice("The note clipboard is empty — copy or cut notes first."); return; } - if (clip.folder !== this.noteFolder) { new Notice("Those notes were cut/copied in another folder — cross-folder paste isn't supported yet."); return; } + // Cross-folder paste: the source notes live in another Stashpad folder, so + // route through the plugin's bundle-based engine — it carries ATTACHMENTS + // into this folder's _attachments, mints fresh ids for a copy (keeps them for + // a cut), and refuses an archive/auto-encrypting destination. + if (clip.folder !== this.noteFolder) { + const cursorX = this.currentChildren[this.cursorIdx] ?? null; + const destParent = ((cursorX?.parent ?? this.focusId) ?? ROOT_ID) as StashpadId; + const mode = clip.mode; + const srcFolder = clip.folder; + const result = await this.plugin.crossFolderPaste(srcFolder, clip.ids, this.noteFolder, destParent, mode); + if (!result || !result.rootIds.length) return; // refused (archive) / nothing found — Notice already shown + if (mode === "cut") this.plugin.clearNoteClipboard(); + const folder = this.noteFolder; + this.tree.rebuild(folder); + this.pendingFocusIds = result.rootIds.slice(); + this.render(); + if (mode === "cut") this.plugin.refreshOpenViewsForFolder(srcFolder); // source lost notes + const srcLabel = srcFolder.split("/").pop(); + const n = result.rootIds.length; + // Undo/redo: the engine returns reversible file-level closures; we wrap them + // with a rebuild + render of THIS folder and a refresh of the source folder. + const refreshBoth = () => { this.tree.rebuild(folder); this.render(); this.plugin.refreshOpenViewsForFolder(srcFolder); }; + this.plugin.getUndoStack(folder).push({ + label: `${mode === "cut" ? "Move" : "Paste"} ${n} note${n === 1 ? "" : "s"} from ${srcLabel}`, + undo: async () => { await result.undo(); refreshBoth(); }, + redo: async () => { await result.redo(); refreshBoth(); }, + }); + const verb = mode === "cut" ? "Moved" : "Pasted (copied)"; + this.plugin.notifications.show({ + message: `${verb} ${n} note${n === 1 ? "" : "s"} (${result.noteCount} total) from "${srcLabel}" into this folder. Undo (in the list) reverses it.`, + kind: "success", category: mode === "cut" ? "move" : "clone", affectedIds: result.rootIds, folder, duration: 0, + }); + return; + } const nodes = clip.ids.map((id) => this.tree.get(id)).filter((n): n is TreeNode => !!n && !!n.file); if (!nodes.length) { this.plugin.clearNoteClipboard(); this.render(); new Notice("Those notes no longer exist."); return; } // Paste position: after the cursor row (same parent); fall back to the @@ -7064,7 +7097,45 @@ export class StashpadView extends ItemView { * deleting the original notes + their subtrees (snapshot-undoable). */ async completeCutIntoComposer(): Promise<void> { const clip = this.plugin.noteClipboard; - if (!clip || clip.mode !== "cut" || clip.folder !== this.noteFolder) return; + if (!clip || clip.mode !== "cut") return; + if (clip.folder !== this.noteFolder) { + // Cross-folder cut → composer: the cut text is on the system clipboard + // (clip.text); insert it here, then trash the source subtree(s). This is the + // "fold the text into what I'm writing" path — no structural move. + const srcFolder = clip.folder; + const rootIds = clip.ids.slice(); + this.plugin.clearNoteClipboard(); + // Build the SAME indented bullet outline as the same-folder path (note + + // all children, 2-space indent per depth, optional time prefix), reading + // the source subtree from disk since it isn't in this view's tree. + const ordered = await this.plugin.orderedSubtreeNodes(srcFolder, rootIds); + const prefixTs = getSettings().prefixTimestampsOnCopy; + const outline: string[] = []; + for (const { file, created, depth } of ordered) { + try { + const body = this.stripFrontmatter(await this.app.vault.cachedRead(file)).trim().split(/\r?\n/).join(" "); + const ts = prefixTs ? `${this.formatTimeInline(created)} ` : ""; + outline.push(`${" ".repeat(depth)}- ${ts}${body}`); + } catch { /* skip unreadable */ } + } + this.insertIntoComposer(outline.length ? outline.join("\n") : (clip.text ?? "")); + // Snapshot the source BEFORE trashing so undo can restore it. + const snapPaths = await this.plugin.subtreeFilePaths(srcFolder, rootIds); + const snap = await this.plugin.snapshotPaths(snapPaths); + const trashed = await this.plugin.trashSubtrees(srcFolder, rootIds); + this.plugin.refreshOpenViewsForFolder(srcFolder); + const noteN = trashed.filter((f) => f.extension === "md").length; + this.plugin.getUndoStack(srcFolder).push({ + label: `Cut ${rootIds.length} note${rootIds.length === 1 ? "" : "s"} into composer (from ${srcFolder.split("/").pop()})`, + undo: async () => { await this.plugin.restoreSnapshot(snap); this.plugin.refreshOpenViewsForFolder(srcFolder); }, + redo: async () => { await this.plugin.trashSubtrees(srcFolder, rootIds); this.plugin.refreshOpenViewsForFolder(srcFolder); }, + }); + this.plugin.notifications.show({ + message: `Pasted the text of ${rootIds.length} cut note${rootIds.length === 1 ? "" : "s"} from "${srcFolder.split("/").pop()}" into the composer and removed the original${noteN === 1 ? "" : "s"} (${noteN} note${noteN === 1 ? "" : "s"}). Undo restores them.`, + kind: "warning", category: "delete", affectedIds: rootIds, folder: srcFolder, duration: 0, + }); + return; + } this.plugin.clearNoteClipboard(); const roots = clip.ids.map((id) => this.tree.get(id)).filter((n): n is TreeNode => !!n && !!n.file); if (!roots.length) return;