diff --git a/main.js b/main.js index 3b20f0a..85a68c8 100644 --- a/main.js +++ b/main.js @@ -1,30 +1,30 @@ -"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 pe=(d,A)=>()=>(d&&(A=d(d=0)),A);var oa=(d,A)=>()=>(A||d((A={exports:{}}).exports,A),A.exports),Si=(d,A)=>{for(var t in A)ki(d,t,{get:A[t],enumerable:!0})},Nn=(d,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of ia(A))!na.call(d,i)&&i!==t&&ki(d,i,{get:()=>A[i],enumerable:!(e=ea(A,i))||e.enumerable});return d};var Ns=(d,A,t)=>(t=d!=null?ta(sa(d)):{},Nn(A||!d||!d.__esModule?ki(t,"default",{value:d,enumerable:!0}):t,d)),aa=d=>Nn(ki({},"__esModule",{value:!0}),d);function xs(d){return Array.isArray(d)?d.filter(A=>typeof A=="string"):typeof d=="string"?d.split(/[,\s]+/).filter(Boolean):[]}function Se(d,A){let t=A.replace(/^#/,"");return xs(d?.tags).some(e=>e.replace(/^#/,"")===t)}function Ms(d,A){let t=A.replace(/^#/,""),e=xs(d.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),d.tags=e}function Hs(d,A){let t=A.replace(/^#/,""),e=xs(d.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?d.tags=e:delete d.tags}function De(d){return d.split("/").some(A=>Xe.has(A))}function xn(d){return d.split("/").some(A=>A==="_archive"||A===".archive")}function Ot(d){let A=(d??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function fe(d){let A=(d??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function Mn(d){let A=d.match(/\.([^./]+)$/);return!!A&&ra.has(A[1].toLowerCase())}function Hn(d,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(d))return!0}catch{}else if(d===e||d.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Di(d,A){let t=d.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function se(d){if(typeof d!="string")return null;let A=d.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function Ze(d){let A=d?.assignedTo,t=Array.isArray(A)?A:A!=null?[A]:[],e=[];for(let i of t){let s=se(i);s&&e.push(s)}return e}var ct,ee,Ie,ue,ke,M,ie,Xe,ra,Et=pe(()=>{"use strict";ct="stashpad-view",ee="stashpad-panels",Ie="stashpad-folder-panel",ue="stashpad-detail",ke="stashpad-trash",M="__root__";ie=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],Xe=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ra=new Set(["edtz"])});function Aa(d,A){return d>12?d>=24?0:d:A==="am"?d===12?0:d:d===12?12:d+12}function Ni(d,A){d.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=d.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let 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 h=[i,s,o,a],I=(E,w)=>{let y=h.indexOf(E);if(y===-1)return;let v=(y+w+h.length)%h.length;h[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=d.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],B=null;for(let E of C){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",E==="backspace"?(0,Gn.setIcon)(w,"delete"):E==="insert"?(w.setText("OK"),B=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())})}B&&h.push(B);for(let E of h)u(E);i.focus(),i.select()}function Rn(d){let{hh:A,mm:t,period:e,is24:i}=d.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var Gn,Ts=pe(()=>{"use strict";Gn=require("obsidian")});function Jn(d){let A=Math.floor(4294967296/d)*d,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%d}function Us(d=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(d.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function ca(d){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function _e(d){let A="stashpad-",t=ca(d),e=64-A.length-1-t.length,i=d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var Ln,la,xi=pe(()=>{"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((d,A,t)=>t.indexOf(d)===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:()=>yt});function yt(d=6){let A="",t=new Uint8Array(d);crypto.getRandomValues(t);for(let e=0;e{"use strict";qn="abcdefghijkmnpqrstuvwxyz23456789"});var Ai={};Si(Ai,{AssignModal:()=>ni,ColorPickerModal:()=>Qe,ConfirmDeleteModal:()=>Ne,ConfirmModal:()=>Ft,CustomColorModal:()=>Hi,DueDatePickerModal:()=>oi,EncryptionPasswordModal:()=>Wt,ExportStashModal:()=>ei,ImportDupChoiceModal:()=>ri,ImportLogModal:()=>Gs,LogModal:()=>be,NotificationHistoryModal:()=>ai,SplitNoteModal:()=>ti,StashPasswordModal:()=>ii,TypeToConfirmModal:()=>si,buildAssigneePicker:()=>Rs});function Rs(d,A){let t=[...A.initial],e=A.knownAuthors,i=d.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),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 h=s.createSpan({cls:"stashpad-assign-chip"});h.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let I=h.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(h=>h.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 h=new Set(t.map(f=>f.id)),u=e.filter(f=>!h.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:yt(6),name:p})}),u.length===0){a.style.display="none";return}a.style.display="";for(let f of u){let C=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});C.onmousedown=B=>{B.preventDefault(),f.onPick()}}};o.addEventListener("input",g),o.addEventListener("focus",g),o.addEventListener("keydown",p=>{if(p.key==="Enter"){p.preventDefault();let h=a.querySelector(".stashpad-assign-suggest-item");h&&h.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,be,Ne,ti,ei,ii,Wt,si,Hi,je,Qe,Ft,ni,oi,me,ai,Gs,ri,Mt=pe(()=>{"use strict";at=require("obsidian");Ts();Et();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;be=Be,Ne=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 ki=Object.defineProperty;var ea=Object.getOwnPropertyDescriptor;var ia=Object.getOwnPropertyNames;var sa=Object.getPrototypeOf,na=Object.prototype.hasOwnProperty;var Ie=(d,A)=>()=>(d&&(A=d(d=0)),A);var oa=(d,A)=>()=>(A||d((A={exports:{}}).exports,A),A.exports),Si=(d,A)=>{for(var t in A)ki(d,t,{get:A[t],enumerable:!0})},Nn=(d,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of ia(A))!na.call(d,i)&&i!==t&&ki(d,i,{get:()=>A[i],enumerable:!(e=ea(A,i))||e.enumerable});return d};var Ns=(d,A,t)=>(t=d!=null?ta(sa(d)):{},Nn(A||!d||!d.__esModule?ki(t,"default",{value:d,enumerable:!0}):t,d)),aa=d=>Nn(ki({},"__esModule",{value:!0}),d);function xs(d){return Array.isArray(d)?d.filter(A=>typeof A=="string"):typeof d=="string"?d.split(/[,\s]+/).filter(Boolean):[]}function Se(d,A){let t=A.replace(/^#/,"");return xs(d?.tags).some(e=>e.replace(/^#/,"")===t)}function Ms(d,A){let t=A.replace(/^#/,""),e=xs(d.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),d.tags=e}function Hs(d,A){let t=A.replace(/^#/,""),e=xs(d.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?d.tags=e:delete d.tags}function De(d){return d.split("/").some(A=>Xe.has(A))}function xn(d){return d.split("/").some(A=>A==="_archive"||A===".archive")}function Ot(d){let A=(d??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function Ce(d){let A=(d??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function Mn(d){let A=d.match(/\.([^./]+)$/);return!!A&&ra.has(A[1].toLowerCase())}function Hn(d,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(d))return!0}catch{}else if(d===e||d.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Di(d,A){let t=d.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function ne(d){if(typeof d!="string")return null;let A=d.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function Ze(d){let A=d?.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,ke,M,se,Xe,ra,yt=Ie(()=>{"use strict";ct="stashpad-view",ie="stashpad-panels",ue="stashpad-folder-panel",fe="stashpad-detail",ke="stashpad-trash",M="__root__";se=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],Xe=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ra=new Set(["edtz"])});function Aa(d,A){return d>12?d>=24?0:d:A==="am"?d===12?0:d:d===12?12:d+12}function Ni(d,A){d.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=d.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let 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 h=[i,s,o,a],I=(E,w)=>{let y=h.indexOf(E);if(y===-1)return;let v=(y+w+h.length)%h.length;h[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=d.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&&h.push(m);for(let E of h)u(E);i.focus(),i.select()}function Gn(d){let{hh:A,mm:t,period:e,is24:i}=d.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var Rn,Ts=Ie(()=>{"use strict";Rn=require("obsidian")});function Jn(d){let A=Math.floor(4294967296/d)*d,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%d}function Us(d=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(d.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function ca(d){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function _e(d){let A="stashpad-",t=ca(d),e=64-A.length-1-t.length,i=d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var 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((d,A,t)=>t.indexOf(d)===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(d=6){let A="",t=new Uint8Array(d);crypto.getRandomValues(t);for(let e=0;e{"use strict";qn="abcdefghijkmnpqrstuvwxyz23456789"});var Ai={};Si(Ai,{AssignModal:()=>ni,ColorPickerModal:()=>Qe,ConfirmDeleteModal:()=>Ne,ConfirmModal:()=>Ft,CustomColorModal:()=>Hi,DueDatePickerModal:()=>oi,EncryptionPasswordModal:()=>$t,ExportStashModal:()=>ei,ImportDupChoiceModal:()=>ri,ImportLogModal:()=>Rs,LogModal:()=>be,NotificationHistoryModal:()=>ai,SplitNoteModal:()=>ti,StashPasswordModal:()=>ii,TypeToConfirmModal:()=>si,buildAssigneePicker:()=>Gs});function Gs(d,A){let t=[...A.initial],e=A.knownAuthors,i=d.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),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 h=s.createSpan({cls:"stashpad-assign-chip"});h.createSpan({cls:"stashpad-assign-chip-name",text:p.name});let I=h.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(h=>h.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 h=new Set(t.map(f=>f.id)),u=e.filter(f=>!h.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 h=a.querySelector(".stashpad-assign-suggest-item");h&&h.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,me,be,Ne,ti,ei,ii,$t,si,Hi,je,Qe,Ft,ni,oi,Be,ai,Rs,ri,Ht=Ie(()=>{"use strict";at=require("obsidian");Ts();yt();xi();Kt();da=at.moment,me=class me 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(me.PAGE)}}setTypeFilter(t){(this.typeFilter??null)!==(t??null)&&(this.typeFilter=t,this.refreshList(),this.renderFooter())}refreshTypeFilter(){if(!this.filterSelEl)return;let t=this.filterSelEl;t.empty();let e=new Map;for(let n of this.events)e.set(n.type,(e.get(n.type)??0)+1);let i=[...e.entries()].sort((n,o)=>o[1]-n[1]||n[0].localeCompare(o[0])),s=t.createEl("option",{text:`All types (${this.events.length})`});s.value="";for(let[n,o]of i){let a=t.createEl("option",{text:`${n} (${o})`});a.value=n}this.typeFilter&&!e.has(this.typeFilter)&&(this.typeFilter=null),t.value=this.typeFilter??""}updateCount(){if(!this.countEl)return;let t=this.visible.length,e=this.typeFilter?`${t} ${this.typeFilter} event${t===1?"":"s"}`:`${t} event${t===1?"":"s"}`;this.shownCount===0||this.shownCount>=t?this.countEl.setText(e):this.countEl.setText(`Showing ${this.shownCount} of ${e}`)}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i{this.appendMore(me.PAGE),this.renderFooter()},t>me.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}shellAct(t){try{let e=this.app.vault.adapter.getFullPath?.(this.jsonlPath);if(!e)throw new Error("no full path");let{shell:i}=window.require("electron");t==="reveal"?i.showItemInFolder(e):i.openPath(e)}catch(e){new 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()}};me.PAGE=100;be=me,Ne=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,` `).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"),h=r.createDiv({cls:"stashpad-export-strength"}),I=h.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),f=h.createEl("span",{cls:"stashpad-strength-label"}),C=r.createDiv({cls:"stashpad-export-genrow"}),B=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);h.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)},B.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()}},Wt=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 B=f.createEl("button",{cls:"stashpad-export-copy"}),E=()=>{let w=C.value.length===0;B.setText(w?"Paste":"Copy"),B.toggleClass("is-paste",w),B.setAttr("aria-label",`${w?"Paste into":"Copy"} ${u.toLowerCase()}`)};return B.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"})),B=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"}),h=!1,I=async()=>{if(h)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}}h=!0,p.disabled=!0,l.style.display="none";let C=p.textContent;p.setText("Working\u2026");try{let B=await this.opts.onSubmit({current:u,next:f,remember:!!a?.checked});if(B){c(B),h=!1,p.disabled=!1,p.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(B){c(`Failed: ${B.message}`),h=!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"});Rs(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 B=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});B.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 h=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});h.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,B]=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,B,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){Rs(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[h,I]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(h)&&(i=h),Number.isFinite(I)&&(s=I)}else{let h=new Date;i=h.getHours(),s=h.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=h=>{!a.contains(h.target)&&h.target!==t&&!t.contains(h.target)&&l()},g=h=>{h.key==="Escape"?(h.preventDefault(),h.stopPropagation(),l()):h.key==="Enter"&&r&&(h.preventDefault(),h.stopPropagation(),r())};this.tinyClosePopover=l,Ni(a,{seedH:o,seedM:s,seedPeriod:n,close:l,setOnEnter:h=>{r=h},onFinalize:h=>{e.value=`${String(h.hours24).padStart(2,"0")}:${String(h.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}`}},me=class me 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(me.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let 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(me.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(me.PAGE),this.renderFooter()},t>me.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};me.PAGE=100;ai=me,Gs=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(d,A=Yt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(d.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function xt(d,A){return`${d}-${A}.md`}function ye(d){let A=d.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var Yt,xe=pe(()=>{"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 Ri={};Si(Ri,{JdBuildConfirmModal:()=>ci,buildJdIndexNotes:()=>Js,buildJdIndexPreview:()=>Pi,buildJdPreviewNotice:()=>Gi,scanForJdNotes:()=>Me});function Ls(d,A){if(/^\d+-\d+$/.test(d))return null;if(d.includes(".")){let e=d.split(".").slice(0,-1).join(".");return A.has(e)?e:Ls(e,A)}if(/^\d+$/.test(d)){let t=parseInt(d,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function Me(d,A,t){let e=d.vault.getMarkdownFiles(),i=ga(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=h=>s?!1:Array.from(n).some(I=>h===I||h.startsWith(I+"/")),a=[],r=[],l=[];for(let h of i){let I=h.parent?.path?.replace(/\/+$/,"")??"";if(o(I)){l.push(h);continue}let u=h.basename.match(On);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:h,folder:null}):r.push(h)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=h=>{let I=h.path.replace(/\/+$/,"");if(!(c&&I&&I!==c&&!I.startsWith(c+"/"))){if(I&&!o(I)){let u=h.name.match(On);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:h})}}for(let u of h.children)u instanceof kt.TFolder&&g(u)};g(d.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((h,I)=>pa(h,I,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:l}}async function Pi(d,A,t){let e=qs(t.jdIndexStashpadFolder??"");if(!e)return{...Me(d,A,t),previewPath:null,error:"no-dest"};let i=Me(d,A,t),s=ha(d,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Ia(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await d.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await d.vault.modify(s,r),{...i,previewPath:s.path}}function ha(d,A){let t=d.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((d.metadataCache.getFileCache(e)?.frontmatter??{}).id===M)return e}return null}async function Js(d,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=Me(d,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let 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=d.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=d.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&c.set(C.jdPrefix,f)}let p=new Map,h=0,I=0,u=0;for(let f of r){let C=n.get(f)??null,B=Ls(f,new Set(n.keys())),E=B?p.get(B)??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()}},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"),h=r.createDiv({cls:"stashpad-export-strength"}),I=h.createDiv({cls:"stashpad-strength-bar"}),u=[0,1,2,3].map(()=>I.createDiv({cls:"stashpad-strength-seg"})),f=h.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);h.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"}),h=!1,I=async()=>{if(h)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}}h=!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),h=!1,p.disabled=!1,p.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(m){c(`Failed: ${m.message}`),h=!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 h=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});h.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[h,I]=e.value.split(":").map(u=>parseInt(u,10));Number.isFinite(h)&&(i=h),Number.isFinite(I)&&(s=I)}else{let h=new Date;i=h.getHours(),s=h.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=h=>{!a.contains(h.target)&&h.target!==t&&!t.contains(h.target)&&l()},g=h=>{h.key==="Escape"?(h.preventDefault(),h.stopPropagation(),l()):h.key==="Enter"&&r&&(h.preventDefault(),h.stopPropagation(),r())};this.tinyClosePopover=l,Ni(a,{seedH:o,seedM:s,seedPeriod:n,close:l,setOnEnter:h=>{r=h},onFinalize:h=>{e.value=`${String(h.hours24).padStart(2,"0")}:${String(h.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}`}},Be=class Be 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(Be.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let 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(Be.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Be.PAGE),this.renderFooter()},t>Be.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Be.PAGE=100;ai=Be,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(d,A=Yt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(d.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function xt(d,A){return`${d}-${A}.md`}function ye(d){let A=d.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var Yt,xe=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:()=>Me});function Ls(d,A){if(/^\d+-\d+$/.test(d))return null;if(d.includes(".")){let e=d.split(".").slice(0,-1).join(".");return A.has(e)?e:Ls(e,A)}if(/^\d+$/.test(d)){let t=parseInt(d,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function Me(d,A,t){let e=d.vault.getMarkdownFiles(),i=ga(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=h=>s?!1:Array.from(n).some(I=>h===I||h.startsWith(I+"/")),a=[],r=[],l=[];for(let h of i){let I=h.parent?.path?.replace(/\/+$/,"")??"";if(o(I)){l.push(h);continue}let u=h.basename.match(On);u?a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:h,folder:null}):r.push(h)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=h=>{let I=h.path.replace(/\/+$/,"");if(!(c&&I&&I!==c&&!I.startsWith(c+"/"))){if(I&&!o(I)){let u=h.name.match(On);u&&a.push({prefix:u[1],segments:u[1].split("."),title:u[2],file:null,folder:h})}}for(let u of h.children)u instanceof kt.TFolder&&g(u)};g(d.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((h,I)=>pa(h,I,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:l}}async function Pi(d,A,t){let e=qs(t.jdIndexStashpadFolder??"");if(!e)return{...Me(d,A,t),previewPath:null,error:"no-dest"};let i=Me(d,A,t),s=ha(d,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Ia(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await d.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await d.vault.modify(s,r),{...i,previewPath:s.path}}function ha(d,A){let t=d.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((d.metadataCache.getFileCache(e)?.frontmatter??{}).id===M)return e}return null}async function Js(d,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=Me(d,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let 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=d.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=d.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&c.set(C.jdPrefix,f)}let p=new Map,h=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} `:`${w} -`,S=c.get(f);if(S){try{let U=null;await d.fileManager.processFrontMatter(S,D=>{D.jdPrefix=f,E&&(D.parent=E),(!D.id||typeof D.id!="string")&&(D.id=yt()),D.created||(D.created=new Date().toISOString()),D.attachments||(D.attachments=[]),U=D.id});let x=(await d.vault.read(S)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=x?`${x[0]}${v}`:v;await d.vault.modify(S,Q),U&&p.set(f,U),I++}catch(U){console.error("[stashpad] buildJdIndexNotes: update failed",U),u++}continue}try{let U=yt();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(` +`,S=c.get(f);if(S){try{let U=null;await d.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 d.vault.read(S)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=x?`${x[0]}${v}`:v;await d.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 d.vault.create(Q,D+v),h++}catch(U){console.error("[stashpad] buildJdIndexNotes: create failed for",f,U),u++}}return{created:h,updated:I,skipped:u,destFolder:e}}function qs(d){return(d||"").trim().replace(/^\/+|\/+$/g,"")}function ga(d,A){if((A.jdIndexScope??"vault")==="vault")return d;let t=qs(A.jdIndexScopeFolder??"");return t?d.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):d}function pa(d,A,t){if(t==="created"){let e=d.file?.stat?.ctime??0,i=A.file?.stat?.ctime??0;if(e!==i)return e-i}return Yn(d.segments,A.segments)}function Kn(d,A){let t=d.match(/^(\d+)-(\d+)$/),e=A.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:d.split("."),s=e?[e[1]]:A.split(".");return Yn(i,s)}function Yn(d,A){let t=Math.min(d.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(d,A,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),d.length===0){let s=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(s)}else{let s=new Map;for(let l of d)s.set(l.prefix,l);for(let l of d)if(l.prefix.includes("."))for(let c=1;c{let c=s.get(l),g=a.get(l)??0,p=" ".repeat(g),h=i(g),I=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${p}- ${h} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${p}- ${h} ${c.prefix}${I}`):e.push(`${p}- ${h} ${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(` `)+` -`}function Gi(d,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=d.vault.getAbstractFileByPath(A.previewPath);a instanceof kt.TFile&&await d.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new kt.Notice(t,0),n}var kt,On,ci,di=pe(()=>{"use strict";kt=require("obsidian");Kt();xe();Et();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,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 Vi=oa((lo,an)=>{(function(d){typeof lo=="object"&&typeof an<"u"?an.exports=d():typeof define=="function"&&define.amd?define([],d):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=d()})(function(){return function d(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,d,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(d,A,t){"use strict";var e=d("./utils"),i=d("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,l,c,g,p,h=[],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,h.push(s.charAt(l)+s.charAt(c)+s.charAt(g)+s.charAt(p));return h.join("")},t.decode=function(n){var o,a,r,l,c,g,p=0,h=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[h++]=o,c!==64&&(u[h++]=a),g!==64&&(u[h++]=r);return u}},{"./support":30,"./utils":32}],2:[function(d,A,t){"use strict";var e=d("./external"),i=d("./stream/DataWorker"),s=d("./stream/Crc32Probe"),n=d("./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(d,A,t){"use strict";var e=d("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=d("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(d,A,t){"use strict";var e=d("./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(d,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(d,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:d("lie"),A.exports={Promise:e}},{lie:37}],7:[function(d,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=d("pako"),s=d("./utils"),n=d("./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(d,A,t){"use strict";function e(c,g){var p,h="";for(p=0;p<g;p++)h+=String.fromCharCode(255&c),c>>>=8;return h}function i(c,g,p,h,I,u){var f,C,B=c.file,E=c.compression,w=u!==o.utf8encode,y=s.transformTo("string",u(B.name)),v=s.transformTo("string",o.utf8encode(B.name)),S=B.comment,U=s.transformTo("string",u(S)),F=s.transformTo("string",o.utf8encode(S)),x=v.length!==B.name.length,Q=F.length!==S.length,D="",K="",N="",Y=B.dir,q=B.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}(B.unixPermissions,Y)):(tt=20,T|=function(V){return 63&(V||0)}(B.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(h,4)+y+D+U}}var s=d("../utils"),n=d("../stream/GenericWorker"),o=d("../utf8"),a=d("../crc32"),r=d("../signature");function l(c,g,p,h){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=p,this.encodeFileName=h,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,h=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-h-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(h){return r.DATA_DESCRIPTOR+e(h.crc32,4)+e(h.compressedSize,4)+e(h.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,h=function(I,u,f,C,B){var E=s.transformTo("string",B(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:h,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(d,A,t){"use strict";var e=d("../compressions"),i=d("./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,B=e[C];if(!B)throw new Error(C+" is not a valid compression method !");return B}(c.options.compression,n.compression),p=c.options.compressionOptions||n.compressionOptions||{},h=c.dir,I=c.date;c._compressWorker(g,p).withStreamInfo("file",{name:l,dir:h,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(d,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=d("./object")).loadAsync=d("./load"),e.support=d("./support"),e.defaults=d("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=d("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(d,A,t){"use strict";var e=d("./utils"),i=d("./external"),s=d("./utf8"),n=d("./zipEntries"),o=d("./stream/Crc32Probe"),a=d("./nodejsUtils");function r(l){return new i.Promise(function(c,g){var p=l.decompressed.getContentWorker().pipe(new o);p.on("error",function(h){g(h)}).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 h=new n(c);return h.load(p),h}).then(function(p){var h=[i.Promise.resolve(p)],I=p.files;if(c.checkCRC32)for(var u=0;u<I.length;u++)h.push(r(I[u]));return i.Promise.all(h)}).then(function(p){for(var h=p.shift(),I=h.files,u=0;u<I.length;u++){var f=I[u],C=f.fileNameStr,B=e.resolve(f.fileNameStr);g.file(B,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(B).unsafeOriginalName=C)}return h.zipComment.length&&(g.comment=h.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(d,A,t){"use strict";var e=d("../utils"),i=d("../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(d,A,t){"use strict";var e=d("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)})}d("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(d,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(d,A,t){"use strict";function e(B,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&&(B=I(B)),S.createFolders&&(y=h(B))&&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(B,E):s.prepareContent(B,E,S.binary,S.optimizedBinaryString,S.base64);var x=new l(B,F,S);this.files[B]=x}var i=d("./utf8"),s=d("./utils"),n=d("./stream/GenericWorker"),o=d("./stream/StreamHelper"),a=d("./defaults"),r=d("./compressedObject"),l=d("./zipObject"),c=d("./generate"),g=d("./nodejsUtils"),p=d("./nodejs/NodejsStreamInputAdapter"),h=function(B){B.slice(-1)==="/"&&(B=B.substring(0,B.length-1));var E=B.lastIndexOf("/");return 0<E?B.substring(0,E):""},I=function(B){return B.slice(-1)!=="/"&&(B+="/"),B},u=function(B,E){return E=E!==void 0?E:a.createFolders,B=I(B),this.files[B]||e.call(this,B,null,{dir:!0,createFolders:E}),this.files[B]};function f(B){return Object.prototype.toString.call(B)==="[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(B){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&&B(w,y)},filter:function(B){var E=[];return this.forEach(function(w,y){B(w,y)&&E.push(y)}),E},file:function(B,E,w){if(arguments.length!==1)return B=this.root+B,e.call(this,B,E,w),this;if(f(B)){var y=B;return this.filter(function(S,U){return!U.dir&&y.test(S)})}var v=this.files[this.root+B];return v&&!v.dir?v:null},folder:function(B){if(!B)return this;if(f(B))return this.filter(function(v,S){return S.dir&&B.test(v)});var E=this.root+B,w=u.call(this,E),y=this.clone();return y.root=w.name,y},remove:function(B){B=this.root+B;var E=this.files[B];if(E||(B.slice(-1)!=="/"&&(B+="/"),E=this.files[B]),E&&!E.dir)delete this.files[B];else for(var w=this.filter(function(v,S){return S.name.slice(0,B.length)===B}),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(B){var E,w={};try{if((w=s.extend(B||{},{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(B,E){return this.generateInternalStream(B).accumulate(E)},generateNodeStream:function(B,E){return(B=B||{}).type||(B.type="nodebuffer"),this.generateInternalStream(B).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(d,A,t){"use strict";A.exports=d("stream")},{stream:void 0}],17:[function(d,A,t){"use strict";var e=d("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}d("../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(d,A,t){"use strict";var e=d("../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(d,A,t){"use strict";var e=d("./Uint8ArrayReader");function i(s){e.call(this,s)}d("../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(d,A,t){"use strict";var e=d("./DataReader");function i(s){e.call(this,s)}d("../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(d,A,t){"use strict";var e=d("./ArrayReader");function i(s){e.call(this,s)}d("../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(d,A,t){"use strict";var e=d("../utils"),i=d("../support"),s=d("./ArrayReader"),n=d("./StringReader"),o=d("./NodeBufferReader"),a=d("./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(d,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(d,A,t){"use strict";var e=d("./GenericWorker"),i=d("../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(d,A,t){"use strict";var e=d("./GenericWorker"),i=d("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}d("../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(d,A,t){"use strict";var e=d("../utils"),i=d("./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(d,A,t){"use strict";var e=d("../utils"),i=d("./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(d,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(d,A,t){"use strict";var e=d("../utils"),i=d("./ConvertWorker"),s=d("./GenericWorker"),n=d("../base64"),o=d("../support"),a=d("../external"),r=null;if(o.nodestream)try{r=d("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(g,p){return new a.Promise(function(h,I){var u=[],f=g._internalType,C=g._outputType,B=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),B);h(E)}catch(w){I(w)}u=[]}).resume()})}function c(g,p,h){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=h,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 h=this;return g==="data"?this._worker.on(g,function(I){p.call(h,I.data,I.meta)}):this._worker.on(g,function(){e.delay(p,arguments,h)}),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(d,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=!!d("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(d,A,t){"use strict";for(var e=d("./utils"),i=d("./support"),s=d("./nodejsUtils"),n=d("./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,h,I,u,f,C=g.length,B=0;for(u=0;u<C;u++)(64512&(h=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(h=65536+(h-55296<<10)+(I-56320),u++),B+=h<128?1:h<2048?2:h<65536?3:4;for(p=i.uint8array?new Uint8Array(B):new Array(B),u=f=0;f<B;u++)(64512&(h=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(h=65536+(h-55296<<10)+(I-56320),u++),h<128?p[f++]=h:(h<2048?p[f++]=192|h>>>6:(h<65536?p[f++]=224|h>>>12:(p[f++]=240|h>>>18,p[f++]=128|h>>>12&63),p[f++]=128|h>>>6&63),p[f++]=128|63&h);return p}(c)},t.utf8decode=function(c){return i.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(g){var p,h,I,u,f=g.length,C=new Array(2*f);for(p=h=0;p<f;)if((I=g[p++])<128)C[h++]=I;else if(4<(u=o[I]))C[h++]=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[h++]=65533:I<65536?C[h++]=I:(I-=65536,C[h++]=55296|I>>10&1023,C[h++]=56320|1023&I)}return C.length!==h&&(C.subarray?C=C.subarray(0,h):C.length=h),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 h=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;h!==g.length&&(i.uint8array?(I=g.subarray(0,h),this.leftOver=g.subarray(h,g.length)):(I=g.slice(0,h),this.leftOver=g.slice(h,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(d,A,t){"use strict";var e=d("./support"),i=d("./base64"),s=d("./nodejsUtils"),n=d("./external");function o(p){return p}function a(p,h){for(var I=0;I<p.length;++I)h[I]=255&p.charCodeAt(I);return h}d("setimmediate"),t.newBlob=function(p,h){t.checkSupport("blob");try{return new Blob([p],{type:h})}catch{try{var I=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return I.append(p),I.getBlob(h)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,h,I){var u=[],f=0,C=p.length;if(C<=I)return String.fromCharCode.apply(null,p);for(;f<C;)h==="array"||h==="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 h="",I=0;I<p.length;I++)h+=String.fromCharCode(p[I]);return h},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 h=65536,I=t.getTypeOf(p),u=!0;if(I==="uint8array"?u=r.applyCanBeUsed.uint8array:I==="nodebuffer"&&(u=r.applyCanBeUsed.nodebuffer),u)for(;1<h;)try{return r.stringifyByChunk(p,I,h)}catch{h=Math.floor(h/2)}return r.stringifyByChar(p)}function c(p,h){for(var I=0;I<p.length;I++)h[I]=p[I];return h}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,h){if(h=h||"",!p)return h;t.checkSupport(p);var I=t.getTypeOf(h);return g[I][p](h)},t.resolve=function(p){for(var h=p.split("/"),I=[],u=0;u<h.length;u++){var f=h[u];f==="."||f===""&&u!==0&&u!==h.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 h,I,u="";for(I=0;I<(p||"").length;I++)u+="\\x"+((h=p.charCodeAt(I))<16?"0":"")+h.toString(16).toUpperCase();return u},t.delay=function(p,h,I){setImmediate(function(){p.apply(I||null,h||[])})},t.inherits=function(p,h){function I(){}I.prototype=h.prototype,p.prototype=new I},t.extend=function(){var p,h,I={};for(p=0;p<arguments.length;p++)for(h in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],h)&&I[h]===void 0&&(I[h]=arguments[p][h]);return I},t.prepareContent=function(p,h,I,u,f){return n.Promise.resolve(h).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(B,E){var w=new FileReader;w.onload=function(y){B(y.target.result)},w.onerror=function(y){E(y.target.error)},w.readAsArrayBuffer(C)}):C}).then(function(C){var B=t.getTypeOf(C);return B?(B==="arraybuffer"?C=t.transformTo("uint8array",C):B==="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(d,A,t){"use strict";var e=d("./reader/readerFor"),i=d("./utils"),s=d("./signature"),n=d("./zipEntry"),o=d("./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(d,A,t){"use strict";var e=d("./reader/readerFor"),i=d("./utils"),s=d("./compressedObject"),n=d("./crc32"),o=d("./utf8"),a=d("./compressions"),r=d("./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(h){for(var I in a)if(Object.prototype.hasOwnProperty.call(a,I)&&a[I].magic===h)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,h,I=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<I;)g=c.readInt(2),p=c.readInt(2),h=c.readData(p),this.extraFields[g]={id:g,length:p,value:h};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 h=this.findExtraFieldUnicodeComment();if(h!==null)this.fileCommentStr=h;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(d,A,t){"use strict";function e(g,p,h){this.name=g,this.dir=h.dir,this.date=h.date,this.comment=h.comment,this.unixPermissions=h.unixPermissions,this.dosPermissions=h.dosPermissions,this._data=p,this._dataBinary=h.binary,this.options={compression:h.compression,compressionOptions:h.compressionOptions}}var i=d("./stream/StreamHelper"),s=d("./stream/DataWorker"),n=d("./utf8"),o=d("./compressedObject"),a=d("./stream/GenericWorker");e.prototype={internalStream:function(g){var p=null,h="string";try{if(!g)throw new Error("No output type specified.");var I=(h=g.toLowerCase())==="string"||h==="text";h!=="binarystring"&&h!=="text"||(h="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,h,"")},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 h=this._decompressWorker();return this._dataBinary||(h=h.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(h,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(d,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,h;s=!0;for(var I=c.length;I;){for(h=c,c=[],p=-1;++p<I;)h[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(d,A,t){"use strict";var e=d("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(B){return s.reject(I,B)}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 B(w){f||(f=!0,s.resolve(I,w))}var E=h(function(){u(B,C)});E.status==="error"&&C(E.value)}function h(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=h(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 B=-1,E=I.queue.length;++B<E;)I.queue[B].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 B=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){B[U]=F,++E!==f||C||(C=!0,s.resolve(y,B))},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 B=-1,E=new this(i);++B<f;)w=I[B],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(d,A,t){"use strict";var e={};(0,d("./lib/utils/common").assign)(e,d("./lib/deflate"),d("./lib/inflate"),d("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(d,A,t){"use strict";var e=d("./zlib/deflate"),i=d("./utils/common"),s=d("./utils/strings"),n=d("./zlib/messages"),o=d("./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 h(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,B=this.strm,E=this.options.chunkSize;if(this.ended)return!1;C=u===~~u?u:u===!0?4:0,typeof I=="string"?B.input=s.string2buf(I):a.call(I)==="[object ArrayBuffer]"?B.input=new Uint8Array(I):B.input=I,B.next_in=0,B.avail_in=B.input.length;do{if(B.avail_out===0&&(B.output=new i.Buf8(E),B.next_out=0,B.avail_out=E),(f=e.deflate(B,C))!==1&&f!==r)return this.onEnd(f),!(this.ended=!0);B.avail_out!==0&&(B.avail_in!==0||C!==4&&C!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(i.shrinkBuf(B.output,B.next_out))):this.onData(i.shrinkBuf(B.output,B.next_out)))}while((0<B.avail_in||B.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),!(B.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=h,t.deflateRaw=function(I,u){return(u=u||{}).raw=!0,h(I,u)},t.gzip=function(I,u){return(u=u||{}).gzip=!0,h(I,u)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(d,A,t){"use strict";var e=d("./zlib/inflate"),i=d("./utils/common"),s=d("./utils/strings"),n=d("./zlib/constants"),o=d("./zlib/messages"),a=d("./zlib/zstream"),r=d("./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 h=this.options;h.raw&&0<=h.windowBits&&h.windowBits<16&&(h.windowBits=-h.windowBits,h.windowBits===0&&(h.windowBits=-15)),!(0<=h.windowBits&&h.windowBits<16)||p&&p.windowBits||(h.windowBits+=32),15<h.windowBits&&h.windowBits<48&&!(15&h.windowBits)&&(h.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,h.windowBits);if(I!==n.Z_OK)throw new Error(o[I]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,h){var I=new c(h);if(I.push(p,!0),I.err)throw I.msg||o[I.err];return I.result}c.prototype.push=function(p,h){var I,u,f,C,B,E,w=this.strm,y=this.options.chunkSize,v=this.options.dictionary,S=!1;if(this.ended)return!1;u=h===~~h?h:h===!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,B=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(B)):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,h){return(h=h||{}).raw=!0,g(p,h)},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(d,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(d,A,t){"use strict";var e=d("./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,h,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=h=0;h<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[h++]=c:(c<2048?l[h++]=192|c>>>6:(c<65536?l[h++]=224|c>>>12:(l[h++]=240|c>>>18,l[h++]=128|c>>>12&63),l[h++]=128|c>>>6&63),l[h++]=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,h,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<(h=n[p]))u[g++]=65533,c+=h-1;else{for(p&=h===2?31:h===3?15:7;1<h&&c<I;)p=p<<6|63&r[c++],h--;1<h?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(d,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(d,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(d,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(d,A,t){"use strict";var e,i=d("../utils/common"),s=d("./trees"),n=d("./adler32"),o=d("./crc32"),a=d("./messages"),r=0,l=4,c=0,g=-2,p=-1,h=4,I=2,u=8,f=9,C=286,B=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(m,J){return m.msg=a[J],J}function q(m){return(m<<1)-(4<m?9:0)}function _(m){for(var J=m.length;0<=--J;)m[J]=0}function L(m){var J=m.state,R=J.pending;R>m.avail_out&&(R=m.avail_out),R!==0&&(i.arraySet(m.output,J.pending_buf,J.pending_out,R,m.next_out),m.next_out+=R,J.pending_out+=R,m.total_out+=R,m.avail_out-=R,J.pending-=R,J.pending===0&&(J.pending_out=0))}function T(m,J){s._tr_flush_block(m,0<=m.block_start?m.block_start:-1,m.strstart-m.block_start,J),m.block_start=m.strstart,L(m.strm)}function tt(m,J){m.pending_buf[m.pending++]=J}function O(m,J){m.pending_buf[m.pending++]=J>>>8&255,m.pending_buf[m.pending++]=255&J}function V(m,J){var R,b,k=m.max_chain_length,H=m.strstart,z=m.prev_length,W=m.nice_match,G=m.strstart>m.w_size-U?m.strstart-(m.w_size-U):0,X=m.window,et=m.w_mask,Z=m.prev,it=m.strstart+S,ut=X[H+z-1],ht=X[H+z];m.prev_length>=m.good_match&&(k>>=2),W>m.lookahead&&(W=m.lookahead);do if(X[(R=J)+z]===ht&&X[R+z-1]===ut&&X[R]===X[H]&&X[++R]===X[H+1]){H+=2,R++;do;while(X[++H]===X[++R]&&X[++H]===X[++R]&&X[++H]===X[++R]&&X[++H]===X[++R]&&X[++H]===X[++R]&&X[++H]===X[++R]&&X[++H]===X[++R]&&X[++H]===X[++R]&&H<it);if(b=S-(it-H),H=it-S,z<b){if(m.match_start=J,W<=(z=b))break;ut=X[H+z-1],ht=X[H+z]}}while((J=Z[J&et])>G&&--k!=0);return z<=m.lookahead?z:m.lookahead}function rt(m){var J,R,b,k,H,z,W,G,X,et,Z=m.w_size;do{if(k=m.window_size-m.lookahead-m.strstart,m.strstart>=Z+(Z-U)){for(i.arraySet(m.window,m.window,Z,Z,0),m.match_start-=Z,m.strstart-=Z,m.block_start-=Z,J=R=m.hash_size;b=m.head[--J],m.head[J]=Z<=b?b-Z:0,--R;);for(J=R=Z;b=m.prev[--J],m.prev[J]=Z<=b?b-Z:0,--R;);k+=Z}if(m.strm.avail_in===0)break;if(z=m.strm,W=m.window,G=m.strstart+m.lookahead,X=k,et=void 0,et=z.avail_in,X<et&&(et=X),R=et===0?0:(z.avail_in-=et,i.arraySet(W,z.input,z.next_in,et,G),z.state.wrap===1?z.adler=n(z.adler,W,et,G):z.state.wrap===2&&(z.adler=o(z.adler,W,et,G)),z.next_in+=et,z.total_in+=et,et),m.lookahead+=R,m.lookahead+m.insert>=v)for(H=m.strstart-m.insert,m.ins_h=m.window[H],m.ins_h=(m.ins_h<<m.hash_shift^m.window[H+1])&m.hash_mask;m.insert&&(m.ins_h=(m.ins_h<<m.hash_shift^m.window[H+v-1])&m.hash_mask,m.prev[H&m.w_mask]=m.head[m.ins_h],m.head[m.ins_h]=H,H++,m.insert--,!(m.lookahead+m.insert<v)););}while(m.lookahead<U&&m.strm.avail_in!==0)}function gt(m,J){for(var R,b;;){if(m.lookahead<U){if(rt(m),m.lookahead<U&&J===r)return Q;if(m.lookahead===0)break}if(R=0,m.lookahead>=v&&(m.ins_h=(m.ins_h<<m.hash_shift^m.window[m.strstart+v-1])&m.hash_mask,R=m.prev[m.strstart&m.w_mask]=m.head[m.ins_h],m.head[m.ins_h]=m.strstart),R!==0&&m.strstart-R<=m.w_size-U&&(m.match_length=V(m,R)),m.match_length>=v)if(b=s._tr_tally(m,m.strstart-m.match_start,m.match_length-v),m.lookahead-=m.match_length,m.match_length<=m.max_lazy_match&&m.lookahead>=v){for(m.match_length--;m.strstart++,m.ins_h=(m.ins_h<<m.hash_shift^m.window[m.strstart+v-1])&m.hash_mask,R=m.prev[m.strstart&m.w_mask]=m.head[m.ins_h],m.head[m.ins_h]=m.strstart,--m.match_length!=0;);m.strstart++}else m.strstart+=m.match_length,m.match_length=0,m.ins_h=m.window[m.strstart],m.ins_h=(m.ins_h<<m.hash_shift^m.window[m.strstart+1])&m.hash_mask;else b=s._tr_tally(m,0,m.window[m.strstart]),m.lookahead--,m.strstart++;if(b&&(T(m,!1),m.strm.avail_out===0))return Q}return m.insert=m.strstart<v-1?m.strstart:v-1,J===l?(T(m,!0),m.strm.avail_out===0?K:N):m.last_lit&&(T(m,!1),m.strm.avail_out===0)?Q:D}function nt(m,J){for(var R,b,k;;){if(m.lookahead<U){if(rt(m),m.lookahead<U&&J===r)return Q;if(m.lookahead===0)break}if(R=0,m.lookahead>=v&&(m.ins_h=(m.ins_h<<m.hash_shift^m.window[m.strstart+v-1])&m.hash_mask,R=m.prev[m.strstart&m.w_mask]=m.head[m.ins_h],m.head[m.ins_h]=m.strstart),m.prev_length=m.match_length,m.prev_match=m.match_start,m.match_length=v-1,R!==0&&m.prev_length<m.max_lazy_match&&m.strstart-R<=m.w_size-U&&(m.match_length=V(m,R),m.match_length<=5&&(m.strategy===1||m.match_length===v&&4096<m.strstart-m.match_start)&&(m.match_length=v-1)),m.prev_length>=v&&m.match_length<=m.prev_length){for(k=m.strstart+m.lookahead-v,b=s._tr_tally(m,m.strstart-1-m.prev_match,m.prev_length-v),m.lookahead-=m.prev_length-1,m.prev_length-=2;++m.strstart<=k&&(m.ins_h=(m.ins_h<<m.hash_shift^m.window[m.strstart+v-1])&m.hash_mask,R=m.prev[m.strstart&m.w_mask]=m.head[m.ins_h],m.head[m.ins_h]=m.strstart),--m.prev_length!=0;);if(m.match_available=0,m.match_length=v-1,m.strstart++,b&&(T(m,!1),m.strm.avail_out===0))return Q}else if(m.match_available){if((b=s._tr_tally(m,0,m.window[m.strstart-1]))&&T(m,!1),m.strstart++,m.lookahead--,m.strm.avail_out===0)return Q}else m.match_available=1,m.strstart++,m.lookahead--}return m.match_available&&(b=s._tr_tally(m,0,m.window[m.strstart-1]),m.match_available=0),m.insert=m.strstart<v-1?m.strstart:v-1,J===l?(T(m,!0),m.strm.avail_out===0?K:N):m.last_lit&&(T(m,!1),m.strm.avail_out===0)?Q:D}function At(m,J,R,b,k){this.good_length=m,this.max_lazy=J,this.nice_length=R,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*B+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(m){var J;return m&&m.state?(m.total_in=m.total_out=0,m.data_type=I,(J=m.state).pending=0,J.pending_out=0,J.wrap<0&&(J.wrap=-J.wrap),J.status=J.wrap?F:x,m.adler=J.wrap===2?0:1,J.last_flush=r,s._tr_init(J),c):Y(m,g)}function mt(m){var J=ot(m);return J===c&&function(R){R.window_size=2*R.w_size,_(R.head),R.max_lazy_match=e[R.level].max_lazy,R.good_match=e[R.level].good_length,R.nice_match=e[R.level].nice_length,R.max_chain_length=e[R.level].max_chain,R.strstart=0,R.block_start=0,R.lookahead=0,R.insert=0,R.match_length=R.prev_length=v-1,R.match_available=0,R.ins_h=0}(m.state),J}function ft(m,J,R,b,k,H){if(!m)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||R!==u||b<8||15<b||J<0||9<J||H<0||h<H)return Y(m,g);b===8&&(b=9);var W=new lt;return(m.state=W).strm=m,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=R,mt(m)}e=[new At(0,0,0,0,function(m,J){var R=65535;for(R>m.pending_buf_size-5&&(R=m.pending_buf_size-5);;){if(m.lookahead<=1){if(rt(m),m.lookahead===0&&J===r)return Q;if(m.lookahead===0)break}m.strstart+=m.lookahead,m.lookahead=0;var b=m.block_start+R;if((m.strstart===0||m.strstart>=b)&&(m.lookahead=m.strstart-b,m.strstart=b,T(m,!1),m.strm.avail_out===0)||m.strstart-m.block_start>=m.w_size-U&&(T(m,!1),m.strm.avail_out===0))return Q}return m.insert=0,J===l?(T(m,!0),m.strm.avail_out===0?K:N):(m.strstart>m.block_start&&(T(m,!1),m.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(m,J){return ft(m,J,u,15,8,0)},t.deflateInit2=ft,t.deflateReset=mt,t.deflateResetKeep=ot,t.deflateSetHeader=function(m,J){return m&&m.state?m.state.wrap!==2?g:(m.state.gzhead=J,c):g},t.deflate=function(m,J){var R,b,k,H;if(!m||!m.state||5<J||J<0)return m?Y(m,g):g;if(b=m.state,!m.output||!m.input&&m.avail_in!==0||b.status===666&&J!==l)return Y(m,m.avail_out===0?-5:g);if(b.strm=m,R=b.last_flush,b.last_flush=J,b.status===F)if(b.wrap===2)m.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&&(m.adler=o(m.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,m.adler>>>16),O(b,65535&m.adler)),m.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&&(m.adler=o(m.adler,b.pending_buf,b.pending-k,k)),L(m),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&&(m.adler=o(m.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&&(m.adler=o(m.adler,b.pending_buf,b.pending-k,k)),L(m),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&&(m.adler=o(m.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&&(m.adler=o(m.adler,b.pending_buf,b.pending-k,k)),L(m),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&&(m.adler=o(m.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(m),b.pending+2<=b.pending_buf_size&&(tt(b,255&m.adler),tt(b,m.adler>>8&255),m.adler=0,b.status=x)):b.status=x),b.pending!==0){if(L(m),m.avail_out===0)return b.last_flush=-1,c}else if(m.avail_in===0&&q(J)<=q(R)&&J!==l)return Y(m,-5);if(b.status===666&&m.avail_in!==0)return Y(m,-5);if(m.avail_in!==0||b.lookahead!==0||J!==r&&b.status!==666){var W=b.strategy===2?function(G,X){for(var et;;){if(G.lookahead===0&&(rt(G),G.lookahead===0)){if(X===r)return Q;break}if(G.match_length=0,et=s._tr_tally(G,0,G.window[G.strstart]),G.lookahead--,G.strstart++,et&&(T(G,!1),G.strm.avail_out===0))return Q}return G.insert=0,X===l?(T(G,!0),G.strm.avail_out===0?K:N):G.last_lit&&(T(G,!1),G.strm.avail_out===0)?Q:D}(b,J):b.strategy===3?function(G,X){for(var et,Z,it,ut,ht=G.window;;){if(G.lookahead<=S){if(rt(G),G.lookahead<=S&&X===r)return Q;if(G.lookahead===0)break}if(G.match_length=0,G.lookahead>=v&&0<G.strstart&&(Z=ht[it=G.strstart-1])===ht[++it]&&Z===ht[++it]&&Z===ht[++it]){ut=G.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);G.match_length=S-(ut-it),G.match_length>G.lookahead&&(G.match_length=G.lookahead)}if(G.match_length>=v?(et=s._tr_tally(G,1,G.match_length-v),G.lookahead-=G.match_length,G.strstart+=G.match_length,G.match_length=0):(et=s._tr_tally(G,0,G.window[G.strstart]),G.lookahead--,G.strstart++),et&&(T(G,!1),G.strm.avail_out===0))return Q}return G.insert=0,X===l?(T(G,!0),G.strm.avail_out===0?K:N):G.last_lit&&(T(G,!1),G.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 m.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(m),m.avail_out===0))return b.last_flush=-1,c}return J!==l?c:b.wrap<=0?1:(b.wrap===2?(tt(b,255&m.adler),tt(b,m.adler>>8&255),tt(b,m.adler>>16&255),tt(b,m.adler>>24&255),tt(b,255&m.total_in),tt(b,m.total_in>>8&255),tt(b,m.total_in>>16&255),tt(b,m.total_in>>24&255)):(O(b,m.adler>>>16),O(b,65535&m.adler)),L(m),0<b.wrap&&(b.wrap=-b.wrap),b.pending!==0?c:1)},t.deflateEnd=function(m){var J;return m&&m.state?(J=m.state.status)!==F&&J!==69&&J!==73&&J!==91&&J!==103&&J!==x&&J!==666?Y(m,g):(m.state=null,J===x?Y(m,-3):c):g},t.deflateSetDictionary=function(m,J){var R,b,k,H,z,W,G,X,et=J.length;if(!m||!m.state||(H=(R=m.state).wrap)===2||H===1&&R.status!==F||R.lookahead)return g;for(H===1&&(m.adler=n(m.adler,J,et,0)),R.wrap=0,et>=R.w_size&&(H===0&&(_(R.head),R.strstart=0,R.block_start=0,R.insert=0),X=new i.Buf8(R.w_size),i.arraySet(X,J,et-R.w_size,R.w_size,0),J=X,et=R.w_size),z=m.avail_in,W=m.next_in,G=m.input,m.avail_in=et,m.next_in=0,m.input=J,rt(R);R.lookahead>=v;){for(b=R.strstart,k=R.lookahead-(v-1);R.ins_h=(R.ins_h<<R.hash_shift^R.window[b+v-1])&R.hash_mask,R.prev[b&R.w_mask]=R.head[R.ins_h],R.head[R.ins_h]=b,b++,--k;);R.strstart=b,R.lookahead=v-1,rt(R)}return R.strstart+=R.lookahead,R.block_start=R.strstart,R.insert=R.lookahead,R.lookahead=0,R.match_length=R.prev_length=v-1,R.match_available=0,m.next_in=W,m.input=G,m.avail_in=z,R.wrap=H,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(d,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(d,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,l,c,g,p,h,I,u,f,C,B,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,h=s.wnext,I=s.window,u=s.hold,f=s.bits,C=s.lencode,B=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=B[u&w];i:for(;;){if(u>>>=v=y>>>24,f-=v,!(16&(v=y>>>16&255))){if(!(64&v)){y=B[(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)===h){if(F+=g-v,v<S){for(S-=v;D[a++]=I[F++],--v;);F=a-U,x=D}}else if(h<v){if(F+=g+h-v,(v-=h)<S){for(S-=v;D[a++]=I[F++],--v;);if(F=0,h<S){for(S-=v=h;D[a++]=I[F++],--v;);F=a-U,x=D}}}else if(F+=h-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(d,A,t){"use strict";var e=d("../utils/common"),i=d("./adler32"),s=d("./crc32"),n=d("./inffast"),o=d("./inftrees"),a=1,r=2,l=0,c=-2,g=1,p=852,h=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(h),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 B(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=B(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=B,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,mt,ft,m,J,R,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,m=8+(15&(L>>>=4)),Q.wbits===0)Q.wbits=m;else if(m>Q.wbits){F.msg="invalid window size",Q.mode=30;break}Q.dmax=1<<m,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&&(m=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,m)),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;m=D[N+V++],Q.head&&m&&Q.length<65536&&(Q.head.name+=String.fromCharCode(m)),m&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,N)),q-=V,N+=V,m)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;m=D[N+V++],Q.head&&m&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(m)),m&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,N)),q-=V,N+=V,m)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,R={bits:Q.lenbits},J=o(0,Q.lens,0,19,Q.lencode,0,Q.work,R),Q.lenbits=R.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}m=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,m=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,m=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++]=m}}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,R={bits:Q.lenbits},J=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,R),Q.lenbits=R.bits,J){F.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,R={bits:Q.distbits},J=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,R),Q.distbits=R.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,mt=At,ft=lt;At=(k=Q.lencode[ft+((L&(1<<ot+mt)-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,mt=At,ft=lt;At=(k=Q.distcode[ft+((L&(1<<ot+mt)-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(d,A,t){"use strict";var e=d("../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,h,I){var u,f,C,B,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&&(h[V[r[l+x]]++]=x);if(w=a===0?(T=rt=h,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,B=(_=1<<(N=K))-1,a===1&&852<_||a===2&&592<_)return 1;for(;;){for(y=F-Y,S=h[x]<w?(v=0,h[x]):h[x]>w?(v=rt[gt+h[x]],T[tt+h[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+h[x]]}if(K<F&&(L&B)!==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&B]=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(d,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(d,A,t){"use strict";var e=d("../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,h=15,I=16,u=7,f=256,C=16,B=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,G){this.static_tree=k,this.extra_bits=H,this.extra_base=z,this.elems=W,this.max_length=G,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,G,X=new Array(h+1),et=0;for(W=1;W<=h;W++)X[W]=et=et+z[W-1]<<1;for(G=0;G<=H;G++){var Z=k[2*G+1];Z!==0&&(k[2*G]=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 G=2*H,X=2*z;return k[G]<k[X]||k[G]===k[X]&&W[H]<=W[z]}function ot(k,H,z){for(var W=k.heap[z],G=z<<1;G<=k.heap_len&&(G<k.heap_len&<(H,k.heap[G+1],k.heap[G],k.depth)&&G++,!lt(H,W,k.heap[G],k.depth));)k.heap[z]=k.heap[G],z=G,G<<=1;k.heap[z]=W}function mt(k,H,z){var W,G,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],G=k.pending_buf[k.l_buf+Z],Z++,W===0?V(k,G,H):(V(k,(X=Q[G])+r+1,H),(et=w[X])!==0&&O(k,G-=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,G,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*(G=k.heap[++k.heap_len]=ut<2?++ut:0)]=1,k.depth[G]=0,k.opt_len--,Z&&(k.static_len-=et[2*G+1]);for(H.max_code=ut,z=k.heap_len>>1;1<=z;z--)ot(k,X,z);for(G=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*G]=X[2*z]+X[2*W],k.depth[G]=(k.depth[z]>=k.depth[W]?k.depth[z]:k.depth[W])+1,X[2*z+1]=X[2*W+1]=G,k.heap[1]=G++,ot(k,X,1),2<=k.heap_len;);k.heap[--k.heap_max]=k.heap[1],function(ht,Tt){var Ve,qt,We,Qt,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,$e=Tt.stat_desc.max_length,Fi=0;for(Qt=0;Qt<=h;Qt++)ht.bl_count[Qt]=0;for(zt[2*ht.heap[ht.heap_max]+1]=0,Ve=ht.heap_max+1;Ve<p;Ve++)$e<(Qt=zt[2*zt[2*(qt=ht.heap[Ve])+1]+1]+1)&&(Qt=$e,Fi++),zt[2*qt+1]=Qt,Dn<qt||(ht.bl_count[Qt]++,vi=0,bn<=qt&&(vi=jo[qt-bn]),bs=zt[2*qt],ht.opt_len+=bs*(Qt+vi),_o&&(ht.static_len+=bs*(Zo[2*qt+1]+vi)));if(Fi!==0){do{for(Qt=$e-1;ht.bl_count[Qt]===0;)Qt--;ht.bl_count[Qt]--,ht.bl_count[Qt+1]+=2,ht.bl_count[$e]--,Fi-=2}while(0<Fi);for(Qt=$e;Qt!==0;Qt--)for(qt=ht.bl_count[Qt];qt!==0;)Dn<(We=ht.heap[--Ve])||(zt[2*We+1]!==Qt&&(ht.opt_len+=(Qt-zt[2*We+1])*zt[2*We],zt[2*We+1]=Qt),qt--)}}(k,H),gt(X,ut,k.bl_count)}function m(k,H,z){var W,G,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++)G=et,et=H[2*(W+1)+1],++Z<it&&G===et||(Z<ut?k.bl_tree[2*G]+=Z:G!==0?(G!==X&&k.bl_tree[2*G]++,k.bl_tree[2*C]++):Z<=10?k.bl_tree[2*B]++:k.bl_tree[2*E]++,X=G,ut=(Z=0)===et?(it=138,3):G===et?(it=6,3):(it=7,4))}function J(k,H,z){var W,G,X=-1,et=H[1],Z=0,it=7,ut=4;for(et===0&&(it=138,ut=3),W=0;W<=z;W++)if(G=et,et=H[2*(W+1)+1],!(++Z<it&&G===et)){if(Z<ut)for(;V(k,G,k.bl_tree),--Z!=0;);else G!==0?(G!==X&&(V(k,G,k.bl_tree),Z--),V(k,C,k.bl_tree),O(k,Z-3,2)):Z<=10?(V(k,B,k.bl_tree),O(k,Z-3,3)):(V(k,E,k.bl_tree),O(k,Z-11,7));X=G,ut=(Z=0)===et?(it=138,3):G===et?(it=6,3):(it=7,4)}}n(q);var R=!1;function b(k,H,z,W){O(k,(o<<1)+(W?1:0),3),function(G,X,et,Z){At(G),Z&&(tt(G,et),tt(G,~et)),e.arraySet(G.pending_buf,G.window,X,et,G.pending),G.pending+=et}(k,H,z,!0)}t._tr_init=function(k){R||(function(){var H,z,W,G,X,et=new Array(h+1);for(G=W=0;G<a-1;G++)for(D[G]=W,H=0;H<1<<w[G];H++)Q[W++]=G;for(Q[W-1]=G,G=X=0;G<16;G++)for(q[G]=X,H=0;H<1<<y[G];H++)x[X++]=G;for(X>>=7;G<c;G++)for(q[G]=X<<7,H=0;H<1<<y[G]-7;H++)x[256+X++]=G;for(z=0;z<=h;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,h),N=new _(F,y,0,c,h),Y=new _(new Array(0),v,0,g,u)}(),R=!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 G,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(m(Z,Z.dyn_ltree,Z.l_desc.max_code),m(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),G=k.opt_len+3+7>>>3,(X=k.static_len+3+7>>>3)<=G&&(G=X)):G=X=z+5,z+4<=G&&H!==-1?b(k,H,z,W):k.strategy===4||X===G?(O(k,2+(W?1:0),3),mt(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),mt(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(d,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(d,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,h=Object.getPrototypeOf&&Object.getPrototypeOf(i);h=h&&h.setTimeout?h:i,n={}.toString.call(i.process)==="[object process]"?function(C){process.nextTick(function(){u(C)})}:function(){if(i.postMessage&&!i.importScripts){var C=!0,B=i.onmessage;return i.onmessage=function(){C=!1},i.postMessage("","*"),i.onmessage=B,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 B=p.createElement("script");B.onreadystatechange=function(){u(C),B.onreadystatechange=null,o.removeChild(B),B=null},o.appendChild(B)}):function(C){setTimeout(u,0,C)},h.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var B=new Array(arguments.length-1),E=0;E<B.length;E++)B[E]=arguments[E+1];var w={callback:C,args:B};return c[l]=w,n(l),l++},h.clearImmediate=I}function I(C){delete c[C]}function u(C){if(g)setTimeout(u,0,C);else{var B=c[C];if(B){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)}})(B)}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");Et();var Dt=require("obsidian");var Bt=require("obsidian");Et();function bi(d){let A=(d.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function Vt(d,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(d))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(d))}}function Ce(d,A){let t=bi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Pn(d,A,!0);case"us":return Vt(d,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Vt(d,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Vt(d,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Vt(d,{...t,dateStyle:"medium",timeStyle:"short"})}}function Tn(d,A){let t=bi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Pn(d,A,!1);case"us":return Vt(d,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Vt(d,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Vt(d,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(d).getFullYear()===e.getFullYear();return Vt(d,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Un(d,A){let t=bi(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return Vt(d,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Pn(d,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(d)),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 Ee(d,A,t){let e=d.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 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 ee}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(li)){let g=li[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,h)=>this.renderPinnedRow(e,p,h));return}let l=new Map;a.forEach((p,h)=>{let I=l.get(p.folder);I||(I=[],l.set(p.folder,I)),I.push({pin:p,idx:h})});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 h=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:h});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 B=p.getBoundingClientRect(),E=C.clientY-B.top<B.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 B=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(B)||B===i)return;let E=p.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(B,w?i:i+1)});let h=p.createSpan({cls:"stashpad-pinned-toggle"});c&&(Ee(h,l,g),h.onclick=C=>{C.stopPropagation();let B=`${e.folder}|${e.id}`;this.expanded.has(B)?this.expanded.delete(B):this.expanded.add(B),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 B=new Bt.Menu;B.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),B.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,h=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&&(Ee(u,g,h),u.onclick=B=>{B.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&&h&&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 Bt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Mt(),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 h=o.createEl("button",{cls:"stashpad-shared-chip",text:c});return g&&h.addClass("is-active"),h.onclick=p,h};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[h,I]of n){let u=c.createEl("option",{text:I});u.value=h}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=p,c.onchange=()=>{let h=c.value;h==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=h,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 h=g.createSpan({cls:"stashpad-pinned-label",text:c.title});h.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(B=>typeof B=="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 h=[...new Set(i.map(N=>N.folder))].sort((N,Y)=>N.localeCompare(Y));this.taskFolderFilter!=="all"&&!h.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 h){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,B=i.filter(N=>o(N)&&C(N));if(B.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 B){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=B.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,Bt.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,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?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 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===M)continue;let r=o.completed===!0,l=Se(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:Ze(o),assignedBy:se(o.assignedBy)})}return i}};async function Ui(d){let A=d.workspace.getLeavesOfType(ee);if(A.length>0){d.workspace.revealLeaf(A[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new Bt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:ee,active:!0}),d.workspace.revealLeaf(t)}var No=require("obsidian");Et();var j=require("obsidian");di();var Li=require("obsidian");Et();var He=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!=="/"&&Xe.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()}};Et();Mt();var we=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)."},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 we.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(d,A,t){let e=d.vault.getAbstractFileByPath(A);if(!(e instanceof we.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=d.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;d.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=we.Platform.isMacOS?"Finder":we.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=d.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(d){if(!d)return"(none)";let A=d.replace(/\bMod\b/g,Ks?"Cmd":"Ctrl");return Ks&&(A=A.replace(/\bAlt\b/g,"Option")),A}function Wn(d,A,t={allowSingleKey:!0}){let e=d.placeholder,i=d.value;d.placeholder="Press a key\u2026 (Backspace to cancel)",d.value="",d.classList.add("is-recording");let s=!1,n=()=>{d.placeholder=e,d.classList.remove("is-recording"),s||(d.value=i),d.removeEventListener("keydown",o,!0),d.removeEventListener("blur",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 d.addEventListener("keydown",o,!0),d.addEventListener("blur",a),n}function fa(d,A){if(!d)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return d.length===1?d.toUpperCase():d}xe();Kt();function ve(d,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(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(d,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 ve(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,Ba=$s.TextEncoder?new $s.TextEncoder:null;function to(d,A){return(d&15)+(d>>6|d>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function eo(d,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;d[e]=to(A.charCodeAt(i),A.charCodeAt(i+1))}}function ma(d,A){if(d.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==to(d.charCodeAt(e),d.charCodeAt(e+1)))return!1}return!0}var $n=87,Xn=48;function Xs(d,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;d[e++]=s>9?s+$n:s+Xn,s=A[i]&15,d[e++]=s>9?s+$n:s+Xn}return String.fromCharCode.apply(null,d)}var Xt=zs!==null?d=>{if(typeof d=="string"){let A=zs.from(d,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(zs.isBuffer(d))return new Uint8Array(d.buffer,d.byteOffset,d.length);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")}:d=>{if(typeof d=="string")return Ba.encode(d);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")},Gt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pi=new Uint8Array(256);for(let d=0;d<Gt.length;d++)pi[Gt.charCodeAt(d)]=d;function Zn(d,A=!0){let t=d.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(d[n]<<16&16711680)+(d[n+1]<<8&65280)+(d[n+2]&255),a=Gt.charAt(o>>18&63)+Gt.charAt(o>>12&63)+Gt.charAt(o>>6&63)+Gt.charAt(o&63);i.push(a)}if(e===1){let n=d[t-1],o=Gt.charAt(n>>2),a=Gt.charAt(n<<4&63);i.push(`${o}${a}`),A&&i.push("==")}else if(e===2){let n=(d[t-2]<<8)+d[t-1],o=Gt.charAt(n>>10),a=Gt.charAt(n>>4&63),r=Gt.charAt(n<<2&63);i.push(`${o}${a}${r}`),A&&i.push("=")}return i.join("")}function Qa(d){let A=Math.floor(d.length*.75),t=d.length;return d[t-1]==="="&&(A-=1,d[t-2]==="="&&(A-=1)),A}function Ea(d){let A=Qa(d),t=d.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=pi[d.charCodeAt(s)],o=pi[d.charCodeAt(s+1)],a=pi[d.charCodeAt(s+2)],r=pi[d.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(d,A){return ve(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(()=>ve(this,void 0,void 0,function*(){if(!Vs.has(d.name)){let v=Ea(d.data),S=WebAssembly.compile(v);Vs.set(d.name,S)}let y=yield Vs.get(d.name);t=yield WebAssembly.instantiate(y,{})})),c=()=>ve(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)}},h=y=>{if(!i)throw new Error("update() called before init()");let v=Xt(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,d.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(!ma(d.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},B=y=>typeof y=="string"?y.length<Oi/4:y.byteLength<Oi,E=B;switch(d.name){case"argon2":case"scrypt":E=()=>!0;break;case"blake2b":case"blake2s":E=(y,v)=>v<=512&&B(y);break;case"blake3":E=(y,v)=>v===0&&B(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),h(y),u("hex",S);let U=Xt(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:h,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(d){return!Number.isInteger(d)||d<8||d>512||d%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function xa(d,A){return d|A<<16}function Zs(d=512,A=null){if(_n(d))return Promise.reject(_n(d));let t=null,e=d;if(A!==null){if(t=Xt(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=xa(d,t.length)}let i=d/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(d,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${Zn(d,!1)}$${Zn(t,!1)}`}var jn=new DataView(new ArrayBuffer(4));function $t(d){return jn.setInt32(0,d,!0),new Uint8Array(jn.buffer)}function Ws(d,A,t){return ve(this,void 0,void 0,function*(){if(t<=64){let a=yield Zs(t*8);return a.update($t(t)),a.update(A),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);d.init(),d.update($t(t)),d.update(A);let s=d.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)d.init(),d.update(s),s=d.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=d,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(d){switch(d){case"d":return 0;case"i":return 1;default:return 2}}function Ta(d){return ve(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=d,s=Xt(d.password),n=Xt(d.salt),o=19,a=Ha(d.hashType),{memorySize:r}=d,l=Xt((A=d.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),h=new DataView(p.buffer);h.setInt32(0,t,!0),h.setInt32(4,i,!0),h.setInt32(8,r,!0),h.setInt32(12,e,!0),h.setInt32(16,o,!0),h.setInt32(20,a,!0),c.writeMemory(p,r*1024),g.init(),g.update(p),g.update($t(s.length)),g.update(s),g.update($t(n.length)),g.update(n),g.update($t(l.length)),g.update(l),g.update($t(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($t(0),64),f.set($t(w),68);let y=w*u,v=yield Ws(g,f,1024);c.writeMemory(v,y*1024),y+=1,f.set($t(1),64),v=yield Ws(g,f,1024),c.writeMemory(v,y*1024)}let B=new Uint8Array(1024);eo(B,c.calculate(new Uint8Array([]),r));let E=yield Ws(g,B,i);if(d.outputType==="hex"){let w=new Uint8Array(i*2);return Xs(w,E,i)}return d.outputType==="encoded"?Ma(n,d,E):E})}var Ua=d=>{var A;if(!d||typeof d!="object")throw new Error("Invalid options parameter. It requires an object.");if(!d.password)throw new Error("Password must be specified");if(d.password=Xt(d.password),d.password.length<1)throw new Error("Password must be specified");if(!d.salt)throw new Error("Salt must be specified");if(d.salt=Xt(d.salt),d.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(d.secret=Xt((A=d.secret)!==null&&A!==void 0?A:""),!Number.isInteger(d.iterations)||d.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(d.parallelism)||d.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(d.hashLength)||d.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(d.memorySize))throw new Error("Memory size should be specified.");if(d.memorySize<8*d.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(d.outputType===void 0&&(d.outputType="hex"),!["hex","binary","encoded"].includes(d.outputType))throw new Error(`Insupported output type ${d.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function _s(d){return ve(this,void 0,void 0,function*(){return Ua(d),Ta(Object.assign(Object.assign({},d),{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 BA=new Ct;Mt();var Rt=new Uint8Array([83,84,65,83,72,69,78,67]),en=2,sn=1,nn=2,oo=3,Pa=32,Te=12,js=32,Ga=6e5,Ra=47104,La=3,Ja=1,wt=d=>d;function Lt(d){if(d.length<Rt.length+1)return!1;for(let A=0;A<Rt.length;A++)if(d[A]!==Rt[A])return!1;return!0}function so(d,A,t){d[A]=t>>>24&255,d[A+1]=t>>>16&255,d[A+2]=t>>>8&255,d[A+3]=t&255}function no(d,A){return d[A]*16777216+(d[A+1]<<16)+(d[A+2]<<8)+d[A+3]}async function tn(d,A,t){if(t.id===nn)return await _s({password:d,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(d)),"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(d){return crypto.subtle.importKey("raw",wt(d),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var ao={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function ui(d,A){let t=crypto.getRandomValues(new Uint8Array(Pa)),e=crypto.getRandomValues(new Uint8Array(Te)),i,s,n;try{i={id:nn,a:Ra,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:Ga,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(d))),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(d,A,t){let e=new Uint8Array(Rt.length+1+1+4+4+1+1+A.length+t.length),i=0;return e.set(Rt,i),i+=Rt.length,e[i++]=en,e[i++]=d.id,so(e,i,d.a),i+=4,so(e,i,d.b),i+=4,e[i++]=d.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function Ue(d,A){if(!Lt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Rt.length];if(t===1)return qa(d,A);if(t!==en)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Rt.length+1,i={id:d[e++],a:0,b:0,c:0};if(i.a=no(d,e),e+=4,i.b=no(d,e),e+=4,i.c=d[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=d[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=d.slice(e,e+s);e+=s;let o=d.slice(e,e+Te);e+=Te;let a=d.slice(0,e),r=d.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(d,A){let t=Rt.length+1,e=d.slice(t,t+16);t+=16;let i=d.slice(t,t+12);t+=12;let s=d.slice(t),n=await crypto.subtle.importKey("raw",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(d,A){if(A.length!==js)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Te)),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(d))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function ne(d,A){if(!Lt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Rt.length];if(t!==en)throw new Error(`Unsupported encrypted version (${t}).`);let e=Rt.length+1;if(d[e++]!==oo)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=d[e++];e+=s;let n=d.slice(e,e+Te);e+=Te;let o=d.slice(0,e),a=d.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 Pe(d,A,t={}){if(!Lt(A))return A;if(t.secretId){let i=d.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Ue(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new ii(d,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Ue(A,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}var Ci="stashpad-vault-encryption";function Bi(){return{wrappedKey:null,kdf:null}}function Ao(d){let A="";for(let t=0;t<d.length;t++)A+=String.fromCharCode(d[t]);return btoa(A)}function on(d){let A=atob(d),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}var 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 Ue(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 Ue(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 Ue(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(Bi())}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();Et();var oe="stash",go=1;function co(d){let t=(d.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var rn=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function mi(d,A){let t=new An.default,e=Ka([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await d.vault.read(o.file),r=a,l=po(a);for(let c of l){let g=d.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 d.vault.readBinary(g)),r=Ya(r,c,p)}r=Wa(r,d,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 Zt(d,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(d,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}=Ht(S),x=co(v.name.slice(6))||`${U.id||"imported-"+yt(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}-${yt(4)}-Imported`),c++):l.set(S,S))}let g=new Date().toISOString(),p=[],h=`${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 d.vault.getFiles())C.has(v.name)||C.set(v.name,v.path)}let B=(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=`${h}/${S}`;await d.vault.adapter.exists(Q)&&F.push(Q);let D=null;for(let N of F)try{if(B(new Uint8Array(await d.vault.adapter.readBinary(N)),U)){D=N;break}}catch{}if(D){f.set(S,D);continue}let K=Q;for(let N=1;await d.vault.adapter.exists(K);N++)K=`${h}/${za(S,N)}`;f.set(S,K),E||(await ho(d,h),E=!0),await d.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,h),D={...v.fm,id:U,parent:x,import_date:g};Array.isArray(D.attachments)&&(D.attachments=D.attachments.map(q=>{let _=uo(fe(q));return Ot(f.get(_)??`${h}/${_}`)}));let K=ae(D,Q),N=U===S?v.originalName:Xa(v.originalName,S,U),Y=`${t}/${N}`;await d.vault.adapter.exists(Y)&&(N=`${N.replace(/\.md$/,"")}-${yt(4)}.md`,Y=`${t}/${N}`),await d.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(d){let A=new Set,t=[];for(let e of d)A.has(e.id)||(A.add(e.id),t.push(e));return t}function po(d){let A=new Set,t;for(rn.lastIndex=0;(t=rn.exec(d))!==null;)A.add(t[1]);return[...A]}async function Io(d,A){let t=await d.vault.read(A),e=[],i=new Set;for(let s of po(t)){let n=d.metadataCache.getFirstLinkpathDest(s,A.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Ya(d,A,t){return d.replace(new RegExp(`!\\[\\[${$a(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function za(d,A){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${A}${d.slice(t)}`:`${d}-${A}`}function Va(d,A,t){return d.replace(rn,(e,i,s)=>{if(i.includes("/"))return e;let n=A.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Wa(d,A,t){let e=Ht(d);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return d;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:uo(n)}),s={...e.fm,attachments:i};return ae(s,e.body)}function $a(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uo(d){let A=d.lastIndexOf("/");return A<0?d:d.slice(A+1)}function Xa(d,A,t){return d.includes(A)?d.replace(A,t):d.replace(/\.md$/,`-${t}.md`)}function Ht(d){if(!d.startsWith("---"))return{fm:{},body:d};let A=d.indexOf(` +`}function Ri(d,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=d.vault.getAbstractFileByPath(A.previewPath);a instanceof kt.TFile&&await d.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();xe();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(d){typeof lo=="object"&&typeof an<"u"?an.exports=d():typeof define=="function"&&define.amd?define([],d):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=d()})(function(){return function d(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,d,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(d,A,t){"use strict";var e=d("./utils"),i=d("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,l,c,g,p,h=[],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,h.push(s.charAt(l)+s.charAt(c)+s.charAt(g)+s.charAt(p));return h.join("")},t.decode=function(n){var o,a,r,l,c,g,p=0,h=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[h++]=o,c!==64&&(u[h++]=a),g!==64&&(u[h++]=r);return u}},{"./support":30,"./utils":32}],2:[function(d,A,t){"use strict";var e=d("./external"),i=d("./stream/DataWorker"),s=d("./stream/Crc32Probe"),n=d("./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(d,A,t){"use strict";var e=d("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=d("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(d,A,t){"use strict";var e=d("./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(d,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(d,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:d("lie"),A.exports={Promise:e}},{lie:37}],7:[function(d,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=d("pako"),s=d("./utils"),n=d("./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(d,A,t){"use strict";function e(c,g){var p,h="";for(p=0;p<g;p++)h+=String.fromCharCode(255&c),c>>>=8;return h}function i(c,g,p,h,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(h,4)+y+D+U}}var s=d("../utils"),n=d("../stream/GenericWorker"),o=d("../utf8"),a=d("../crc32"),r=d("../signature");function l(c,g,p,h){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=p,this.encodeFileName=h,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,h=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-h-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(h){return r.DATA_DESCRIPTOR+e(h.crc32,4)+e(h.compressedSize,4)+e(h.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,h=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:h,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(d,A,t){"use strict";var e=d("../compressions"),i=d("./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||{},h=c.dir,I=c.date;c._compressWorker(g,p).withStreamInfo("file",{name:l,dir:h,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(d,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=d("./object")).loadAsync=d("./load"),e.support=d("./support"),e.defaults=d("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=d("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(d,A,t){"use strict";var e=d("./utils"),i=d("./external"),s=d("./utf8"),n=d("./zipEntries"),o=d("./stream/Crc32Probe"),a=d("./nodejsUtils");function r(l){return new i.Promise(function(c,g){var p=l.decompressed.getContentWorker().pipe(new o);p.on("error",function(h){g(h)}).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 h=new n(c);return h.load(p),h}).then(function(p){var h=[i.Promise.resolve(p)],I=p.files;if(c.checkCRC32)for(var u=0;u<I.length;u++)h.push(r(I[u]));return i.Promise.all(h)}).then(function(p){for(var h=p.shift(),I=h.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 h.zipComment.length&&(g.comment=h.zipComment),g})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(d,A,t){"use strict";var e=d("../utils"),i=d("../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(d,A,t){"use strict";var e=d("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)})}d("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(d,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(d,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=h(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=d("./utf8"),s=d("./utils"),n=d("./stream/GenericWorker"),o=d("./stream/StreamHelper"),a=d("./defaults"),r=d("./compressedObject"),l=d("./zipObject"),c=d("./generate"),g=d("./nodejsUtils"),p=d("./nodejs/NodejsStreamInputAdapter"),h=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(d,A,t){"use strict";A.exports=d("stream")},{stream:void 0}],17:[function(d,A,t){"use strict";var e=d("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}d("../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(d,A,t){"use strict";var e=d("../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(d,A,t){"use strict";var e=d("./Uint8ArrayReader");function i(s){e.call(this,s)}d("../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(d,A,t){"use strict";var e=d("./DataReader");function i(s){e.call(this,s)}d("../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(d,A,t){"use strict";var e=d("./ArrayReader");function i(s){e.call(this,s)}d("../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(d,A,t){"use strict";var e=d("../utils"),i=d("../support"),s=d("./ArrayReader"),n=d("./StringReader"),o=d("./NodeBufferReader"),a=d("./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(d,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(d,A,t){"use strict";var e=d("./GenericWorker"),i=d("../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(d,A,t){"use strict";var e=d("./GenericWorker"),i=d("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}d("../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(d,A,t){"use strict";var e=d("../utils"),i=d("./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(d,A,t){"use strict";var e=d("../utils"),i=d("./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(d,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(d,A,t){"use strict";var e=d("../utils"),i=d("./ConvertWorker"),s=d("./GenericWorker"),n=d("../base64"),o=d("../support"),a=d("../external"),r=null;if(o.nodestream)try{r=d("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(g,p){return new a.Promise(function(h,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);h(E)}catch(w){I(w)}u=[]}).resume()})}function c(g,p,h){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=h,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 h=this;return g==="data"?this._worker.on(g,function(I){p.call(h,I.data,I.meta)}):this._worker.on(g,function(){e.delay(p,arguments,h)}),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(d,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=!!d("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(d,A,t){"use strict";for(var e=d("./utils"),i=d("./support"),s=d("./nodejsUtils"),n=d("./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,h,I,u,f,C=g.length,m=0;for(u=0;u<C;u++)(64512&(h=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(h=65536+(h-55296<<10)+(I-56320),u++),m+=h<128?1:h<2048?2:h<65536?3:4;for(p=i.uint8array?new Uint8Array(m):new Array(m),u=f=0;f<m;u++)(64512&(h=g.charCodeAt(u)))==55296&&u+1<C&&(64512&(I=g.charCodeAt(u+1)))==56320&&(h=65536+(h-55296<<10)+(I-56320),u++),h<128?p[f++]=h:(h<2048?p[f++]=192|h>>>6:(h<65536?p[f++]=224|h>>>12:(p[f++]=240|h>>>18,p[f++]=128|h>>>12&63),p[f++]=128|h>>>6&63),p[f++]=128|63&h);return p}(c)},t.utf8decode=function(c){return i.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(g){var p,h,I,u,f=g.length,C=new Array(2*f);for(p=h=0;p<f;)if((I=g[p++])<128)C[h++]=I;else if(4<(u=o[I]))C[h++]=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[h++]=65533:I<65536?C[h++]=I:(I-=65536,C[h++]=55296|I>>10&1023,C[h++]=56320|1023&I)}return C.length!==h&&(C.subarray?C=C.subarray(0,h):C.length=h),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 h=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;h!==g.length&&(i.uint8array?(I=g.subarray(0,h),this.leftOver=g.subarray(h,g.length)):(I=g.slice(0,h),this.leftOver=g.slice(h,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(d,A,t){"use strict";var e=d("./support"),i=d("./base64"),s=d("./nodejsUtils"),n=d("./external");function o(p){return p}function a(p,h){for(var I=0;I<p.length;++I)h[I]=255&p.charCodeAt(I);return h}d("setimmediate"),t.newBlob=function(p,h){t.checkSupport("blob");try{return new Blob([p],{type:h})}catch{try{var I=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return I.append(p),I.getBlob(h)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,h,I){var u=[],f=0,C=p.length;if(C<=I)return String.fromCharCode.apply(null,p);for(;f<C;)h==="array"||h==="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 h="",I=0;I<p.length;I++)h+=String.fromCharCode(p[I]);return h},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 h=65536,I=t.getTypeOf(p),u=!0;if(I==="uint8array"?u=r.applyCanBeUsed.uint8array:I==="nodebuffer"&&(u=r.applyCanBeUsed.nodebuffer),u)for(;1<h;)try{return r.stringifyByChunk(p,I,h)}catch{h=Math.floor(h/2)}return r.stringifyByChar(p)}function c(p,h){for(var I=0;I<p.length;I++)h[I]=p[I];return h}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,h){if(h=h||"",!p)return h;t.checkSupport(p);var I=t.getTypeOf(h);return g[I][p](h)},t.resolve=function(p){for(var h=p.split("/"),I=[],u=0;u<h.length;u++){var f=h[u];f==="."||f===""&&u!==0&&u!==h.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 h,I,u="";for(I=0;I<(p||"").length;I++)u+="\\x"+((h=p.charCodeAt(I))<16?"0":"")+h.toString(16).toUpperCase();return u},t.delay=function(p,h,I){setImmediate(function(){p.apply(I||null,h||[])})},t.inherits=function(p,h){function I(){}I.prototype=h.prototype,p.prototype=new I},t.extend=function(){var p,h,I={};for(p=0;p<arguments.length;p++)for(h in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],h)&&I[h]===void 0&&(I[h]=arguments[p][h]);return I},t.prepareContent=function(p,h,I,u,f){return n.Promise.resolve(h).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(d,A,t){"use strict";var e=d("./reader/readerFor"),i=d("./utils"),s=d("./signature"),n=d("./zipEntry"),o=d("./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(d,A,t){"use strict";var e=d("./reader/readerFor"),i=d("./utils"),s=d("./compressedObject"),n=d("./crc32"),o=d("./utf8"),a=d("./compressions"),r=d("./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(h){for(var I in a)if(Object.prototype.hasOwnProperty.call(a,I)&&a[I].magic===h)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,h,I=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<I;)g=c.readInt(2),p=c.readInt(2),h=c.readData(p),this.extraFields[g]={id:g,length:p,value:h};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 h=this.findExtraFieldUnicodeComment();if(h!==null)this.fileCommentStr=h;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(d,A,t){"use strict";function e(g,p,h){this.name=g,this.dir=h.dir,this.date=h.date,this.comment=h.comment,this.unixPermissions=h.unixPermissions,this.dosPermissions=h.dosPermissions,this._data=p,this._dataBinary=h.binary,this.options={compression:h.compression,compressionOptions:h.compressionOptions}}var i=d("./stream/StreamHelper"),s=d("./stream/DataWorker"),n=d("./utf8"),o=d("./compressedObject"),a=d("./stream/GenericWorker");e.prototype={internalStream:function(g){var p=null,h="string";try{if(!g)throw new Error("No output type specified.");var I=(h=g.toLowerCase())==="string"||h==="text";h!=="binarystring"&&h!=="text"||(h="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,h,"")},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 h=this._decompressWorker();return this._dataBinary||(h=h.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(h,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(d,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,h;s=!0;for(var I=c.length;I;){for(h=c,c=[],p=-1;++p<I;)h[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(d,A,t){"use strict";var e=d("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=h(function(){u(m,C)});E.status==="error"&&C(E.value)}function h(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=h(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(d,A,t){"use strict";var e={};(0,d("./lib/utils/common").assign)(e,d("./lib/deflate"),d("./lib/inflate"),d("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(d,A,t){"use strict";var e=d("./zlib/deflate"),i=d("./utils/common"),s=d("./utils/strings"),n=d("./zlib/messages"),o=d("./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 h(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=h,t.deflateRaw=function(I,u){return(u=u||{}).raw=!0,h(I,u)},t.gzip=function(I,u){return(u=u||{}).gzip=!0,h(I,u)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(d,A,t){"use strict";var e=d("./zlib/inflate"),i=d("./utils/common"),s=d("./utils/strings"),n=d("./zlib/constants"),o=d("./zlib/messages"),a=d("./zlib/zstream"),r=d("./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 h=this.options;h.raw&&0<=h.windowBits&&h.windowBits<16&&(h.windowBits=-h.windowBits,h.windowBits===0&&(h.windowBits=-15)),!(0<=h.windowBits&&h.windowBits<16)||p&&p.windowBits||(h.windowBits+=32),15<h.windowBits&&h.windowBits<48&&!(15&h.windowBits)&&(h.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,h.windowBits);if(I!==n.Z_OK)throw new Error(o[I]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,h){var I=new c(h);if(I.push(p,!0),I.err)throw I.msg||o[I.err];return I.result}c.prototype.push=function(p,h){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=h===~~h?h:h===!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,h){return(h=h||{}).raw=!0,g(p,h)},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(d,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(d,A,t){"use strict";var e=d("./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,h,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=h=0;h<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[h++]=c:(c<2048?l[h++]=192|c>>>6:(c<65536?l[h++]=224|c>>>12:(l[h++]=240|c>>>18,l[h++]=128|c>>>12&63),l[h++]=128|c>>>6&63),l[h++]=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,h,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<(h=n[p]))u[g++]=65533,c+=h-1;else{for(p&=h===2?31:h===3?15:7;1<h&&c<I;)p=p<<6|63&r[c++],h--;1<h?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(d,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(d,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(d,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(d,A,t){"use strict";var e,i=d("../utils/common"),s=d("./trees"),n=d("./adler32"),o=d("./crc32"),a=d("./messages"),r=0,l=4,c=0,g=-2,p=-1,h=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||h<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(d,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(d,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,l,c,g,p,h,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,h=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)===h){if(F+=g-v,v<S){for(S-=v;D[a++]=I[F++],--v;);F=a-U,x=D}}else if(h<v){if(F+=g+h-v,(v-=h)<S){for(S-=v;D[a++]=I[F++],--v;);if(F=0,h<S){for(S-=v=h;D[a++]=I[F++],--v;);F=a-U,x=D}}}else if(F+=h-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(d,A,t){"use strict";var e=d("../utils/common"),i=d("./adler32"),s=d("./crc32"),n=d("./inffast"),o=d("./inftrees"),a=1,r=2,l=0,c=-2,g=1,p=852,h=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(h),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(d,A,t){"use strict";var e=d("../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,h,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&&(h[V[r[l+x]]++]=x);if(w=a===0?(T=rt=h,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=h[x]<w?(v=0,h[x]):h[x]>w?(v=rt[gt+h[x]],T[tt+h[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+h[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(d,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(d,A,t){"use strict";var e=d("../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,h=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(h+1),et=0;for(W=1;W<=h;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 Ve,qt,We,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,$e=Tt.stat_desc.max_length,Fi=0;for(Et=0;Et<=h;Et++)ht.bl_count[Et]=0;for(zt[2*ht.heap[ht.heap_max]+1]=0,Ve=ht.heap_max+1;Ve<p;Ve++)$e<(Et=zt[2*zt[2*(qt=ht.heap[Ve])+1]+1]+1)&&(Et=$e,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=$e-1;ht.bl_count[Et]===0;)Et--;ht.bl_count[Et]--,ht.bl_count[Et+1]+=2,ht.bl_count[$e]--,Fi-=2}while(0<Fi);for(Et=$e;Et!==0;Et--)for(qt=ht.bl_count[Et];qt!==0;)Dn<(We=ht.heap[--Ve])||(zt[2*We+1]!==Et&&(ht.opt_len+=(Et-zt[2*We+1])*zt[2*We],zt[2*We+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(h+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<=h;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,h),N=new _(F,y,0,c,h),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(d,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(d,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,h=Object.getPrototypeOf&&Object.getPrototypeOf(i);h=h&&h.setTimeout?h: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)},h.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++},h.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(d){let A=(d.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function Vt(d,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(d))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(d))}}function Wt(d,A){let t=bi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Pn(d,A,!0);case"us":return Vt(d,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Vt(d,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Vt(d,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Vt(d,{...t,dateStyle:"medium",timeStyle:"short"})}}function Tn(d,A){let t=bi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Pn(d,A,!1);case"us":return Vt(d,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Vt(d,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Vt(d,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(d).getFullYear()===e.getFullYear();return Vt(d,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function Un(d,A){let t=bi(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return Vt(d,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Pn(d,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(d)),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 Ee(d,A,t){let e=d.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,h)=>this.renderPinnedRow(e,p,h));return}let l=new Map;a.forEach((p,h)=>{let I=l.get(p.folder);I||(I=[],l.set(p.folder,I)),I.push({pin:p,idx:h})});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 h=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:h});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 h=p.createSpan({cls:"stashpad-pinned-toggle"});c&&(Ee(h,l,g),h.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,h=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&&(Ee(u,g,h),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&&h&&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 h=o.createEl("button",{cls:"stashpad-shared-chip",text:c});return g&&h.addClass("is-active"),h.onclick=p,h};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[h,I]of n){let u=c.createEl("option",{text:I});u.value=h}let p=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=p,c.onchange=()=>{let h=c.value;h==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=h,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 h=g.createSpan({cls:"stashpad-pinned-label",text:c.title});h.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 h=[...new Set(i.map(N=>N.folder))].sort((N,Y)=>N.localeCompare(Y));this.taskFolderFilter!=="all"&&!h.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 h){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=Se(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:Ze(o),assignedBy:ne(o.assignedBy)})}return i}};async function Ui(d){let A=d.workspace.getLeavesOfType(ie);if(A.length>0){d.workspace.revealLeaf(A[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new mt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:ie,active:!0}),d.workspace.revealLeaf(t)}var No=require("obsidian");yt();var j=require("obsidian");di();var Li=require("obsidian");yt();var He=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!=="/"&&Xe.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 we=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 we.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(d,A,t){let e=d.vault.getAbstractFileByPath(A);if(!(e instanceof we.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=d.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;d.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=we.Platform.isMacOS?"Finder":we.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=d.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(d){if(!d)return"(none)";let A=d.replace(/\bMod\b/g,Ks?"Cmd":"Ctrl");return Ks&&(A=A.replace(/\bAlt\b/g,"Option")),A}function Wn(d,A,t={allowSingleKey:!0}){let e=d.placeholder,i=d.value;d.placeholder="Press a key\u2026 (Backspace to cancel)",d.value="",d.classList.add("is-recording");let s=!1,n=()=>{d.placeholder=e,d.classList.remove("is-recording"),s||(d.value=i),d.removeEventListener("keydown",o,!0),d.removeEventListener("blur",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 d.addEventListener("keydown",o,!0),d.addEventListener("blur",a),n}function fa(d,A){if(!d)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return d.length===1?d.toUpperCase():d}xe();Kt();function ve(d,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(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(d,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 ve(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(d,A){return(d&15)+(d>>6|d>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function eo(d,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;d[e]=to(A.charCodeAt(i),A.charCodeAt(i+1))}}function Ba(d,A){if(d.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==to(d.charCodeAt(e),d.charCodeAt(e+1)))return!1}return!0}var $n=87,Xn=48;function Xs(d,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;d[e++]=s>9?s+$n:s+Xn,s=A[i]&15,d[e++]=s>9?s+$n:s+Xn}return String.fromCharCode.apply(null,d)}var Zt=zs!==null?d=>{if(typeof d=="string"){let A=zs.from(d,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(zs.isBuffer(d))return new Uint8Array(d.buffer,d.byteOffset,d.length);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")}:d=>{if(typeof d=="string")return ma.encode(d);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")},Rt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",pi=new Uint8Array(256);for(let d=0;d<Rt.length;d++)pi[Rt.charCodeAt(d)]=d;function Zn(d,A=!0){let t=d.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(d[n]<<16&16711680)+(d[n+1]<<8&65280)+(d[n+2]&255),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=d[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=(d[t-2]<<8)+d[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(d){let A=Math.floor(d.length*.75),t=d.length;return d[t-1]==="="&&(A-=1,d[t-2]==="="&&(A-=1)),A}function Ea(d){let A=Qa(d),t=d.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=pi[d.charCodeAt(s)],o=pi[d.charCodeAt(s+1)],a=pi[d.charCodeAt(s+2)],r=pi[d.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(d,A){return ve(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(()=>ve(this,void 0,void 0,function*(){if(!Vs.has(d.name)){let v=Ea(d.data),S=WebAssembly.compile(v);Vs.set(d.name,S)}let y=yield Vs.get(d.name);t=yield WebAssembly.instantiate(y,{})})),c=()=>ve(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)}},h=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,d.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(d.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(d.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),h(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:h,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(d){return!Number.isInteger(d)||d<8||d>512||d%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function xa(d,A){return d|A<<16}function Zs(d=512,A=null){if(_n(d))return Promise.reject(_n(d));let t=null,e=d;if(A!==null){if(t=Zt(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=xa(d,t.length)}let i=d/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(d,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${Zn(d,!1)}$${Zn(t,!1)}`}var jn=new DataView(new ArrayBuffer(4));function Xt(d){return jn.setInt32(0,d,!0),new Uint8Array(jn.buffer)}function Ws(d,A,t){return ve(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);d.init(),d.update(Xt(t)),d.update(A);let s=d.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)d.init(),d.update(s),s=d.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=d,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(d){switch(d){case"d":return 0;case"i":return 1;default:return 2}}function Ta(d){return ve(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=d,s=Zt(d.password),n=Zt(d.salt),o=19,a=Ha(d.hashType),{memorySize:r}=d,l=Zt((A=d.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),h=new DataView(p.buffer);h.setInt32(0,t,!0),h.setInt32(4,i,!0),h.setInt32(8,r,!0),h.setInt32(12,e,!0),h.setInt32(16,o,!0),h.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(d.outputType==="hex"){let w=new Uint8Array(i*2);return Xs(w,E,i)}return d.outputType==="encoded"?Ma(n,d,E):E})}var Ua=d=>{var A;if(!d||typeof d!="object")throw new Error("Invalid options parameter. It requires an object.");if(!d.password)throw new Error("Password must be specified");if(d.password=Zt(d.password),d.password.length<1)throw new Error("Password must be specified");if(!d.salt)throw new Error("Salt must be specified");if(d.salt=Zt(d.salt),d.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(d.secret=Zt((A=d.secret)!==null&&A!==void 0?A:""),!Number.isInteger(d.iterations)||d.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(d.parallelism)||d.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(d.hashLength)||d.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(d.memorySize))throw new Error("Memory size should be specified.");if(d.memorySize<8*d.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(d.outputType===void 0&&(d.outputType="hex"),!["hex","binary","encoded"].includes(d.outputType))throw new Error(`Insupported output type ${d.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function _s(d){return ve(this,void 0,void 0,function*(){return Ua(d),Ta(Object.assign(Object.assign({},d),{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,Te=12,js=32,Ra=6e5,Ga=47104,La=3,Ja=1,wt=d=>d;function Lt(d){if(d.length<Gt.length+1)return!1;for(let A=0;A<Gt.length;A++)if(d[A]!==Gt[A])return!1;return!0}function so(d,A,t){d[A]=t>>>24&255,d[A+1]=t>>>16&255,d[A+2]=t>>>8&255,d[A+3]=t&255}function no(d,A){return d[A]*16777216+(d[A+1]<<16)+(d[A+2]<<8)+d[A+3]}async function tn(d,A,t){if(t.id===nn)return await _s({password:d,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(d)),"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(d){return crypto.subtle.importKey("raw",wt(d),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var ao={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function ui(d,A){let t=crypto.getRandomValues(new Uint8Array(Pa)),e=crypto.getRandomValues(new Uint8Array(Te)),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(d))),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(d,A,t){let e=new Uint8Array(Gt.length+1+1+4+4+1+1+A.length+t.length),i=0;return e.set(Gt,i),i+=Gt.length,e[i++]=en,e[i++]=d.id,so(e,i,d.a),i+=4,so(e,i,d.b),i+=4,e[i++]=d.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function Ue(d,A){if(!Lt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Gt.length];if(t===1)return qa(d,A);if(t!==en)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Gt.length+1,i={id:d[e++],a:0,b:0,c:0};if(i.a=no(d,e),e+=4,i.b=no(d,e),e+=4,i.c=d[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=d[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=d.slice(e,e+s);e+=s;let o=d.slice(e,e+Te);e+=Te;let a=d.slice(0,e),r=d.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(d,A){let t=Gt.length+1,e=d.slice(t,t+16);t+=16;let i=d.slice(t,t+12);t+=12;let s=d.slice(t),n=await crypto.subtle.importKey("raw",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(d,A){if(A.length!==js)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Te)),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(d))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function oe(d,A){if(!Lt(d))throw new Error("Not an encrypted Stashpad file.");let t=d[Gt.length];if(t!==en)throw new Error(`Unsupported encrypted version (${t}).`);let e=Gt.length+1;if(d[e++]!==oo)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=d[e++];e+=s;let n=d.slice(e,e+Te);e+=Te;let o=d.slice(0,e),a=d.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 Pe(d,A,t={}){if(!Lt(A))return A;if(t.secretId){let i=d.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await Ue(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new ii(d,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await Ue(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(d){let A="";for(let t=0;t<d.length;t++)A+=String.fromCharCode(d[t]);return btoa(A)}function on(d){let A=atob(d),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}var 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 Ue(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 Ue(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 Ue(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(d){let t=(d.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var rn=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function Bi(d,A){let t=new An.default,e=Ka([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await d.vault.read(o.file),r=a,l=po(a);for(let c of l){let g=d.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 d.vault.readBinary(g)),r=Ya(r,c,p)}r=Wa(r,d,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(d,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(d,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=[],h=`${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 d.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=`${h}/${S}`;await d.vault.adapter.exists(Q)&&F.push(Q);let D=null;for(let N of F)try{if(m(new Uint8Array(await d.vault.adapter.readBinary(N)),U)){D=N;break}}catch{}if(D){f.set(S,D);continue}let K=Q;for(let N=1;await d.vault.adapter.exists(K);N++)K=`${h}/${za(S,N)}`;f.set(S,K),E||(await ho(d,h),E=!0),await d.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,h),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(_)??`${h}/${_}`)}));let K=re(D,Q),N=U===S?v.originalName:Xa(v.originalName,S,U),Y=`${t}/${N}`;await d.vault.adapter.exists(Y)&&(N=`${N.replace(/\.md$/,"")}-${Bt(4)}.md`,Y=`${t}/${N}`),await d.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(d){let A=new Set,t=[];for(let e of d)A.has(e.id)||(A.add(e.id),t.push(e));return t}function po(d){let A=new Set,t;for(rn.lastIndex=0;(t=rn.exec(d))!==null;)A.add(t[1]);return[...A]}async function Io(d,A){let t=await d.vault.read(A),e=[],i=new Set;for(let s of po(t)){let n=d.metadataCache.getFirstLinkpathDest(s,A.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function Ya(d,A,t){return d.replace(new RegExp(`!\\[\\[${$a(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function za(d,A){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${A}${d.slice(t)}`:`${d}-${A}`}function Va(d,A,t){return d.replace(rn,(e,i,s)=>{if(i.includes("/"))return e;let n=A.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Wa(d,A,t){let e=Mt(d);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return d;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:uo(n)}),s={...e.fm,attachments:i};return re(s,e.body)}function $a(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function uo(d){let A=d.lastIndexOf("/");return A<0?d:d.slice(A+1)}function Xa(d,A,t){return d.includes(A)?d.replace(A,t):d.replace(/\.md$/,`-${t}.md`)}function Mt(d){if(!d.startsWith("---"))return{fm:{},body:d};let A=d.indexOf(` ---`,3);if(A<0)return{fm:{},body:d};let t=d.slice(3,A).replace(/^\n/,""),e=d.slice(A+4),i={};try{i=(0,Wi.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` -`)?e.slice(1):e;return{fm:i,body:s}}function ae(d,A){return`--- +`)?e.slice(1):e;return{fm:i,body:s}}function re(d,A){return`--- ${(0,Wi.stringifyYaml)(d).trimEnd()} --- -${A}`}async function ho(d,A){if(!(!A||await d.vault.adapter.exists(A)))try{await d.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}var re="stashenc",Za="stashmeta";function Ae(d){return d.replace(/\.stashenc$/,`.${Za}`)}async function fo(d,A){try{return JSON.parse(await d.vault.adapter.read(Ae(A)))}catch{return null}}async function Co(d,A,t){let e=A.replace(/\/+$/,""),i=[];for(let l of d.vault.getMarkdownFiles()){if((l.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let c;try{c=Ht(await d.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(d){if(!d)return null;let A=d.replace(/\/+$/,"");return!A||A.startsWith("/")||A.includes("\\")||/^[a-zA-Z]:/.test(A)||A.split("/").some(t=>t===".."||t===".")?null:A}async function cn(d,A,t){await d.vault.adapter.writeBinary(A,t);let e;try{e=new Uint8Array(await d.vault.adapter.readBinary(A))}catch(s){throw new Error(`Couldn't read back the encrypted file to verify it (${s.message}). Nothing was deleted.`)}let i=e.length===t.length;if(i){for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}}if(!i){try{await d.vault.adapter.remove(A)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function $i(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function Ge(d){return(d.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function Bo(d,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(d,a.file))i.set(r.path,r);let s=new Set,n=d.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 d.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 d.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 d.vault.delete(r)}catch(l){console.warn("[Stashpad] couldn't delete exclusive attachment",a,l),o.push(a)}return{unpurged:o}}async function mo(d,A,t,e,i=null,s=!1,n){let o=await Co(d,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 d.vault.adapter.stat(y.file.path);v&&g.set(y.file.path,v.mtime)}catch{}let p=await mi(d,{rootNotes:[{id:a.id,file:a.file}],allDescendants:r.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),h=await fi(p,e),I=await ne(h,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 d.vault.adapter.exists(u)&&await d.vault.adapter.mkdir(u);let f=Ge(s?t:$i(a.file)),C=`${u}/${f}.${re}`;for(let y=1;await d.vault.adapter.exists(C);y++)C=`${u}/${f} (${y}).${re}`;await cn(d,C,h);let B=c,E={v:1,parentId:l,title:s?"":$i(a.file),count:B.length,created:a.created,rootId:t,prevSibling:i};try{await d.vault.adapter.write(Ae(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:w}=await Bo(d,B,g);return{blobPath:C,noteCount:B.length,rootId:t,parentId:l,title:E.title,created:a.created,unpurged:w}}async function Qo(d,A,t,e,i){let s=new Uint8Array(await d.vault.adapter.readBinary(A));if(!Lt(s))throw new Error("Not an encrypted bundle.");let n=await ne(s,t),o=ln(i)??A.replace(/\/[^/]*$/,""),a=await Zt(d,n,o,e,{dedupeExisting:!0});await d.vault.adapter.remove(A);try{await d.vault.adapter.remove(Ae(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ut="_deleted";function _a(d){let A="";for(let t=0;t<d.length;t++)A+=String.fromCharCode(d[t]);return btoa(A)}function ja(d){let A=atob(d),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}async function dn(d,A,t,e){let i=ln(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=ln(new TextDecoder().decode(await ne(ja(t.originalFolderEnc),e)))}catch{i=null}if(i)return await d.vault.adapter.exists(i)||await d.vault.adapter.mkdir(i),i;let s=A.replace(/\/[^/]*$/,"");if(s===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(d){let A=[""];for(;A.length;){let t=A.shift(),e;try{e=await d.vault.adapter.list(t||"/")}catch{continue}if(e.files.some(i=>i.endsWith(`.${re}`)))return!0;for(let i of e.folders)i===".obsidian"||i.endsWith("/.obsidian")||A.push(i)}return!1}async function Eo(d,A,t,e,i,s=!1){let n=await Co(d,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 d.vault.adapter.stat(y.file.path);v&&c.set(y.file.path,v.mtime)}catch{}let g=await mi(d,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),p=await fi(g,e),h=await ne(p,e);if(h.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let y=0;y<g.length;y++)if(h[y]!==g[y])throw new Error("Encryption self-check failed (content).");await d.vault.adapter.exists(Ut)||await d.vault.adapter.mkdir(Ut);let I=A.replace(/\/+$/,""),u=I.split("/").pop()||"vault",f=Ge(s?t:`${u} ${$i(o.file)}`),C=`${Ut}/${f}.${re}`;for(let y=1;await d.vault.adapter.exists(C);y++)C=`${Ut}/${f} (${y}).${re}`;await cn(d,C,p);let B=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:B.length,created:o.created,rootId:t,deletedAt:i};try{await d.vault.adapter.write(Ae(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write deleted sidecar",y)}let{unpurged:w}=await Bo(d,B,c);return{blobPath:C,noteCount:B.length,rootId:t,originalFolder:I,title:E.title,unpurged:w}}async function yo(d,A,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(A));if(!Lt(i))throw new Error("Not an encrypted bundle.");let s=await Xi(d,A),n=await dn(d,A,s,t),o=await ne(i,t),a=await Zt(d,o,n,e,{dedupeExisting:!0});await d.vault.adapter.remove(A);try{await d.vault.adapter.remove(Ae(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function Xi(d,A){try{return JSON.parse(await d.vault.adapter.read(Ae(A)))}catch{return null}}var Jt=".trash";async function tr(d,A){let t=[],e=[A];for(;e.length;){let i=e.shift(),s;try{s=await d.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function er(d){let A=d.split("/").filter(Boolean);if(A.length===0)return null;for(let t of A)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return A.join("/")}async function wo(d,A,t,e=!1){if(!await d.vault.adapter.exists(Jt))return null;let i=await tr(d,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 d.vault.adapter.readBinary(I));try{let f=await d.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 ne(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 d.vault.adapter.exists(Ut)||await d.vault.adapter.mkdir(Ut);let c=Ge(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),g=`${Ut}/${c}.${re}`;for(let I=1;await d.vault.adapter.exists(g);I++)g=`${Ut}/${c} (${I}).${re}`;await cn(d,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 d.vault.adapter.write(Ae(g),JSON.stringify(p))}catch(I){console.warn("[Stashpad] couldn't write backfill sidecar",I)}let h=[];for(let I of i){let u=o.get(I);try{if(u!=null){let f=await d.vault.adapter.stat(I);if(f&&f.mtime!==u){h.push(I);continue}}await d.vault.adapter.remove(I)}catch(f){console.warn("[Stashpad] couldn't delete trash file",I,f),h.push(I)}}return{blobPath:g,fileCount:i.length,unpurged:h}}async function vo(d,A,t){let e=new Uint8Array(await d.vault.adapter.readBinary(A));if(!Lt(e))throw new Error("Not an encrypted bundle.");let i=await ne(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 h of c.split("/"))g=g?`${g}/${h}`:h,await d.vault.adapter.exists(g)||await d.vault.adapter.mkdir(g);let p=`${Jt}/${l}`;for(let h=1;await d.vault.adapter.exists(p);h++)p=`${Jt}/${l.replace(/(\.[^./]*)?$/,` (${h})$1`)}`;await d.vault.adapter.writeBinary(p,await r.async("arraybuffer")),o++}await d.vault.adapter.remove(A);try{await d.vault.adapter.remove(Ae(A))}catch{}return{filesWritten:o}}async function Fo(d){if(!await d.vault.adapter.exists(Ut))return[];try{return(await d.vault.adapter.list(Ut)).files.filter(t=>t.endsWith(`.${re}`))}catch{return[]}}var Qi=null,Zi=new Set;function _i(d){if(Qi!==d){Qi=d;for(let A of Zi)A()}}function _t(){return Qi}function ko(d){if(Qi===d){Qi=null;for(let A of Zi)A()}}function So(d){return Zi.add(d),()=>Zi.delete(d)}function ir(){return j.Platform.isMacOS?"Finder":j.Platform.isWin?"File Explorer":"file manager"}var Re=[{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 d={};for(let A of Re)d[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return d}var le={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:Bi(),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,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(le)),pn=new Set;function It(){return Do}function un(d){Do=d;for(let A of pn)A()}function bo(d){return pn.add(d),()=>pn.delete(d)}function es(d){try{let A=d.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var 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(d,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(d,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();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 be(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 be(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 He(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||le.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,"")||le.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(),h=[];h.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),g>0&&h.push(`imported ${g} loose file${g===1?"":"s"}`),p>0&&h.push(`linked attachments on ${p} note${p===1?"":"s"}`),r>0?h.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&h.push(`frontmatter already in sync (${a} notes checked)`),l>0&&h.push(`renamed ${l} note${l===1?"":"s"} to match body`),c>0&&h.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new j.Notice(`Stashpad: ${h.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: ${Ce(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 ho(d,A){if(!(!A||await d.vault.adapter.exists(A)))try{await d.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}var Ae="stashenc",Za="stashmeta";function le(d){return d.replace(/\.stashenc$/,`.${Za}`)}async function fo(d,A){try{return JSON.parse(await d.vault.adapter.read(le(A)))}catch{return null}}async function Co(d,A,t){let e=A.replace(/\/+$/,""),i=[];for(let l of d.vault.getMarkdownFiles()){if((l.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let c;try{c=Mt(await d.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(d){if(!d)return null;let A=d.replace(/\/+$/,"");return!A||A.startsWith("/")||A.includes("\\")||/^[a-zA-Z]:/.test(A)||A.split("/").some(t=>t===".."||t===".")?null:A}async function cn(d,A,t){await d.vault.adapter.writeBinary(A,t);let e;try{e=new Uint8Array(await d.vault.adapter.readBinary(A))}catch(s){throw new Error(`Couldn't read back the encrypted file to verify it (${s.message}). Nothing was deleted.`)}let i=e.length===t.length;if(i){for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}}if(!i){try{await d.vault.adapter.remove(A)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function $i(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function Re(d){return(d.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function mo(d,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(d,a.file))i.set(r.path,r);let s=new Set,n=d.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 d.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 d.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 d.vault.delete(r)}catch(l){console.warn("[Stashpad] couldn't delete exclusive attachment",a,l),o.push(a)}return{unpurged:o}}async function Bo(d,A,t,e,i=null,s=!1,n){let o=await Co(d,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 d.vault.adapter.stat(y.file.path);v&&g.set(y.file.path,v.mtime)}catch{}let p=await Bi(d,{rootNotes:[{id:a.id,file:a.file}],allDescendants:r.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),h=await fi(p,e),I=await oe(h,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 d.vault.adapter.exists(u)&&await d.vault.adapter.mkdir(u);let f=Re(s?t:$i(a.file)),C=`${u}/${f}.${Ae}`;for(let y=1;await d.vault.adapter.exists(C);y++)C=`${u}/${f} (${y}).${Ae}`;await cn(d,C,h);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 d.vault.adapter.write(le(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write lock sidecar",y)}let{unpurged:w}=await mo(d,m,g);return{blobPath:C,noteCount:m.length,rootId:t,parentId:l,title:E.title,created:a.created,unpurged:w}}async function Qo(d,A,t,e,i){let s=new Uint8Array(await d.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(d,n,o,e,{dedupeExisting:!0});await d.vault.adapter.remove(A);try{await d.vault.adapter.remove(le(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ut="_deleted";function _a(d){let A="";for(let t=0;t<d.length;t++)A+=String.fromCharCode(d[t]);return btoa(A)}function ja(d){let A=atob(d),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}async function dn(d,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 d.vault.adapter.exists(i)||await d.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(d){let A=[""];for(;A.length;){let t=A.shift(),e;try{e=await d.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(d,A,t,e,i,s=!1){let n=await Co(d,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 d.vault.adapter.stat(y.file.path);v&&c.set(y.file.path,v.mtime)}catch{}let g=await Bi(d,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(y=>({id:y.id,file:y.file})),sourceFolder:A}),p=await fi(g,e),h=await oe(p,e);if(h.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let y=0;y<g.length;y++)if(h[y]!==g[y])throw new Error("Encryption self-check failed (content).");await d.vault.adapter.exists(Ut)||await d.vault.adapter.mkdir(Ut);let I=A.replace(/\/+$/,""),u=I.split("/").pop()||"vault",f=Re(s?t:`${u} ${$i(o.file)}`),C=`${Ut}/${f}.${Ae}`;for(let y=1;await d.vault.adapter.exists(C);y++)C=`${Ut}/${f} (${y}).${Ae}`;await cn(d,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 d.vault.adapter.write(le(C),JSON.stringify(E))}catch(y){console.warn("[Stashpad] couldn't write deleted sidecar",y)}let{unpurged:w}=await mo(d,m,c);return{blobPath:C,noteCount:m.length,rootId:t,originalFolder:I,title:E.title,unpurged:w}}async function yo(d,A,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(A));if(!Lt(i))throw new Error("Not an encrypted bundle.");let s=await Xi(d,A),n=await dn(d,A,s,t),o=await oe(i,t),a=await _t(d,o,n,e,{dedupeExisting:!0});await d.vault.adapter.remove(A);try{await d.vault.adapter.remove(le(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function Xi(d,A){try{return JSON.parse(await d.vault.adapter.read(le(A)))}catch{return null}}var Jt=".trash";async function tr(d,A){let t=[],e=[A];for(;e.length;){let i=e.shift(),s;try{s=await d.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function er(d){let A=d.split("/").filter(Boolean);if(A.length===0)return null;for(let t of A)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return A.join("/")}async function wo(d,A,t,e=!1){if(!await d.vault.adapter.exists(Jt))return null;let i=await tr(d,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 d.vault.adapter.readBinary(I));try{let f=await d.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 d.vault.adapter.exists(Ut)||await d.vault.adapter.mkdir(Ut);let c=Re(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),g=`${Ut}/${c}.${Ae}`;for(let I=1;await d.vault.adapter.exists(g);I++)g=`${Ut}/${c} (${I}).${Ae}`;await cn(d,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 d.vault.adapter.write(le(g),JSON.stringify(p))}catch(I){console.warn("[Stashpad] couldn't write backfill sidecar",I)}let h=[];for(let I of i){let u=o.get(I);try{if(u!=null){let f=await d.vault.adapter.stat(I);if(f&&f.mtime!==u){h.push(I);continue}}await d.vault.adapter.remove(I)}catch(f){console.warn("[Stashpad] couldn't delete trash file",I,f),h.push(I)}}return{blobPath:g,fileCount:i.length,unpurged:h}}async function vo(d,A,t){let e=new Uint8Array(await d.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 h of c.split("/"))g=g?`${g}/${h}`:h,await d.vault.adapter.exists(g)||await d.vault.adapter.mkdir(g);let p=`${Jt}/${l}`;for(let h=1;await d.vault.adapter.exists(p);h++)p=`${Jt}/${l.replace(/(\.[^./]*)?$/,` (${h})$1`)}`;await d.vault.adapter.writeBinary(p,await r.async("arraybuffer")),o++}await d.vault.adapter.remove(A);try{await d.vault.adapter.remove(le(A))}catch{}return{filesWritten:o}}async function Fo(d){if(!await d.vault.adapter.exists(Ut))return[];try{return(await d.vault.adapter.list(Ut)).files.filter(t=>t.endsWith(`.${Ae}`))}catch{return[]}}var Qi=null,Zi=new Set;function _i(d){if(Qi!==d){Qi=d;for(let A of Zi)A()}}function jt(){return Qi}function ko(d){if(Qi===d){Qi=null;for(let A of Zi)A()}}function So(d){return Zi.add(d),()=>Zi.delete(d)}function ir(){return j.Platform.isMacOS?"Finder":j.Platform.isWin?"File Explorer":"file manager"}var Ge=[{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 d={};for(let A of Ge)d[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return d}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(d){Do=d;for(let A of pn)A()}function bo(d){return pn.add(d),()=>pn.delete(d)}function es(d){try{let A=d.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var 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(d,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(d,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 be(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 be(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 He(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(),h=[];h.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),g>0&&h.push(`imported ${g} loose file${g===1?"":"s"}`),p>0&&h.push(`linked attachments on ${p} note${p===1?"":"s"}`),r>0?h.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&h.push(`frontmatter already in sync (${a} notes checked)`),l>0&&h.push(`renamed ${l} note${l===1?"":"s"} to match body`),c>0&&h.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new j.Notice(`Stashpad: ${h.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(` `);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 Wt(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 Wt(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 Wt(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=Re.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 He(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 He(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=Me(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}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 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")??{},h=`${g}/${l}`;p?.openPath?.(h)}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=_t()?.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()}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=yt()),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 h=()=>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),B=w=>{let y=w.toLowerCase();return C.every(v=>y.includes(v))},E=h().filter(w=>B(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(),B={...this.plugin.settings.noteTemplates??{}};C?B[o]=C:delete B[o],this.plugin.settings.noteTemplates=B,await this.plugin.saveSettings(),f()},f=()=>{p.empty(),p.style.display="none";let C=c.value.trim();if(!C)return;let B=this.app.vault.getAbstractFileByPath(C);if(!B||B.extension!=="md"){p.style.display="",p.setText(`\u26A0 "${C}" is not a markdown file in this vault.`);return}let E=this.app.metadataCache.getFileCache(B)?.frontmatter??{},y=ie.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 Qe(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 h=await this.plugin.recolorAllInFolder(e,i,p??null);if(h>0)new j.Notice(`Recolored ${h} note${h===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 h=(this.plugin.settings.customPalette??[]).filter(I=>I.toLowerCase()!==p.toLowerCase());return this.plugin.settings.customPalette=h,await this.plugin.saveSettings(),h}).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=h=>{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()[h]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=h==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{Wn(u,async y=>{this.plugin.settings.bindings[e.id][h]=y,u.value=hi(y),f(),await this.plugin.saveSettings(),o(),w()})};let B=I.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});B.title="Clear this slot",B.onclick=async()=>{this.plugin.settings.bindings[e.id][h]="",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()[h]!==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][h]=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 h=i(),I=!!(h.primary&&h.secondary);g.checked=!!h.useBoth,g.disabled=!I,c.toggleClass("is-disabled",!I);let u=!!h.useBoth&&I;r.toggleClass("is-disabled",!I||u),r.toggleClass("is-right",h.preferRight),r.setAttribute("aria-checked",String(h.preferRight)),r.setAttribute("aria-disabled",String(!I||u)),l.setText(h.preferRight?"R":"L"),r.title=I?u?'Overridden by "Use both"':h.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 h=i();!h.primary||!h.secondary||(this.plugin.settings.bindings[e.id].preferRight=!h.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void p(),r.onkeydown=h=>{(h.key===" "||h.key==="Enter")&&(h.preventDefault(),p())},o()}};var Le=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()}};Et();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 ue}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):Ce(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 h=this.composerInputEl;if(e&&h&&(h.focus(),i!=null)){let I=Math.min(i,h.value.length);try{h.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 Le(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}`,h=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&&(Ee(u,c.length,h),u.onclick=E=>{E.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Se(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 B=I.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(B.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},g&&h)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)?Ce(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(d){let A=d.workspace.getLeavesOfType(ue);if(A.length>0){d.workspace.revealLeaf(A[0]);return}let t=d.workspace.getRightLeaf(!1);if(!t){new Dt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:ue,active:!0}),d.workspace.revealLeaf(t)}var P=require("obsidian");Et();var ce=require("obsidian");Et();function nr(d,A){let t=d.vault.getAbstractFileByPath(A);if(!(t instanceof ce.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof ce.TFile?n.extension==="md"&&e.push(n):n instanceof ce.TFolder&&(Xe.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 ce.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof ce.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 ce.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(De(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(De(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",Je=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)}};Et();var de="parentLink",qe="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[de]=="string"?n[de]:null,a=n?.[qe],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[de]=i:delete n[de],s.length>0?n[qe]=s:delete n[qe]}))}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 Oe(d,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let l of d.vault.getMarkdownFiles()){if(l.path!==A&&!l.path.startsWith(t))continue;let c=d.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 h=i.get(p)??[];h.push(g),i.set(p,h)}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 h=e.get(p);h&&g.push(s(h))}return g},a=0,r=0;for(let l of e.values()){a+=1;let c=n(l),g=o(l),p=d.metadataCache.getFileCache(l.file)?.frontmatter,h=p&&typeof p[de]=="string"?p[de]:null,I=p?.[qe],u=Array.isArray(I)?I.filter(B=>typeof B=="string"):[],f=(h??null)===(c??null),C=u.length===g.length&&u.every((B,E)=>B===g[E]);if(!(f&&C))try{await d.fileManager.processFrontMatter(l.file,B=>{c?B[de]=c:delete B[de],g.length>0?B[qe]=g:delete B[qe]}),r+=1,await new Promise(B=>setTimeout(B,50))}catch(B){console.warn("[Stashpad] rebootstrap fm sync failed",l.file.path,B)}}return{checked:a,written:r}}function as(d){return`[[${d.replace(/\.md$/i,"")}]]`}Kt();xe();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");Et();Ts();var St=vt.moment;function Bn(d){let A=d.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 h=St(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return h.isValid()?r(h.startOf("day").valueOf()):null}function Ho(d){let A={text:[],filters:{}},t=(d||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let a=Bn(o);a!=null&&(A.filters.before=a)}else if(n==="after"){let a=Bn(o);a!=null&&(A.filters.after=a)}else if(n==="on"){let a=Bn(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 jt=class d 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 B of s)if(!C.includes(B))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 B=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||B(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)B(x.title)&&F(x.cross.id)}}let r=C=>{let B=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(B.before||B.after||B.on){let E=this.createdMsFor(C);if(E==null||B.before!=null&&E>=B.before||B.after!=null&&E<=B.after||B.on&&(E<B.on.start||E>=B.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,B)=>({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,B),matchLine:B,crossFolder:C.cross?.folder,crossFile:C.cross?.file,crossId:C.cross?.id}),h=C=>{let B=[];for(let E of C)if(r(E))if(this.opts.mode==="search"){if(!e){B.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)B.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))B.push(p(E,Q))}}else{if(e&&!n(E.title.toLowerCase())&&!n(E.body.toLowerCase()))continue;B.push(p(E,-1))}return B},I=h(c),u=[...I];if(this.opts.mode==="search"?e?!0:I.length<10:!!e){let C=h(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(),B={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(B):u.unshift(B))}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()),B=u.filter(C);if(B.length>0){let E=u.filter(w=>!C(w));u.splice(0,u.length,...B,...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 $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=Ge.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 He(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 He(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=Me(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")??{},h=`${g}/${l}`;p?.openPath?.(h)}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 h=()=>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=h().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 Qe(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 h=await this.plugin.recolorAllInFolder(e,i,p??null);if(h>0)new j.Notice(`Recolored ${h} note${h===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 h=(this.plugin.settings.customPalette??[]).filter(I=>I.toLowerCase()!==p.toLowerCase());return this.plugin.settings.customPalette=h,await this.plugin.saveSettings(),h}).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=h=>{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()[h]),u.classList.add("stashpad-binding-input");let f=()=>{u.size=Math.max(3,u.value.length||u.placeholder.length)};f();let C=h==="primary"?e.defaultPrimary:e.defaultSecondary??"";u.onclick=()=>{Wn(u,async y=>{this.plugin.settings.bindings[e.id][h]=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][h]="",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()[h]!==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][h]=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 h=i(),I=!!(h.primary&&h.secondary);g.checked=!!h.useBoth,g.disabled=!I,c.toggleClass("is-disabled",!I);let u=!!h.useBoth&&I;r.toggleClass("is-disabled",!I||u),r.toggleClass("is-right",h.preferRight),r.setAttribute("aria-checked",String(h.preferRight)),r.setAttribute("aria-disabled",String(!I||u)),l.setText(h.preferRight?"R":"L"),r.title=I?u?'Overridden by "Use both"':h.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 h=i();!h.primary||!h.secondary||(this.plugin.settings.bindings[e.id].preferRight=!h.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void p(),r.onkeydown=h=>{(h.key===" "||h.key==="Enter")&&(h.preventDefault(),p())},o()}};var Le=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 h=this.composerInputEl;if(e&&h&&(h.focus(),i!=null)){let I=Math.min(i,h.value.length);try{h.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 Le(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}`,h=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&&(Ee(u,c.length,h),u.onclick=E=>{E.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Se(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&&h)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(d){let A=d.workspace.getLeavesOfType(fe);if(A.length>0){d.workspace.revealLeaf(A[0]);return}let t=d.workspace.getRightLeaf(!1);if(!t){new Dt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:fe,active:!0}),d.workspace.revealLeaf(t)}var P=require("obsidian");yt();var de=require("obsidian");yt();function nr(d,A){let t=d.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&&(Xe.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(De(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(De(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",Je=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",qe="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?.[qe],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[qe]=s:delete n[qe]}))}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 Oe(d,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let l of d.vault.getMarkdownFiles()){if(l.path!==A&&!l.path.startsWith(t))continue;let c=d.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 h=i.get(p)??[];h.push(g),i.set(p,h)}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 h=e.get(p);h&&g.push(s(h))}return g},a=0,r=0;for(let l of e.values()){a+=1;let c=n(l),g=o(l),p=d.metadataCache.getFileCache(l.file)?.frontmatter,h=p&&typeof p[he]=="string"?p[he]:null,I=p?.[qe],u=Array.isArray(I)?I.filter(m=>typeof m=="string"):[],f=(h??null)===(c??null),C=u.length===g.length&&u.every((m,E)=>m===g[E]);if(!(f&&C))try{await d.fileManager.processFrontMatter(l.file,m=>{c?m[he]=c:delete m[he],g.length>0?m[qe]=g:delete m[qe]}),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(d){return`[[${d.replace(/\.md$/i,"")}]]`}Kt();xe();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(d){let A=d.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 h=St(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return h.isValid()?r(h.startOf("day").valueOf()):null}function Ho(d){let A={text:[],filters:{}},t=(d||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let 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 d 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}),h=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=h(c),u=[...I];if(this.opts.mode==="search"?e?!0:I.length<10:!!e){let C=h(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(` `);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 h=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),I=h.createSpan({cls:"stashpad-search-excluded-icon"});(0,vt.setIcon)(I,"folder-search"),h.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(h=>t.crossFolder?h.cross?.folder===t.crossFolder&&h.cross?.id===t.crossId:h.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 h=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(h,t.bodyPreview,n)}let l="";if(t.crossFolder?l=s?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let h=i.createDiv({cls:"stashpad-suggest-preview"});h.appendText("Parent: "),this.highlightInto(h,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),g=t.crossFolder??this.opts.localFolder??null;if(g||c){let h=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[g?g.split("/").pop()||g:"",c].filter(f=>f&&f.length>0).join(" \u203A ");u&&h.setText(u)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let h=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let I=h.createDiv({cls:"stashpad-suggest-time"});I.setText(this.formatRelativeTime(p)),I.title=St(p).format("YYYY-MM-DD HH:mm")}r&&h.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),h=t.value.slice(c,g),I=t.value.slice(g);t.value=`${p}[${h}]${I}`;let u=c+1+h.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 h=document.activeElement,I=h?p.indexOf(h):-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 B=this.whenMode;B!=="between"&&u.id==="between"?this.whenBetweenEndText="":B==="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 B=St().format("YYYY-MM-DD"),E=!f||f===B;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,B=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(B);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 B=u.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return B?B[1]:null},h=(u,f,C,B)=>{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,R)=>{if(!rt)return`${J}${R}`;let b={d:"days",w:"weeks",m:"months",y:"years"}[R];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 R=nt.createEl("button",{cls:"stashpad-when-pop-chip",text:J.label});R.type="button",R.addEventListener("mousedown",b=>b.preventDefault()),R.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"}}),mt=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 R=mt.createEl("option",{text:J.label});R.value=J.v}let ft=lt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});ft.type="button";let m=()=>{let J=parseInt(ot.value,10);!Number.isFinite(J)||J<1||(g(K,gt(J,mt.value)),O())};ft.addEventListener("mousedown",J=>J.preventDefault()),ft.addEventListener("click",J=>{J.preventDefault(),m()}),V(m),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,Rn(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 mt=rt.createEl("button",{cls:"stashpad-when-pop-chip",text:ot});mt.type="button",mt.addEventListener("mousedown",ft=>ft.preventDefault()),mt.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 mt=nt[ot],ft=gt.createEl("button",{cls:"stashpad-when-pop-chip",text:mt.slice(0,3)});ft.type="button",ft.title=mt,ot===lt&&ft.addClass("is-today"),ft.addEventListener("mousedown",m=>m.preventDefault()),ft.addEventListener("click",m=>{if(m.preventDefault(),B==="betweenEnd"){let J=ot,R=St().startOf("day"),b=(R.day()+6)%7,k=(J-b+7)%7;k===0&&(k=7);let H=R.clone().add(k,"days").format("YYYY-MM-DD");g(K,H)}else g(K,mt);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,B),[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=h("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=h("end (date / day / timeframe)",()=>this.whenBetweenEndText,y=>{this.whenBetweenEndText=y},"betweenEnd"),C=r.createDiv({cls:"stashpad-when-actions"}),B=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});B.type="button",B.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()};B.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=h("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 B=()=>{let w=u.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};C.addEventListener("click",w=>{w.preventDefault(),B()});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,B),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 h=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${h}\u201D in a new tab`,node:null,kind:"folder-open",folder:p})},o=new mn(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 d(g,r,l,c);p.open(),setTimeout(()=>{let h=p.inputEl;h&&(i&&(h.value=i,h.dispatchEvent(new Event("input",{bubbles:!0}))),h.focus(),h.setSelectionRange(h.value.length,h.value.length))},0)}},o.open();return}this.opts.onPick(t)}},mn=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");Et();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(d){return d.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||d}Mt();var Qn=require("obsidian");function rr(d,A){return!A||d.metaKey||d.ctrlKey||d.altKey?!1:d.key.toLowerCase()===A.toLowerCase()}function Ke(d,A){return A?A.includes("+")?Ar(d,A):rr(d,A):!1}function st(d,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?Ke(d,t)||Ke(d,e):i?Ke(d,e):Ke(d,t):Ke(d,t)||Ke(d,e)}function yi(d){if(!d)return"";let A=Qn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return d.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function Ar(d,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")?d.metaKey:d.ctrlKey;return s&&!c||n&&!d.ctrlKey||o&&!d.metaKey||a!==d.altKey||r!==d.shiftKey||!s&&(!n&&d.ctrlKey||!o&&d.metaKey)?!1:d.key.toLowerCase()===e}var Fe=require("obsidian");Mt();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 Fe.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 Fe.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 Fe.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let h=this.host.app.metadataCache.getFileCache(p)?.frontmatter,I=typeof h?.author=="string"?h.author:"";if(!I.trim()){s.push(p.path);continue}if(I.includes(e)||!A.contributorMode)continue;(Array.isArray(h?.contributors)?h.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 Fe.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(" ")}? +`)}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 h=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),I=h.createSpan({cls:"stashpad-search-excluded-icon"});(0,vt.setIcon)(I,"folder-search"),h.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(h=>t.crossFolder?h.cross?.folder===t.crossFolder&&h.cross?.id===t.crossId:h.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 h=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(h,t.bodyPreview,n)}let l="";if(t.crossFolder?l=s?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let h=i.createDiv({cls:"stashpad-suggest-preview"});h.appendText("Parent: "),this.highlightInto(h,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),g=t.crossFolder??this.opts.localFolder??null;if(g||c){let h=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),u=[g?g.split("/").pop()||g:"",c].filter(f=>f&&f.length>0).join(" \u203A ");u&&h.setText(u)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let h=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let I=h.createDiv({cls:"stashpad-suggest-time"});I.setText(this.formatRelativeTime(p)),I.title=St(p).format("YYYY-MM-DD HH:mm")}r&&h.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),h=t.value.slice(c,g),I=t.value.slice(g);t.value=`${p}[${h}]${I}`;let u=c+1+h.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 h=document.activeElement,I=h?p.indexOf(h):-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},h=(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=h("start (date / day / timeframe)",()=>this.whenSingleText,y=>{this.whenSingleText=y},"betweenStart"),f=h("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=h("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 h=p.split("/").pop()??p;this.opts.onPick({id:`folder:${p}`,label:`Open folder \u201C${h}\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 d(g,r,l,c);p.open(),setTimeout(()=>{let h=p.inputEl;h&&(i&&(h.value=i,h.dispatchEvent(new Event("input",{bubbles:!0}))),h.focus(),h.setSelectionRange(h.value.length,h.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(d){return d.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||d}Ht();var Qn=require("obsidian");function rr(d,A){return!A||d.metaKey||d.ctrlKey||d.altKey?!1:d.key.toLowerCase()===A.toLowerCase()}function Ke(d,A){return A?A.includes("+")?Ar(d,A):rr(d,A):!1}function st(d,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?Ke(d,t)||Ke(d,e):i?Ke(d,e):Ke(d,t):Ke(d,t)||Ke(d,e)}function yi(d){if(!d)return"";let A=Qn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return d.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function Ar(d,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")?d.metaKey:d.ctrlKey;return s&&!c||n&&!d.ctrlKey||o&&!d.metaKey||a!==d.altKey||r!==d.shiftKey||!s&&(!n&&d.ctrlKey||!o&&d.metaKey)?!1:d.key.toLowerCase()===e}var Fe=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 Fe.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 Fe.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 Fe.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let p of i){let h=this.host.app.metadataCache.getFileCache(p)?.frontmatter,I=typeof h?.author=="string"?h.author:"";if(!I.trim()){s.push(p.path);continue}if(I.includes(e)||!A.contributorMode)continue;(Array.isArray(h?.contributors)?h.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 Fe.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,h)=>{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(h))}),await this.pacedFrontmatter(n,p=>{let h=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];h.some(I=>I.includes(e))||h.push(r),p.contributors=h})};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,h)=>{if(typeof p.author=="string"&&p.author.includes(e)&&delete p.author,l.has(h)){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(h=>!(typeof h=="string"&&h.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 Fe.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,` -`).trim(),attachments:t}}};function Go(d,A,t){return d.tree.getChildren(A).slice().sort((i,s)=>lr(d,i,s,t)).map(i=>i.id)}function lr(d,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=Po(d,A)||A.created||"",s=Po(d,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=d.titleForNode(A),s=d.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function Po(d,A){if(!A.file)return"";let t=d.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Ye=require("obsidian");var Ro=require("obsidian");function he(d,A,t){d.empty();try{(0,Ro.setIcon)(d,A)}catch{}let e=d.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(d.empty(),d.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Lo(d){if(d instanceof Element&&d.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);d instanceof Element&&d.ownerDocument&&A.add(d.ownerDocument);for(let t of A)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}function Jo(d){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(d))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function wi(d){return d.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function qo(d,A,t){let e=new Set(A),i=d.filter(n=>!e.has(n)),s=d.findIndex(n=>e.has(n));if(s<0)return d.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let l=-1;return d.forEach((c,g)=>{e.has(c)&&(l=g)}),l})(),o=0;for(let l=0;l<Math.min(d.length,n+2);l++)e.has(d[l])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function En(d,A){if(d.length!==A.length)return!1;for(let t=0;t<d.length;t++)if(d[t]!==A[t])return!1;return!0}async function yn(d){let A=d.getActionTargets();if(!A.length)return;let t=It().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await d.app.vault.cachedRead(i.file),n=d.stripFrontmatter(s).trim();e.push(t?`${d.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function Ro(d,A,t){return d.tree.getChildren(A).slice().sort((i,s)=>lr(d,i,s,t)).map(i=>i.id)}function lr(d,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=Po(d,A)||A.created||"",s=Po(d,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=d.titleForNode(A),s=d.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function Po(d,A){if(!A.file)return"";let t=d.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Ye=require("obsidian");var Go=require("obsidian");function ge(d,A,t){d.empty();try{(0,Go.setIcon)(d,A)}catch{}let e=d.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(d.empty(),d.createSpan({cls:"stashpad-icon-fallback",text:t}))}function Lo(d){if(d instanceof Element&&d.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);d instanceof Element&&d.ownerDocument&&A.add(d.ownerDocument);for(let t of A)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}function Jo(d){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(d))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function wi(d){return d.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function qo(d,A,t){let e=new Set(A),i=d.filter(n=>!e.has(n)),s=d.findIndex(n=>e.has(n));if(s<0)return d.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let l=-1;return d.forEach((c,g)=>{e.has(c)&&(l=g)}),l})(),o=0;for(let l=0;l<Math.min(d.length,n+2);l++)e.has(d[l])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function En(d,A){if(d.length!==A.length)return!1;for(let t=0;t<d.length;t++)if(d[t]!==A[t])return!1;return!0}async function yn(d){let A=d.getActionTargets();if(!A.length)return;let t=It().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await d.app.vault.cachedRead(i.file),n=d.stripFrontmatter(s).trim();e.push(t?`${d.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` `)),d.plugin.notifications.show({message:`Copied ${d.titleList(A)} to clipboard`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:d.noteFolder})}async function Oo(d){let A=d.getActionTargets();if(!A.length||!A[0].file){new Ye.Notice("Nothing to copy from.");return}let t=A[0],e=await d.app.vault.cachedRead(t.file),i=d.stripFrontmatter(e),s=Jo(i);if(s.length===0){d.plugin.notifications.show({message:`No codeblock found in "${d.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:d.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),d.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${d.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:d.noteFolder});return}let n=s.map((a,r)=>({kind:"one",idx:r,label:`${r+1}. ${a.lang||"(no language)"} \u2014 ${a.code.split(` `)[0].slice(0,60)}${a.code.includes(` @@ -32,85 +32,85 @@ Existing authors are never overwritten. This can be undone.`,"Claim",I).open()}) `):s[a.idx].code;await navigator.clipboard.writeText(r),d.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${d.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${d.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:d.noteFolder})}}(d.app);o.setPlaceholder(`${s.length} codeblocks in "${d.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function Ko(d){let A=d.getActionTargets();if(A.length===0){let n=d.tree.get(d.focusId);n?.file&&(A=[n])}if(A.length===0){new Ye.Notice("Nothing to copy.");return}let t=It().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await d.app.vault.cachedRead(n.file),r=d.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),l=t?`${d.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${l}${r}`)}for(let a of d.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),d.plugin.clearNoteClipboard(),d.plugin.noteClipboard={mode:"copy",folder:d.noteFolder,ids:A.map(n=>n.id),text:s},d.render(),d.plugin.notifications.show({message:`Copied tree of ${d.titleList(A)} (${e.length} entries) \u2014 paste in the list to clone, in a note to drop the outline in`,kind:"success",category:"system",affectedIds:A.map(n=>n.id),folder:d.noteFolder})}async function Yo(d){let A=d.getActionTargets();if(A.length===0){let i=d.tree.get(d.focusId);i?.file&&(A=[i])}if(A.length===0){new Ye.Notice("Nothing to copy.");return}let t=[],e=(i,s)=>{if(!i.file)return;let n=" ".repeat(s);t.push(`${n}- ![[${i.file.basename}]]`);for(let o of d.tree.getChildren(i.id))e(o,s+1)};for(let i of A)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),d.plugin.notifications.show({message:`Copied outline of ${d.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:d.noteFolder})}var ge=require("obsidian");Et();xi();Mt();function dr(d){return d.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function zo(d,A){let t=gr(d,A);if(t.length===0){new ge.Notice("Nothing to export.");return}let e=pr(d,t);if(e.length===0){new ge.Notice("No exportable notes (no files attached).");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-${t.length}notes`;new ei(d.app,s,e.length,(n,o,a)=>{hr(d,t,e,n,o,a)},Yi).open()}async function hr(d,A,t,e,i,s=!1){try{let n=await mi(d.app,{rootNotes:A.filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),allDescendants:t.filter(h=>!A.some(I=>I.id===h.id)).filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),sourceFolder:d.noteFolder}),o="";if(i){let h=await ui(n,i);n=h.data;let I=ao[h.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,ge.moment)().format("YYYYMMDD-HHmmss"),r=dr(e),l=(d.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${d.noteFolder}/${l}`;await d.ensureFolder(c);let g=`${r}-${a}`,p=`${c}/${g}.${oe}`;if(await d.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let h=d.app.secretStorage;try{h?.setSecret(_e(g),i)}catch(I){console.warn("[Stashpad] couldn't save export passphrase to secret storage",I)}}await d.log.append({type:"stash_export",id:A[0].id,payload:{path:p,noteCount:t.length,rootIds:A.map(h=>h.id)}}),d.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:d.noteFolder,actions:d.actionsForFile(p),duration:0})}catch(n){d.plugin.notifications.show({message:`Stashpad: export failed +`)),d.plugin.notifications.show({message:`Copied outline of ${d.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:d.noteFolder})}var pe=require("obsidian");yt();xi();Ht();function dr(d){return d.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function zo(d,A){let t=gr(d,A);if(t.length===0){new pe.Notice("Nothing to export.");return}let e=pr(d,t);if(e.length===0){new pe.Notice("No exportable notes (no files attached).");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-${t.length}notes`;new ei(d.app,s,e.length,(n,o,a)=>{hr(d,t,e,n,o,a)},Yi).open()}async function hr(d,A,t,e,i,s=!1){try{let n=await Bi(d.app,{rootNotes:A.filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),allDescendants:t.filter(h=>!A.some(I=>I.id===h.id)).filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),sourceFolder:d.noteFolder}),o="";if(i){let h=await ui(n,i);n=h.data;let I=ao[h.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=(d.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${d.noteFolder}/${l}`;await d.ensureFolder(c);let g=`${r}-${a}`,p=`${c}/${g}.${ae}`;if(await d.app.vault.createBinary(p,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let h=d.app.secretStorage;try{h?.setSecret(_e(g),i)}catch(I){console.warn("[Stashpad] couldn't save export passphrase to secret storage",I)}}await d.log.append({type:"stash_export",id:A[0].id,payload:{path:p,noteCount:t.length,rootIds:A.map(h=>h.id)}}),d.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${p}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[p],folder:d.noteFolder,actions:d.actionsForFile(p),duration:0})}catch(n){d.plugin.notifications.show({message:`Stashpad: export failed Error: ${n.message} -Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function gr(d,A){if(A?.file)return[A];if(d.selection.size>0)return[...d.selection].map(e=>d.tree.get(e)).filter(e=>!!e?.file);if(d.cursorIdx>=0&&d.currentChildren[d.cursorIdx])return[d.currentChildren[d.cursorIdx]];let t=d.tree.get(d.focusId);return t?.file?[t]:[]}function pr(d,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of d.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function Vo(d){let A=d.app.vault.getFiles().filter(e=>e.extension===oe);if(A.length===0){new ge.Notice("No .stash files found in this vault.");return}let t=new class extends ge.FuzzySuggestModal{getItems(){return A}getItemText(e){return e.path}onChooseItem(e){wn(d,e)}}(d.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function wn(d,A){try{let t=new Uint8Array(await d.app.vault.readBinary(A)),e=await Pe(d.app,t,{secretId:_e(A.basename)});if(!e)return;let i=await Zt(d.app,e,d.noteFolder,Ir(d));d.tree.rebuild(d.noteFolder),d.render(),await d.log.append({type:"stash_import",id:M,payload:{from:A.path,into:d.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await d.app.fileManager.trashFile(A)}catch{}d.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),d.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:d.noteFolder})}catch(t){d.plugin.notifications.show({message:`Stashpad: import failed +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function gr(d,A){if(A?.file)return[A];if(d.selection.size>0)return[...d.selection].map(e=>d.tree.get(e)).filter(e=>!!e?.file);if(d.cursorIdx>=0&&d.currentChildren[d.cursorIdx])return[d.currentChildren[d.cursorIdx]];let t=d.tree.get(d.focusId);return t?.file?[t]:[]}function pr(d,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of d.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function Vo(d){let A=d.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(d,e)}}(d.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function wn(d,A){try{let t=new Uint8Array(await d.app.vault.readBinary(A)),e=await Pe(d.app,t,{secretId:_e(A.basename)});if(!e)return;let i=await _t(d.app,e,d.noteFolder,Ir(d));d.tree.rebuild(d.noteFolder),d.render(),await d.log.append({type:"stash_import",id:M,payload:{from:A.path,into:d.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await d.app.fileManager.trashFile(A)}catch{}d.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),d.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:d.noteFolder})}catch(t){d.plugin.notifications.show({message:`Stashpad: import failed File: \`${A.name}\` Error: ${t.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[A.path],actions:d.actionsForFile(A.path)}),console.error(t)}}function Ir(d){let A=new Set,t=e=>{if(A.add(e),!!d.tree.get(e))for(let s of d.tree.getChildren(e))t(s.id)};return t(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 Je(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):Go(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 h=this.app.metadataCache.getFirstLinkpathDest(p,"");h&&!r.has(h.path)&&(r.add(h.path),l.push(h))}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=fe(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 h of this.plugin.lockedSubtreesFor(this.noteFolder,p))g.has(h.blob)||(g.add(h.blob),a.push(h))}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),h=r.map(({lk:u})=>u).filter(u=>u.rootId).sort((u,f)=>n(f)-n(u)),I=!0;for(;h.length&&I;){I=!1;for(let u=0;u<h.length;u++){let f=h[u],C=f.prevSibling??null,B;if(C==null)B=0;else{let E=p.indexOf(C);if(E<0)continue;B=E+1}p.splice(B,0,f.rootId),h.splice(u,1),u--,I=!0}}for(let u of h)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,h=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),B=h&&C.includes(h)?C.indexOf(h)+1:0;C.splice(Math.max(0,B),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 h=window.require?.("electron")?.shell,I=this.app.vault.adapter?.getFullPath?.(e.blob);I&&h?.showItemInFolder&&h.showItemInFolder(I)}catch(h){console.warn("[Stashpad] showItemInFolder failed",h)}}))}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=se(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(B=>B.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 h=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,h&&this.listEl){let I=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,h.kind){case"preserve":I?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=h.scrollTop,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let B=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(u,B),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=h.id,f=h.align,C=this.listEl,B=()=>{this.suppressScrollSave=!0;let E=C.querySelector(`[data-id="${u}"]`);E&&E.scrollIntoView({block:f,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};B(),requestAnimationFrame(B),setTimeout(B,60),setTimeout(B,200),setTimeout(B,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 B=Math.max(0,I.scrollHeight-I.clientHeight);I.scrollTop<u&&u<=B?I.scrollTop=u:u=I.scrollTop});f.observe(I),this.listResizeObserver=f,I.addEventListener("wheel",B=>{B.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;I.addEventListener("touchstart",B=>{C=B.touches[0]?.clientY??0},{passive:!0}),I.addEventListener("touchmove",B=>{let E=B.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:d.actionsForFile(A.path)}),console.error(t)}}function Ir(d){let A=new Set,t=e=>{if(A.add(e),!!d.tree.get(e))for(let s of d.tree.getChildren(e))t(s.id)};return t(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 Je(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 h=this.app.metadataCache.getFirstLinkpathDest(p,"");h&&!r.has(h.path)&&(r.add(h.path),l.push(h))}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 h of this.plugin.lockedSubtreesFor(this.noteFolder,p))g.has(h.blob)||(g.add(h.blob),a.push(h))}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),h=r.map(({lk:u})=>u).filter(u=>u.rootId).sort((u,f)=>n(f)-n(u)),I=!0;for(;h.length&&I;){I=!1;for(let u=0;u<h.length;u++){let f=h[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),h.splice(u,1),u--,I=!0}}for(let u of h)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,h=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=h&&C.includes(h)?C.indexOf(h)+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 h=window.require?.("electron")?.shell,I=this.app.vault.adapter?.getFullPath?.(e.blob);I&&h?.showItemInFolder&&h.showItemInFolder(I)}catch(h){console.warn("[Stashpad] showItemInFolder failed",h)}}))}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 h=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,h&&this.listEl){let I=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,h.kind){case"preserve":I?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let u=h.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=h.id,f=h.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=h=>{h.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});he(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=h=>{h.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=h=>{h.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let h of Is){let I=this.timeFilterCalendar?h.calShort:h.rollShort,u=this.timeFilterCalendar?h.calLong:h.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:I});f.title=u,this.timeFilter===h.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(h.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let h of Is){let I=this.timeFilterCalendar?h.calLong:h.rollLong,u=l.createEl("option",{text:I});u.value=h.key,this.timeFilter===h.key&&(u.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!P.Platform.isMobile){let h=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,P.setIcon)(h,"minimize-2"),h.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",h.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=h=>{h.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=h=>{h.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"});he(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"});he(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;he(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(h=>h.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"});he(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(h=>h.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 h=i.createDiv({cls:"stashpad-mobile-filters-section"}),I=h.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=h.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 h=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),I=h.createEl("input",{type:"checkbox"});I.checked=this.importedOnly,h.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),h.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),h.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=se(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"}),B=C.createDiv({cls:"stashpad-view-popover-main"});B.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let E=B.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"});he(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"});he(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 override for this tab.`,s&&i.addClass("is-override"),i.onclick=h=>{h.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=h=>{h.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=h=>{h.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let h of Is){let I=this.timeFilterCalendar?h.calShort:h.rollShort,u=this.timeFilterCalendar?h.calLong:h.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:I});f.title=u,this.timeFilter===h.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(h.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let h of Is){let I=this.timeFilterCalendar?h.calLong:h.rollLong,u=l.createEl("option",{text:I});u.value=h.key,this.timeFilter===h.key&&(u.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!P.Platform.isMobile){let h=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,P.setIcon)(h,"minimize-2"),h.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",h.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=h=>{h.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=h=>{h.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(h=>h.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(h=>h.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 h=i.createDiv({cls:"stashpad-mobile-filters-section"}),I=h.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=h.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 h=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),I=h.createEl("input",{type:"checkbox"});I.checked=this.importedOnly,h.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),h.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),h.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 h=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,P.setIcon)(h,this.compactMode?"panel-top":"rows-2"),h.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&h.addClass("is-active"),h.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=h=>{h.preventDefault(),this.openCrumbMenu(h,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(` `):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"}),h=p.createDiv({cls:"stashpad-note-meta-top"});h.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let I=this.colorForNode(e),u=h.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 B=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(B,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 h=c.scrollHeight>c.clientHeight+4;if(o.ovW=p,o.ovV=h,!h&&!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 Le(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"}),h=p.createDiv({cls:"stashpad-note-meta-top"});h.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let I=this.colorForNode(e),u=h.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 h=c.scrollHeight>c.clientHeight+4;if(o.ovW=p,o.ovV=h,!h&&!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 Le(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(` `)?` `:"";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 h=n.createDiv({cls:"stashpad-composer-btn-rail"}),I=h.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 B=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 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 h=n.createDiv({cls:"stashpad-composer-btn-rail"}),I=h.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&&B(N)}a.focus()});let w=h.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,P.setIcon)(w,"chevron-left"),w.title="Show more composer options",h.insertBefore(w,I);let y=D=>{h.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(!h.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=h.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,h=await this.plugin.lockNoteSubtree(i,l.id,p,{silent:!0,blobFolder:e});h&&a.push(h.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 jt(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 jt(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 jt(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 jt(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," "),h,I=c?.parent??null;if(I&&I!==M){let u=r.get(I);u&&(h=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:l,folder:o,id:g,title:p,body:"",parentBlurb:h,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 Qe(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(h=>h.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 h=this.app.vault.getAbstractFileByPath(p.path);if(h)try{await this.app.fileManager.processFrontMatter(h,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 jt(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,h)=>{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,B=f?f[2]:"";for(let E=1;E<1e3;E++){let w=`${C}-${E}${B}.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:h});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,h=>{h.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(h){new P.Notice(`Move failed for ${p.id}: ${h.message}`)}if(It().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{Oe(this.app,p),Oe(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 h=this.app.vault.getAbstractFileByPath(p.newPath);if(h)try{await this.app.fileManager.renameFile(h,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(h,I=>{I.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let h=this.app.vault.getAbstractFileByPath(p.oldPath);if(h)try{await this.app.fileManager.renameFile(h,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(h,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 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=h.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,P.setIcon)(w,"chevron-left"),w.title="Show more composer options",h.insertBefore(w,I);let y=D=>{h.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(!h.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=h.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,h=await this.plugin.lockNoteSubtree(i,l.id,p,{silent:!0,blobFolder:e});h&&a.push(h.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," "),h,I=c?.parent??null;if(I&&I!==M){let u=r.get(I);u&&(h=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:l,folder:o,id:g,title:p,body:"",parentBlurb:h,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 Qe(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(h=>h.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 h=this.app.vault.getAbstractFileByPath(p.path);if(h)try{await this.app.fileManager.processFrontMatter(h,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,h)=>{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:h});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,h=>{h.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(h){new P.Notice(`Move failed for ${p.id}: ${h.message}`)}if(It().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{Oe(this.app,p),Oe(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 h=this.app.vault.getAbstractFileByPath(p.newPath);if(h)try{await this.app.fileManager.renameFile(h,p.oldPath),p.isRoot&&await this.app.fileManager.processFrontMatter(h,I=>{I.parent=p.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let p of n){let h=this.app.vault.getAbstractFileByPath(p.oldPath);if(h)try{await this.app.fileManager.renameFile(h,p.newPath),p.isRoot&&await this.app.fileManager.processFrontMatter(h,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(` `),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 h=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${h}"`}),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 B=this.currentChildren.findIndex(E=>E.id===u);B<0||(this.selection.add(u),this.cursorIdx=B,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,B=>{B.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,B=>{B.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=yt(),c=Nt(a,this.activeStopwords()),g=xt(c,l),p=`${this.noteFolder}/${g}`,h=new Date().toISOString(),I=this.extractAttachments(a),u=["---",`id: ${l}`,`parent: ${e}`,`created: ${h}`];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[B,E]of Object.entries(r))ie.includes(B)||(C[B]=E)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:f,created:h})}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:ye(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 h=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${h}"`}),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}`,h=new Date().toISOString(),I=this.extractAttachments(a),u=["---",`id: ${l}`,`parent: ${e}`,`created: ${h}`];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:h})}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:ye(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} ${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(` `);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 h=s;h&&h!==M;h=this.tree.get(h)?.parent??null)if(g.has(h)){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(h=>h.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:ye(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,h)=>{if(!s.has(p.id)){s.add(p.id),i.push({node:p,depth:h});for(let I of this.tree.getChildren(p.id))n(I,h+1)}};for(let p of e)n(p,0);let o=this.noteFolder,a=It().prefixTimestampsOnCopy,r=[];for(let{node:p,depth:h}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(h)}- ${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(h){console.warn("[Stashpad] cut-paste delete failed",p.file.path,h)}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 h=this.app.vault.getAbstractFileByPath(p.path);if(h)try{await this.app.fileManager.trashFile(h)}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 jt(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:ye(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 +`));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(h){console.warn("[Stashpad] cut-paste delete failed",p.file.path,h)}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 h=this.app.vault.getAbstractFileByPath(p.path);if(h)try{await this.app.fileManager.trashFile(h)}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:ye(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 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?Se(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.authorRegistry.all().map(a=>({id:a.id,name:a.name})),o=Ze(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,h=>{e===null?delete h.due:(h.due=e,h.task=!0),a.length>0?(h.assignedTo=a,o&&(h.assignedBy=o.link),h.task=!0):(delete h.assignedTo,delete h.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 ${Ce(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.authorRegistry.all().map(o=>({id:o.id,name:o.name})),n=Ze(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)),h=p.indexOf(i);h<0&&(h=p.length),s==="after"&&(h+=1);let I=[...p.slice(0,h),...t.filter(S=>!!this.tree.get(S)),...p.slice(h)];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 B=this.selectionGuardKey,E=()=>{if(this.selectionGuardKey!==B||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(B=>this.tree.get(B)).filter(B=>!!B&&!!B.file);if(n.length===0)return;if(n.some(B=>B.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 B of n)if(this.isDescendant(e,B.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(B)}" 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(B=>(B.parent??M)!==o)){let B=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(B.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(B=>B.id),c=this.tree.getChildren(r).map(B=>B.id),g=new Set(l),p=c.filter(B=>!g.has(B)),h=p.indexOf(e);if(h<0)return;i==="after"&&(h+=1);let I=[...p.slice(0,h),...l,...p.slice(h)];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(B=>this.tree.get(B)).filter(B=>!!B);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 B=this.order.cache.get(u)??{};delete B[r],this.order.cache.set(u,B)}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(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(g.length===0)return;if(new Set(g.map(h=>h.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(fe(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 B=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:B,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,h=r.length>0&&g.confirmAttachmentDelete;if(!p&&!h){await c(!1);return}new Ne(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,r.length,h,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 h=s.startsWith("---")?s.slice(0,s.indexOf(` +`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===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?Se(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=Ze(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,h=>{e===null?delete h.due:(h.due=e,h.task=!0),a.length>0?(h.assignedTo=a,o&&(h.assignedBy=o.link),h.task=!0):(delete h.assignedTo,delete h.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=Ze(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)),h=p.indexOf(i);h<0&&(h=p.length),s==="after"&&(h+=1);let I=[...p.slice(0,h),...t.filter(S=>!!this.tree.get(S)),...p.slice(h)];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)),h=p.indexOf(e);if(h<0)return;i==="after"&&(h+=1);let I=[...p.slice(0,h),...l,...p.slice(h)];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(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(g.length===0)return;if(new Set(g.map(h=>h.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,h=r.length>0&&g.confirmAttachmentDelete;if(!p&&!h){await c(!1);return}new Ne(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,r.length,h,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 h=s.startsWith("---")?s.slice(0,s.indexOf(` ---`,3)+4):"",I=h+(h?` `:"")+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(),B=await this.createNoteUnder(g,u,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:B,...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=B?this.tree.get(B):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(h){new P.Notice(`Stashpad: split failed (${h.message})`),console.error(h)}};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??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(h){new P.Notice(`Stashpad: split failed (${h.message})`),console.error(h)}};new ti(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=yt(),a=null;{let f=(this.plugin.settings.noteTemplates??{})[s];if(f){let C=this.app.vault.getAbstractFileByPath(f);if(C&&C.extension==="md")try{let B=await this.app.vault.cachedRead(C),E=this.stripFrontmatter(B);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 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} -${E}`):t=E}catch(B){console.warn("[Stashpad] template read failed",B)}}}let r=Nt(t,this.activeStopwords()),l=xt(r,o),c=`${s}/${l}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),h=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,'\\"')}"`),h.length>0){u.push("attachments:");for(let f of h)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 B=s.split("/").pop()||s,E=(t.split(` -`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${E}" landed in \`${B}\``,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,B=>{for(let[E,w]of Object.entries(a))ie.includes(E)||B[E]===void 0&&(B[E]=w)})}catch(B){console.warn("[Stashpad] template fm overlay failed",B)}}}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 B=this.app.vault.getAbstractFileByPath(c);if(B)try{await this.app.fileManager.trashFile(B)}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("|"),B=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",B),w.setAttribute("href",B)},h=[];r&&h.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(I,n)}),l&&h.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&I.createSpan({text:", "}),p(I,u)})}),c&&h.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"edited "}),I.createSpan({text:this.formatTimeInline(a)})}),h.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=ye(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=>fe(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=Nt(t,this.activeStopwords()),l=xt(r,o),c=`${s}/${l}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),h=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,'\\"')}"`),h.length>0){u.push("attachments:");for(let f of h)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)},h=[];r&&h.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(I,n)}),l&&h.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((u,f)=>{f>0&&I.createSpan({text:", "}),p(I,u)})}),c&&h.push(I=>{I.createSpan({cls:"stashpad-authorship-label",text:"edited "}),I.createSpan({text:this.formatTimeInline(a)})}),h.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=ye(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.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(fe(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 B=this.currentChildren.findIndex(x=>x.id===t.id),E=null;if(B>=0){for(let x=B+1;x<this.currentChildren.length;x++)if(this.currentChildren[x].id!==t.id){E=this.currentChildren[x].id;break}if(!E){for(let x=B-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,h=r.length>0&&g.confirmAttachmentDelete;if(!p&&!h){await c(!1),this.focusView();return}new Ne(this.app,this.titleForNode(t),e.length,r.length,h,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(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,h=r.length>0&&g.confirmAttachmentDelete;if(!p&&!h){await c(!1),this.focusView();return}new Ne(this.app,this.titleForNode(t),e.length,r.length,h,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(` `),"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(h=>h.id!==e.id).filter(h=>!!h.file),a=o.map(h=>({id:h.id,path:h.file.path,was:h.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,h=>{h.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,h=>{h.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let h of o)await this.app.fileManager.processFrontMatter(h.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(h.id,t.id,e.id);if(r.length>0){let h=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,h)}let g=o.map(h=>h.id),p=[t.id,...l.filter(h=>h!==t.id&&!g.includes(h)),...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 h of a)await this.log.append({type:"parent_change",id:h.id,payload:{from:h.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 h=this.tree.get(t.id),I=this.tree.get(e.id);h?.file&&await this.app.fileManager.processFrontMatter(h.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,h=()=>{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(h,120),setTimeout(h,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,h=()=>{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(h,120),setTimeout(h,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 te=require("obsidian");Et();var Cr=te.moment,Cs=class extends te.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0}getViewType(){return ke}getDisplayText(){return"Encrypted trash"}getIcon(){return"trash-2"}async onOpen(){this.containerEl.addClass("stashpad-trash-view"),this.registerEvent(this.app.vault.on("create",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),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,te.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,te.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,te.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 h 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":h.meta?.title||"Locked note"});let f=h.meta?.deletedAt?`deleted ${Cr(h.meta.deletedAt).fromNow()}`:"deleted",C=h.meta&&h.meta.count>1?` \xB7 ${h.meta.count} ${h.meta.kind==="rawtrash"?"files":"notes"}`:"";u.createSpan({cls:"stashpad-trash-sub",text:f+C});let B=I.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,te.setIcon)(B.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),B.onclick=async()=>{B.disabled=!0,await this.plugin.restoreDeletedAt(h.blob)?await this.render():B.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function Wo(d){let{workspace:A}=d.app,t=A.getLeavesOfType(ke);if(t.length>0){A.revealLeaf(t[0]);return}let e=A.getLeaf("tab");await e.setViewState({type:ke,active:!0}),A.revealLeaf(e)}Et();var dt=require("obsidian");Et();Mt();var Bs=class d extends dt.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return Ie}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),h=t.createDiv({cls:"stashpad-pinned-row"});a&&(h.addClass("has-color"),h.style.setProperty("--stashpad-note-color",a)),r&&h.addClass("is-completed"),h.draggable=!0,h.dataset.pinIdx=String(n),h.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),h.addClass("is-dragging")}),h.addEventListener("dragend",()=>h.removeClass("is-dragging")),h.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let B=h.getBoundingClientRect(),E=C.clientY-B.top<B.height/2;h.toggleClass("drop-before",E),h.toggleClass("drop-after",!E)}),h.addEventListener("dragleave",()=>{h.removeClass("drop-before"),h.removeClass("drop-after")}),h.addEventListener("drop",C=>{C.preventDefault(),h.removeClass("drop-before"),h.removeClass("drop-after");let B=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(B)||B===n)return;let E=h.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(B,w?n:n+1)});let I=h.createSpan({cls:"stashpad-pinned-toggle"});c&&(Ee(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=h.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let f=h.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},h.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),h.oncontextmenu=C=>{C.preventDefault();let B=new dt.Menu;B.addItem(E=>E.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),B.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}`,h=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&&(Ee(u,c.length,h),u.onclick=B=>{B.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&&h&&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=d.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=d.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(d.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==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(d.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let 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 h=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(h,"plus-square"),h.setAttr("aria-label","Open in new tab"),h.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(` +`),"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(h=>h.id!==e.id).filter(h=>!!h.file),a=o.map(h=>({id:h.id,path:h.file.path,was:h.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,h=>{h.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,h=>{h.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let h of o)await this.app.fileManager.processFrontMatter(h.file,I=>{I.parent=e.id}),this.fmSync.scheduleParentChange(h.id,t.id,e.id);if(r.length>0){let h=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,h)}let g=o.map(h=>h.id),p=[t.id,...l.filter(h=>h!==t.id&&!g.includes(h)),...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 h of a)await this.log.append({type:"parent_change",id:h.id,payload:{from:h.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 h=this.tree.get(t.id),I=this.tree.get(e.id);h?.file&&await this.app.fileManager.processFrontMatter(h.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,h=()=>{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(h,120),setTimeout(h,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,h=()=>{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(h,120),setTimeout(h,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 ke}getDisplayText(){return"Encrypted trash"}getIcon(){return"trash-2"}async onOpen(){this.containerEl.addClass("stashpad-trash-view"),this.registerEvent(this.app.vault.on("create",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),this.registerEvent(this.app.vault.on("delete",t=>{t.path.startsWith("_deleted/")&&this.scheduleRender()})),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 h 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":h.meta?.title||"Locked note"});let f=h.meta?.deletedAt?`deleted ${Cr(h.meta.deletedAt).fromNow()}`:"deleted",C=h.meta&&h.meta.count>1?` \xB7 ${h.meta.count} ${h.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(h.blob)?await this.render():m.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function Wo(d){let{workspace:A}=d.app,t=A.getLeavesOfType(ke);if(t.length>0){A.revealLeaf(t[0]);return}let e=A.getLeaf("tab");await e.setViewState({type:ke,active:!0}),A.revealLeaf(e)}yt();var dt=require("obsidian");yt();Ht();var ms=class d 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),h=t.createDiv({cls:"stashpad-pinned-row"});a&&(h.addClass("has-color"),h.style.setProperty("--stashpad-note-color",a)),r&&h.addClass("is-completed"),h.draggable=!0,h.dataset.pinIdx=String(n),h.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),h.addClass("is-dragging")}),h.addEventListener("dragend",()=>h.removeClass("is-dragging")),h.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=h.getBoundingClientRect(),E=C.clientY-m.top<m.height/2;h.toggleClass("drop-before",E),h.toggleClass("drop-after",!E)}),h.addEventListener("dragleave",()=>{h.removeClass("drop-before"),h.removeClass("drop-after")}),h.addEventListener("drop",C=>{C.preventDefault(),h.removeClass("drop-before"),h.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let E=h.getBoundingClientRect(),w=C.clientY-E.top<E.height/2;this.reorderPin(m,w?n:n+1)});let I=h.createSpan({cls:"stashpad-pinned-toggle"});c&&(Ee(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=h.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let f=h.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},h.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),h.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}`,h=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&&(Ee(u,c.length,h),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&&h&&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=d.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=d.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(d.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==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(d.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let 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 h=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(h,"plus-square"),h.setAttr("aria-label","Open in new tab"),h.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 ms(d){let A=d.workspace.getLeavesOfType(Ie);if(A.length>0){d.workspace.revealLeaf(A[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new dt.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:Ie,active:!0}),d.workspace.revealLeaf(t)}Mt();xe();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))}};Et();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");Et();Kt();xe();xi();Mt();var ws=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),$o="_archive",Xo=new Set([oe,"edtz","stashenc","stashmeta"]),ze=class ze{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(),ze.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}=Ht(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(` +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(d){let A=d.workspace.getLeavesOfType(ue);if(A.length>0){d.workspace.revealLeaf(A[0]);return}let t=d.workspace.getLeftLeaf(!1);if(!t){new dt.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:ue,active:!0}),d.workspace.revealLeaf(t)}Ht();xe();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();xe();xi();Ht();var ws=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),$o="_archive",Xo=new Set([ae,"edtz","stashenc","stashmeta"]),ze=class ze{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(),ze.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(` `),p=l.length>5?` \u2026and ${l.length-5} more`:"",h=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(h==="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(h==="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(B){console.warn("[Stashpad] replace: couldn't remove prior note",f,B)}}}}if(o=a.length+n,o>=ze.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,h=g.extension==="md"?await this.importMarkdown(g):await this.importOtherFile(g);h&&(c.push(h),this.plugin.importLog.append({ts:new Date().toISOString(),folder:h.folder,kind:h.kind,originalName:g.name,size:p,sourcePath:g.path,notePaths:h.kind==="folder"?h.notePaths:[h.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}=Ht(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))ie.includes(g)||(a[g]=p);a.id=yt(),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,ae(a,s)),{kind:"md",folder:t,archivePath:o,notePath:c,originalName:A.name}}async importOtherFile(A){let t=A.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,A.name);await this.app.fileManager.renameFile(A,i);let s=A.basename,n=yt(),o={id:n,parent: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(h==="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(h==="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>=ze.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,h=g.extension==="md"?await this.importMarkdown(g):await this.importOtherFile(g);h&&(c.push(h),this.plugin.importLog.append({ts:new Date().toISOString(),folder:h.folder,kind:h.kind,originalName:g.name,size:p,sourcePath:g.path,notePaths:h.kind==="folder"?h.notePaths:[h.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} ![[${i}]] -`,r=Nt(s)||s,l=await this.uniquePath(t,xt(r,n));return await this.createNote(l,ae(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=yt();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,ae(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}=Ht(a),c={};for(let[f,C]of Object.entries(r))ie.includes(f)||(c[f]=C);let g=typeof r.id=="string"&&r.id?r.id:null,p=g&&!s.has(g)?g:yt();s.add(p),c.id=p,c.parent=e;let h=this.preservedTimes(r,o);c.created=h.created,h.modified&&(c.modified=h.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,ae(c,l)),i.push(u)}else{if(Xo.has(o.extension))continue;{let a=yt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[Ot(o.path)]},l=`${o.basename} +`,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 h=this.preservedTimes(r,o);c.created=h.created,h.modified&&(c.modified=h.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} ![[${o.path}]] -`,c=Nt(o.basename)||o.basename,g=await this.uniquePath(t,xt(c,a));await this.createNote(g,ae(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 Pe(this.app,n,{...s,secretId:_e(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: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===oe);if(i.length===0)return 0;let s=this.liveRootIds(e),n=0;for(let o of i)await this.importOneStash(o,e,s,!!t.auto)&&n++;return n}async importLooseInto(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}};ze.DEBOUNCE_MS=900,ze.BATCH_CONFIRM_AT=8;var vs=ze;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={...le};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{}}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??Bi(),async h=>{this.settings.encryption=h,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",h=>this.renderCacheStore.evict(h.path))),this.registerEvent(this.app.vault.on("rename",(h,I)=>this.renderCacheStore.evict(I))),await this.authorRegistry.load();{let h=(this.settings.authorId??"").trim();h&&this.authorRegistry.record({id:h,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{this.reconcileLockedRegistry(),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,h=>new us(h,this)),this.registerView(ue,h=>new is(h,this)),this.registerView(ee,h=>new Ti(h,this)),this.registerView(ke,h=>new Cs(h,this)),this.registerView(Ie,h=>new Bs(h,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",h=>{h&&h.view.getViewType()===ct&&(this.lastActiveStashpadLeaf=h,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(ue).length===0&&setTimeout(()=>{ss(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let h=_t(),I=!!h&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===h,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=h=>{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&&h.head.querySelector(C))continue;let B=h.createElement("style");f?B.setAttribute("data-stashpad-source",f):B.setAttribute("data-stashpad-source","anon"),B.textContent=u.textContent??"",h.head.appendChild(B)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",h=>{let I=h?.doc??h?.win?.document??null;I&&e(I)})),this.registerEvent(this.app.workspace.on("file-menu",(h,I)=>{if(!(I instanceof $.TFolder))return;let u=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(u)&&h.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(u))})})),setTimeout(()=>{try{let h=this.app.workspace;typeof h.iterateAllLeaves=="function"&&h.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 h=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=h&&h.isConnected?h.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",h=>{h.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{Ui(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{ms(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=h=>{let I=_t();I&&typeof I[h]=="function"&&I[h]()};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 h=bt.report();console.log(h);try{await navigator.clipboard.writeText(h)}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:h}=await Promise.resolve().then(()=>(Mt(),Ai));new h(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:h=>{let I=this.importService.defaultDestination();return h?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:h=>{let I=this.importService.defaultDestination();return h?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:h=>{let I=this.importService.defaultDestination();return h?!!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 ms(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:h=>{let I=this.app.workspace.getActiveFile(),u=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return h||u&&I&&this.revealNoteInStashpad(I),u}});let a=Object.keys(li);for(let h of a){let I=li[h];this.addCommand({id:`stashpad-open-panels-${h}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await Ui(this.app),this.app.workspace.getLeavesOfType(ee)[0]?.view?.setActivePanel?.(h)}})}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:h=>{let I=_t(),u=I&&I.noteFolder;return u?(h||(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 h=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${h.total} author(s) \u2014 ${h.fromStubs} from stubs, ${h.fromNotes} from note links.`,kind:"success",category:"system"})}catch(h){new $.Notice(`Author registry rebuild failed: ${h.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 h=await this.restoreMissingAuthorStubs();this.notifications.show({message:h.created>0?`Restored ${h.created} author stub(s) across ${h.folders} folder(s).`:`No missing author stubs \u2014 all present across ${h.folders} folder(s).`,kind:"success",category:"system"})}catch(h){new $.Notice(`Restore author stubs failed: ${h.message}`)}}}),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:h,fmChecked:I,fmWritten:u,slugsRenamed:f,authors:C,imported:B,attachmentsLinked:E}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${h.length} folder${h.length===1?"":"s"}`),B>0&&w.push(`imported ${B} loose file${B===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(h){new $.Notice(`Stashpad: rebootstrap failed (${h.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:h=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(h||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Mt(),Ai)).then(({NotificationHistoryModal:h,LogModal:I})=>{new h(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 h of r){let I=`stashpad-toggle-${String(h.key).replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${h.label}`,callback:async()=>{let u=!this.settings[h.key];this.settings[h.key]=u,await this.saveSettings(),new $.Notice(`${h.label}: ${u?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id),setTimeout(()=>{h?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let h of ji)this.addCommand({id:`stashpad-open-settings-${h.id}`,name:`Open Stashpad settings: ${h.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let l=()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.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:h}=await Promise.resolve().then(()=>(di(),Ri)),I=await h(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(),Ri));u(this.app,I)}catch(h){console.error("[stashpad] preview failed",h),new $.Notice(`Preview failed: ${h?.message??h}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:h,scanForJdNotes:I,JdBuildConfirmModal:u}=await Promise.resolve().then(()=>(di(),Ri));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 h(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(h){console.error("[stashpad] build failed",h),new $.Notice(`Build failed: ${h?.message??h}`,8e3)}}});let c=h=>{if(h.extension!==oe)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),u=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=h.parent?.path||"",C=f.split("/").pop()??"";if(I&&C===I){if(u&&f.endsWith(`/${u}`))return;let B=f.slice(0,f.length-I.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(h,B);return}this.settings.autoImport&&this.importService.isArmed()&&(De(h.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(h,f))};this.registerEvent(this.app.vault.on("create",h=>{h instanceof $.TFile&&c(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof $.TFile&&c(h)}));let g=h=>{if(h.extension!=="md")return;let I=h.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(h)},800)},p=h=>{if(h.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let u=h.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(h,C)},200)};this.registerEvent(this.app.vault.on("create",h=>{h instanceof $.TFile&&(g(h),p(h))})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof $.TFile&&(g(h),p(h))})),this.registerEvent(this.app.vault.on("delete",h=>{if(!(h instanceof $.TFolder))return;let I=h.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(h,I)=>{h instanceof $.TFile&&this.maybeReHomeOnCrossFolderMove(h,I)})),this.registerEvent(this.app.vault.on("rename",(h,I)=>{h instanceof $.TFile&&this.maybeArchiveOnMoveIn(h,I)})),this.registerEvent(this.app.vault.on("create",h=>{h instanceof $.TFile?this.importService.enqueue(h):h instanceof $.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof $.TFile?this.importService.enqueue(h):h instanceof $.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",(h,I)=>{h instanceof $.TFile&&this.maybeAdoptAuthorRename(h,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,h=!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(),h=!0))}),!g&&!p&&!h)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:h}}),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 Pe(this.app,i);if(!s)return;let n=_t(),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: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=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 Pe(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}};ze.DEBOUNCE_MS=900,ze.BATCH_CONFIRM_AT=8;var vs=ze;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 h=>{this.settings.encryption=h,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",h=>this.renderCacheStore.evict(h.path))),this.registerEvent(this.app.vault.on("rename",(h,I)=>this.renderCacheStore.evict(I))),await this.authorRegistry.load();{let h=(this.settings.authorId??"").trim();h&&this.authorRegistry.record({id:h,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,h=>new us(h,this)),this.registerView(fe,h=>new is(h,this)),this.registerView(ie,h=>new Ti(h,this)),this.registerView(ke,h=>new Cs(h,this)),this.registerView(ue,h=>new ms(h,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",h=>{h&&h.view.getViewType()===ct&&(this.lastActiveStashpadLeaf=h,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(fe).length===0&&setTimeout(()=>{ss(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let h=jt(),I=!!h&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===h,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=h=>{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&&h.head.querySelector(C))continue;let m=h.createElement("style");f?m.setAttribute("data-stashpad-source",f):m.setAttribute("data-stashpad-source","anon"),m.textContent=u.textContent??"",h.head.appendChild(m)}}catch(I){console.warn("[Stashpad] inject popout styles failed",I)}};this.registerEvent(this.app.workspace.on("window-open",h=>{let I=h?.doc??h?.win?.document??null;I&&e(I)})),this.registerEvent(this.app.workspace.on("file-menu",(h,I)=>{if(!(I instanceof $.TFolder))return;let u=I.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(u)&&h.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(u))})})),setTimeout(()=>{try{let h=this.app.workspace;typeof h.iterateAllLeaves=="function"&&h.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 h=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),I=h&&h.isConnected?h.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",h=>{h.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=h=>{let I=jt();I&&typeof I[h]=="function"&&I[h]()};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 h=bt.report();console.log(h);try{await navigator.clipboard.writeText(h)}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:h}=await Promise.resolve().then(()=>(Ht(),Ai));new h(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:h=>{let I=this.importService.defaultDestination();return h?!!I:(I&&this.runImportLooseFiles(I),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:h=>{let I=this.importService.defaultDestination();return h?!!I:(I&&this.runFolderSlugPass(I),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:h=>{let I=this.importService.defaultDestination();return h?!!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:h=>{let I=this.app.workspace.getActiveFile(),u=!!I&&I.extension==="md"&&this.isStashpadNoteFile(I);return h||u&&I&&this.revealNoteInStashpad(I),u}});let a=Object.keys(li);for(let h of a){let I=li[h];this.addCommand({id:`stashpad-open-panels-${h}`,name:`Open Stashpad panel: ${I.label}`,callback:async()=>{await Ui(this.app),this.app.workspace.getLeavesOfType(ie)[0]?.view?.setActivePanel?.(h)}})}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:h=>{let I=jt(),u=I&&I.noteFolder;return u?(h||(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 h=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${h.total} author(s) \u2014 ${h.fromStubs} from stubs, ${h.fromNotes} from note links.`,kind:"success",category:"system"})}catch(h){new $.Notice(`Author registry rebuild failed: ${h.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 h=await this.restoreMissingAuthorStubs();this.notifications.show({message:h.created>0?`Restored ${h.created} author stub(s) across ${h.folders} folder(s).`:`No missing author stubs \u2014 all present across ${h.folders} folder(s).`,kind:"success",category:"system"})}catch(h){new $.Notice(`Restore author stubs failed: ${h.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:h,fmChecked:I,fmWritten:u,slugsRenamed:f,authors:C,imported:m,attachmentsLinked:E}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${h.length} folder${h.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(h){new $.Notice(`Stashpad: rebootstrap failed (${h.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:h=>{let I=this.app.workspace.getActiveFile();return!I||I.extension!=="md"?!1:(h||this.adoptNote(I),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ht(),Ai)).then(({NotificationHistoryModal:h,LogModal:I})=>{new h(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 h of r){let I=`stashpad-toggle-${String(h.key).replace(/[A-Z]/g,u=>`-${u.toLowerCase()}`)}`;this.addCommand({id:I,name:`Toggle: ${h.label}`,callback:async()=>{let u=!this.settings[h.key];this.settings[h.key]=u,await this.saveSettings(),new $.Notice(`${h.label}: ${u?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.openTabById(this.manifest.id),setTimeout(()=>{h?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let h of ji)this.addCommand({id:`stashpad-open-settings-${h.id}`,name:`Open Stashpad settings: ${h.label}`,callback:()=>{let I=this.app.setting;!I?.open||!I?.openTabById||(I.open(),I.openTabById(this.manifest.id))}});let l=()=>{let h=this.app.setting;!h?.open||!h?.openTabById||(h.open(),h.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:h}=await Promise.resolve().then(()=>(di(),Gi)),I=await h(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(h){console.error("[stashpad] preview failed",h),new $.Notice(`Preview failed: ${h?.message??h}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:h,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 h(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(h){console.error("[stashpad] build failed",h),new $.Notice(`Build failed: ${h?.message??h}`,8e3)}}});let c=h=>{if(h.extension!==ae)return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),u=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=h.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(h,m);return}this.settings.autoImport&&this.importService.isArmed()&&(De(h.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(h,f))};this.registerEvent(this.app.vault.on("create",h=>{h instanceof $.TFile&&c(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof $.TFile&&c(h)}));let g=h=>{if(h.extension!=="md")return;let I=h.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(I)&&setTimeout(()=>{this.fixOrphanParentForFile(h)},800)},p=h=>{if(h.extension!=="md")return;let I=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!I)return;let u=h.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(h,C)},200)};this.registerEvent(this.app.vault.on("create",h=>{h instanceof $.TFile&&(g(h),p(h))})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof $.TFile&&(g(h),p(h))})),this.registerEvent(this.app.vault.on("delete",h=>{if(!(h instanceof $.TFolder))return;let I=h.path.replace(/\/+$/,"");this.knownStashpadFolders.has(I)&&this.handleStashpadFolderDeleted(I)})),this.registerEvent(this.app.vault.on("rename",(h,I)=>{h instanceof $.TFile&&this.maybeReHomeOnCrossFolderMove(h,I)})),this.registerEvent(this.app.vault.on("rename",(h,I)=>{h instanceof $.TFile&&this.maybeArchiveOnMoveIn(h,I)})),this.registerEvent(this.app.vault.on("create",h=>{h instanceof $.TFile?this.importService.enqueue(h):h instanceof $.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof $.TFile?this.importService.enqueue(h):h instanceof $.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",(h,I)=>{h instanceof $.TFile&&this.maybeAdoptAuthorRename(h,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,h=!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(),h=!0))}),!g&&!p&&!h)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:h}}),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 Pe(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 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 h of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(h)?.frontmatter?.id!==t)continue;let u=h.parent?.path;u&&e.add(u)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async h=>{if(h&&!await this.app.vault.adapter.exists(h))try{await this.app.vault.createFolder(h)}catch(I){let u=I?.message??"";if(!/already exists/i.test(u))throw I}},a=0,r=0,l=0,c=0;for(let h of e)try{if(i&&await o(`${h}/${i}`),s&&await o(`${h}/${s}`),this.settings.autoImport)try{let u=await this.importService.importLooseInto(h);c+=u.files+u.folders+u.stashes}catch(u){console.warn("Stashpad: loose sweep failed",h,u)}let I=await Oe(this.app,h);a+=I.checked,r+=I.written,l+=await this.rebootstrapFolderSlugs(h),n.push(h)}catch(I){console.warn(`Stashpad: rebootstrap skipped ${h}`,I)}let g=0;try{g=(await this.rebuildAuthorRegistry()).total}catch(h){console.warn("Stashpad: rebootstrap author-registry rebuild failed",h)}let p=0;try{p=await this.convertAttachmentsToLinks()}catch(h){console.warn("Stashpad: attachment-link conversion failed",h)}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=ye(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),h=xt(p,r);if(a.name===h)continue;let I=a.parent?`${a.parent.path}/${h}`:h;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(ee);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=_t(),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,h=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},B=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)&&B.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)B.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);B.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 B.push(...w),p.encryption?.isConfigured?.()&&C("trash deleted encrypted")&&B.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),B}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(()=>(Mt(),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 B=>{if(B)try{await p.activateViewForFolder(f)}catch(E){new $.Notice(`Stashpad: couldn't convert folder (${E.message})`)}}).open();return}}}(this.app);h.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"),h.open()}async openTinyWindow(){let t=_t(),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 ms(this.app);let t=this.app.workspace.getLeavesOfType(Ie)[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 Wt(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 mo(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): +---`,3)+4).replace(/^\r?\n/,""):c,p=Nt(g,s),h=xt(p,r);if(a.name===h)continue;let I=a.parent?`${a.parent.path}/${h}`:h;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,h=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);h.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"),h.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): ${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=Ht(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=Ht(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 Je(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),h=p>0?a[p-1]:null;await this.lockNoteSubtree(e,g,h,{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=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 Je(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),h=p>0?a[p-1]:null;await this.lockNoteSubtree(e,g,h,{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=Ht(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 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): ${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=Ht(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),B=a.get(u)?.has(f)??!1;if(!C&&!B){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 B=E=>E===e?2:E.isDeferred?0:1;return B(C)-B(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,h=document.createDocumentFragment();return h.createEl("div",{text:g+r>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),h.createEl("div",{text:`\u2022 ${g} duplicate tab${g===1?"":"s"} closed`}),h.createEl("div",{text:`\u2022 ${r} orphaned tab${r===1?"":"s"} pruned (note no longer exists)`}),h.createEl("div",{text:`\u2022 ${p} Stashpad tab${p===1?"":"s"} remaining`}),new $.Notice(h,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 h=s.get(p);l&&h.authored++,c&&h.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return se(t)}authorRefFor(t,e,i){let s=i.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${s}-${e}.md`,o=i.replace(/[\[\]|]/g,"").trim()||s;return`[[${n}|${o}]]`}async ensureAuthorStubFor(t,e,i){if(!e||!i)return;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),r=`${s}/${a}-${e}.md`;try{if(await this.ensureFolderPath(s),await this.app.vault.adapter.exists(r))return;await this.app.vault.create(r,this.buildAuthorStub({id:e,name:i,role:o?.role,department:o?.department},new Date().toISOString()))}catch(l){console.warn("[Stashpad] ensureAuthorStubFor failed",r,l)}}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,i=0;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=[];if(typeof o.author=="string"&&a.push(o.author),Array.isArray(o.contributors))for(let r of o.contributors)typeof r=="string"&&a.push(r);for(let r of a){let l=this.parseAuthorRef(r);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),i++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter,g=((Array.isArray(l?.aliases)?l.aliases.find(u=>typeof u=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||r.name).trim(),p=typeof l?.role=="string"?l.role:void 0,h=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:h??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(` +`)}`,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,h=document.createDocumentFragment();return h.createEl("div",{text:g+r>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),h.createEl("div",{text:`\u2022 ${g} duplicate tab${g===1?"":"s"} closed`}),h.createEl("div",{text:`\u2022 ${r} orphaned tab${r===1?"":"s"} pruned (note no longer exists)`}),h.createEl("div",{text:`\u2022 ${p} Stashpad tab${p===1?"":"s"} remaining`}),new $.Notice(h,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 h=s.get(p);l&&h.authored++,c&&h.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=[];for(let n of this.app.vault.getMarkdownFiles()){if(n.path.includes("/_authors/"))continue;let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o||o.due==null)continue;let a=typeof o.id=="string"?o.id:"";if(!a)continue;let r=String(o.due),l=typeof o.due=="number"?o.due:Date.parse(r);if(!Number.isFinite(l)||l>t)continue;let c=`${a}@${r}`;e.has(c)||i.push({id:a,folder:(n.parent?.path??"").replace(/\/+$/,""),file:n,dueMs:l,key:c})}if(i.length===0)return;this.settings.notifiedDueKeys=[...this.settings.notifiedDueKeys??[],...i.map(n=>n.key)].slice(-2e3),await this.saveSettings();let s=async n=>{try{let a=Mt(await this.app.vault.cachedRead(n)).body.split(/\r?\n/).map(r=>r.trim()).find(r=>r.length>0);if(a)return a.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return n.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(i.length<=3)for(let n of i){let o=await s(n.file);this.notifications.show({message:`\u23F0 Task due: \u201C${o}\u201D (${Wt(n.dueMs,this.settings)})`,kind:"warning",category:"reminder",duration:0,folder:n.folder,affectedIds:[n.id],actions:[{label:"Open",onClick:()=>void this.revealNoteByRef(n.folder,n.id)}]})}else this.notifications.show({message:`\u23F0 ${i.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,h=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:h??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+"/")||De(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(h=>typeof h=="string"&&h.trim()?Ot(h):h):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}\` 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 Oe(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={...le,...t,shortcuts:{...le.shortcuts,...t?.shortcuts??{}},mod:{...le.mod,...t?.mod??{}},bindings:Br(t?.bindings,t?.shortcuts,t?.mod),customPalette:Array.isArray(t?.customPalette)?t.customPalette.filter(e=>typeof e=="string"&&/^#[0-9a-f]{6}$/i.test(e)):[],colorAliases:t?.colorAliases&&typeof t.colorAliases=="object"?t.colorAliases:{},noteTemplates:t?.noteTemplates&&typeof t.noteTemplates=="object"?t.noteTemplates:{},authorName:typeof t?.authorName=="string"?t.authorName:"",authorId:typeof t?.authorId=="string"?t.authorId:"",authorRole:typeof t?.authorRole=="string"?t.authorRole:"",authorDepartment:typeof t?.authorDepartment=="string"?t.authorDepartment:"",showAuthor:typeof t?.showAuthor=="boolean"?t.showAuthor:!0,showContributors:typeof t?.showContributors=="boolean"?t.showContributors:!0,showLastEdit:typeof t?.showLastEdit=="boolean"?t.showLastEdit:!0,viewModes:t?.viewModes&&typeof t.viewModes=="object"&&!Array.isArray(t.viewModes)?t.viewModes:{},includeAttachmentsInEverything:t?.includeAttachmentsInEverything&&typeof t.includeAttachmentsInEverything=="object"&&!Array.isArray(t.includeAttachmentsInEverything)?t.includeAttachmentsInEverything:{},hideChildlessNotes:t?.hideChildlessNotes&&typeof t.hideChildlessNotes=="object"&&!Array.isArray(t.hideChildlessNotes)?t.hideChildlessNotes:{},hideCompletedNotes:t?.hideCompletedNotes&&typeof t.hideCompletedNotes=="object"&&!Array.isArray(t.hideCompletedNotes)?t.hideCompletedNotes:{},mutedNotificationCategories:Array.isArray(t?.mutedNotificationCategories)?t.mutedNotificationCategories.filter(e=>typeof e=="string"):[],notificationHistoryLimit:typeof t?.notificationHistoryLimit=="number"&&Number.isFinite(t.notificationHistoryLimit)?t.notificationHistoryLimit:5e3,drafts:mr(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,h=typeof p?.id=="string"?p.id.trim():"";h&&e.add(h)}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 h=this.app.metadataCache.getFileCache(g)?.frontmatter,I=typeof h?.id=="string"?h.id.trim():"",u=h?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof h?.created=="string"&&h.created.trim()!=="",B=!I,E=!f,w=!C;!B&&!E&&!w||o.push({file:g,addId:B,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 h=this.app.metadataCache.getFileCache(g.file)?.frontmatter,I=p??h?.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 Br(d,A,t){let e=In();for(let i of Re){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(d&&typeof d=="object")for(let i of Re){let s=d[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of Re){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 mr(d){let A={};if(!d||typeof d!="object")return A;for(let[t,e]of Object.entries(d))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var 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)}}; +${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,h=typeof p?.id=="string"?p.id.trim():"";h&&e.add(h)}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 h=this.app.metadataCache.getFileCache(g)?.frontmatter,I=typeof h?.id=="string"?h.id.trim():"",u=h?.parent,f=typeof u=="string"?u.trim()!=="":u!=null,C=typeof h?.created=="string"&&h.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 h=this.app.metadataCache.getFileCache(g.file)?.frontmatter,I=p??h?.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(d,A,t){let e=In();for(let i of Ge){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(d&&typeof d=="object")for(let i of Ge){let s=d[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of Ge){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(d){let A={};if(!d||typeof d!="object")return A;for(let[t,e]of Object.entries(d))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var 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)}}; /*! Bundled license information: jszip/dist/jszip.min.js: diff --git a/manifest.json b/manifest.json index 07a7beb..9a82277 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.99.14", + "version": "0.99.19", "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 faff817..bea8d32 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.99.14", + "version": "0.99.19", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.99.19.md b/release-notes/0.99.19.md new file mode 100644 index 0000000..da7cfa1 --- /dev/null +++ b/release-notes/0.99.19.md @@ -0,0 +1,28 @@ +# 0.99.19 — Multiplayer authorship, task reminders, full settings search + +## Task due-date reminders + +- Setting a due date on a task now actually reminds you. Because a plugin can't + run while the app is closed, reminders fire **when Obsidian next launches** + (for anything that came due while it was closed) and on a periodic check while + it's open. Each is a persistent notification with an **Open** button, recorded + in the notification history under a new **Reminder** category (and respecting + its mute toggle). A reminder won't re-fire for the same task + date once shown. + +## Multiplayer authorship (shared vaults) + +- **Assigning works across the whole vault now.** The "Assign to" / due-date + picker lists every author found anywhere in the vault — not just the ones this + device's registry happens to know — so a coworker who's only worked in *other* + folders shows up with their real identity, and assigning them no longer creates + a duplicate. +- **New folders auto-populate** with every known author, so you can assign anyone + immediately without waiting for them to contribute there first. +- **New command: "Sync authors across all folders."** Backfills existing folders + so every known author exists everywhere — handy after adding a collaborator. + +## Settings search + +- Every Stashpad setting is now findable in Obsidian's settings search, including + the **Authorship**, **Templates** (color aliases / note templates), and **JD + Index** pages — previously only their page names matched. diff --git a/scripts/backup-dev-folder b/scripts/backup-dev-folder new file mode 100755 index 0000000..0b97b20 --- /dev/null +++ b/scripts/backup-dev-folder @@ -0,0 +1,18 @@ +#!/bin/sh +# Back up a Claude Dev Vault folder to a timestamped zip BEFORE running tests +# that might touch it (especially the real "Stashpad" folder, or vault-wide +# commands). Stored OUTSIDE the vault so it isn't indexed/imported. +# Usage: scripts/backup-dev-folder <FolderName> (e.g. Stashpad) +# Paths are relative to this script (scripts/ inside the dev repo): the dev vault +# is a sibling of the dev repo, under the parent project dir. +DIR="$(cd "$(dirname "$0")" && pwd)" +ROOT="$(cd "$DIR/../.." && pwd)" # parent of the dev repo (the project dir) +VAULT="$ROOT/Claude Dev Vault" +DEST="$ROOT/Claude Dev Vault Backups" +F="$1" +[ -n "$F" ] || { echo "usage: backup-dev-folder <FolderName>" >&2; exit 1; } +[ -d "$VAULT/$F" ] || { echo "no such folder: $VAULT/$F" >&2; exit 1; } +mkdir -p "$DEST" +TS=$(date "+%Y-%m-%d-%H%M%S") +OUT="$DEST/$F-$TS.zip" +( cd "$VAULT" && zip -rq "$OUT" "$F" ) && echo "backed up '$F' -> $OUT" diff --git a/scripts/obs-test-guard b/scripts/obs-test-guard index 205b9d3..c0e5298 100755 --- a/scripts/obs-test-guard +++ b/scripts/obs-test-guard @@ -100,7 +100,7 @@ case "$1" in try { window.__claudeTestBanner.hide(); } catch (e) {} } window.__claudeTestBanner = null; - new Notice('✅ Safe to use Stashpad again — Claude has finished testing.', 6000); + new Notice('✅ Safe to use Stashpad again — Claude has finished testing.', 0); return 'cleared'; })()" >/dev/null 2>&1 echo "guard: banner cleared, all-clear shown" diff --git a/src/main.ts b/src/main.ts index 77dba7b..b528733 100644 --- a/src/main.ts +++ b/src/main.ts @@ -16,6 +16,7 @@ import { import { DEFAULT_STOPWORDS, bodyToSlug, buildFilename, parseIdFromFilename } from "./slug-service"; import { getActiveView, onActiveViewChange } from "./active-view"; import { importStashZip, STASH_EXT, splitFrontmatter } from "./stash-package"; +import { formatDateTime } from "./format"; import { resolveStashBytes, isEncryptedStash } from "./stash-crypto"; import { StashpadLog } from "./log"; import { ROOT_ID } from "./types"; @@ -291,6 +292,9 @@ export default class StashpadPlugin extends Plugin { // 0.77.7: seed the local user's author page into the new folder so // their links resolve everywhere from the start. try { await this.seedLocalAuthorStub(cleaned); } catch {} + // 0.99.17 (#2): also seed every KNOWN author (coworkers from other folders) + // so a new folder auto-populates and you can assign anyone immediately. + try { await this.seedKnownAuthorsInFolder(cleaned); } catch {} } /** Tally per-note colors found in EVERY markdown file under `folder`. @@ -710,6 +714,11 @@ export default class StashpadPlugin extends Plugin { // Vault is fully indexed now — safe to reconcile locked placeholders // (drop entries whose blob is truly gone, add cross-device blobs). void this.reconcileLockedRegistry(); + // 0.99.19: fire reminders for tasks that came due while Obsidian was + // closed (delay so the metadata cache is populated), then re-check on an + // interval so tasks coming due while it's open also surface. + window.setTimeout(() => void this.checkDueReminders(), 6000); + this.registerInterval(window.setInterval(() => void this.checkDueReminders(), 5 * 60 * 1000)); window.setTimeout(() => { void this.seedLocalAuthorStubsEverywhere(); }, 4000); // 0.79.12: register each Stashpad folder's _archive in Obsidian's // "Excluded files" so native search / quick switcher / graph / link @@ -1408,6 +1417,11 @@ export default class StashpadPlugin extends Plugin { // 0.58.0: rebootstrap as a command palette entry — mirrors the // "Rebootstrap now" button in settings. Useful when troubleshooting // / migrating without opening Settings. + 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)", @@ -3620,29 +3634,150 @@ export default class StashpadPlugin extends Plugin { * Used when assigning a task to someone so the assignee wikilink * resolves. No-op if a stub for this id already exists in the dir * (under any name). Also registers the author. */ - async ensureAuthorStubFor(folder: string, id: string, name: string): Promise<void> { - if (!id || !name) return; + async ensureAuthorStubFor(folder: string, id: string, name: string): Promise<boolean> { + if (!id || !name) return false; this.authorRegistry.record({ id, name }); const dir = `${folder.replace(/\/+$/, "")}/_authors`; const exists = this.app.vault.getMarkdownFiles().some( (f) => f.path.startsWith(dir + "/") && this.parseAuthorFilePath(f.path)?.id === id, ); - if (exists) return; + if (exists) return false; const rec = this.authorRegistry.get(id); const safe = this.authorNameToSafe(name); const path = `${dir}/${safe}-${id}.md`; try { await this.ensureFolderPath(dir); - if (await this.app.vault.adapter.exists(path)) return; + if (await this.app.vault.adapter.exists(path)) return false; await this.app.vault.create(path, this.buildAuthorStub( { id, name, role: rec?.role, department: rec?.department }, new Date().toISOString(), )); + return true; } catch (e) { console.warn("[Stashpad] ensureAuthorStubFor failed", path, e); + return false; } } + /** 0.99.17 (#2): seed EVERY known author (vault-wide) into `folder`'s + * `_authors/`, not just the local user — so a new folder auto-populates with + * coworkers and assignment works without waiting for them to contribute. Each + * stub reuses the author's real id. Returns how many stubs were created. */ + async seedKnownAuthorsInFolder(folder: string): Promise<number> { + let created = 0; + for (const a of this.collectKnownAuthors()) { + if (await this.ensureAuthorStubFor(folder, a.id, a.name)) created++; + } + return created; + } + + /** 0.99.19: Task due-date reminders. Obsidian plugins can't fire while the app + * is closed, so this runs at LAUNCH (onLayoutReady) and on an interval while + * running: it finds tasks whose `due` has passed and that haven't been + * reminded yet (tracked by `<id>@<dueRaw>` in settings.notifiedDueKeys, so the + * same task+due never re-fires — a changed due date re-keys and reminds again), + * shows a PERSISTENT notification under the "reminder" category (so it lands in + * the history log + respects mute), then records it. */ + async checkDueReminders(): Promise<void> { + const now = Date.now(); + const notified = new Set(this.settings.notifiedDueKeys ?? []); + const due: Array<{ id: string; folder: string; file: TFile; dueMs: number; key: string }> = []; + for (const f of this.app.vault.getMarkdownFiles()) { + if (f.path.includes("/_authors/")) continue; + const fm = this.app.metadataCache.getFileCache(f)?.frontmatter as { id?: unknown; due?: unknown } | undefined; + if (!fm || fm.due == null) continue; + const id = typeof fm.id === "string" ? fm.id : ""; + if (!id) continue; + const dueRaw = String(fm.due); + const dueMs = typeof fm.due === "number" ? fm.due : Date.parse(dueRaw); + if (!Number.isFinite(dueMs) || dueMs > now) continue; // not due yet + const key = `${id}@${dueRaw}`; + if (notified.has(key)) continue; + due.push({ id, folder: (f.parent?.path ?? "").replace(/\/+$/, ""), file: f, dueMs, key }); + } + if (due.length === 0) return; + // Record up front so the interval / a fast re-entry can't double-fire. + this.settings.notifiedDueKeys = [...(this.settings.notifiedDueKeys ?? []), ...due.map((d) => d.key)].slice(-2000); + await this.saveSettings(); + const titleOf = async (file: TFile): Promise<string> => { + try { + const body = splitFrontmatter(await this.app.vault.cachedRead(file)).body; + const line = body.split(/\r?\n/).map((l) => l.trim()).find((l) => l.length > 0); + if (line) return line.replace(/^[#>\-*\s]+/, "").slice(0, 60); + } catch { /* fall through to filename */ } + return file.basename.replace(/-[a-z0-9]{4,12}$/, "").replace(/-/g, " "); + }; + if (due.length <= 3) { + for (const d of due) { + const title = await titleOf(d.file); + this.notifications.show({ + message: `⏰ Task due: “${title}” (${formatDateTime(d.dueMs, this.settings)})`, + kind: "warning", category: "reminder", duration: 0, folder: d.folder, affectedIds: [d.id], + actions: [{ label: "Open", onClick: () => void this.revealNoteByRef(d.folder, d.id) }], + }); + } + } else { + this.notifications.show({ + message: `⏰ ${due.length} tasks are due — open the Tasks panel to review.`, + kind: "warning", category: "reminder", duration: 0, folder: "", + }); + } + } + + /** 0.99.17 (#3): the "centralized sync" — rebuild the registry from the whole + * vault, then ensure every known author has a stub in every Stashpad folder. + * Backfills existing folders (new folders are handled at creation). */ + async syncAuthorsAcrossFolders(): Promise<void> { + await this.rebuildAuthorRegistry(); // learn every author from the vault first + const authors = this.collectKnownAuthors(); + const folders = this.discoverStashpadFolders(); + if (!authors.length || !folders.length) { new Notice("No authors or Stashpad folders to sync."); return; } + const prog = folders.length * authors.length > 8 ? new Notice("", 0) : null; + let created = 0; + for (const folder of folders) { + prog?.setMessage(`Syncing authors → ${folder.split("/").pop()}…`); + for (const a of authors) { + if (await this.ensureAuthorStubFor(folder, a.id, a.name)) created++; + } + } + prog?.hide(); + this.notifications.show({ + message: `Synced authors across ${folders.length} folder${folders.length === 1 ? "" : "s"} — ${created} new stub${created === 1 ? "" : "s"} (${authors.length} author${authors.length === 1 ? "" : "s"} known).`, + kind: "success", category: "system", folder: "", + }); + } + + /** 0.99.16: VAULT-WIDE list of known authors for the assignee pickers — the + * union of the LOCAL registry (per-config, so in a shared vault it mostly + * knows just this user) AND a scan of every folder's `_authors/` stub files + * (id from the filename, display name from the stub's aliases/name). This is + * what surfaces COWORKERS who exist in shared folders but aren't in this + * device's registry — the reason only the local user showed up before. + * Deduped by id (registry name wins); the local user is listed first. Also + * warms the registry with anything new it finds (idempotent after the first). */ + collectKnownAuthors(): Array<{ id: string; name: string }> { + const byId = new Map<string, string>(); + // The local user is always "known" (from settings), even before they have a + // stub or any authored notes — and listed first. + const myId = (this.settings.authorId ?? "").trim(); + const myName = (this.settings.authorName ?? "").trim(); + if (myId && myName) byId.set(myId, myName); + for (const a of this.authorRegistry.all()) if (!byId.has(a.id)) byId.set(a.id, a.name); + for (const f of this.app.vault.getMarkdownFiles()) { + if (!f.path.includes("/_authors/")) continue; + const parsed = this.parseAuthorFilePath(f.path); + if (!parsed) continue; + const fm = this.app.metadataCache.getFileCache(f)?.frontmatter as { aliases?: unknown; name?: unknown } | undefined; + const aliasName = Array.isArray(fm?.aliases) + ? ((fm!.aliases as unknown[]).find((x) => typeof x === "string") as string | undefined ?? "") + : (typeof fm?.aliases === "string" ? fm.aliases : ""); + const name = (aliasName || (typeof fm?.name === "string" ? fm.name : "") || parsed.name).trim(); + if (!byId.has(parsed.id)) byId.set(parsed.id, name); + this.authorRegistry.record({ id: parsed.id, name }); // warm the registry (no-op if unchanged) + } + return [...byId.entries()].map(([id, name]) => ({ id, name })); + } + /** 0.77.2: rebuild the author registry from scratch by scanning the * vault. The authoritative inputs are (a) the `_authors` stub files * (id from filename, display name from `aliases`/`name`/H1, plus role/ @@ -4141,6 +4276,9 @@ export default class StashpadPlugin extends Plugin { notificationHistoryLimit: (typeof data?.notificationHistoryLimit === "number" && Number.isFinite(data.notificationHistoryLimit)) ? data.notificationHistoryLimit : 5000, + notifiedDueKeys: Array.isArray(data?.notifiedDueKeys) + ? data.notifiedDueKeys.filter((x: unknown): x is string => typeof x === "string").slice(-2000) + : [], drafts: normalizeDrafts(data?.drafts), lastSubmitted: data?.lastSubmitted && typeof data.lastSubmitted === "object" ? data.lastSubmitted : {}, // Migrate: when slugStopWords has never been set on this install diff --git a/src/notifications.ts b/src/notifications.ts index 18bd3fb..b30e968 100644 --- a/src/notifications.ts +++ b/src/notifications.ts @@ -24,6 +24,7 @@ export type NotificationCategory = | "attachment" | "color" | "reorder" | "multiplayer" + | "reminder" | "system"; /** Human-readable labels for each category, used by the settings UI @@ -45,6 +46,7 @@ export const CATEGORY_LABELS: Record<NotificationCategory, { label: string; desc 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 — 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." }, }; diff --git a/src/settings.ts b/src/settings.ts index 07c5662..ed3b875 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -406,6 +406,9 @@ export interface StashpadSettings { * Default 5000. Persisted alongside the live history in * `<pluginDir>/notifications.json`. */ notificationHistoryLimit: number; + /** Keys (`<id>@<dueRaw>`) of task due-reminders already fired, so they don't + * re-fire on every launch. Bounded; pruned when it grows. */ + notifiedDueKeys: string[]; /** 0.71.0 / 0.71.2: JD Index Builder. Two flavors: * - "Preview" → writes a single Index.md inside the designated * Stashpad folder, showing the would-be hierarchy + non-matches. @@ -503,6 +506,7 @@ export const DEFAULT_SETTINGS: StashpadSettings = { attachmentsOnlyNotes: {}, mutedNotificationCategories: [], notificationHistoryLimit: 5000, + notifiedDueKeys: [], autoNavOnMoveIn: false, autoNavOnMoveOut: false, autoExpandCursorRow: false, @@ -657,10 +661,12 @@ export class StashpadSettingTab extends PluginSettingTab { case "diagnostics": return this.diagnosticsItems(); case "general": return this.generalItems(); case "encryption": return this.encryptionItems(); - // authorship/templates/jdindex still render via the fresh-at-open `page:` - // path (searchable by page name). They're per-folder editors that don't - // decompose into clean per-setting entries; render-at-display via the page - // renderer keeps them correct. Returning null falls back to that path. + // 0.99.15: authorship/templates/jdindex decomposed too — static fields as + // per-setting items, the per-folder editors as sectionDefs (rendered fresh + // at display) — so individual settings are searchable, not just page names. + case "authorship": return this.authorshipItems(); + case "templates": return this.templatesItems(); + case "jdindex": return this.jdIndexItems(); default: return null; } } @@ -1449,6 +1455,89 @@ export class StashpadSettingTab extends PluginSettingTab { * unique links). The id never changes once set, so already-stamped * notes keep referring to the right person even if they rename * themselves later. */ + /** 0.99.15: Authorship tab decomposed for native settings search — static + * fields as per-setting renderDefs; the dynamic "folders worked in" + "known + * authors" lists as sectionDefs (rendered fresh at display). */ + private authorshipItems(): SettingDefinitionItem[] { + const items: SettingDefinitionItem[] = []; + items.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).", + (s) => s.addText((t) => t.setValue(this.plugin.settings.authorName).onChange(async (v) => { + this.plugin.settings.authorName = v.trim(); + if (this.plugin.settings.authorName && !this.plugin.settings.authorId) this.plugin.settings.authorId = newId(); + await this.plugin.saveSettings(); + await this.plugin.syncAuthorFilesToName(); + })), ["author", "name", "identity", "stamp"])); + items.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.", + (s) => s.addText((t) => t.setValue(this.plugin.settings.authorId).setDisabled(true)), ["author", "id"])); + items.push(this.renderDef("Title / role", + "Optional. Shown on your author page (e.g. \"Engineer\", \"PM\", \"Designer\").", + (s) => s.addText((t) => t.setValue(this.plugin.settings.authorRole).onChange(async (v) => { + this.plugin.settings.authorRole = v.trim(); await this.plugin.saveSettings(); await this.plugin.syncAuthorFilesToName(); + })), ["role", "title", "job"])); + items.push(this.renderDef("Department / team", + "Optional. Shown on your author page (e.g. \"Engineering\", \"Growth\").", + (s) => s.addText((t) => t.setValue(this.plugin.settings.authorDepartment).onChange(async (v) => { + this.plugin.settings.authorDepartment = v.trim(); await this.plugin.saveSettings(); await this.plugin.syncAuthorFilesToName(); + })), ["department", "team"])); + const footerToggle = (name: string, get: () => boolean, put: (v: boolean) => void, aliases: string[]): SettingDefinitionItem => + this.renderDef(name, "", (s) => s.addToggle((t) => t.setValue(get()).onChange(async (v) => { put(v); await this.plugin.saveSettings(); })), aliases); + items.push(footerToggle("Show author in note footer", () => this.plugin.settings.showAuthor, (v) => { this.plugin.settings.showAuthor = v; }, ["author", "footer", "show"])); + items.push(footerToggle("Show contributors in note footer", () => this.plugin.settings.showContributors, (v) => { this.plugin.settings.showContributors = v; }, ["contributors", "footer", "show"])); + items.push(footerToggle("Show last edit time in note footer", () => this.plugin.settings.showLastEdit, (v) => { this.plugin.settings.showLastEdit = v; }, ["last edit", "modified", "footer", "time"])); + items.push(this.sectionDef("Folders you've worked in", + "Folders where you've authored or contributed notes. Click one to open it.", + (host) => this.renderAuthoredFolders(host), + ["folders", "authored", "contributed", "worked"])); + items.push(this.sectionDef("Known authors", + "Everyone the plugin has seen, with role/department + rename history; rebuild/restore the registry.", + (host) => this.renderKnownAuthorsSection(host), + ["authors", "registry", "rename", "known", "rebuild"])); + return items; + } + + /** The "folders you've worked in" list, extracted so the authorship sectionDef + * can render it fresh at display time. */ + private renderAuthoredFolders(parent: HTMLElement): void { + const folders = this.plugin.collectAuthoredFolders(); + if (folders.length === 0) { parent.createEl("p", { cls: "setting-item-description", text: "No authored or contributed folders yet." }); return; } + const list = parent.createDiv({ cls: "stashpad-authored-folders-list" }); + for (const f of folders) { + const row = list.createDiv({ cls: "stashpad-authored-folder-row" }); + const a = row.createEl("a", { cls: "stashpad-authored-folder-link", text: f.folder }); + a.onclick = (e) => { e.preventDefault(); void this.plugin.activateViewForFolder(f.folder); }; + const counts: string[] = []; + if (f.authored > 0) counts.push(`authored ${f.authored}`); + if (f.contributed > 0) counts.push(`contributed to ${f.contributed}`); + row.createSpan({ cls: "stashpad-authored-folder-counts", text: ` · ${counts.join(", ")}` }); + } + } + + /** 0.99.15: Templates tab — the two per-folder editors as searchable sections. */ + private templatesItems(): SettingDefinitionItem[] { + return [ + this.sectionDef("Color aliases", + "Give your note colors friendly names, per Stashpad folder.", + (host) => this.renderColorAliasesSection(host), + ["color", "colour", "alias", "name", "swatch", "palette", "label"]), + this.sectionDef("Note templates", + "Per-Stashpad note templates — content stamped into new notes.", + (host) => this.renderNoteTemplatesSection(host), + ["template", "note", "default", "boilerplate", "snippet"]), + ]; + } + + /** 0.99.15: JD Index tab as a searchable section (scope/preview/build inside). */ + private jdIndexItems(): SettingDefinitionItem[] { + return [ + this.sectionDef("JD Index (Johnny Decimal)", + "Build a Johnny-Decimal-style index from dotted-prefix note titles — set the scope, preview, then build.", + (host) => this.renderJdIndexSection(host), + ["jd", "johnny", "decimal", "index", "scope", "build", "preview", "hierarchy", "folder"]), + ]; + } + private renderAuthorshipSection(parent: HTMLElement): void { parent.createEl("h3", { text: "Authorship" }); parent.createEl("p", { diff --git a/src/view.ts b/src/view.ts index 12504b4..662ca9a 100644 --- a/src/view.ts +++ b/src/view.ts @@ -7889,7 +7889,7 @@ export class StashpadView extends ItemView { const current = curFm && (typeof curFm.due === "string" || typeof curFm.due === "number") ? String(curFm.due) : null; // 0.78.1: offer known authors (registry, newest-first) for assignment, // and pre-fill any assignees already on the first target. - const knownAuthors = this.plugin.authorRegistry.all().map((a) => ({ id: a.id, name: a.name })); + const knownAuthors = this.plugin.collectKnownAuthors(); const currentAssignees = parseAssignees(curFm ?? {}); new DueDatePickerModal(this.app, current, (result) => { void this.applyDue(targets, result.iso, result.assignees); @@ -7984,7 +7984,7 @@ export class StashpadView extends ItemView { if (targets.length === 0) { new Notice("Nothing to assign."); return; } const first = targets[0]; const curFm = first.file ? this.app.metadataCache.getFileCache(first.file)?.frontmatter as any : null; - const knownAuthors = this.plugin.authorRegistry.all().map((a) => ({ id: a.id, name: a.name })); + const knownAuthors = this.plugin.collectKnownAuthors(); const currentAssignees = parseAssignees(curFm ?? {}); new AssignModal(this.app, { knownAuthors, currentAssignees }, (assignees) => { void this.applyAssignees(targets, assignees); diff --git a/styles.css b/styles.css index 64045d2..93addca 100644 --- a/styles.css +++ b/styles.css @@ -4077,6 +4077,19 @@ background: var(--background-primary); color: var(--text-normal); } +/* 0.99.18: explicit selection + focus highlight so the auto-selected HH/MM text + reads clearly in BOTH the search "when" popover AND the due-date modal — the + modal context was swallowing the default text-selection highlight. Same class + in both pickers, so this fixes both. */ +.stashpad-when-time-field::selection { + background: var(--interactive-accent); + color: var(--text-on-accent); +} +.stashpad-when-time-field:focus { + outline: none; + border-color: var(--interactive-accent); + box-shadow: 0 0 0 2px var(--interactive-accent); +} .stashpad-when-time-colon { font-size: 1.15em; color: var(--text-muted); } .stashpad-when-time-period { display: inline-flex;