diff --git a/docs/okf-guide.md b/docs/okf-guide.md new file mode 100644 index 0000000..3e85a27 --- /dev/null +++ b/docs/okf-guide.md @@ -0,0 +1,113 @@ +# OKF in Stashpad — a getting-started guide + +This guide assumes you know **nothing** about OKF *or* Stashpad. By the end you'll +know what OKF is, why Stashpad is a natural way to produce it, and exactly how to +turn one of your folders into an OKF bundle and share it. + +--- + +## What is OKF? + +**OKF (Open Knowledge Format)** is Google's open, vendor-neutral spec for packaging +curated knowledge so that LLMs and AI agents can browse and use it reliably. An OKF +"bundle" is deliberately simple — just a folder of plain Markdown files: + +- **one file per "concept"** (a table, a dataset, a metric, a runbook, a note…), +- each with a little **YAML frontmatter** at the top (`type` is required; + `title` / `description` / `tags` / `timestamp` are recommended), +- **cross-links between concepts are relative Markdown links** (e.g. + `[Onboarding](onboarding.md)`), not app-specific `[[wikilinks]]`, +- an **`index.md`** in the folder that lists the concepts, +- the **file path is the concept's identity**. + +That's the whole idea: knowledge as a tidy, linkable folder of Markdown that any +tool — or any AI — can read without a proprietary importer. + +Spec & background: +- https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf +- https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing/ + +## What is Stashpad? + +**Stashpad** is an Obsidian plugin that turns a folder into a chat-style outliner: +you jot notes, nest them under one another, and navigate the tree. Under the hood +every note is just a Markdown file with YAML frontmatter, and the parent/child +structure is recorded there too. + +## Why Stashpad is a good fit for OKF + +Look at the two descriptions above — they're almost the same shape: + +| OKF wants… | Stashpad already has… | +|---|---| +| one Markdown file per concept | one Markdown file per note | +| YAML frontmatter on each | frontmatter on every note | +| a folder of related concepts | a Stashpad folder of related notes | +| relative-Markdown cross-links | a real parent/child hierarchy | +| an `index.md` per folder | a known folder structure to generate one from | + +So an OKF bundle is basically "a Stashpad folder, written down in OKF's +conventions." Stashpad can therefore **generate the OKF layer for you** — the +required frontmatter keys, the relative-Markdown links, and the `index.md` — instead +of you hand-authoring any of it. And it does so **without disturbing your notes**: +the OKF fields are added *alongside* Stashpad's own (nothing is renamed or removed), +so the same folder stays a normal Stashpad folder AND becomes a valid OKF bundle. + +## Get started in ~1 minute + +1. **Turn OKF on.** Settings → **Open Knowledge Format (OKF)** → toggle **Enable OKF**. + This creates an `OKF Template.md` file in your vault. +2. **Pick which folders use OKF.** Click **Create template + open Templates**. In the + Templates list, set a folder's template to `OKF Template.md`. Do this for as many + (or as few) folders as you want — it's per-folder. (Archive folders are skipped on + purpose; OKF is about sharing, archives are about privacy.) +3. **Build the OKF layer.** Back on the OKF page, click **Rebuild OKF frontmatter**. + For every OKF folder this writes the OKF fields onto each note and generates the + folder's `index.md`. +4. **Share it.** Right-click a note (or a selection) → **Export as OKF…** and tick the + format(s) you want: **.zip** or **.tar.gz** (portable OKF bundles) and/or **.stash** + (Stashpad's own re-importable format). The export lands in the folder's `_exports`. + +That's it. Hand the `.zip`/`.tar.gz` to a colleague, an agent, or a data tool — it's +standard OKF. + +## What Stashpad writes for you + +On a note in an OKF folder, after a Rebuild: + +- `okfType` — the concept type (defaults to `concept`; **edit this freely** per note). +- `okfTitle`, `okfTimestamp` — filled in if missing (yours to edit after). +- `okfParent`, `okfChildren` — relative-Markdown links to the parent/child notes + (Stashpad keeps these in sync; they mirror your tree). + +And per folder: an **`index.md`** (`type: index`) with a nested list of the concepts +plus a short **legend** explaining the field names — so even an AI reading the *live* +folder knows how Stashpad's `okf*` fields map to OKF's standard keys. + +> Why the `okf` prefix? So these never collide with your own `tags`/`title`/`type` +> frontmatter or other plugins'. On **export**, Stashpad maps them to OKF's bare spec +> keys (`type`/`title`/`description`/`tags`/`timestamp`) in the bundle, while keeping +> the `okf*` + `id` fields too so the bundle can be re-imported into Stashpad +> losslessly. + +## Good to know + +- **Complementary, never destructive.** Your existing Stashpad notes and links are + untouched; OKF fields are added on top. +- **Auto-updates, but not instantly.** When you add, move, or delete notes in an OKF + folder, Stashpad refreshes that folder's OKF fields + `index.md` automatically — a + few seconds *after you stop* (it's debounced, so a burst of changes becomes one + rebuild). A brand-new note gets `okfType` right away; its `okfParent`/`okfChildren` + and the folder's `index.md` catch up on that refresh. Want it immediately? Click + **Rebuild OKF frontmatter** in Settings → OKF. +- **Archive folders are excluded** from all OKF processing by design. +- **Export scope.** Exporting a note/selection bundles that subtree, and the bundle's + `index.md` reflects just what you exported. + +## Glossary + +- **Concept** — one OKF Markdown file (= one Stashpad note). +- **Bundle** — a folder of concepts + `index.md`, optionally zipped/tarred. +- **`index.md`** — the per-folder table of contents OKF expects (Stashpad generates it). +- **Rebuild** — Stashpad's pass that (re)writes the OKF fields + `index.md`. + diff --git a/main.js b/main.js index 6c6be97..16d01d3 100644 --- a/main.js +++ b/main.js @@ -1,117 +1,132 @@ -"use strict";var ha=Object.create;var Di=Object.defineProperty;var ga=Object.getOwnPropertyDescriptor;var pa=Object.getOwnPropertyNames;var ua=Object.getPrototypeOf,Ia=Object.prototype.hasOwnProperty;var fe=(h,A)=>()=>(h&&(A=h(h=0)),A);var fa=(h,A)=>()=>(A||h((A={exports:{}}).exports,A),A.exports),bi=(h,A)=>{for(var t in A)Di(h,t,{get:A[t],enumerable:!0})},Jn=(h,A,t,e)=>{if(A&&typeof A=="object"||typeof A=="function")for(let i of pa(A))!Ia.call(h,i)&&i!==t&&Di(h,i,{get:()=>A[i],enumerable:!(e=ga(A,i))||e.enumerable});return h};var Gs=(h,A,t)=>(t=h!=null?ha(ua(h)):{},Jn(A||!h||!h.__esModule?Di(t,"default",{value:h,enumerable:!0}):t,h)),Ca=h=>Jn(Di({},"__esModule",{value:!0}),h);function Ls(h){return Array.isArray(h)?h.filter(A=>typeof A=="string"):typeof h=="string"?h.split(/[,\s]+/).filter(Boolean):[]}function Me(h,A){let t=A.replace(/^#/,"");return Ls(h?.tags).some(e=>e.replace(/^#/,"")===t)}function Js(h,A){let t=A.replace(/^#/,""),e=Ls(h.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),h.tags=e}function qs(h,A){let t=A.replace(/^#/,""),e=Ls(h.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?h.tags=e:delete h.tags}function Te(h){return h.split("/").some(A=>ei.has(A))}function qn(h){return h.split("/").some(A=>A==="_archive"||A===".archive")}function Yt(h){let A=(h??"").trim();return!A||/^\[\[.*\]\]$/.test(A)?A:`[[${A}]]`}function Be(h){let A=(h??"").trim(),t=A.match(/^\[\[(.*)\]\]$/);return t&&(A=t[1]),A.split("|")[0].split("#")[0].split("^")[0].trim()}function On(h){let A=h.match(/\.([^./]+)$/);return!!A&&ma.has(A[1].toLowerCase())}function Kn(h,A){if(!Array.isArray(A))return!1;for(let t of A){let e=(t??"").trim();if(e){if(e.length>2&&e.startsWith("/")&&e.endsWith("/"))try{if(new RegExp(e.slice(1,-1)).test(h))return!0}catch{}else if(h===e||h.startsWith(e.endsWith("/")?e:e+"/"))return!0}}return!1}function Ni(h,A){let t=h.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=A.toLowerCase();return t.every(i=>e.includes(i))}function ae(h){if(typeof h!="string")return null;let A=h.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=A.split("|"),i=t.match(/_authors\/(.+?)-([a-z0-9]{4,12})(?:\.md)?$/i);if(!i)return null;let s=i[2],n=(e??"").trim()||i[1].replace(/-/g," ").trim();return{id:s,name:n}}function Qe(h){let A=h?.assignedTo,t=Array.isArray(A)?A:A!=null?[A]:[],e=[];for(let i of t){let s=ae(i);s&&e.push(s)}return e}var ct,ne,Ce,me,xe,T,oe,ei,ma,Et=fe(()=>{"use strict";ct="stashpad-view",ne="stashpad-panels",Ce="stashpad-folder-panel",me="stashpad-detail",xe="stashpad-trash",T="__root__";oe=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported"],ei=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);ma=new Set(["edtz"])});function Ba(h,A){return h>12?h>=24?0:h:A==="am"?h===12?0:h:h===12?12:h+12}function Mi(h,A){h.addClass("stashpad-when-pop-time");let t=A.seedPeriod,e=h.createDiv({cls:"stashpad-when-time-display"}),i=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});i.value=String(A.seedH),e.createSpan({cls:"stashpad-when-time-colon",text:":"});let s=e.createEl("input",{cls:"stashpad-when-time-field",attr:{type:"text",inputmode:"numeric",maxlength:"2"}});s.value=String(A.seedM).padStart(2,"0");let n=e.createDiv({cls:"stashpad-when-time-period"}),o=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"AM"});o.type="button";let a=n.createEl("button",{cls:"stashpad-when-time-ampm",text:"PM"});a.type="button";let r=()=>{o.toggleClass("is-active",t==="am"),a.toggleClass("is-active",t==="pm")};r(),o.addEventListener("mousedown",y=>y.preventDefault()),a.addEventListener("mousedown",y=>y.preventDefault()),o.addEventListener("click",y=>{y.preventDefault(),t="am",r()}),a.addEventListener("click",y=>{y.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},p=y=>{let w=y.value.replace(/\D/g,"").slice(0,2);if(w===""){y.value="",y===i&&c();return}let E=parseInt(w,10);y===i?E>24&&(E=24):E>59&&(E=59),y.value=String(E),y===i&&c()};for(let y of[i,s])y.addEventListener("input",()=>p(y));c();let g=()=>{let y=parseInt(i.value||"12",10)||12,w=parseInt(s.value||"0",10)||0,E=y>12;A.onFinalize({hours24:Ba(y,t),minutes:w,raw:{hh:y,mm:w,period:t,is24:E}}),A.close()};A.setOnEnter?.(g);let d=[i,s,o,a],u=(y,w)=>{let E=d.indexOf(y);if(E===-1)return;let v=(E+w+d.length)%d.length;d[v].focus()},I=y=>{y.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),g()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),A.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),u(y,w.shiftKey?-1:1))})},f=h.createDiv({cls:"stashpad-when-time-pad"}),C=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],m=null;for(let y of C){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",y==="backspace"?(0,Wn.setIcon)(w,"delete"):y==="insert"?(w.setText("OK"),m=w):w.setText(y),y==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",E=>E.preventDefault()),w.addEventListener("click",E=>{if(E.preventDefault(),y==="insert"){g();return}if(y==="backspace"){l.value=l.value.slice(0,-1),p(l),l.focus();return}let v=l.selectionStart===0&&l.selectionEnd===l.value.length&&l.value.length>0,S=2,M=v||l.value.length>=S?y:l.value+y;l.value=M,p(l),l.focus(),l.setSelectionRange(l.value.length,l.value.length),l===i&&l.value.length>=S&&(s.focus(),s.select())})}m&&d.push(m);for(let y of d)I(y);i.focus(),i.select()}function $n(h){let{hh:A,mm:t,period:e,is24:i}=h.raw;return i?`${A}:${String(t).padStart(2,"0")}`:`${A}:${String(t).padStart(2,"0")}${e}`}var Wn,Os=fe(()=>{"use strict";Wn=require("obsidian")});function Zn(h){let A=Math.floor(4294967296/h)*h,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=A);return e%h}function Ks(h=5){let A=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),Qa.has(h.toLowerCase())&&(i=Math.min(i,12));let n=i<36?0:i<56?1:i<76?2:3,o=["Weak \u2014 easily guessed","Fair","Good","Strong"][n];return{bits:i,level:n,label:o}}function ya(h){let A=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function ii(h){let A="stashpad-",t=ya(h),e=64-A.length-1-t.length,i=h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${A}${i}-${t}`}var Xn,Qa,Ti=fe(()=>{"use strict";Xn="able acid acorn actor adept agile alarm album alert algae amber amble anchor angle ankle apple april arbor arc arctic arena armor arrow ascot aspen atlas atom attic auburn audio autumn award axis bacon badge bagel baker balmy bamboo banjo barge basil basin batch beach beam bean bear beaver begin belt bench berry birch bison black blade blaze bliss bloom blue board boat bold bolt bonus boost booth borax bother bottle boulder bounce bovine bowl brave bread breeze brick bridge brisk broad bronze brook broom brown brush bubble bucket bug bulb bundle burst cabin cable cacao cactus camel cameo candle canoe canvas canyon cargo carol carrot castle catch cedar cello chalk charm chart cheese cherry chess chime chirp cider cinder circle citrus clamp clay clever cliff cloak clock cloud clover coast cobra cocoa comet coral cosmos cotton couch cougar crane crater cream crest cricket crisp crown crumb crystal cube cumin curio dagger daisy dapper dawn deck deer delta denim depot desert dial diamond dingo ditch dock dodge dolphin domino donut draft dragon drift drum dune dusk eagle early earth easel ebony echo eclipse edge eel eagle elbow elder ember emboss emerald ember emu engine ermine ether ever fable falcon fancy farm fawn feather felt fennel fern ferry fiber fiddle field fig finch flame flask flax fleet flint float flock flora flute focus foam forest fossil fox frame frost fudge garden gecko ginger glacier glade glass glide globe glory glove gnat goat golden gopher gourd grape grass gravel grove guava gull hammer hamlet harbor hatch hazel heron hickory hippo honey hornet hostel ivory ivy jade jaguar jasmine jelly jetty jewel jolly jungle juniper kayak kelp kettle kiwi koala ladle lagoon lamp lantern larch lark lasso lava ledge lemon lentil leopard lever lilac lime linen lizard llama lobby locket lodge lotus lunar lupine lynx maple marble marsh meadow medal melon mellow mentor mesa metro mimic mint mirror mocha morsel moss mottle mural muslin nacho nectar nest noble nomad noodle nougat nutmeg oasis oat ocean ochre olive onyx opal orbit orca otter oval owl oxide oyster pace paddle palm panda pantry papaya parka parsley pasta pearl pebble pelican pepper pewter phantom piano picnic pigeon pilot pine pixel plank plaza plum pocket pollen pond poplar poppy portal potato pottery prairie prism puffin pumice quail quartz quill quilt quince rabbit radish raft rapid raven reed reef relish ribbon ridge rind ripple river robin rocket rope rover ruby rudder rust saffron sage salmon sandal sash satin sauce scout sedge sequin shadow shale shark shell shore shrub silk silo silver siren sketch slate sleet slope sloth smoke snail sonar sorrel spark sparrow spice spire sprig spruce squid stable stamp starling steam stem stilt stone stork storm stove straw stream stucco summit sundae sunset swan sweater syrup tabby talon tango tapir tassel tawny teal tempo thicket thimble thistle thorn thunder tidal tiger timber toffee token topaz torch totem trail tulip tundra turtle tusk twig umber unicorn valley vanilla velvet vermil violet viper vista vivid vortex waffle walnut warbler wasp water weasel wharf wheat whisk willow window winter wisp wombat wonder woven yam yarn yeast yew yodel yonder zebra zenith zephyr zigzag zinc zircon".split(/\s+/).filter(Boolean).filter((h,A,t)=>t.indexOf(h)===A);Qa=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 Hi={};bi(Hi,{newId:()=>pt});function pt(h=6){let A="",t=new Uint8Array(h);crypto.getRandomValues(t);for(let e=0;e{"use strict";_n="abcdefghijkmnpqrstuvwxyz23456789"});var hi={};bi(hi,{AssignModal:()=>Ai,ColorPickerModal:()=>we,ConfirmDeleteModal:()=>Pe,ConfirmModal:()=>Ft,CustomColorModal:()=>Pi,DueDatePickerModal:()=>li,EncryptionPasswordModal:()=>xt,ExportStashModal:()=>oi,ImportDupChoiceModal:()=>di,ImportLogModal:()=>zs,LogModal:()=>He,NotificationHistoryModal:()=>ci,SplitNoteModal:()=>ni,StashPasswordModal:()=>ai,TypeToConfirmModal:()=>ri,buildAssigneePicker:()=>Vs});function Vs(h,A){let t=[...A.initial],e=A.knownAuthors,i=h.createDiv({cls:"stashpad-assign"});i.createDiv({cls:"stashpad-assign-label",text:"Assign to"});let s=i.createDiv({cls:"stashpad-assign-chips"}),n=i.createDiv({cls:"stashpad-assign-input-wrap"}),o=n.createEl("input",{type:"text",cls:"stashpad-assign-input",attr:{placeholder:"Add a person \u2014 type a name\u2026"}}),a=n.createDiv({cls:"stashpad-assign-suggest"});a.style.display="none";let r=()=>A.onChange([...t]),l=()=>{s.empty(),t.length===0&&s.createSpan({cls:"stashpad-assign-empty",text:"No one yet"});for(let g of t){let d=s.createSpan({cls:"stashpad-assign-chip"});d.createSpan({cls:"stashpad-assign-chip-name",text:g.name});let u=d.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});u.title=`Remove ${g.name}`,u.onclick=()=>{t=t.filter(I=>I.id!==g.id),r(),l()}}},c=g=>{g.name.trim()&&(t.some(d=>d.id===g.id)||t.push(g),o.value="",a.style.display="none",r(),l(),o.focus())},p=()=>{let g=o.value.trim();a.empty();let d=new Set(t.map(f=>f.id)),I=e.filter(f=>!d.has(f.id)&&Ni(g,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>c(f)}));if(g&&!e.some(f=>f.name.toLowerCase()===g.toLowerCase())&&I.push({label:`Create \u201C${g}\u201D`,onPick:()=>c({id:pt(6),name:g})}),I.length===0){a.style.display="none";return}a.style.display="";for(let f of I){let C=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});C.onmousedown=m=>{m.preventDefault(),f.onPick()}}};o.addEventListener("input",p),o.addEventListener("focus",p),o.addEventListener("keydown",g=>{if(g.key==="Enter"){g.preventDefault();let d=a.querySelector(".stashpad-assign-suggest-item");d&&d.dispatchEvent(new MouseEvent("mousedown"))}else g.key==="Escape"&&a.style.display!=="none"&&(g.stopPropagation(),a.style.display="none")}),o.addEventListener("blur",()=>{window.setTimeout(()=>{a.style.display="none"},120)}),l()}var at,Ea,ye,He,Pe,ni,oi,ai,xt,ri,Pi,si,we,Ft,Ai,li,Ee,ci,zs,di,Ht=fe(()=>{"use strict";at=require("obsidian");Os();Et();Ti();Gt();Ea=at.moment,ye=class ye 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(ye.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(ye.PAGE),this.renderFooter()},t>ye.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()}};ye.PAGE=100;He=ye,Pe=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()}},ni=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 ba=Object.create;var Ti=Object.defineProperty;var xa=Object.getOwnPropertyDescriptor;var Na=Object.getOwnPropertyNames;var Ma=Object.getPrototypeOf,Ta=Object.prototype.hasOwnProperty;var Ce=(d,l)=>()=>(d&&(l=d(d=0)),l);var Ha=(d,l)=>()=>(l||d((l={exports:{}}).exports,l),l.exports),Hi=(d,l)=>{for(var t in l)Ti(d,t,{get:l[t],enumerable:!0})},Xn=(d,l,t,e)=>{if(l&&typeof l=="object"||typeof l=="function")for(let i of Na(l))!Ta.call(d,i)&&i!==t&&Ti(d,i,{get:()=>l[i],enumerable:!(e=xa(l,i))||e.enumerable});return d};var Pi=(d,l,t)=>(t=d!=null?ba(Ma(d)):{},Xn(l||!d||!d.__esModule?Ti(t,"default",{value:d,enumerable:!0}):t,d)),Pa=d=>Xn(Ti({},"__esModule",{value:!0}),d);function zs(d){return Array.isArray(d)?d.filter(l=>typeof l=="string"):typeof d=="string"?d.split(/[,\s]+/).filter(Boolean):[]}function Me(d,l){let t=l.replace(/^#/,"");return zs(d?.tags).some(e=>e.replace(/^#/,"")===t)}function Vs(d,l){let t=l.replace(/^#/,""),e=zs(d.tags);e.some(i=>i.replace(/^#/,"")===t)||e.push(t),d.tags=e}function $s(d,l){let t=l.replace(/^#/,""),e=zs(d.tags).filter(i=>i.replace(/^#/,"")!==t);e.length?d.tags=e:delete d.tags}function Te(d){return d.split("/").some(l=>ii.has(l))}function Zn(d){return d.split("/").some(l=>l==="_archive"||l===".archive")}function zt(d){let l=(d??"").trim();return!l||/^\[\[.*\]\]$/.test(l)?l:`[[${l}]]`}function ye(d){let l=(d??"").trim(),t=l.match(/^\[\[(.*)\]\]$/);return t&&(l=t[1]),l.split("|")[0].split("#")[0].split("^")[0].trim()}function _n(d){let l=d.match(/\.([^./]+)$/);return!!l&&Ua.has(l[1].toLowerCase())}function jn(d,l){if(!Array.isArray(l))return!1;for(let t of l){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 Ui(d,l){let t=d.toLowerCase().split(/\s+/).filter(Boolean);if(t.length===0)return!0;let e=l.toLowerCase();return t.every(i=>e.includes(i))}function le(d){if(typeof d!="string")return null;let l=d.replace(/^\[\[/,"").replace(/\]\]$/,""),[t,e]=l.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 Ee(d){let l=d?.assignedTo,t=Array.isArray(l)?l:l!=null?[l]:[],e=[];for(let i of t){let s=le(i);s&&e.push(s)}return e}var ct,ae,Be,Qe,Ne,T,re,ii,Ua,Qt=Ce(()=>{"use strict";ct="stashpad-view",ae="stashpad-panels",Be="stashpad-folder-panel",Qe="stashpad-detail",Ne="stashpad-trash",T="__root__";re=["id","parent","created","modified","attachments","position","author","contributors","parentLink","children","due","assignedTo","assignedBy","pinned","pinnedAt","imported","okfParent","okfChildren"],ii=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]);Ua=new Set(["edtz"])});function Ra(d,l){return d>12?d>=24?0:d:l==="am"?d===12?0:d:d===12?12:d+12}function Gi(d,l){d.addClass("stashpad-when-pop-time");let t=l.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(l.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(l.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",y=>y.preventDefault()),a.addEventListener("mousedown",y=>y.preventDefault()),o.addEventListener("click",y=>{y.preventDefault(),t="am",r()}),a.addEventListener("click",y=>{y.preventDefault(),t="pm",r()});let A=i;i.addEventListener("focus",()=>{A=i,i.select()}),s.addEventListener("focus",()=>{A=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=y=>{let w=y.value.replace(/\D/g,"").slice(0,2);if(w===""){y.value="",y===i&&c();return}let E=parseInt(w,10);y===i?E>24&&(E=24):E>59&&(E=59),y.value=String(E),y===i&&c()};for(let y of[i,s])y.addEventListener("input",()=>g(y));c();let p=()=>{let y=parseInt(i.value||"12",10)||12,w=parseInt(s.value||"0",10)||0,E=y>12;l.onFinalize({hours24:Ra(y,t),minutes:w,raw:{hh:y,mm:w,period:t,is24:E}}),l.close()};l.setOnEnter?.(p);let h=[i,s,o,a],u=(y,w)=>{let E=h.indexOf(y);if(E===-1)return;let v=(E+w+h.length)%h.length;h[v].focus()},I=y=>{y.addEventListener("keydown",w=>{w.key==="Enter"?(w.preventDefault(),w.stopPropagation(),p()):w.key==="Escape"?(w.preventDefault(),w.stopPropagation(),l.close()):w.key==="Tab"&&(w.preventDefault(),w.stopPropagation(),u(y,w.shiftKey?-1:1))})},f=d.createDiv({cls:"stashpad-when-time-pad"}),m=["1","2","3","4","5","6","7","8","9","backspace","0","insert"],C=null;for(let y of m){let w=f.createEl("button",{cls:"stashpad-when-time-padbtn"});w.type="button",y==="backspace"?(0,so.setIcon)(w,"delete"):y==="insert"?(w.setText("OK"),C=w):w.setText(y),y==="insert"&&w.addClass("is-go"),w.addEventListener("mousedown",E=>E.preventDefault()),w.addEventListener("click",E=>{if(E.preventDefault(),y==="insert"){p();return}if(y==="backspace"){A.value=A.value.slice(0,-1),g(A),A.focus();return}let v=A.selectionStart===0&&A.selectionEnd===A.value.length&&A.value.length>0,D=2,x=v||A.value.length>=D?y:A.value+y;A.value=x,g(A),A.focus(),A.setSelectionRange(A.value.length,A.value.length),A===i&&A.value.length>=D&&(s.focus(),s.select())})}C&&h.push(C);for(let y of h)I(y);i.focus(),i.select()}function no(d){let{hh:l,mm:t,period:e,is24:i}=d.raw;return i?`${l}:${String(t).padStart(2,"0")}`:`${l}:${String(t).padStart(2,"0")}${e}`}var so,Ws=Ce(()=>{"use strict";so=require("obsidian")});function ao(d){let l=Math.floor(4294967296/d)*d,t=new Uint32Array(1),e;do crypto.getRandomValues(t),e=t[0];while(e>=l);return e%d}function Xs(d=5){let l=[];for(let t=0;t=1&&s.every(a=>/^[a-zA-Z]+$/.test(a))&&(i=Math.min(i,s.length*11)),Ga.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 La(d){let l=2166136261;for(let t=0;t>>0).toString(16).padStart(8,"0")}function si(d){let l="stashpad-",t=La(d),e=64-l.length-1-t.length,i=d.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,Math.max(0,e)).replace(/-+$/g,"");return`${l}${i}-${t}`}var oo,Ga,Li=Ce(()=>{"use strict";oo="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,l,t)=>t.indexOf(d)===l);Ga=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 Ji={};Hi(Ji,{newId:()=>gt});function gt(d=6){let l="",t=new Uint8Array(d);crypto.getRandomValues(t);for(let e=0;e{"use strict";ro="abcdefghijkmnpqrstuvwxyz23456789"});var gi={};Hi(gi,{AssignModal:()=>Ai,ColorPickerModal:()=>Fe,ConfirmDeleteModal:()=>Pe,ConfirmModal:()=>kt,CustomColorModal:()=>qi,DueDatePickerModal:()=>ci,EncryptionPasswordModal:()=>Nt,ExportStashModal:()=>ai,ImportDupChoiceModal:()=>hi,ImportLogModal:()=>_s,LogModal:()=>He,NotificationHistoryModal:()=>di,OkfExportModal:()=>pi,SplitNoteModal:()=>oi,StashPasswordModal:()=>ri,TypeToConfirmModal:()=>li,buildAssigneePicker:()=>js});function js(d,l){let t=[...l.initial],e=l.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=()=>l.onChange([...t]),A=()=>{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 u=h.createSpan({cls:"stashpad-assign-chip-x",text:"\xD7"});u.title=`Remove ${p.name}`,u.onclick=()=>{t=t.filter(I=>I.id!==p.id),r(),A()}}},c=p=>{p.name.trim()&&(t.some(h=>h.id===p.id)||t.push(p),o.value="",a.style.display="none",r(),A(),o.focus())},g=()=>{let p=o.value.trim();a.empty();let h=new Set(t.map(f=>f.id)),I=e.filter(f=>!h.has(f.id)&&Ui(p,f.name)).slice(0,6).map(f=>({label:f.name,onPick:()=>c(f)}));if(p&&!e.some(f=>f.name.toLowerCase()===p.toLowerCase())&&I.push({label:`Create \u201C${p}\u201D`,onPick:()=>c({id:gt(6),name:p})}),I.length===0){a.style.display="none";return}a.style.display="";for(let f of I){let m=a.createDiv({cls:"stashpad-assign-suggest-item",text:f.label});m.onmousedown=C=>{C.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)}),A()}var ot,Ja,we,He,Pe,oi,ai,ri,Nt,li,qi,ni,Fe,kt,Ai,ci,ve,di,_s,hi,pi,Ht=Ce(()=>{"use strict";ot=require("obsidian");Ws();Qt();Li();Lt();Ja=ot.moment,we=class we extends ot.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(we.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(we.PAGE),this.renderFooter()},t>we.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 ot.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,ot.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 ot.Notice(`Exported log \u2192 ${i}`),i}catch(t){return new ot.Notice(`Export failed: ${t.message}`),null}}clearLog(){new kt(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 ot.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 ot.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let i=(0,ot.moment)(t.ts).isValid()?(0,ot.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()}};we.PAGE=100;He=we,Pe=class extends ot.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()}},oi=class extends ot.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()}},oi=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},p=c("Password"),g=c("Confirm password"),d=r.createDiv({cls:"stashpad-export-strength"}),u=d.createDiv({cls:"stashpad-strength-bar"}),I=[0,1,2,3].map(()=>u.createDiv({cls:"stashpad-strength-seg"})),f=d.createEl("span",{cls:"stashpad-strength-label"}),C=r.createDiv({cls:"stashpad-export-genrow"}),m=C.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),y=C.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=r.createEl("div",{cls:"stashpad-export-pw-hint"}),E=r.createEl("div",{cls:"stashpad-export-pw-suite"});E.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(O=>{E.toggleClass("is-weak",!O),E.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(()=>{E.setText("Encryption: AES-256-GCM with a password-derived key.")}):E.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let v=this.app.secretStorage,S=r.createDiv({cls:"stashpad-export-remember"}),M=S.createEl("input",{type:"checkbox"});M.id="stashpad-export-remember-cb";let F=S.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});F.htmlFor=M.id;let N=r.createDiv({cls:"stashpad-export-remember-note"});N.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),N.style.display="none",M.onchange=()=>{N.style.display=M.checked?"":"none"},v||(S.style.display="none");let Q=()=>{let O=e.value.trim()||this.defaultBaseName;return o.checked?`${O}-encrypted`:O},D=()=>i.setText(`Saves as: ${Q()}-.stash`);e.oninput=D;let K=this.contentEl.createDiv({cls:"stashpad-export-footer"}),x=K.createEl("button",{text:"Cancel"});x.onclick=()=>this.close();let Y=K.createEl("button",{cls:"mod-cta",text:"Export"}),q=()=>{let O=Ys(p.value);d.style.visibility=p.value?"visible":"hidden",I.forEach((V,rt)=>V.toggleClass("is-on",p.value!==""&&rt<=O.level)),u.dataset.level=String(O.level),f.setText(O.label)},j=()=>{let O=o.checked;r.style.display=O?"":"none";let V=!0;O&&(p.value?p.value!==g.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,P=O=>{L=O,p.type=g.type=O?"text":"password",y.setText(O?"Hide":"Show")};y.onclick=O=>{O.preventDefault(),P(!L)},m.onclick=O=>{O.preventDefault(),p.value=g.value=Ks(),P(!1),new at.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),j()},o.onchange=j,p.oninput=j,g.oninput=j,j();let tt=()=>this.commit(Q(),o.checked?p.value:null,o.checked&&M.checked);Y.onclick=tt,this.scope.register([],"Enter",O=>{O.preventDefault(),Y.disabled||tt()}),requestAnimationFrame(()=>{e.focus(),e.select()})}commit(t,e,i){let s=t.trim()||this.defaultBaseName,n=e&&e.length?e:null;this.delivered=!0,this.close(),this.onConfirm(s,n,!!n&&i)}onClose(){this.contentEl.empty()}},ai=class extends at.Modal{constructor(t,e,i,s){super(t);this.errorMsg=e;this.allowLater=i;this.onResult=s;this.delivered=!1}onOpen(){this.contentEl.empty(),this.titleEl.setText("Encrypted .stash"),this.modalEl.addClass("stashpad-export-modal"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This export is password-protected. Enter its password to import it."}),this.errorMsg&&this.contentEl.createEl("div",{cls:"stashpad-export-error",text:this.errorMsg});let t=this.contentEl.createEl("input",{type:"password"});t.addClass("stashpad-export-name"),t.placeholder="Password";let e=this.contentEl.createDiv({cls:"stashpad-export-footer"});if(e.createEl("button",{text:"Cancel"}).onclick=()=>this.close(),this.allowLater){let s=e.createEl("button",{text:"Remind me later"});s.title="Don't import now \u2014 surface the reminder again later.",s.onclick=()=>this.finish({kind:"later"})}let i=e.createEl("button",{cls:"mod-cta",text:"Decrypt & import"});i.onclick=()=>this.submit(t.value),this.scope.register([],"Enter",s=>{s.preventDefault(),this.submit(t.value)}),requestAnimationFrame(()=>t.focus())}submit(t){t&&this.finish({kind:"password",value:t})}finish(t){this.delivered=!0,this.close(),this.onResult(t)}onClose(){this.delivered||(this.delivered=!0,this.onResult({kind:"cancel"})),this.contentEl.empty()}},xt=class extends at.Modal{constructor(t,e){super(t);this.opts=e;this.succeeded=!1}onOpen(){let{mode:t}=this.opts;this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal","stashpad-encryption-modal"),this.titleEl.setText(this.opts.title??(t==="setup"?"Set up encryption password":t==="change"?"Change encryption password":"Unlock encryption")),this.contentEl.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),this.opts.intro?this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:this.opts.intro}):t==="setup"&&this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This single password protects everything you encrypt in this vault. It is stored only on this device. There is NO recovery \u2014 if you lose it, anything you've encrypted is gone for good."});let e=[],i=I=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),C=f.createEl("input",{type:"password"});C.addClass("stashpad-export-name","stashpad-encryption-field"),C.placeholder=I;let m=f.createEl("button",{cls:"stashpad-export-copy"}),y=()=>{let w=C.value.length===0;m.setText(w?"Paste":"Copy"),m.toggleClass("is-paste",w),m.setAttr("aria-label",`${w?"Paste into":"Copy"} ${I.toLowerCase()}`)};return m.onclick=async w=>{if(w.preventDefault(),C.value.length===0)try{let E=(await navigator.clipboard?.readText())?.trim();if(!E){new at.Notice("Clipboard is empty.");return}C.value=E,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",y),y(),e.push(y),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 I=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=I.createDiv({cls:"stashpad-strength-bar"}),C=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),m=I.createEl("span",{cls:"stashpad-strength-label"}),y=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),w=()=>{let M=n.value,F=Ys(M);C.forEach((N,Q)=>N.toggleClass("is-on",Q0&&M.length<6?" \u2014 use at least 6":""}`),y.toggleClass("is-weak",M.length>0&&M.length<6)};n.addEventListener("input",w),w();let E=this.contentEl.createDiv({cls:"stashpad-export-genrow"});E.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=M=>{M.preventDefault();let F=Ks(5);n.value=F,o&&(o.value=F),w(),e.forEach(N=>N()),new at.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(F).catch(()=>{})};let v=E.createEl("button",{cls:"stashpad-export-show",text:"Show"});v.onclick=M=>{M.preventDefault();let F=n.type==="password";n.type=F?"text":"password",o&&(o.type=F?"text":"password"),v.setText(F?"Hide":"Show")};let S=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});S.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(M=>{S.toggleClass("is-weak",!M),S.setText(M?"Encryption: Argon2id + AES-256-GCM \u2014 the strongest suite (used on this device).":"\u26A0\uFE0F Argon2id can't run here, so this will use the weaker PBKDF2 (600k) + AES-256-GCM fallback.")}).catch(()=>S.setText("Encryption: AES-256-GCM with a password-derived key.")):S.setText("Encryption: Argon2id + AES-256-GCM (PBKDF2 fallback if Argon2 can't run here).")}let a=null,r=this.app.secretStorage;if(this.opts.offerKeychain&&r){let I=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=I.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let f=I.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=I=>{l.setText(I),l.style.display=""},p=this.contentEl.createDiv({cls:"stashpad-export-footer"});p.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let g=p.createEl("button",{cls:"mod-cta",text:t==="setup"?"Set up":t==="change"?"Change":"Unlock"}),d=!1,u=async()=>{if(d)return;let I=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!I){c("Enter your current password.");return}if(t==="setup"||t==="change"){if(!f){c("Enter a password.");return}if(f.length<6){c("Use at least 6 characters.");return}if(f!==o?.value){c("Passwords don't match.");return}}d=!0,g.disabled=!0,l.style.display="none";let C=g.textContent;g.setText("Working\u2026");try{let m=await this.opts.onSubmit({current:I,next:f,remember:!!a?.checked});if(m){c(m),d=!1,g.disabled=!1,g.setText(C??"OK");return}this.succeeded=!0,this.close()}catch(m){c(`Failed: ${m.message}`),d=!1,g.disabled=!1,g.setText(C??"OK")}};g.onclick=()=>void u(),this.scope.register([],"Enter",I=>{I.preventDefault(),u()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},ri=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().toLowerCase()===this.opts.phrase.trim().toLowerCase(),a=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",a),t?.addEventListener("input",a),a();let 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()}},Pi=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 p=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(p)&&(this.value=p,e.style.background=p,i.value=p,s.value!==p&&(s.value=p))};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()}},si=class si 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=[...si.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=!si.DEFAULT_PALETTE.some(p=>p.toLowerCase()===a.toLowerCase()),c=this.items.length;if(r.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let p=r.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});p.title="Remove from palette",p.onclick=g=>{g.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 Pi(this.app,this.currentColor,(i,s)=>{this.onPick(i,s)}).open();return}this.close(),this.onPick(e.color,{addToPalette:!1})}columns(){if(!this.items.length)return 1;let t=this.items[0].el.parentElement;if(!t)return 1;let e=t.getBoundingClientRect(),i=this.items[0].el.getBoundingClientRect();if(i.width<=0)return 1;let s=i.top,n=0;for(let o of this.items){let a=o.el.getBoundingClientRect();if(Math.abs(a.top-s)<1)n++;else break}return Math.max(1,n)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(i=>i.toLowerCase()!==t.toLowerCase()),this.onOpen()}catch(e){console.warn("Stashpad: palette delete failed",e)}}moveFocus(t){if(!this.items.length)return;let e=Math.max(0,Math.min(this.items.length-1,this.focusIdx+t));this.focusIdx=e,this.refreshActive()}refreshActive(){for(let t=0;t{this.didChoose=!0,this.close(),this.onChoose(!1)};let s=e.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};Ai=class extends at.Modal{constructor(t,e,i){super(t);this.opts=e;this.onPick=i;this.didChoose=!1;this.assignees=[];this.assignees=[...e.currentAssignees]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Assign task");let t=this.contentEl.createDiv({cls:"stashpad-due-picker"});Vs(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}},li=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"}),p=(f,C)=>{let m=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});m.onclick=()=>{let y=C();o.value=this.toDateValue(y),l.value||(l.value=this.toTimeValue(y))}},g=f=>(f.setHours(9,0,0,0),f);p("Today",()=>g(this.startOfTodayLocal())),p("Tomorrow",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+1),g(f)}),p("Next week",()=>{let f=this.startOfTodayLocal();return f.setDate(f.getDate()+7),g(f)});let d=c.createEl("button",{cls:"stashpad-due-btn",text:"Clear"});d.onclick=()=>{o.value="",l.value="",o.focus()};let u=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});u.onclick=()=>{this.didChoose=!0,this.close()};let I=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});I.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)),y=9,w=0;if(l.value){let[v,S]=l.value.split(":").map(M=>parseInt(M,10));y=v,w=S}let E=new Date(f,C-1,m,y,w,0,0);this.didChoose=!0,this.close(),this.onPick({iso:E.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){Vs(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let i=9,s=0;if(e.value){let[d,u]=e.value.split(":").map(I=>parseInt(I,10));Number.isFinite(d)&&(i=d),Number.isFinite(u)&&(s=u)}else{let d=new Date;i=d.getHours(),s=d.getMinutes()}let n=i>=12?"pm":"am",o=i===0?12:i>12?i-12:i,a=document.body.createDiv({cls:"stashpad-when-popover stashpad-due-time-pop"});a.style.position="fixed",a.style.zIndex="9999";let r=null,l=()=>{a.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",p,!0),this.tinyClosePopover===l&&(this.tinyClosePopover=null)},c=d=>{!a.contains(d.target)&&d.target!==t&&!t.contains(d.target)&&l()},p=d=>{d.key==="Escape"?(d.preventDefault(),d.stopPropagation(),l()):d.key==="Enter"&&r&&(d.preventDefault(),d.stopPropagation(),r())};this.tinyClosePopover=l,Mi(a,{seedH:o,seedM:s,seedPeriod:n,close:l,setOnEnter:d=>{r=d},onFinalize:d=>{e.value=`${String(d.hours24).padStart(2,"0")}:${String(d.minutes).padStart(2,"0")}`}});let g=t.getBoundingClientRect();a.style.left=`${Math.max(8,Math.min(g.left,window.innerWidth-220))}px`,a.style.top=`${g.bottom+4}px`,setTimeout(()=>{document.addEventListener("mousedown",c,!0),document.addEventListener("keydown",p,!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}`}},Ee=class Ee 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(Ee.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 p=l.createSpan({cls:"stashpad-notif-action-chip"});p.setText(c),p.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(Ee.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(Ee.PAGE),this.renderFooter()},t>Ee.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};Ee.PAGE=100;ci=Ee,zs=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()}},di=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 Mt(h,A=zt){let t=A instanceof Set?A:new Set(A.map(o=>o.toLowerCase())),e=(h.split(/\r?\n/).find(o=>o.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ]/g,"").replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(o=>o&&!t.has(o.toLowerCase())).map(o=>o.length>=2&&/^[A-Z0-9]+$/.test(o)?o:o.charAt(0).toUpperCase()+o.slice(1).toLowerCase()),n="";for(let o of s){let a=n?`${n}-${o}`:o;if(a.length>50)break;n=a}return n||"Untitled"}function Tt(h,A){return`${h}-${A}.md`}function Fe(h){let A=h.match(/-([a-z0-9]{4,12})$/);return A?A[1]:null}var zt,Ue=fe(()=>{"use strict";zt=["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 Ji={};bi(Ji,{JdBuildConfirmModal:()=>pi,buildJdIndexNotes:()=>$s,buildJdIndexPreview:()=>Gi,buildJdPreviewNotice:()=>Li,scanForJdNotes:()=>Re});function Ws(h,A){if(/^\d+-\d+$/.test(h))return null;if(h.includes(".")){let e=h.split(".").slice(0,-1).join(".");return A.has(e)?e:Ws(e,A)}if(/^\d+$/.test(h)){let t=parseInt(h,10);for(let e of A){let i=e.match(/^(\d+)-(\d+)$/);if(!i)continue;let s=parseInt(i[1],10),n=parseInt(i[2],10);if(t>=s&&t<=n)return e}return null}return null}function Re(h,A,t){let e=h.vault.getMarkdownFiles(),i=va(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(A.discoverStashpadFolders()),o=d=>s?!1:Array.from(n).some(u=>d===u||d.startsWith(u+"/")),a=[],r=[],l=[];for(let d of i){let u=d.parent?.path?.replace(/\/+$/,"")??"";if(o(u)){l.push(d);continue}let I=d.basename.match(jn);I?a.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:d,folder:null}):r.push(d)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",p=d=>{let u=d.path.replace(/\/+$/,"");if(!(c&&u&&u!==c&&!u.startsWith(c+"/"))){if(u&&!o(u)){let I=d.name.match(jn);I&&a.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:null,folder:d})}}for(let I of d.children)I instanceof kt.TFolder&&p(I)};p(h.vault.getRoot());let g=t.jdIndexSort??"natural";return a.sort((d,u)=>Fa(d,u,g)),{indexed:a,nonIndex:r,skippedStashpadNotes:l}}async function Gi(h,A,t){let e=Xs(t.jdIndexStashpadFolder??"");if(!e)return{...Re(h,A,t),previewPath:null,error:"no-dest"};let i=Re(h,A,t),s=wa(h,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=ka(i.indexed,i.nonIndex,i.skippedStashpadNotes),a=(await h.vault.read(s)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),r=a?`${a[0]}${n}`:n;return await h.vault.modify(s,r),{...i,previewPath:s.path}}function wa(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof kt.TFolder))return null;for(let e of t.children){if(!(e instanceof kt.TFile)||e.extension!=="md")continue;if((h.metadataCache.getFileCache(e)?.frontmatter??{}).id===T)return e}return null}async function $s(h,A,t){let e=Xs(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=Re(h,A,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let C=1;C{r.push(f);for(let C of a.get(f)??[])l(C)};for(let f of o)l(f);let c=new Map,p=h.vault.getAbstractFileByPath(e);if(p instanceof kt.TFolder)for(let f of p.children){if(!(f instanceof kt.TFile)||f.extension!=="md")continue;let C=h.metadataCache.getFileCache(f)?.frontmatter??{};typeof C.jdPrefix=="string"&&c.set(C.jdPrefix,f)}let g=new Map,d=0,u=0,I=0;for(let f of r){let C=n.get(f)??null,m=Ws(f,new Set(n.keys())),y=m?g.get(m)??T:T,w=C?`${f} ${C.title}`:f,E=C?.file?`[[${C.file.basename}]]`:"",v=E?`${E} +`),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 ot.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"});ot.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=ot.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()}},ai=class extends ot.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 A=[],c=K=>{let $=r.createDiv({cls:"stashpad-export-pw-row"}),rt=$.createEl("input",{type:"password"});rt.addClass("stashpad-export-name"),rt.placeholder=K;let pt=$.createEl("button",{cls:"stashpad-export-copy"}),nt=()=>{let lt=rt.value.length===0;pt.setText(lt?"Paste":"Copy"),pt.toggleClass("is-paste",lt),pt.setAttr("aria-label",`${lt?"Paste into":"Copy"} ${K.toLowerCase()}`)};return pt.onclick=async lt=>{if(lt.preventDefault(),rt.value.length===0)try{let At=(await navigator.clipboard?.readText())?.trim();if(!At){new ot.Notice("Clipboard is empty.");return}rt.value=At,rt.dispatchEvent(new Event("input")),new ot.Notice("Pasted from clipboard.")}catch{new ot.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(rt.value).then(()=>new ot.Notice("Passphrase copied to clipboard."),()=>new ot.Notice("Couldn't access the clipboard."))},nt(),A.push(nt),rt},g=c("Password"),p=c("Confirm password"),h=r.createDiv({cls:"stashpad-export-strength"}),u=h.createDiv({cls:"stashpad-strength-bar"}),I=[0,1,2,3].map(()=>u.createDiv({cls:"stashpad-strength-seg"})),f=h.createEl("span",{cls:"stashpad-strength-label"}),m=r.createDiv({cls:"stashpad-export-genrow"}),C=m.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}),y=m.createEl("button",{cls:"stashpad-export-show",text:"Show"}),w=r.createEl("div",{cls:"stashpad-export-pw-hint"}),E=r.createEl("div",{cls:"stashpad-export-pw-suite"});E.setText("Encryption: AES-256-GCM. Checking key-derivation suite for this device\u2026"),this.kdfProbe?this.kdfProbe().then(K=>{E.toggleClass("is-weak",!K),E.setText(K?"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(()=>{E.setText("Encryption: AES-256-GCM with a password-derived key.")}):E.setText("Encryption: Argon2id + AES-256-GCM (falls back to PBKDF2 if Argon2 can't run here).");let v=this.app.secretStorage,D=r.createDiv({cls:"stashpad-export-remember"}),x=D.createEl("input",{type:"checkbox"});x.id="stashpad-export-remember-cb";let F=D.createEl("label",{text:"Remember in this vault (this device) \u2014 skips the prompt when you re-import here."});F.htmlFor=x.id;let N=r.createDiv({cls:"stashpad-export-remember-note"});N.setText("Saved only in this device's keychain \u2014 it doesn't sync to your other devices and isn't shared with anyone you send this file to. Keep the passphrase somewhere safe if you'll open this export elsewhere."),N.style.display="none",x.onchange=()=>{N.style.display=x.checked?"":"none"},v||(D.style.display="none");let Q=()=>{let K=e.value.trim()||this.defaultBaseName;return o.checked?`${K}-encrypted`:K},S=()=>i.setText(`Saves as: ${Q()}-.stash`);e.oninput=S;let O=this.contentEl.createDiv({cls:"stashpad-export-footer"}),M=O.createEl("button",{text:"Cancel"});M.onclick=()=>this.close();let Y=O.createEl("button",{cls:"mod-cta",text:"Export"}),q=()=>{let K=Zs(g.value);h.style.visibility=g.value?"visible":"hidden",I.forEach(($,rt)=>$.toggleClass("is-on",g.value!==""&&rt<=K.level)),u.dataset.level=String(K.level),f.setText(K.label)},j=()=>{let K=o.checked;r.style.display=K?"":"none";let $=!0;K&&(g.value?g.value!==p.value?(w.setText("Passwords don't match."),w.addClass("is-error"),$=!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"),$=!1)),q(),A.forEach(rt=>rt()),Y.disabled=!$,Y.toggleClass("is-disabled",!$),S()},L=!1,P=K=>{L=K,g.type=p.type=K?"text":"password",y.setText(K?"Hide":"Show")};y.onclick=K=>{K.preventDefault(),P(!L)},C.onclick=K=>{K.preventDefault(),g.value=p.value=Xs(),P(!1),new ot.Notice("Passphrase generated (hidden) \u2014 Show to view, or Copy to save it."),j()},o.onchange=j,g.oninput=j,p.oninput=j,j();let tt=()=>this.commit(Q(),o.checked?g.value:null,o.checked&&x.checked);Y.onclick=tt,this.scope.register([],"Enter",K=>{K.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()}},ri=class extends ot.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()}},Nt=class extends ot.Modal{constructor(t,e){super(t);this.opts=e;this.succeeded=!1}onOpen(){let{mode:t}=this.opts;this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal","stashpad-encryption-modal"),this.titleEl.setText(this.opts.title??(t==="setup"?"Set up encryption password":t==="change"?"Change encryption password":"Unlock encryption")),this.contentEl.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),this.opts.intro?this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:this.opts.intro}):t==="setup"&&this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:"This single password protects everything you encrypt in this vault. It is stored only on this device. There is NO recovery \u2014 if you lose it, anything you've encrypted is gone for good."});let e=[],i=I=>{let f=this.contentEl.createDiv({cls:"stashpad-export-pw-row stashpad-encryption-row"}),m=f.createEl("input",{type:"password"});m.addClass("stashpad-export-name","stashpad-encryption-field"),m.placeholder=I;let C=f.createEl("button",{cls:"stashpad-export-copy"}),y=()=>{let w=m.value.length===0;C.setText(w?"Paste":"Copy"),C.toggleClass("is-paste",w),C.setAttr("aria-label",`${w?"Paste into":"Copy"} ${I.toLowerCase()}`)};return C.onclick=async w=>{if(w.preventDefault(),m.value.length===0)try{let E=(await navigator.clipboard?.readText())?.trim();if(!E){new ot.Notice("Clipboard is empty.");return}m.value=E,m.dispatchEvent(new Event("input")),new ot.Notice("Pasted from clipboard.")}catch{new ot.Notice("Couldn't read the clipboard.")}else navigator.clipboard?.writeText(m.value).then(()=>new ot.Notice("Copied to clipboard."),()=>new ot.Notice("Couldn't access the clipboard."))},m.addEventListener("input",y),y(),e.push(y),m},s=null,n=null,o=null;if((t==="unlock"||t==="change")&&(s=i("Current password")),(t==="setup"||t==="change")&&(n=i(t==="change"?"New password":"Password"),o=i("Confirm password")),n){let I=this.contentEl.createDiv({cls:"stashpad-export-strength"}),f=I.createDiv({cls:"stashpad-strength-bar"}),m=[0,1,2,3].map(()=>f.createDiv({cls:"stashpad-strength-seg"})),C=I.createEl("span",{cls:"stashpad-strength-label"}),y=this.contentEl.createDiv({cls:"stashpad-encryption-counter"}),w=()=>{let x=n.value,F=Zs(x);m.forEach((N,Q)=>N.toggleClass("is-on",Q0&&x.length<6?" \u2014 use at least 6":""}`),y.toggleClass("is-weak",x.length>0&&x.length<6)};n.addEventListener("input",w),w();let E=this.contentEl.createDiv({cls:"stashpad-export-genrow"});E.createEl("button",{cls:"stashpad-export-gen",text:"Generate strong passphrase"}).onclick=x=>{x.preventDefault();let F=Xs(5);n.value=F,o&&(o.value=F),w(),e.forEach(N=>N()),new ot.Notice("Generated \u2014 copy it somewhere safe; there's no recovery."),navigator.clipboard?.writeText(F).catch(()=>{})};let v=E.createEl("button",{cls:"stashpad-export-show",text:"Show"});v.onclick=x=>{x.preventDefault();let F=n.type==="password";n.type=F?"text":"password",o&&(o.type=F?"text":"password"),v.setText(F?"Hide":"Show")};let D=this.contentEl.createEl("div",{cls:"stashpad-export-pw-suite"});D.setText("Encryption: AES-256-GCM. Checking key-derivation suite\u2026"),this.opts.kdfProbe?this.opts.kdfProbe().then(x=>{D.toggleClass("is-weak",!x),D.setText(x?"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(()=>D.setText("Encryption: AES-256-GCM with a password-derived key.")):D.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 I=this.contentEl.createDiv({cls:"stashpad-export-remember"});a=I.createEl("input",{type:"checkbox"}),a.id="stashpad-enc-remember";let f=I.createEl("label",{text:"Remember on this device (keychain) \u2014 auto-unlock here without re-typing."});f.htmlFor=a.id;let m=this.contentEl.createDiv({cls:"stashpad-export-remember-note"});m.setText("Stored only in this device's keychain \u2014 doesn't sync to your other devices. Anyone with access to this unlocked device + keychain could decrypt."),m.style.display="none",a.onchange=()=>{m.style.display=a.checked?"":"none"}}let A=this.contentEl.createEl("div",{cls:"stashpad-export-error"});A.style.display="none";let c=I=>{A.setText(I),A.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,u=async()=>{if(h)return;let I=s?.value??void 0,f=n?.value??void 0;if((t==="unlock"||t==="change")&&!I){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,A.style.display="none";let m=p.textContent;p.setText("Working\u2026");try{let C=await this.opts.onSubmit({current:I,next:f,remember:!!a?.checked});if(C){c(C),h=!1,p.disabled=!1,p.setText(m??"OK");return}this.succeeded=!0,this.close()}catch(C){c(`Failed: ${C.message}`),h=!1,p.disabled=!1,p.setText(m??"OK")}};p.onclick=()=>void u(),this.scope.register([],"Enter",I=>{I.preventDefault(),u()}),requestAnimationFrame(()=>(s??n)?.focus())}onClose(){this.contentEl.empty(),this.succeeded||this.opts.onCancel?.()}},li=class extends ot.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().toLowerCase()===this.opts.phrase.trim().toLowerCase(),a=()=>{n.disabled=!o()||!!this.opts.requirePassword&&!t?.value};e.addEventListener("input",a),t?.addEventListener("input",a),a();let r=!1,A=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 A(),this.scope.register([],"Enter",c=>{c.preventDefault(),A()}),requestAnimationFrame(()=>(t??e).focus())}onClose(){this.contentEl.empty()}},qi=class extends ot.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 A=o.createEl("button",{cls:"mod-cta",text:"Add to palette"});A.title="Apply and save this color so it appears as a tile next time.",A.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",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()}},ni=class ni extends ot.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=[...ni.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 A=!ni.DEFAULT_PALETTE.some(g=>g.toLowerCase()===a.toLowerCase()),c=this.items.length;if(r.onclick=()=>this.activate(c),A&&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:A?"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 qi(this.app,this.currentColor,(i,s)=>{this.onPick(i,s)}).open();return}this.close(),this.onPick(e.color,{addToPalette:!1})}columns(){if(!this.items.length)return 1;let t=this.items[0].el.parentElement;if(!t)return 1;let e=t.getBoundingClientRect(),i=this.items[0].el.getBoundingClientRect();if(i.width<=0)return 1;let s=i.top,n=0;for(let o of this.items){let a=o.el.getBoundingClientRect();if(Math.abs(a.top-s)<1)n++;else break}return Math.max(1,n)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(i=>i.toLowerCase()!==t.toLowerCase()),this.onOpen()}catch(e){console.warn("Stashpad: palette delete failed",e)}}moveFocus(t){if(!this.items.length)return;let e=Math.max(0,Math.min(this.items.length-1,this.focusIdx+t));this.focusIdx=e,this.refreshActive()}refreshActive(){for(let t=0;t{this.didChoose=!0,this.close(),this.onChoose(!1)};let s=e.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.didChoose=!0,this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty(),this.didChoose||(this.didChoose=!0,this.onChoose(!1))}};Ai=class extends ot.Modal{constructor(t,e,i){super(t);this.opts=e;this.onPick=i;this.didChoose=!1;this.assignees=[];this.assignees=[...e.currentAssignees]}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Assign task");let t=this.contentEl.createDiv({cls:"stashpad-due-picker"});js(t,{knownAuthors:this.opts.knownAuthors,initial:this.assignees,onChange:n=>{this.assignees=n}});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Cancel"});i.onclick=()=>{this.didChoose=!0,this.close()};let s=e.createEl("button",{cls:"mod-cta",text:"Save"});s.onclick=()=>{this.didChoose=!0,this.close(),this.onPick(this.assignees)}}onClose(){this.contentEl.empty(),this.didChoose}},ci=class extends ot.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,ot.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,ot.setIcon)(r,"clock");let A=a.createEl("input",{type:"time",cls:"stashpad-due-time"});n.onclick=()=>{try{o.showPicker?.()}catch{}},r.onclick=()=>this.openTimeNumpad(r,A),t&&(o.value=this.toDateValue(t),A.value=this.toTimeValue(t)),this.renderAssignSection(e);let c=e.createDiv({cls:"stashpad-due-grid"}),g=(f,m)=>{let C=c.createEl("button",{cls:"stashpad-due-btn stashpad-due-preset",text:f});C.onclick=()=>{let y=m();o.value=this.toDateValue(y),A.value||(A.value=this.toTimeValue(y))}},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="",A.value="",o.focus()};let u=c.createEl("button",{cls:"stashpad-due-btn",text:"Cancel"});u.onclick=()=>{this.didChoose=!0,this.close()};let I=c.createEl("button",{cls:"stashpad-due-btn mod-cta",text:"Set"});I.onclick=()=>{if(!o.value){this.didChoose=!0,this.close(),this.onPick({iso:null,assignees:this.assignees});return}let[f,m,C]=o.value.split("-").map(v=>parseInt(v,10)),y=9,w=0;if(A.value){let[v,D]=A.value.split(":").map(x=>parseInt(x,10));y=v,w=D}let E=new Date(f,m-1,C,y,w,0,0);this.didChoose=!0,this.close(),this.onPick({iso:E.toISOString(),assignees:this.assignees})},requestAnimationFrame(()=>o.focus())}onClose(){this.tinyClosePopover?.(),this.contentEl.empty(),this.didChoose}renderAssignSection(t){js(t,{knownAuthors:this.opts.knownAuthors??[],initial:this.assignees,onChange:e=>{this.assignees=e}})}openTimeNumpad(t,e){this.tinyClosePopover?.();let i=9,s=0;if(e.value){let[h,u]=e.value.split(":").map(I=>parseInt(I,10));Number.isFinite(h)&&(i=h),Number.isFinite(u)&&(s=u)}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,A=()=>{a.remove(),document.removeEventListener("mousedown",c,!0),document.removeEventListener("keydown",g,!0),this.tinyClosePopover===A&&(this.tinyClosePopover=null)},c=h=>{!a.contains(h.target)&&h.target!==t&&!t.contains(h.target)&&A()},g=h=>{h.key==="Escape"?(h.preventDefault(),h.stopPropagation(),A()):h.key==="Enter"&&r&&(h.preventDefault(),h.stopPropagation(),r())};this.tinyClosePopover=A,Gi(a,{seedH:o,seedM:s,seedPeriod:n,close:A,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}`}},ve=class ve extends ot.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 kt(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(ve.PAGE)}}appendMore(t){if(!this.listEl)return;let e=Math.min(this.visible.length,this.shownCount+t);for(let i=this.shownCount;i0){let A=i.createDiv({cls:"stashpad-notif-actions-snapshot"});for(let c of e.actionLabels){let g=A.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(ve.PAGE,t)} more`});if(e.onclick=()=>{this.appendMore(ve.PAGE),this.renderFooter()},t>ve.PAGE){let i=this.footerEl.createEl("button",{text:`Load all (${t})`});i.onclick=()=>{this.appendMore(t),this.renderFooter()}}}};ve.PAGE=100;di=ve,_s=class extends ot.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,ot.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()}},hi=class extends ot.Modal{constructor(t,e,i){super(t);this.message=e;this.onChoose=i;this.chose=!1}onOpen(){this.modalEl?.addClass("stashpad-compact-modal"),this.contentEl.empty(),this.titleEl.setText("Possible duplicate import");let t=this.contentEl.createDiv({cls:"stashpad-confirm-body"});for(let o of this.message.split(` +`))t.createDiv({cls:"stashpad-confirm-line",text:o});let e=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=e.createEl("button",{text:"Skip duplicates"});i.onclick=()=>{this.chose=!0,this.close(),this.onChoose("skip")};let s=e.createEl("button",{text:"Replace existing"});s.onclick=()=>{this.chose=!0,this.close(),this.onChoose("replace")};let n=e.createEl("button",{cls:"mod-cta",text:"Import anyway"});n.onclick=()=>{this.chose=!0,this.close(),this.onChoose("anyway")}}onClose(){this.chose||this.onChoose("skip"),this.contentEl.empty()}},pi=class extends ot.Modal{constructor(t,e,i,s){super(t);this.noteCount=i;this.onConfirm=s;this.base=e}onOpen(){this.contentEl.empty(),this.modalEl.addClass("stashpad-export-modal"),this.titleEl.setText("Export as OKF"),this.contentEl.createEl("p",{cls:"stashpad-export-desc",text:`Export ${this.noteCount} note${this.noteCount===1?"":"s"} as an Open Knowledge Format bundle. Pick one or more formats.`});let t=this.contentEl.createEl("input",{type:"text"});t.addClass("stashpad-export-name"),t.value=this.base,t.placeholder="Export name";let e=(r,A)=>{let c=this.contentEl.createDiv({cls:"stashpad-okf-fmt"}),g=c.createEl("input",{type:"checkbox"});return g.checked=A,c.createEl("label",{text:r}),g},i=e(".zip \u2014 OKF bundle (portable)",!0),s=e(".tar.gz \u2014 OKF bundle (tarball)",!1),n=e(".stash \u2014 Stashpad format (re-importable)",!1),o=this.contentEl.createDiv({cls:"stashpad-export-footer"});o.createEl("button",{text:"Cancel"}).onclick=()=>this.close();let a=o.createEl("button",{cls:"mod-cta",text:"Export"});a.onclick=()=>{if(!i.checked&&!s.checked&&!n.checked){new ot.Notice("Pick at least one format.");return}this.close(),this.onConfirm(t.value.trim()||this.base,{zip:i.checked,targz:s.checked,stash:n.checked})},requestAnimationFrame(()=>t.focus())}onClose(){this.contentEl.empty()}}});function Mt(d,l=Vt){let t=l instanceof Set?l:new Set(l.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 Tt(d,l){return`${d}-${l}.md`}function Se(d){let l=d.match(/-([a-z0-9]{4,12})$/);return l?l[1]:null}var Vt,Ue=Ce(()=>{"use strict";Vt=["a","an","the","and","or","but","if","then","else","of","in","on","at","to","for","with","by","from","as","is","are","was","were","be","been","being","i","you","he","she","it","we","they","this","that","these","those","my","your","our","their","do","does","did","so","just","very","really","im"]});var Vi={};Hi(Vi,{JdBuildConfirmModal:()=>Ii,buildJdIndexNotes:()=>en,buildJdIndexPreview:()=>Yi,buildJdPreviewNotice:()=>zi,scanForJdNotes:()=>Re});function tn(d,l){if(/^\d+-\d+$/.test(d))return null;if(d.includes(".")){let e=d.split(".").slice(0,-1).join(".");return l.has(e)?e:tn(e,l)}if(/^\d+$/.test(d)){let t=parseInt(d,10);for(let e of l){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 Re(d,l,t){let e=d.vault.getMarkdownFiles(),i=Oa(e,t),s=t.jdIndexIncludeStashpadFolders===!0,n=s?new Set:new Set(l.discoverStashpadFolders()),o=h=>s?!1:Array.from(n).some(u=>h===u||h.startsWith(u+"/")),a=[],r=[],A=[];for(let h of i){let u=h.parent?.path?.replace(/\/+$/,"")??"";if(o(u)){A.push(h);continue}let I=h.basename.match(lo);I?a.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:h,folder:null}):r.push(h)}let c=(t.jdIndexScope??"vault")==="folder"?(t.jdIndexScopeFolder??"").trim().replace(/^\/+|\/+$/g,""):"",g=h=>{let u=h.path.replace(/\/+$/,"");if(!(c&&u&&u!==c&&!u.startsWith(c+"/"))){if(u&&!o(u)){let I=h.name.match(lo);I&&a.push({prefix:I[1],segments:I[1].split("."),title:I[2],file:null,folder:h})}}for(let I of h.children)I instanceof St.TFolder&&g(I)};g(d.vault.getRoot());let p=t.jdIndexSort??"natural";return a.sort((h,u)=>Ka(h,u,p)),{indexed:a,nonIndex:r,skippedStashpadNotes:A}}async function Yi(d,l,t){let e=sn(t.jdIndexStashpadFolder??"");if(!e)return{...Re(d,l,t),previewPath:null,error:"no-dest"};let i=Re(d,l,t),s=qa(d,e);if(!s)return{...i,previewPath:null,error:"no-home"};let n=Ya(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 qa(d,l){let t=d.vault.getAbstractFileByPath(l);if(!(t instanceof St.TFolder))return null;for(let e of t.children){if(!(e instanceof St.TFile)||e.extension!=="md")continue;if((d.metadataCache.getFileCache(e)?.frontmatter??{}).id===T)return e}return null}async function en(d,l,t){let e=sn(t.jdIndexStashpadFolder??"");if(!e)return{created:0,updated:0,skipped:0,destFolder:"",error:"no-dest"};if(!new Set(l.discoverStashpadFolders()).has(e))return{created:0,updated:0,skipped:0,destFolder:e,error:"dest-not-stashpad"};let s=Re(d,l,t),n=new Map;for(let f of s.indexed)n.set(f.prefix,f);for(let f of s.indexed)if(f.prefix.includes("."))for(let m=1;m{r.push(f);for(let m of a.get(f)??[])A(m)};for(let f of o)A(f);let c=new Map,g=d.vault.getAbstractFileByPath(e);if(g instanceof St.TFolder)for(let f of g.children){if(!(f instanceof St.TFile)||f.extension!=="md")continue;let m=d.metadataCache.getFileCache(f)?.frontmatter??{};typeof m.jdPrefix=="string"&&c.set(m.jdPrefix,f)}let p=new Map,h=0,u=0,I=0;for(let f of r){let m=n.get(f)??null,C=tn(f,new Set(n.keys())),y=C?p.get(C)??T:T,w=m?`${f} ${m.title}`:f,E=m?.file?`[[${m.file.basename}]]`:"",v=E?`${E} `:`${w} -`,S=c.get(f);if(S){try{let M=null;await h.fileManager.processFrontMatter(S,D=>{D.jdPrefix=f,y&&(D.parent=y),(!D.id||typeof D.id!="string")&&(D.id=pt()),D.created||(D.created=new Date().toISOString()),D.attachments||(D.attachments=[]),M=D.id});let N=(await h.vault.read(S)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=N?`${N[0]}${v}`:v;await h.vault.modify(S,Q),M&&g.set(f,M),u++}catch(M){console.error("[stashpad] buildJdIndexNotes: update failed",M),I++}continue}try{let M=pt();g.set(f,M);let F=Mt(w,t.slugStopWords),N=Tt(F,M),Q=`${e}/${N}`,D=["---",`id: ${M}`,`parent: ${y}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` -`);await h.vault.create(Q,D+v),d++}catch(M){console.error("[stashpad] buildJdIndexNotes: create failed for",f,M),I++}}return{created:d,updated:u,skipped:I,destFolder:e}}function Xs(h){return(h||"").trim().replace(/^\/+|\/+$/g,"")}function va(h,A){if((A.jdIndexScope??"vault")==="vault")return h;let t=Xs(A.jdIndexScopeFolder??"");return t?h.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):h}function Fa(h,A,t){if(t==="created"){let e=h.file?.stat?.ctime??0,i=A.file?.stat?.ctime??0;if(e!==i)return e-i}return eo(h.segments,A.segments)}function to(h,A){let t=h.match(/^(\d+)-(\d+)$/),e=A.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:h.split("."),s=e?[e[1]]:A.split(".");return eo(i,s)}function eo(h,A){let t=Math.min(h.length,A.length);for(let e=0;e{s.set(o,a);for(let r of e.get(o)??[])n(r,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function ka(h,A,t){let e=[],i=s=>"#".repeat(Math.min(s+1,6));if(e.push("# Indexed"),e.push(""),h.length===0){let s=t.length>0?`_No notes matched. ${t.length} note${t.length===1?" was":"s were"} excluded because they live inside a Stashpad folder \u2014 toggle "Include Stashpad folders in scan" in Settings \u2192 JD Index Builder if you want them included._`:"_No notes matched the JD-prefix convention. Check Scope and Designated folder in Settings \u2192 JD Index Builder._";e.push(s)}else{let s=new Map;for(let l of h)s.set(l.prefix,l);for(let l of h)if(l.prefix.includes("."))for(let c=1;c{let c=s.get(l),p=a.get(l)??0,g=" ".repeat(p),d=i(p),u=c?.folder?` ${c.title} _(folder)_`:(c?.file,"");c?.file?e.push(`${g}- ${d} [[${c.file.basename}|${c.prefix} ${c.title}]]`):c?.folder?e.push(`${g}- ${d} ${c.prefix}${u}`):e.push(`${g}- ${d} ${l}`);for(let I of o.get(l)??[])r(I)};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(` +`,D=c.get(f);if(D){try{let x=null;await d.fileManager.processFrontMatter(D,S=>{S.jdPrefix=f,y&&(S.parent=y),(!S.id||typeof S.id!="string")&&(S.id=gt()),S.created||(S.created=new Date().toISOString()),S.attachments||(S.attachments=[]),x=S.id});let N=(await d.vault.read(D)).match(/^---\r?\n[\s\S]*?\r?\n---\r?\n/),Q=N?`${N[0]}${v}`:v;await d.vault.modify(D,Q),x&&p.set(f,x),u++}catch(x){console.error("[stashpad] buildJdIndexNotes: update failed",x),I++}continue}try{let x=gt();p.set(f,x);let F=Mt(w,t.slugStopWords),N=Tt(F,x),Q=`${e}/${N}`,S=["---",`id: ${x}`,`parent: ${y}`,`created: "${new Date().toISOString()}"`,"attachments: []",`jdPrefix: "${f}"`,"---",""].join(` +`);await d.vault.create(Q,S+v),h++}catch(x){console.error("[stashpad] buildJdIndexNotes: create failed for",f,x),I++}}return{created:h,updated:u,skipped:I,destFolder:e}}function sn(d){return(d||"").trim().replace(/^\/+|\/+$/g,"")}function Oa(d,l){if((l.jdIndexScope??"vault")==="vault")return d;let t=sn(l.jdIndexScopeFolder??"");return t?d.filter(e=>{let i=e.parent?.path?.replace(/\/+$/,"")??"";return i===t||i.startsWith(t+"/")}):d}function Ka(d,l,t){if(t==="created"){let e=d.file?.stat?.ctime??0,i=l.file?.stat?.ctime??0;if(e!==i)return e-i}return co(d.segments,l.segments)}function Ao(d,l){let t=d.match(/^(\d+)-(\d+)$/),e=l.match(/^(\d+)-(\d+)$/),i=t?[t[1]]:d.split("."),s=e?[e[1]]:l.split(".");return co(i,s)}function co(d,l){let t=Math.min(d.length,l.length);for(let e=0;e<t;e++){let i=d[e],s=l[e],n=/^\d+$/.test(i),o=/^\d+$/.test(s);if(n&&o){let a=parseInt(i,10)-parseInt(s,10);if(a!==0)return a}else{if(n&&!o)return-1;if(!n&&o)return 1;{let a=i.localeCompare(s,void 0,{numeric:!0,sensitivity:"base"});if(a!==0)return a}}}return d.length-l.length}function ho(d){let l=new Set(d.keys()),t=new Map,e=new Map;for(let o of l){let a=tn(o,l);if(t.set(o,a),a!==null){let r=e.get(a)??[];r.push(o),e.set(a,r)}}let i=[];for(let o of l)t.get(o)===null&&i.push(o);i.sort(Ao);for(let o of e.values())o.sort(Ao);let s=new Map,n=(o,a)=>{s.set(o,a);for(let r of e.get(o)??[])n(r,a+1)};for(let o of i)n(o,0);return{roots:i,childrenOf:e,depthOf:s}}function Ya(d,l,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 A of d)s.set(A.prefix,A);for(let A of d)if(A.prefix.includes("."))for(let c=1;c<A.segments.length;c++){let g=A.segments.slice(0,c).join(".");s.has(g)||s.set(g,null)}let{roots:n,childrenOf:o,depthOf:a}=ho(s),r=A=>{let c=s.get(A),g=a.get(A)??0,p=" ".repeat(g),h=i(g),u=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}${u}`):e.push(`${p}- ${h} ${A}`);for(let I of o.get(A)??[])r(I)};for(let A of n)r(A)}if(l.length>0){e.push(""),e.push(`# Non-indexed (${l.length})`),e.push(""),e.push("_These notes don't match the JD-prefix convention. Rename them to `<prefix> <title>` and re-run to include them._"),e.push("");for(let s of l)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 Li(h,A){let t=document.createDocumentFragment(),e=t.createEl("div",{text:"Home note updated"});e.style.fontWeight="600",e.style.marginBottom="6px";let i=t.createEl("ul");i.style.margin="0 0 8px 0",i.style.paddingLeft="18px",i.createEl("li",{text:`${A.indexed.length} indexed`}),i.createEl("li",{text:`${A.nonIndex.length+A.skippedStashpadNotes.length} excluded`});let s=t.createEl("button",{text:"Open",cls:"mod-cta"});s.style.padding="2px 10px",s.style.fontSize="var(--font-ui-smaller)";let n;return s.onclick=async o=>{if(o.stopPropagation(),A.previewPath){let a=h.vault.getAbstractFileByPath(A.previewPath);a instanceof kt.TFile&&await h.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new kt.Notice(t,0),n}var kt,jn,pi,ui=fe(()=>{"use strict";kt=require("obsidian");Gt();Ue();Et();jn=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;pi=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 Gi(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,Li(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 ts=fa((wo,In)=>{(function(h){typeof wo=="object"&&typeof In<"u"?In.exports=h():typeof define=="function"&&define.amd?define([],h):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=h()})(function(){return function h(A,t,e){function i(o,a){if(!t[o]){if(!A[o]){var r=typeof require=="function"&&require;if(!a&&r)return r(o,!0);if(s)return s(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[o]={exports:{}};A[o][0].call(c.exports,function(p){var g=A[o][1][p];return i(g||p)},c,c.exports,h,A,t,e)}return t[o].exports}for(var s=typeof require=="function"&&require,n=0;n<e.length;n++)i(e[n]);return i}({1:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,l,c,p,g,d=[],u=0,I=n.length,f=I,C=e.getTypeOf(n)!=="string";u<n.length;)f=I-u,r=C?(o=n[u++],a=u<I?n[u++]:0,u<I?n[u++]:0):(o=n.charCodeAt(u++),a=u<I?n.charCodeAt(u++):0,u<I?n.charCodeAt(u++):0),l=o>>2,c=(3&o)<<4|a>>4,p=1<f?(15&a)<<2|r>>6:64,g=2<f?63&r:64,d.push(s.charAt(l)+s.charAt(c)+s.charAt(p)+s.charAt(g));return d.join("")},t.decode=function(n){var o,a,r,l,c,p,g=0,d=0,u="data:";if(n.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var I,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(I=i.uint8array?new Uint8Array(0|f):new Array(0|f);g<n.length;)o=s.indexOf(n.charAt(g++))<<2|(l=s.indexOf(n.charAt(g++)))>>4,a=(15&l)<<4|(c=s.indexOf(n.charAt(g++)))>>2,r=(3&c)<<6|(p=s.indexOf(n.charAt(g++))),I[d++]=o,c!==64&&(I[d++]=a),p!==64&&(I[d++]=r);return I}},{"./support":30,"./utils":32}],2:[function(h,A,t){"use strict";var e=h("./external"),i=h("./stream/DataWorker"),s=h("./stream/Crc32Probe"),n=h("./stream/DataLengthProbe");function o(a,r,l,c,p){this.compressedSize=a,this.uncompressedSize=r,this.crc32=l,this.compression=c,this.compressedContent=p}o.prototype={getContentWorker:function(){var a=new i(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new n("data_length")),r=this;return a.on("end",function(){if(this.streamInfo.data_length!==r.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new i(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},o.createWorkerFrom=function(a,r,l){return a.pipe(new s).pipe(new n("uncompressedSize")).pipe(r.compressWorker(l)).pipe(new n("compressedSize")).withStreamInfo("compression",r)},A.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(h,A,t){"use strict";var e=h("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=h("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(h,A,t){"use strict";var e=h("./utils"),i=function(){for(var s,n=[],o=0;o<256;o++){s=o;for(var a=0;a<8;a++)s=1&s?3988292384^s>>>1:s>>>1;n[o]=s}return n}();A.exports=function(s,n){return s!==void 0&&s.length?e.getTypeOf(s)!=="string"?function(o,a,r,l){var c=i,p=l+r;o^=-1;for(var g=l;g<p;g++)o=o>>>8^c[255&(o^a[g])];return-1^o}(0|n,s,s.length,0):function(o,a,r,l){var c=i,p=l+r;o^=-1;for(var g=l;g<p;g++)o=o>>>8^c[255&(o^a.charCodeAt(g))];return-1^o}(0|n,s,s.length,0):0}},{"./utils":32}],5:[function(h,A,t){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},{}],6:[function(h,A,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:h("lie"),A.exports={Promise:e}},{lie:37}],7:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",i=h("pako"),s=h("./utils"),n=h("./stream/GenericWorker"),o=e?"uint8array":"array";function a(r,l){n.call(this,"FlateWorker/"+r),this._pako=null,this._pakoAction=r,this._pakoOptions=l,this.meta={}}t.magic="\b\0",s.inherits(a,n),a.prototype.processChunk=function(r){this.meta=r.meta,this._pako===null&&this._createPako(),this._pako.push(s.transformTo(o,r.data),!1)},a.prototype.flush=function(){n.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},a.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this._pako=null},a.prototype._createPako=function(){this._pako=new i[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var r=this;this._pako.onData=function(l){r.push({data:l,meta:r.meta})}},t.compressWorker=function(r){return new a("Deflate",r)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(h,A,t){"use strict";function e(c,p){var g,d="";for(g=0;g<p;g++)d+=String.fromCharCode(255&c),c>>>=8;return d}function i(c,p,g,d,u,I){var f,C,m=c.file,y=c.compression,w=I!==o.utf8encode,E=s.transformTo("string",I(m.name)),v=s.transformTo("string",o.utf8encode(m.name)),S=m.comment,M=s.transformTo("string",I(S)),F=s.transformTo("string",o.utf8encode(S)),N=v.length!==m.name.length,Q=F.length!==S.length,D="",K="",x="",Y=m.dir,q=m.date,j={crc32:0,compressedSize:0,uncompressedSize:0};p&&!g||(j.crc32=c.crc32,j.compressedSize=c.compressedSize,j.uncompressedSize=c.uncompressedSize);var L=0;p&&(L|=8),w||!N&&!Q||(L|=2048);var P=0,tt=0;Y&&(P|=16),u==="UNIX"?(tt=798,P|=function(V,rt){var gt=V;return V||(gt=rt?16893:33204),(65535>)<<16}(m.unixPermissions,Y)):(tt=20,P|=function(V){return 63&(V||0)}(m.dosPermissions)),f=q.getUTCHours(),f<<=6,f|=q.getUTCMinutes(),f<<=5,f|=q.getUTCSeconds()/2,C=q.getUTCFullYear()-1980,C<<=4,C|=q.getUTCMonth()+1,C<<=5,C|=q.getUTCDate(),N&&(K=e(1,1)+e(a(E),4)+v,D+="up"+e(K.length,2)+K),Q&&(x=e(1,1)+e(a(M),4)+F,D+="uc"+e(x.length,2)+x);var O="";return O+=` -\0`,O+=e(L,2),O+=y.magic,O+=e(f,2),O+=e(C,2),O+=e(j.crc32,4),O+=e(j.compressedSize,4),O+=e(j.uncompressedSize,4),O+=e(E.length,2),O+=e(D.length,2),{fileRecord:r.LOCAL_FILE_HEADER+O+E+D,dirRecord:r.CENTRAL_FILE_HEADER+e(tt,2)+O+e(M.length,2)+"\0\0\0\0"+e(P,4)+e(d,4)+E+D+M}}var s=h("../utils"),n=h("../stream/GenericWorker"),o=h("../utf8"),a=h("../crc32"),r=h("../signature");function l(c,p,g,d){n.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=p,this.zipPlatform=g,this.encodeFileName=d,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}s.inherits(l,n),l.prototype.push=function(c){var p=c.meta.percent||0,g=this.entriesCount,d=this._sources.length;this.accumulate?this.contentBuffer.push(c):(this.bytesWritten+=c.data.length,n.prototype.push.call(this,{data:c.data,meta:{currentFile:this.currentFile,percent:g?(p+100*(g-d-1))/g:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var p=this.streamFiles&&!c.file.dir;if(p){var g=i(c,p,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:g.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var p=this.streamFiles&&!c.file.dir,g=i(c,p,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(g.dirRecord),p)this.push({data:function(d){return r.DATA_DESCRIPTOR+e(d.crc32,4)+e(d.compressedSize,4)+e(d.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:g.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,p=0;p<this.dirRecords.length;p++)this.push({data:this.dirRecords[p],meta:{percent:100}});var g=this.bytesWritten-c,d=function(u,I,f,C,m){var y=s.transformTo("string",m(C));return r.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(u,2)+e(u,2)+e(I,4)+e(f,4)+e(y.length,2)+y}(this.dirRecords.length,g,c,this.zipComment,this.encodeFileName);this.push({data:d,meta:{percent:100}})},l.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},l.prototype.registerPrevious=function(c){this._sources.push(c);var p=this;return c.on("data",function(g){p.processChunk(g)}),c.on("end",function(){p.closedSource(p.previous.streamInfo),p._sources.length?p.prepareNextSource():p.end()}),c.on("error",function(g){p.error(g)}),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 p=this._sources;if(!n.prototype.error.call(this,c))return!1;for(var g=0;g<p.length;g++)try{p[g].error(c)}catch{}return!0},l.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,p=0;p<c.length;p++)c[p].lock()},A.exports=l},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(h,A,t){"use strict";var e=h("../compressions"),i=h("./ZipFileWorker");t.generateWorker=function(s,n,o){var a=new i(n.streamFiles,o,n.platform,n.encodeFileName),r=0;try{s.forEach(function(l,c){r++;var p=function(I,f){var C=I||f,m=e[C];if(!m)throw new Error(C+" is not a valid compression method !");return m}(c.options.compression,n.compression),g=c.options.compressionOptions||n.compressionOptions||{},d=c.dir,u=c.date;c._compressWorker(p,g).withStreamInfo("file",{name:l,dir:d,date:u,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(a)}),a.entriesCount=r}catch(l){a.error(l)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(h,A,t){"use strict";function e(){if(!(this instanceof e))return new e;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var i=new e;for(var s in this)typeof this[s]!="function"&&(i[s]=this[s]);return i}}(e.prototype=h("./object")).loadAsync=h("./load"),e.support=h("./support"),e.defaults=h("./defaults"),e.version="3.10.1",e.loadAsync=function(i,s){return new e().loadAsync(i,s)},e.external=h("./external"),A.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(h,A,t){"use strict";var e=h("./utils"),i=h("./external"),s=h("./utf8"),n=h("./zipEntries"),o=h("./stream/Crc32Probe"),a=h("./nodejsUtils");function r(l){return new i.Promise(function(c,p){var g=l.decompressed.getContentWorker().pipe(new o);g.on("error",function(d){p(d)}).on("end",function(){g.streamInfo.crc32!==l.decompressed.crc32?p(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}A.exports=function(l,c){var p=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(g){var d=new n(c);return d.load(g),d}).then(function(g){var d=[i.Promise.resolve(g)],u=g.files;if(c.checkCRC32)for(var I=0;I<u.length;I++)d.push(r(u[I]));return i.Promise.all(d)}).then(function(g){for(var d=g.shift(),u=d.files,I=0;I<u.length;I++){var f=u[I],C=f.fileNameStr,m=e.resolve(f.fileNameStr);p.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||(p.file(m).unsafeOriginalName=C)}return d.zipComment.length&&(p.comment=d.zipComment),p})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../stream/GenericWorker");function s(n,o){i.call(this,"Nodejs stream input adapter for "+n),this._upstreamEnded=!1,this._bindStream(o)}e.inherits(s,i),s.prototype._bindStream=function(n){var o=this;(this._stream=n).pause(),n.on("data",function(a){o.push({data:a,meta:{percent:0}})}).on("error",function(a){o.isPaused?this.generatedError=a:o.error(a)}).on("end",function(){o.isPaused?o._upstreamEnded=!0:o.end()})},s.prototype.pause=function(){return!!i.prototype.pause.call(this)&&(this._stream.pause(),!0)},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},A.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(h,A,t){"use strict";var e=h("readable-stream").Readable;function i(s,n,o){e.call(this,n),this._helper=s;var a=this;s.on("data",function(r,l){a.push(r)||a._helper.pause(),o&&o(l)}).on("error",function(r){a.emit("error",r)}).on("end",function(){a.push(null)})}h("../utils").inherits(i,e),i.prototype._read=function(){this._helper.resume()},A.exports=i},{"../utils":32,"readable-stream":16}],14:[function(h,A,t){"use strict";A.exports={isNode:typeof Buffer<"u",newBufferFrom:function(e,i){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,i);if(typeof e=="number")throw new Error('The "data" argument must not be a number');return new Buffer(e,i)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var i=new Buffer(e);return i.fill(0),i},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&typeof e.on=="function"&&typeof e.pause=="function"&&typeof e.resume=="function"}}},{}],15:[function(h,A,t){"use strict";function e(m,y,w){var E,v=s.getTypeOf(y),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=u(m)),S.createFolders&&(E=d(m))&&I.call(this,E,!0);var M=v==="string"&&S.binary===!1&&S.base64===!1;w&&w.binary!==void 0||(S.binary=!M),(y instanceof r&&y.uncompressedSize===0||S.dir||!y||y.length===0)&&(S.base64=!1,S.binary=!0,y="",S.compression="STORE",v="string");var F=null;F=y instanceof r||y instanceof n?y:p.isNode&&p.isStream(y)?new g(m,y):s.prepareContent(m,y,S.binary,S.optimizedBinaryString,S.base64);var N=new l(m,F,S);this.files[m]=N}var i=h("./utf8"),s=h("./utils"),n=h("./stream/GenericWorker"),o=h("./stream/StreamHelper"),a=h("./defaults"),r=h("./compressedObject"),l=h("./zipObject"),c=h("./generate"),p=h("./nodejsUtils"),g=h("./nodejs/NodejsStreamInputAdapter"),d=function(m){m.slice(-1)==="/"&&(m=m.substring(0,m.length-1));var y=m.lastIndexOf("/");return 0<y?m.substring(0,y):""},u=function(m){return m.slice(-1)!=="/"&&(m+="/"),m},I=function(m,y){return y=y!==void 0?y:a.createFolders,m=u(m),this.files[m]||e.call(this,m,null,{dir:!0,createFolders:y}),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 y,w,E;for(y in this.files)E=this.files[y],(w=y.slice(this.root.length,y.length))&&y.slice(0,this.root.length)===this.root&&m(w,E)},filter:function(m){var y=[];return this.forEach(function(w,E){m(w,E)&&y.push(E)}),y},file:function(m,y,w){if(arguments.length!==1)return m=this.root+m,e.call(this,m,y,w),this;if(f(m)){var E=m;return this.filter(function(S,M){return!M.dir&&E.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 y=this.root+m,w=I.call(this,y),E=this.clone();return E.root=w.name,E},remove:function(m){m=this.root+m;var y=this.files[m];if(y||(m.slice(-1)!=="/"&&(m+="/"),y=this.files[m]),y&&!y.dir)delete this.files[m];else for(var w=this.filter(function(v,S){return S.name.slice(0,m.length)===m}),E=0;E<w.length;E++)delete this.files[w[E].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 y,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 E=w.comment||this.comment||"";y=c.generateWorker(this,w,E)}catch(v){(y=new n("error")).error(v)}return new o(y,w.type||"string",w.mimeType)},generateAsync:function(m,y){return this.generateInternalStream(m).accumulate(y)},generateNodeStream:function(m,y){return(m=m||{}).type||(m.type="nodebuffer"),this.generateInternalStream(m).toNodejsStream(y)}};A.exports=C},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(h,A,t){"use strict";A.exports=h("stream")},{stream:void 0}],17:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s);for(var n=0;n<this.data.length;n++)s[n]=255&s[n]}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data[this.zero+s]},i.prototype.lastIndexOfSignature=function(s){for(var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.length-4;0<=l;--l)if(this.data[l]===n&&this.data[l+1]===o&&this.data[l+2]===a&&this.data[l+3]===r)return l-this.zero;return-1},i.prototype.readAndCheckSignature=function(s){var n=s.charCodeAt(0),o=s.charCodeAt(1),a=s.charCodeAt(2),r=s.charCodeAt(3),l=this.readData(4);return n===l[0]&&o===l[1]&&a===l[2]&&r===l[3]},i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return[];var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],18:[function(h,A,t){"use strict";var e=h("../utils");function i(s){this.data=s,this.length=s.length,this.index=0,this.zero=0}i.prototype={checkOffset:function(s){this.checkIndex(this.index+s)},checkIndex:function(s){if(this.length<this.zero+s||s<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+s+"). Corrupted zip ?")},setIndex:function(s){this.checkIndex(s),this.index=s},skip:function(s){this.setIndex(this.index+s)},byteAt:function(){},readInt:function(s){var n,o=0;for(this.checkOffset(s),n=this.index+s-1;n>=this.index;n--)o=(o<<8)+this.byteAt(n);return this.index+=s,o},readString:function(s){return e.transformTo("string",this.readData(s))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var s=this.readInt(4);return new Date(Date.UTC(1980+(s>>25&127),(s>>21&15)-1,s>>16&31,s>>11&31,s>>5&63,(31&s)<<1))}},A.exports=i},{"../utils":32}],19:[function(h,A,t){"use strict";var e=h("./Uint8ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(h,A,t){"use strict";var e=h("./DataReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.byteAt=function(s){return this.data.charCodeAt(this.zero+s)},i.prototype.lastIndexOfSignature=function(s){return this.data.lastIndexOf(s)-this.zero},i.prototype.readAndCheckSignature=function(s){return s===this.readData(4)},i.prototype.readData=function(s){this.checkOffset(s);var n=this.data.slice(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./DataReader":18}],21:[function(h,A,t){"use strict";var e=h("./ArrayReader");function i(s){e.call(this,s)}h("../utils").inherits(i,e),i.prototype.readData=function(s){if(this.checkOffset(s),s===0)return new Uint8Array(0);var n=this.data.subarray(this.zero+this.index,this.zero+this.index+s);return this.index+=s,n},A.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(h,A,t){"use strict";var e=h("../utils"),i=h("../support"),s=h("./ArrayReader"),n=h("./StringReader"),o=h("./NodeBufferReader"),a=h("./Uint8ArrayReader");A.exports=function(r){var l=e.getTypeOf(r);return e.checkSupport(l),l!=="string"||i.uint8array?l==="nodebuffer"?new o(r):i.uint8array?new a(e.transformTo("uint8array",r)):new s(e.transformTo("array",r)):new n(r)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(h,A,t){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../utils");function s(n){e.call(this,"ConvertWorker to "+n),this.destType=n}i.inherits(s,e),s.prototype.processChunk=function(n){this.push({data:i.transformTo(this.destType,n.data),meta:n.meta})},A.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(h,A,t){"use strict";var e=h("./GenericWorker"),i=h("../crc32");function s(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}h("../utils").inherits(s,e),s.prototype.processChunk=function(n){this.streamInfo.crc32=i(n.data,this.streamInfo.crc32||0),this.push(n)},A.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataLengthProbe for "+n),this.propName=n,this.withStreamInfo(n,0)}e.inherits(s,i),s.prototype.processChunk=function(n){if(n){var o=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=o+n.data.length}i.prototype.processChunk.call(this,n)},A.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./GenericWorker");function s(n){i.call(this,"DataWorker");var o=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,n.then(function(a){o.dataIsReady=!0,o.data=a,o.max=a&&a.length||0,o.type=e.getTypeOf(a),o.isPaused||o._tickAndRepeat()},function(a){o.error(a)})}e.inherits(s,i),s.prototype.cleanUp=function(){i.prototype.cleanUp.call(this),this.data=null},s.prototype.resume=function(){return!!i.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},s.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},s.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var n=null,o=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":n=this.data.substring(this.index,o);break;case"uint8array":n=this.data.subarray(this.index,o);break;case"array":case"nodebuffer":n=this.data.slice(this.index,o)}return this.index=o,this.push({data:n,meta:{percent:this.max?this.index/this.max*100:0}})},A.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(h,A,t){"use strict";function e(i){this.name=i||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}e.prototype={push:function(i){this.emit("data",i)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(i){this.emit("error",i)}return!0},error:function(i){return!this.isFinished&&(this.isPaused?this.generatedError=i:(this.isFinished=!0,this.emit("error",i),this.previous&&this.previous.error(i),this.cleanUp()),!0)},on:function(i,s){return this._listeners[i].push(s),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(i,s){if(this._listeners[i])for(var n=0;n<this._listeners[i].length;n++)this._listeners[i][n].call(this,s)},pipe:function(i){return i.registerPrevious(this)},registerPrevious:function(i){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=i.streamInfo,this.mergeStreamInfo(),this.previous=i;var s=this;return i.on("data",function(n){s.processChunk(n)}),i.on("end",function(){s.end()}),i.on("error",function(n){s.error(n)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var i=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),i=!0),this.previous&&this.previous.resume(),!i},flush:function(){},processChunk:function(i){this.push(i)},withStreamInfo:function(i,s){return this.extraStreamInfo[i]=s,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var i in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,i)&&(this.streamInfo[i]=this.extraStreamInfo[i])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var i="Worker "+this.name;return this.previous?this.previous+" -> "+i:i}},A.exports=e},{}],29:[function(h,A,t){"use strict";var e=h("../utils"),i=h("./ConvertWorker"),s=h("./GenericWorker"),n=h("../base64"),o=h("../support"),a=h("../external"),r=null;if(o.nodestream)try{r=h("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(p,g){return new a.Promise(function(d,u){var I=[],f=p._internalType,C=p._outputType,m=p._mimeType;p.on("data",function(y,w){I.push(y),g&&g(w)}).on("error",function(y){I=[],u(y)}).on("end",function(){try{var y=function(w,E,v){switch(w){case"blob":return e.newBlob(e.transformTo("arraybuffer",E),v);case"base64":return n.encode(E);default:return e.transformTo(w,E)}}(C,function(w,E){var v,S=0,M=null,F=0;for(v=0;v<E.length;v++)F+=E[v].length;switch(w){case"string":return E.join("");case"array":return Array.prototype.concat.apply([],E);case"uint8array":for(M=new Uint8Array(F),v=0;v<E.length;v++)M.set(E[v],S),S+=E[v].length;return M;case"nodebuffer":return Buffer.concat(E);default:throw new Error("concat : unsupported type '"+w+"'")}}(f,I),m);d(y)}catch(w){u(w)}I=[]}).resume()})}function c(p,g,d){var u=g;switch(g){case"blob":case"arraybuffer":u="uint8array";break;case"base64":u="string"}try{this._internalType=u,this._outputType=g,this._mimeType=d,e.checkSupport(u),this._worker=p.pipe(new i(u)),p.lock()}catch(I){this._worker=new s("error"),this._worker.error(I)}}c.prototype={accumulate:function(p){return l(this,p)},on:function(p,g){var d=this;return p==="data"?this._worker.on(p,function(u){g.call(d,u.data,u.meta)}):this._worker.on(p,function(){e.delay(g,arguments,d)}),this},resume:function(){return e.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(p){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"},p)}},A.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(h,A,t){"use strict";if(t.base64=!0,t.array=!0,t.string=!0,t.arraybuffer=typeof ArrayBuffer<"u"&&typeof Uint8Array<"u",t.nodebuffer=typeof Buffer<"u",t.uint8array=typeof Uint8Array<"u",typeof ArrayBuffer>"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);i.append(e),t.blob=i.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!h("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(h,A,t){"use strict";for(var e=h("./utils"),i=h("./support"),s=h("./nodejsUtils"),n=h("./stream/GenericWorker"),o=new Array(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;o[254]=o[254]=1;function r(){n.call(this,"utf-8 decode"),this.leftOver=null}function l(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return i.nodebuffer?s.newBufferFrom(c,"utf-8"):function(p){var g,d,u,I,f,C=p.length,m=0;for(I=0;I<C;I++)(64512&(d=p.charCodeAt(I)))==55296&&I+1<C&&(64512&(u=p.charCodeAt(I+1)))==56320&&(d=65536+(d-55296<<10)+(u-56320),I++),m+=d<128?1:d<2048?2:d<65536?3:4;for(g=i.uint8array?new Uint8Array(m):new Array(m),I=f=0;f<m;I++)(64512&(d=p.charCodeAt(I)))==55296&&I+1<C&&(64512&(u=p.charCodeAt(I+1)))==56320&&(d=65536+(d-55296<<10)+(u-56320),I++),d<128?g[f++]=d:(d<2048?g[f++]=192|d>>>6:(d<65536?g[f++]=224|d>>>12:(g[f++]=240|d>>>18,g[f++]=128|d>>>12&63),g[f++]=128|d>>>6&63),g[f++]=128|63&d);return g}(c)},t.utf8decode=function(c){return i.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(p){var g,d,u,I,f=p.length,C=new Array(2*f);for(g=d=0;g<f;)if((u=p[g++])<128)C[d++]=u;else if(4<(I=o[u]))C[d++]=65533,g+=I-1;else{for(u&=I===2?31:I===3?15:7;1<I&&g<f;)u=u<<6|63&p[g++],I--;1<I?C[d++]=65533:u<65536?C[d++]=u:(u-=65536,C[d++]=55296|u>>10&1023,C[d++]=56320|1023&u)}return C.length!==d&&(C.subarray?C=C.subarray(0,d):C.length=d),e.applyFromCharCode(C)}(c=e.transformTo(i.uint8array?"uint8array":"array",c))},e.inherits(r,n),r.prototype.processChunk=function(c){var p=e.transformTo(i.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(i.uint8array){var g=p;(p=new Uint8Array(g.length+this.leftOver.length)).set(this.leftOver,0),p.set(g,this.leftOver.length)}else p=this.leftOver.concat(p);this.leftOver=null}var d=function(I,f){var C;for((f=f||I.length)>I.length&&(f=I.length),C=f-1;0<=C&&(192&I[C])==128;)C--;return C<0||C===0?f:C+o[I[C]]>f?C:f}(p),u=p;d!==p.length&&(i.uint8array?(u=p.subarray(0,d),this.leftOver=p.subarray(d,p.length)):(u=p.slice(0,d),this.leftOver=p.slice(d,p.length))),this.push({data:t.utf8decode(u),meta:c.meta})},r.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=r,e.inherits(l,n),l.prototype.processChunk=function(c){this.push({data:t.utf8encode(c.data),meta:c.meta})},t.Utf8EncodeWorker=l},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(h,A,t){"use strict";var e=h("./support"),i=h("./base64"),s=h("./nodejsUtils"),n=h("./external");function o(g){return g}function a(g,d){for(var u=0;u<g.length;++u)d[u]=255&g.charCodeAt(u);return d}h("setimmediate"),t.newBlob=function(g,d){t.checkSupport("blob");try{return new Blob([g],{type:d})}catch{try{var u=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return u.append(g),u.getBlob(d)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(g,d,u){var I=[],f=0,C=g.length;if(C<=u)return String.fromCharCode.apply(null,g);for(;f<C;)d==="array"||d==="nodebuffer"?I.push(String.fromCharCode.apply(null,g.slice(f,Math.min(f+u,C)))):I.push(String.fromCharCode.apply(null,g.subarray(f,Math.min(f+u,C)))),f+=u;return I.join("")},stringifyByChar:function(g){for(var d="",u=0;u<g.length;u++)d+=String.fromCharCode(g[u]);return d},applyCanBeUsed:{uint8array:function(){try{return e.uint8array&&String.fromCharCode.apply(null,new Uint8Array(1)).length===1}catch{return!1}}(),nodebuffer:function(){try{return e.nodebuffer&&String.fromCharCode.apply(null,s.allocBuffer(1)).length===1}catch{return!1}}()}};function l(g){var d=65536,u=t.getTypeOf(g),I=!0;if(u==="uint8array"?I=r.applyCanBeUsed.uint8array:u==="nodebuffer"&&(I=r.applyCanBeUsed.nodebuffer),I)for(;1<d;)try{return r.stringifyByChunk(g,u,d)}catch{d=Math.floor(d/2)}return r.stringifyByChar(g)}function c(g,d){for(var u=0;u<g.length;u++)d[u]=g[u];return d}t.applyFromCharCode=l;var p={};p.string={string:o,array:function(g){return a(g,new Array(g.length))},arraybuffer:function(g){return p.string.uint8array(g).buffer},uint8array:function(g){return a(g,new Uint8Array(g.length))},nodebuffer:function(g){return a(g,s.allocBuffer(g.length))}},p.array={string:l,array:o,arraybuffer:function(g){return new Uint8Array(g).buffer},uint8array:function(g){return new Uint8Array(g)},nodebuffer:function(g){return s.newBufferFrom(g)}},p.arraybuffer={string:function(g){return l(new Uint8Array(g))},array:function(g){return c(new Uint8Array(g),new Array(g.byteLength))},arraybuffer:o,uint8array:function(g){return new Uint8Array(g)},nodebuffer:function(g){return s.newBufferFrom(new Uint8Array(g))}},p.uint8array={string:l,array:function(g){return c(g,new Array(g.length))},arraybuffer:function(g){return g.buffer},uint8array:o,nodebuffer:function(g){return s.newBufferFrom(g)}},p.nodebuffer={string:l,array:function(g){return c(g,new Array(g.length))},arraybuffer:function(g){return p.nodebuffer.uint8array(g).buffer},uint8array:function(g){return c(g,new Uint8Array(g.length))},nodebuffer:o},t.transformTo=function(g,d){if(d=d||"",!g)return d;t.checkSupport(g);var u=t.getTypeOf(d);return p[u][g](d)},t.resolve=function(g){for(var d=g.split("/"),u=[],I=0;I<d.length;I++){var f=d[I];f==="."||f===""&&I!==0&&I!==d.length-1||(f===".."?u.pop():u.push(f))}return u.join("/")},t.getTypeOf=function(g){return typeof g=="string"?"string":Object.prototype.toString.call(g)==="[object Array]"?"array":e.nodebuffer&&s.isBuffer(g)?"nodebuffer":e.uint8array&&g instanceof Uint8Array?"uint8array":e.arraybuffer&&g instanceof ArrayBuffer?"arraybuffer":void 0},t.checkSupport=function(g){if(!e[g.toLowerCase()])throw new Error(g+" is not supported by this platform")},t.MAX_VALUE_16BITS=65535,t.MAX_VALUE_32BITS=-1,t.pretty=function(g){var d,u,I="";for(u=0;u<(g||"").length;u++)I+="\\x"+((d=g.charCodeAt(u))<16?"0":"")+d.toString(16).toUpperCase();return I},t.delay=function(g,d,u){setImmediate(function(){g.apply(u||null,d||[])})},t.inherits=function(g,d){function u(){}u.prototype=d.prototype,g.prototype=new u},t.extend=function(){var g,d,u={};for(g=0;g<arguments.length;g++)for(d in arguments[g])Object.prototype.hasOwnProperty.call(arguments[g],d)&&u[d]===void 0&&(u[d]=arguments[g][d]);return u},t.prepareContent=function(g,d,u,I,f){return n.Promise.resolve(d).then(function(C){return e.blob&&(C instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(C))!==-1)&&typeof FileReader<"u"?new n.Promise(function(m,y){var w=new FileReader;w.onload=function(E){m(E.target.result)},w.onerror=function(E){y(E.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):u&&I!==!0&&(C=function(y){return a(y,e.uint8array?new Uint8Array(y.length):new Array(y.length))}(C))),C):n.Promise.reject(new Error("Can't read the data of '"+g+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./signature"),n=h("./zipEntry"),o=h("./support");function a(r){this.files=[],this.loadOptions=r}a.prototype={checkSignature:function(r){if(!this.reader.readAndCheckSignature(r)){this.reader.index-=4;var l=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(l)+", expected "+i.pretty(r)+")")}},isSignature:function(r,l){var c=this.reader.index;this.reader.setIndex(r);var p=this.reader.readString(4)===l;return this.reader.setIndex(c),p},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,p=this.zip64EndOfCentralSize-44;0<p;)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 p=l-c;if(0<p)this.isSignature(l,s.CENTRAL_FILE_HEADER)||(this.reader.zero=p);else if(p<0)throw new Error("Corrupted zip: missing "+Math.abs(p)+" bytes.")},prepareReader:function(r){this.reader=e(r)},load:function(r){this.prepareReader(r),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},A.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(h,A,t){"use strict";var e=h("./reader/readerFor"),i=h("./utils"),s=h("./compressedObject"),n=h("./crc32"),o=h("./utf8"),a=h("./compressions"),r=h("./support");function l(c,p){this.options=c,this.loadOptions=p}l.prototype={isEncrypted:function(){return(1&this.bitFlag)==1},useUTF8:function(){return(2048&this.bitFlag)==2048},readLocalPart:function(c){var p,g;if(c.skip(22),this.fileNameLength=c.readInt(2),g=c.readInt(2),this.fileName=c.readData(this.fileNameLength),c.skip(g),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((p=function(d){for(var u in a)if(Object.prototype.hasOwnProperty.call(a,u)&&a[u].magic===d)return a[u];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,p,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 p=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(p),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 p,g,d,u=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<u;)p=c.readInt(2),g=c.readInt(2),d=c.readData(g),this.extraFields[p]={id:p,length:g,value:d};c.setIndex(u)},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 p=this.findExtraFieldUnicodePath();if(p!==null)this.fileNameStr=p;else{var g=i.transformTo(c,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(g)}var d=this.findExtraFieldUnicodeComment();if(d!==null)this.fileCommentStr=d;else{var u=i.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(u)}}},findExtraFieldUnicodePath:function(){var c=this.extraFields[28789];if(c){var p=e(c.value);return p.readInt(1)!==1||n(this.fileName)!==p.readInt(4)?null:o.utf8decode(p.readData(c.length-5))}return null},findExtraFieldUnicodeComment:function(){var c=this.extraFields[25461];if(c){var p=e(c.value);return p.readInt(1)!==1||n(this.fileComment)!==p.readInt(4)?null:o.utf8decode(p.readData(c.length-5))}return null}},A.exports=l},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(h,A,t){"use strict";function e(p,g,d){this.name=p,this.dir=d.dir,this.date=d.date,this.comment=d.comment,this.unixPermissions=d.unixPermissions,this.dosPermissions=d.dosPermissions,this._data=g,this._dataBinary=d.binary,this.options={compression:d.compression,compressionOptions:d.compressionOptions}}var i=h("./stream/StreamHelper"),s=h("./stream/DataWorker"),n=h("./utf8"),o=h("./compressedObject"),a=h("./stream/GenericWorker");e.prototype={internalStream:function(p){var g=null,d="string";try{if(!p)throw new Error("No output type specified.");var u=(d=p.toLowerCase())==="string"||d==="text";d!=="binarystring"&&d!=="text"||(d="string"),g=this._decompressWorker();var I=!this._dataBinary;I&&!u&&(g=g.pipe(new n.Utf8EncodeWorker)),!I&&u&&(g=g.pipe(new n.Utf8DecodeWorker))}catch(f){(g=new a("error")).error(f)}return new i(g,d,"")},async:function(p,g){return this.internalStream(p).accumulate(g)},nodeStream:function(p,g){return this.internalStream(p||"nodebuffer").toNodejsStream(g)},_compressWorker:function(p,g){if(this._data instanceof o&&this._data.compression.magic===p.magic)return this._data.getCompressedWorker();var d=this._decompressWorker();return this._dataBinary||(d=d.pipe(new n.Utf8EncodeWorker)),o.createWorkerFrom(d,p,g)},_decompressWorker:function(){return this._data instanceof o?this._data.getContentWorker():this._data instanceof a?this._data:new s(this._data)}};for(var r=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],l=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<r.length;c++)e.prototype[r[c]]=l;A.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(h,A,t){(function(e){"use strict";var i,s,n=e.MutationObserver||e.WebKitMutationObserver;if(n){var o=0,a=new n(p),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 g=e.document.createElement("script");g.onreadystatechange=function(){p(),g.onreadystatechange=null,g.parentNode.removeChild(g),g=null},e.document.documentElement.appendChild(g)}:function(){setTimeout(p,0)};else{var l=new e.MessageChannel;l.port1.onmessage=p,i=function(){l.port2.postMessage(0)}}var c=[];function p(){var g,d;s=!0;for(var u=c.length;u;){for(d=c,c=[],g=-1;++g<u;)d[g]();u=c.length}s=!1}A.exports=function(g){c.push(g)!==1||s||i()}}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}],37:[function(h,A,t){"use strict";var e=h("immediate");function i(){}var s={},n=["REJECTED"],o=["FULFILLED"],a=["PENDING"];function r(u){if(typeof u!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,u!==i&&g(this,u)}function l(u,I,f){this.promise=u,typeof I=="function"&&(this.onFulfilled=I,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function c(u,I,f){e(function(){var C;try{C=I(f)}catch(m){return s.reject(u,m)}C===u?s.reject(u,new TypeError("Cannot resolve promise with itself")):s.resolve(u,C)})}function p(u){var I=u&&u.then;if(u&&(typeof u=="object"||typeof u=="function")&&typeof I=="function")return function(){I.apply(u,arguments)}}function g(u,I){var f=!1;function C(w){f||(f=!0,s.reject(u,w))}function m(w){f||(f=!0,s.resolve(u,w))}var y=d(function(){I(m,C)});y.status==="error"&&C(y.value)}function d(u,I){var f={};try{f.value=u(I),f.status="success"}catch(C){f.status="error",f.value=C}return f}(A.exports=r).prototype.finally=function(u){if(typeof u!="function")return this;var I=this.constructor;return this.then(function(f){return I.resolve(u()).then(function(){return f})},function(f){return I.resolve(u()).then(function(){throw f})})},r.prototype.catch=function(u){return this.then(null,u)},r.prototype.then=function(u,I){if(typeof u!="function"&&this.state===o||typeof I!="function"&&this.state===n)return this;var f=new this.constructor(i);return this.state!==a?c(f,this.state===o?u:I,this.outcome):this.queue.push(new l(f,u,I)),f},l.prototype.callFulfilled=function(u){s.resolve(this.promise,u)},l.prototype.otherCallFulfilled=function(u){c(this.promise,this.onFulfilled,u)},l.prototype.callRejected=function(u){s.reject(this.promise,u)},l.prototype.otherCallRejected=function(u){c(this.promise,this.onRejected,u)},s.resolve=function(u,I){var f=d(p,I);if(f.status==="error")return s.reject(u,f.value);var C=f.value;if(C)g(u,C);else{u.state=o,u.outcome=I;for(var m=-1,y=u.queue.length;++m<y;)u.queue[m].callFulfilled(I)}return u},s.reject=function(u,I){u.state=n,u.outcome=I;for(var f=-1,C=u.queue.length;++f<C;)u.queue[f].callRejected(I);return u},r.resolve=function(u){return u instanceof this?u:s.resolve(new this(i),u)},r.reject=function(u){var I=new this(i);return s.reject(I,u)},r.all=function(u){var I=this;if(Object.prototype.toString.call(u)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=u.length,C=!1;if(!f)return this.resolve([]);for(var m=new Array(f),y=0,w=-1,E=new this(i);++w<f;)v(u[w],w);return E;function v(S,M){I.resolve(S).then(function(F){m[M]=F,++y!==f||C||(C=!0,s.resolve(E,m))},function(F){C||(C=!0,s.reject(E,F))})}},r.race=function(u){var I=this;if(Object.prototype.toString.call(u)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=u.length,C=!1;if(!f)return this.resolve([]);for(var m=-1,y=new this(i);++m<f;)w=u[m],I.resolve(w).then(function(E){C||(C=!0,s.resolve(y,E))},function(E){C||(C=!0,s.reject(y,E))});var w;return y}},{immediate:36}],38:[function(h,A,t){"use strict";var e={};(0,h("./lib/utils/common").assign)(e,h("./lib/deflate"),h("./lib/inflate"),h("./lib/zlib/constants")),A.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(h,A,t){"use strict";var e=h("./zlib/deflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/messages"),o=h("./zlib/zstream"),a=Object.prototype.toString,r=0,l=-1,c=0,p=8;function g(u){if(!(this instanceof g))return new g(u);this.options=i.assign({level:l,method:p,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},u||{});var I=this.options;I.raw&&0<I.windowBits?I.windowBits=-I.windowBits:I.gzip&&0<I.windowBits&&I.windowBits<16&&(I.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,I.level,I.method,I.windowBits,I.memLevel,I.strategy);if(f!==r)throw new Error(n[f]);if(I.header&&e.deflateSetHeader(this.strm,I.header),I.dictionary){var C;if(C=typeof I.dictionary=="string"?s.string2buf(I.dictionary):a.call(I.dictionary)==="[object ArrayBuffer]"?new Uint8Array(I.dictionary):I.dictionary,(f=e.deflateSetDictionary(this.strm,C))!==r)throw new Error(n[f]);this._dict_set=!0}}function d(u,I){var f=new g(I);if(f.push(u,!0),f.err)throw f.msg||n[f.err];return f.result}g.prototype.push=function(u,I){var f,C,m=this.strm,y=this.options.chunkSize;if(this.ended)return!1;C=I===~~I?I:I===!0?4:0,typeof u=="string"?m.input=s.string2buf(u):a.call(u)==="[object ArrayBuffer]"?m.input=new Uint8Array(u):m.input=u,m.next_in=0,m.avail_in=m.input.length;do{if(m.avail_out===0&&(m.output=new i.Buf8(y),m.next_out=0,m.avail_out=y),(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))},g.prototype.onData=function(u){this.chunks.push(u)},g.prototype.onEnd=function(u){u===r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=u,this.msg=this.strm.msg},t.Deflate=g,t.deflate=d,t.deflateRaw=function(u,I){return(I=I||{}).raw=!0,d(u,I)},t.gzip=function(u,I){return(I=I||{}).gzip=!0,d(u,I)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(h,A,t){"use strict";var e=h("./zlib/inflate"),i=h("./utils/common"),s=h("./utils/strings"),n=h("./zlib/constants"),o=h("./zlib/messages"),a=h("./zlib/zstream"),r=h("./zlib/gzheader"),l=Object.prototype.toString;function c(g){if(!(this instanceof c))return new c(g);this.options=i.assign({chunkSize:16384,windowBits:0,to:""},g||{});var d=this.options;d.raw&&0<=d.windowBits&&d.windowBits<16&&(d.windowBits=-d.windowBits,d.windowBits===0&&(d.windowBits=-15)),!(0<=d.windowBits&&d.windowBits<16)||g&&g.windowBits||(d.windowBits+=32),15<d.windowBits&&d.windowBits<48&&!(15&d.windowBits)&&(d.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var u=e.inflateInit2(this.strm,d.windowBits);if(u!==n.Z_OK)throw new Error(o[u]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function p(g,d){var u=new c(d);if(u.push(g,!0),u.err)throw u.msg||o[u.err];return u.result}c.prototype.push=function(g,d){var u,I,f,C,m,y,w=this.strm,E=this.options.chunkSize,v=this.options.dictionary,S=!1;if(this.ended)return!1;I=d===~~d?d:d===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof g=="string"?w.input=s.binstring2buf(g):l.call(g)==="[object ArrayBuffer]"?w.input=new Uint8Array(g):w.input=g,w.next_in=0,w.avail_in=w.input.length;do{if(w.avail_out===0&&(w.output=new i.Buf8(E),w.next_out=0,w.avail_out=E),(u=e.inflate(w,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&v&&(y=typeof v=="string"?s.string2buf(v):l.call(v)==="[object ArrayBuffer]"?new Uint8Array(v):v,u=e.inflateSetDictionary(this.strm,y)),u===n.Z_BUF_ERROR&&S===!0&&(u=n.Z_OK,S=!1),u!==n.Z_STREAM_END&&u!==n.Z_OK)return this.onEnd(u),!(this.ended=!0);w.next_out&&(w.avail_out!==0&&u!==n.Z_STREAM_END&&(w.avail_in!==0||I!==n.Z_FINISH&&I!==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=E-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)&&u!==n.Z_STREAM_END);return u===n.Z_STREAM_END&&(I=n.Z_FINISH),I===n.Z_FINISH?(u=e.inflateEnd(this.strm),this.onEnd(u),this.ended=!0,u===n.Z_OK):I!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),!(w.avail_out=0))},c.prototype.onData=function(g){this.chunks.push(g)},c.prototype.onEnd=function(g){g===n.Z_OK&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=g,this.msg=this.strm.msg},t.Inflate=c,t.inflate=p,t.inflateRaw=function(g,d){return(d=d||{}).raw=!0,p(g,d)},t.ungzip=p},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(h,A,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Int32Array<"u";t.assign=function(n){for(var o=Array.prototype.slice.call(arguments,1);o.length;){var a=o.shift();if(a){if(typeof a!="object")throw new TypeError(a+"must be non-object");for(var r in a)a.hasOwnProperty(r)&&(n[r]=a[r])}}return n},t.shrinkBuf=function(n,o){return n.length===o?n:n.subarray?n.subarray(0,o):(n.length=o,n)};var i={arraySet:function(n,o,a,r,l){if(o.subarray&&n.subarray)n.set(o.subarray(a,a+r),l);else for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){var o,a,r,l,c,p;for(o=r=0,a=n.length;o<a;o++)r+=n[o].length;for(p=new Uint8Array(r),o=l=0,a=n.length;o<a;o++)c=n[o],p.set(c,l),l+=c.length;return p}},s={arraySet:function(n,o,a,r,l){for(var c=0;c<r;c++)n[l+c]=o[a+c]},flattenChunks:function(n){return[].concat.apply([],n)}};t.setTyped=function(n){n?(t.Buf8=Uint8Array,t.Buf16=Uint16Array,t.Buf32=Int32Array,t.assign(t,i)):(t.Buf8=Array,t.Buf16=Array,t.Buf32=Array,t.assign(t,s))},t.setTyped(e)},{}],42:[function(h,A,t){"use strict";var e=h("./common"),i=!0,s=!0;try{String.fromCharCode.apply(null,[0])}catch{i=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch{s=!1}for(var n=new e.Buf8(256),o=0;o<256;o++)n[o]=252<=o?6:248<=o?5:240<=o?4:224<=o?3:192<=o?2:1;function a(r,l){if(l<65537&&(r.subarray&&s||!r.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(r,l));for(var c="",p=0;p<l;p++)c+=String.fromCharCode(r[p]);return c}n[254]=n[254]=1,t.string2buf=function(r){var l,c,p,g,d,u=r.length,I=0;for(g=0;g<u;g++)(64512&(c=r.charCodeAt(g)))==55296&&g+1<u&&(64512&(p=r.charCodeAt(g+1)))==56320&&(c=65536+(c-55296<<10)+(p-56320),g++),I+=c<128?1:c<2048?2:c<65536?3:4;for(l=new e.Buf8(I),g=d=0;d<I;g++)(64512&(c=r.charCodeAt(g)))==55296&&g+1<u&&(64512&(p=r.charCodeAt(g+1)))==56320&&(c=65536+(c-55296<<10)+(p-56320),g++),c<128?l[d++]=c:(c<2048?l[d++]=192|c>>>6:(c<65536?l[d++]=224|c>>>12:(l[d++]=240|c>>>18,l[d++]=128|c>>>12&63),l[d++]=128|c>>>6&63),l[d++]=128|63&c);return l},t.buf2binstring=function(r){return a(r,r.length)},t.binstring2buf=function(r){for(var l=new e.Buf8(r.length),c=0,p=l.length;c<p;c++)l[c]=r.charCodeAt(c);return l},t.buf2string=function(r,l){var c,p,g,d,u=l||r.length,I=new Array(2*u);for(c=p=0;c<u;)if((g=r[c++])<128)I[p++]=g;else if(4<(d=n[g]))I[p++]=65533,c+=d-1;else{for(g&=d===2?31:d===3?15:7;1<d&&c<u;)g=g<<6|63&r[c++],d--;1<d?I[p++]=65533:g<65536?I[p++]=g:(g-=65536,I[p++]=55296|g>>10&1023,I[p++]=56320|1023&g)}return a(I,p)},t.utf8border=function(r,l){var c;for((l=l||r.length)>r.length&&(l=r.length),c=l-1;0<=c&&(192&r[c])==128;)c--;return c<0||c===0?l:c+n[r[c]]>l?c:l}},{"./common":41}],43:[function(h,A,t){"use strict";A.exports=function(e,i,s,n){for(var o=65535&e|0,a=e>>>16&65535|0,r=0;s!==0;){for(s-=r=2e3<s?2e3:s;a=a+(o=o+i[n++]|0)|0,--r;);o%=65521,a%=65521}return o|a<<16|0}},{}],44:[function(h,A,t){"use strict";A.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(h,A,t){"use strict";var e=function(){for(var i,s=[],n=0;n<256;n++){i=n;for(var o=0;o<8;o++)i=1&i?3988292384^i>>>1:i>>>1;s[n]=i}return s}();A.exports=function(i,s,n,o){var a=e,r=o+n;i^=-1;for(var l=o;l<r;l++)i=i>>>8^a[255&(i^s[l])];return-1^i}},{}],46:[function(h,A,t){"use strict";var e,i=h("../utils/common"),s=h("./trees"),n=h("./adler32"),o=h("./crc32"),a=h("./messages"),r=0,l=4,c=0,p=-2,g=-1,d=4,u=2,I=8,f=9,C=286,m=30,y=19,w=2*C+1,E=15,v=3,S=258,M=S+v+1,F=42,N=113,Q=1,D=2,K=3,x=4;function Y(B,J){return B.msg=a[J],J}function q(B){return(B<<1)-(4<B?9:0)}function j(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 P(B,J){s._tr_flush_block(B,0<=B.block_start?B.block_start:-1,B.strstart-B.block_start,J),B.block_start=B.strstart,L(B.strm)}function tt(B,J){B.pending_buf[B.pending++]=J}function O(B,J){B.pending_buf[B.pending++]=J>>>8&255,B.pending_buf[B.pending++]=255&J}function V(B,J){var G,b,k=B.max_chain_length,H=B.strstart,z=B.prev_length,W=B.nice_match,R=B.strstart>B.w_size-M?B.strstart-(B.w_size-M):0,Z=B.window,et=B.w_mask,_=B.prev,it=B.strstart+S,ft=Z[H+z-1],ht=Z[H+z];B.prev_length>=B.good_match&&(k>>=2),W>B.lookahead&&(W=B.lookahead);do if(Z[(G=J)+z]===ht&&Z[G+z-1]===ft&&Z[G]===Z[H]&&Z[++G]===Z[H+1]){H+=2,G++;do;while(Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&H<it);if(b=S-(it-H),H=it-S,z<b){if(B.match_start=J,W<=(z=b))break;ft=Z[H+z-1],ht=Z[H+z]}}while((J=_[J&et])>R&&--k!=0);return z<=B.lookahead?z:B.lookahead}function rt(B){var J,G,b,k,H,z,W,R,Z,et,_=B.w_size;do{if(k=B.window_size-B.lookahead-B.strstart,B.strstart>=_+(_-M)){for(i.arraySet(B.window,B.window,_,_,0),B.match_start-=_,B.strstart-=_,B.block_start-=_,J=G=B.hash_size;b=B.head[--J],B.head[J]=_<=b?b-_:0,--G;);for(J=G=_;b=B.prev[--J],B.prev[J]=_<=b?b-_:0,--G;);k+=_}if(B.strm.avail_in===0)break;if(z=B.strm,W=B.window,R=B.strstart+B.lookahead,Z=k,et=void 0,et=z.avail_in,Z<et&&(et=Z),G=et===0?0:(z.avail_in-=et,i.arraySet(W,z.input,z.next_in,et,R),z.state.wrap===1?z.adler=n(z.adler,W,et,R):z.state.wrap===2&&(z.adler=o(z.adler,W,et,R)),z.next_in+=et,z.total_in+=et,et),B.lookahead+=G,B.lookahead+B.insert>=v)for(H=B.strstart-B.insert,B.ins_h=B.window[H],B.ins_h=(B.ins_h<<B.hash_shift^B.window[H+1])&B.hash_mask;B.insert&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[H+v-1])&B.hash_mask,B.prev[H&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=H,H++,B.insert--,!(B.lookahead+B.insert<v)););}while(B.lookahead<M&&B.strm.avail_in!==0)}function gt(B,J){for(var G,b;;){if(B.lookahead<M){if(rt(B),B.lookahead<M&&J===r)return Q;if(B.lookahead===0)break}if(G=0,B.lookahead>=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),G!==0&&B.strstart-G<=B.w_size-M&&(B.match_length=V(B,G)),B.match_length>=v)if(b=s._tr_tally(B,B.strstart-B.match_start,B.match_length-v),B.lookahead-=B.match_length,B.match_length<=B.max_lazy_match&&B.lookahead>=v){for(B.match_length--;B.strstart++,B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart,--B.match_length!=0;);B.strstart++}else B.strstart+=B.match_length,B.match_length=0,B.ins_h=B.window[B.strstart],B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+1])&B.hash_mask;else b=s._tr_tally(B,0,B.window[B.strstart]),B.lookahead--,B.strstart++;if(b&&(P(B,!1),B.strm.avail_out===0))return Q}return B.insert=B.strstart<v-1?B.strstart:v-1,J===l?(P(B,!0),B.strm.avail_out===0?K:x):B.last_lit&&(P(B,!1),B.strm.avail_out===0)?Q:D}function nt(B,J){for(var G,b,k;;){if(B.lookahead<M){if(rt(B),B.lookahead<M&&J===r)return Q;if(B.lookahead===0)break}if(G=0,B.lookahead>=v&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),B.prev_length=B.match_length,B.prev_match=B.match_start,B.match_length=v-1,G!==0&&B.prev_length<B.max_lazy_match&&B.strstart-G<=B.w_size-M&&(B.match_length=V(B,G),B.match_length<=5&&(B.strategy===1||B.match_length===v&&4096<B.strstart-B.match_start)&&(B.match_length=v-1)),B.prev_length>=v&&B.match_length<=B.prev_length){for(k=B.strstart+B.lookahead-v,b=s._tr_tally(B,B.strstart-1-B.prev_match,B.prev_length-v),B.lookahead-=B.prev_length-1,B.prev_length-=2;++B.strstart<=k&&(B.ins_h=(B.ins_h<<B.hash_shift^B.window[B.strstart+v-1])&B.hash_mask,G=B.prev[B.strstart&B.w_mask]=B.head[B.ins_h],B.head[B.ins_h]=B.strstart),--B.prev_length!=0;);if(B.match_available=0,B.match_length=v-1,B.strstart++,b&&(P(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]))&&P(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?(P(B,!0),B.strm.avail_out===0?K:x):B.last_lit&&(P(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=I,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*y+1)),j(this.dyn_ltree),j(this.dyn_dtree),j(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(E+1),this.heap=new i.Buf16(2*C+1),j(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*C+1),j(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=u,(J=B.state).pending=0,J.pending_out=0,J.wrap<0&&(J.wrap=-J.wrap),J.status=J.wrap?F:N,B.adler=J.wrap===2?0:1,J.last_flush=r,s._tr_init(J),c):Y(B,p)}function Qt(B){var J=ot(B);return J===c&&function(G){G.window_size=2*G.w_size,j(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 Ct(B,J,G,b,k,H){if(!B)return p;var z=1;if(J===g&&(J=6),b<0?(z=0,b=-b):15<b&&(z=2,b-=16),k<1||f<k||G!==I||b<8||15<b||J<0||9<J||H<0||d<H)return Y(B,p);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,P(B,!1),B.strm.avail_out===0)||B.strstart-B.block_start>=B.w_size-M&&(P(B,!1),B.strm.avail_out===0))return Q}return B.insert=0,J===l?(P(B,!0),B.strm.avail_out===0?K:x):(B.strstart>B.block_start&&(P(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 Ct(B,J,I,15,8,0)},t.deflateInit2=Ct,t.deflateReset=Qt,t.deflateResetKeep=ot,t.deflateSetHeader=function(B,J){return B&&B.state?B.state.wrap!==2?p:(B.state.gzhead=J,c):p},t.deflate=function(B,J){var G,b,k,H;if(!B||!B.state||5<J||J<0)return B?Y(B,p):p;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:p);if(b.strm=B,G=b.last_flush,b.last_flush=J,b.status===F)if(b.wrap===2)B.adler=0,tt(b,31),tt(b,139),tt(b,8),b.gzhead?(tt(b,(b.gzhead.text?1:0)+(b.gzhead.hcrc?2:0)+(b.gzhead.extra?4:0)+(b.gzhead.name?8:0)+(b.gzhead.comment?16:0)),tt(b,255&b.gzhead.time),tt(b,b.gzhead.time>>8&255),tt(b,b.gzhead.time>>16&255),tt(b,b.gzhead.time>>24&255),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,255&b.gzhead.os),b.gzhead.extra&&b.gzhead.extra.length&&(tt(b,255&b.gzhead.extra.length),tt(b,b.gzhead.extra.length>>8&255)),b.gzhead.hcrc&&(B.adler=o(B.adler,b.pending_buf,b.pending,0)),b.gzindex=0,b.status=69):(tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,3),b.status=N);else{var z=I+(b.w_bits-8<<4)<<8;z|=(2<=b.strategy||b.level<2?0:b.level<6?1:b.level===6?2:3)<<6,b.strstart!==0&&(z|=32),z+=31-z%31,b.status=N,O(b,z),b.strstart!==0&&(O(b,B.adler>>>16),O(b,65535&B.adler)),B.adler=1}if(b.status===69)if(b.gzhead.extra){for(k=b.pending;b.gzindex<(65535&b.gzhead.extra.length)&&(b.pending!==b.pending_buf_size||(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending!==b.pending_buf_size));)tt(b,255&b.gzhead.extra[b.gzindex]),b.gzindex++;b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),b.gzindex===b.gzhead.extra.length&&(b.gzindex=0,b.status=73)}else b.status=73;if(b.status===73)if(b.gzhead.name){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.name.length?255&b.gzhead.name.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.gzindex=0,b.status=91)}else b.status=91;if(b.status===91)if(b.gzhead.comment){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.comment.length?255&b.gzhead.comment.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.status=103)}else b.status=103;if(b.status===103&&(b.gzhead.hcrc?(b.pending+2>b.pending_buf_size&&L(B),b.pending+2<=b.pending_buf_size&&(tt(b,255&B.adler),tt(b,B.adler>>8&255),B.adler=0,b.status=N)):b.status=N),b.pending!==0){if(L(B),B.avail_out===0)return b.last_flush=-1,c}else if(B.avail_in===0&&q(J)<=q(G)&&J!==l)return Y(B,-5);if(b.status===666&&B.avail_in!==0)return Y(B,-5);if(B.avail_in!==0||b.lookahead!==0||J!==r&&b.status!==666){var W=b.strategy===2?function(R,Z){for(var et;;){if(R.lookahead===0&&(rt(R),R.lookahead===0)){if(Z===r)return Q;break}if(R.match_length=0,et=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++,et&&(P(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,Z===l?(P(R,!0),R.strm.avail_out===0?K:x):R.last_lit&&(P(R,!1),R.strm.avail_out===0)?Q:D}(b,J):b.strategy===3?function(R,Z){for(var et,_,it,ft,ht=R.window;;){if(R.lookahead<=S){if(rt(R),R.lookahead<=S&&Z===r)return Q;if(R.lookahead===0)break}if(R.match_length=0,R.lookahead>=v&&0<R.strstart&&(_=ht[it=R.strstart-1])===ht[++it]&&_===ht[++it]&&_===ht[++it]){ft=R.strstart+S;do;while(_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&it<ft);R.match_length=S-(ft-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&&(P(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,Z===l?(P(R,!0),R.strm.avail_out===0?K:x):R.last_lit&&(P(R,!1),R.strm.avail_out===0)?Q:D}(b,J):e[b.level].func(b,J);if(W!==K&&W!==x||(b.status=666),W===Q||W===K)return B.avail_out===0&&(b.last_flush=-1),c;if(W===D&&(J===1?s._tr_align(b):J!==5&&(s._tr_stored_block(b,0,0,!1),J===3&&(j(b.head),b.lookahead===0&&(b.strstart=0,b.block_start=0,b.insert=0))),L(B),B.avail_out===0))return b.last_flush=-1,c}return J!==l?c:b.wrap<=0?1:(b.wrap===2?(tt(b,255&B.adler),tt(b,B.adler>>8&255),tt(b,B.adler>>16&255),tt(b,B.adler>>24&255),tt(b,255&B.total_in),tt(b,B.total_in>>8&255),tt(b,B.total_in>>16&255),tt(b,B.total_in>>24&255)):(O(b,B.adler>>>16),O(b,65535&B.adler)),L(B),0<b.wrap&&(b.wrap=-b.wrap),b.pending!==0?c:1)},t.deflateEnd=function(B){var J;return B&&B.state?(J=B.state.status)!==F&&J!==69&&J!==73&&J!==91&&J!==103&&J!==N&&J!==666?Y(B,p):(B.state=null,J===N?Y(B,-3):c):p},t.deflateSetDictionary=function(B,J){var G,b,k,H,z,W,R,Z,et=J.length;if(!B||!B.state||(H=(G=B.state).wrap)===2||H===1&&G.status!==F||G.lookahead)return p;for(H===1&&(B.adler=n(B.adler,J,et,0)),G.wrap=0,et>=G.w_size&&(H===0&&(j(G.head),G.strstart=0,G.block_start=0,G.insert=0),Z=new i.Buf8(G.w_size),i.arraySet(Z,J,et-G.w_size,G.w_size,0),J=Z,et=G.w_size),z=B.avail_in,W=B.next_in,R=B.input,B.avail_in=et,B.next_in=0,B.input=J,rt(G);G.lookahead>=v;){for(b=G.strstart,k=G.lookahead-(v-1);G.ins_h=(G.ins_h<<G.hash_shift^G.window[b+v-1])&G.hash_mask,G.prev[b&G.w_mask]=G.head[G.ins_h],G.head[G.ins_h]=b,b++,--k;);G.strstart=b,G.lookahead=v-1,rt(G)}return G.strstart+=G.lookahead,G.block_start=G.strstart,G.insert=G.lookahead,G.lookahead=0,G.match_length=G.prev_length=v-1,G.match_available=0,B.next_in=W,B.input=R,B.avail_in=z,G.wrap=H,c},t.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(h,A,t){"use strict";A.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(h,A,t){"use strict";A.exports=function(e,i){var s,n,o,a,r,l,c,p,g,d,u,I,f,C,m,y,w,E,v,S,M,F,N,Q,D;s=e.state,n=e.next_in,Q=e.input,o=n+(e.avail_in-5),a=e.next_out,D=e.output,r=a-(i-e.avail_out),l=a+(e.avail_out-257),c=s.dmax,p=s.wsize,g=s.whave,d=s.wnext,u=s.window,I=s.hold,f=s.bits,C=s.lencode,m=s.distcode,y=(1<<s.lenbits)-1,w=(1<<s.distbits)-1;t:do{f<15&&(I+=Q[n++]<<f,f+=8,I+=Q[n++]<<f,f+=8),E=C[I&y];e:for(;;){if(I>>>=v=E>>>24,f-=v,(v=E>>>16&255)===0)D[a++]=65535&E;else{if(!(16&v)){if(!(64&v)){E=C[(65535&E)+(I&(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&E,(v&=15)&&(f<v&&(I+=Q[n++]<<f,f+=8),S+=I&(1<<v)-1,I>>>=v,f-=v),f<15&&(I+=Q[n++]<<f,f+=8,I+=Q[n++]<<f,f+=8),E=m[I&w];i:for(;;){if(I>>>=v=E>>>24,f-=v,!(16&(v=E>>>16&255))){if(!(64&v)){E=m[(65535&E)+(I&(1<<v)-1)];continue i}e.msg="invalid distance code",s.mode=30;break t}if(M=65535&E,f<(v&=15)&&(I+=Q[n++]<<f,(f+=8)<v&&(I+=Q[n++]<<f,f+=8)),c<(M+=I&(1<<v)-1)){e.msg="invalid distance too far back",s.mode=30;break t}if(I>>>=v,f-=v,(v=a-r)<M){if(g<(v=M-v)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break t}if(N=u,(F=0)===d){if(F+=p-v,v<S){for(S-=v;D[a++]=u[F++],--v;);F=a-M,N=D}}else if(d<v){if(F+=p+d-v,(v-=d)<S){for(S-=v;D[a++]=u[F++],--v;);if(F=0,d<S){for(S-=v=d;D[a++]=u[F++],--v;);F=a-M,N=D}}}else if(F+=d-v,v<S){for(S-=v;D[a++]=u[F++],--v;);F=a-M,N=D}for(;2<S;)D[a++]=N[F++],D[a++]=N[F++],D[a++]=N[F++],S-=3;S&&(D[a++]=N[F++],1<S&&(D[a++]=N[F++]))}else{for(F=a-M;D[a++]=D[F++],D[a++]=D[F++],D[a++]=D[F++],2<(S-=3););S&&(D[a++]=D[F++],1<S&&(D[a++]=D[F++]))}break}}break}}while(n<o&&a<l);n-=S=f>>3,I&=(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=I,s.bits=f}},{}],49:[function(h,A,t){"use strict";var e=h("../utils/common"),i=h("./adler32"),s=h("./crc32"),n=h("./inffast"),o=h("./inftrees"),a=1,r=2,l=0,c=-2,p=1,g=852,d=592;function u(F){return(F>>>24&255)+(F>>>8&65280)+((65280&F)<<8)+((255&F)<<24)}function I(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(F){var N;return F&&F.state?(N=F.state,F.total_in=F.total_out=N.total=0,F.msg="",N.wrap&&(F.adler=1&N.wrap),N.mode=p,N.last=0,N.havedict=0,N.dmax=32768,N.head=null,N.hold=0,N.bits=0,N.lencode=N.lendyn=new e.Buf32(g),N.distcode=N.distdyn=new e.Buf32(d),N.sane=1,N.back=-1,l):c}function C(F){var N;return F&&F.state?((N=F.state).wsize=0,N.whave=0,N.wnext=0,f(F)):c}function m(F,N){var Q,D;return F&&F.state?(D=F.state,N<0?(Q=0,N=-N):(Q=1+(N>>4),N<48&&(N&=15)),N&&(N<8||15<N)?c:(D.window!==null&&D.wbits!==N&&(D.window=null),D.wrap=Q,D.wbits=N,C(F))):c}function y(F,N){var Q,D;return F?(D=new I,(F.state=D).window=null,(Q=m(F,N))!==l&&(F.state=null),Q):c}var w,E,v=!0;function S(F){if(v){var N;for(w=new e.Buf32(512),E=new e.Buf32(32),N=0;N<144;)F.lens[N++]=8;for(;N<256;)F.lens[N++]=9;for(;N<280;)F.lens[N++]=7;for(;N<288;)F.lens[N++]=8;for(o(a,F.lens,0,288,w,0,F.work,{bits:9}),N=0;N<32;)F.lens[N++]=5;o(r,F.lens,0,32,E,0,F.work,{bits:5}),v=!1}F.lencode=w,F.lenbits=9,F.distcode=E,F.distbits=5}function M(F,N,Q,D){var K,x=F.state;return x.window===null&&(x.wsize=1<<x.wbits,x.wnext=0,x.whave=0,x.window=new e.Buf8(x.wsize)),D>=x.wsize?(e.arraySet(x.window,N,Q-x.wsize,x.wsize,0),x.wnext=0,x.whave=x.wsize):(D<(K=x.wsize-x.wnext)&&(K=D),e.arraySet(x.window,N,Q-D,K,x.wnext),(D-=K)?(e.arraySet(x.window,N,Q-D,D,0),x.wnext=D,x.whave=x.wsize):(x.wnext+=K,x.wnext===x.wsize&&(x.wnext=0),x.whave<x.wsize&&(x.whave+=K))),0}t.inflateReset=C,t.inflateReset2=m,t.inflateResetKeep=f,t.inflateInit=function(F){return y(F,15)},t.inflateInit2=y,t.inflate=function(F,N){var Q,D,K,x,Y,q,j,L,P,tt,O,V,rt,gt,nt,At,lt,ot,Qt,Ct,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,j=F.avail_out,x=F.next_in,D=F.input,q=F.avail_in,L=Q.hold,P=Q.bits,tt=q,O=j,J=l;t:for(;;)switch(Q.mode){case p:if(Q.wrap===0){Q.mode=13;break}for(;P<16;){if(q===0)break t;q--,L+=D[x++]<<P,P+=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),P=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(P-=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,P=L=0;break;case 2:for(;P<16;){if(q===0)break t;q--,L+=D[x++]<<P,P+=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)),P=L=0,Q.mode=3;case 3:for(;P<32;){if(q===0)break t;q--,L+=D[x++]<<P,P+=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)),P=L=0,Q.mode=4;case 4:for(;P<16;){if(q===0)break t;q--,L+=D[x++]<<P,P+=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)),P=L=0,Q.mode=5;case 5:if(1024&Q.flags){for(;P<16;){if(q===0)break t;q--,L+=D[x++]<<P,P+=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)),P=L=0}else Q.head&&(Q.head.extra=null);Q.mode=6;case 6:if(1024&Q.flags&&(q<(V=Q.length)&&(V=q),V&&(Q.head&&(B=Q.head.extra_len-Q.length,Q.head.extra||(Q.head.extra=new Array(Q.head.extra_len)),e.arraySet(Q.head.extra,D,x,V,B)),512&Q.flags&&(Q.check=s(Q.check,D,V,x)),q-=V,x+=V,Q.length-=V),Q.length))break t;Q.length=0,Q.mode=7;case 7:if(2048&Q.flags){if(q===0)break t;for(V=0;B=D[x+V++],Q.head&&B&&Q.length<65536&&(Q.head.name+=String.fromCharCode(B)),B&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,x)),q-=V,x+=V,B)break t}else Q.head&&(Q.head.name=null);Q.length=0,Q.mode=8;case 8:if(4096&Q.flags){if(q===0)break t;for(V=0;B=D[x+V++],Q.head&&B&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(B)),B&&V<q;);if(512&Q.flags&&(Q.check=s(Q.check,D,V,x)),q-=V,x+=V,B)break t}else Q.head&&(Q.head.comment=null);Q.mode=9;case 9:if(512&Q.flags){for(;P<16;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(L!==(65535&Q.check)){F.msg="header crc mismatch",Q.mode=30;break}P=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(;P<32;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}F.adler=Q.check=u(L),P=L=0,Q.mode=11;case 11:if(Q.havedict===0)return F.next_out=Y,F.avail_out=j,F.next_in=x,F.avail_in=q,Q.hold=L,Q.bits=P,2;F.adler=Q.check=1,Q.mode=12;case 12:if(N===5||N===6)break t;case 13:if(Q.last){L>>>=7&P,P-=7&P,Q.mode=27;break}for(;P<3;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}switch(Q.last=1&L,P-=1,3&(L>>>=1)){case 0:Q.mode=14;break;case 1:if(S(Q),Q.mode=20,N!==6)break;L>>>=2,P-=2;break t;case 2:Q.mode=17;break;case 3:F.msg="invalid block type",Q.mode=30}L>>>=2,P-=2;break;case 14:for(L>>>=7&P,P-=7&P;P<32;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if((65535&L)!=(L>>>16^65535)){F.msg="invalid stored block lengths",Q.mode=30;break}if(Q.length=65535&L,P=L=0,Q.mode=15,N===6)break t;case 15:Q.mode=16;case 16:if(V=Q.length){if(q<V&&(V=q),j<V&&(V=j),V===0)break t;e.arraySet(K,D,x,V,Y),q-=V,x+=V,j-=V,Y+=V,Q.length-=V;break}Q.mode=12;break;case 17:for(;P<14;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(Q.nlen=257+(31&L),L>>>=5,P-=5,Q.ndist=1+(31&L),L>>>=5,P-=5,Q.ncode=4+(15&L),L>>>=4,P-=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(;P<3;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}Q.lens[z[Q.have++]]=7&L,L>>>=3,P-=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)<=P);){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(lt<16)L>>>=nt,P-=nt,Q.lens[Q.have++]=lt;else{if(lt===16){for(b=nt+2;P<b;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(L>>>=nt,P-=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,P-=2}else if(lt===17){for(b=nt+3;P<b;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}P-=nt,B=0,V=3+(7&(L>>>=nt)),L>>>=3,P-=3}else{for(b=nt+7;P<b;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}P-=nt,B=0,V=11+(127&(L>>>=nt)),L>>>=7,P-=7}if(Q.have+V>Q.nlen+Q.ndist){F.msg="invalid bit length repeat",Q.mode=30;break}for(;V--;)Q.lens[Q.have++]=B}}if(Q.mode===30)break;if(Q.lens[256]===0){F.msg="invalid code -- missing end-of-block",Q.mode=30;break}if(Q.lenbits=9,G={bits:Q.lenbits},J=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,G),Q.lenbits=G.bits,J){F.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,G={bits:Q.distbits},J=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,G),Q.distbits=G.bits,J){F.msg="invalid distances set",Q.mode=30;break}if(Q.mode=20,N===6)break t;case 20:Q.mode=21;case 21:if(6<=q&&258<=j){F.next_out=Y,F.avail_out=j,F.next_in=x,F.avail_in=q,Q.hold=L,Q.bits=P,n(F,O),Y=F.next_out,K=F.output,j=F.avail_out,x=F.next_in,D=F.input,q=F.avail_in,L=Q.hold,P=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)<=P);){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(At&&!(240&At)){for(ot=nt,Qt=At,Ct=lt;At=(k=Q.lencode[Ct+((L&(1<<ot+Qt)-1)>>ot)])>>>16&255,lt=65535&k,!(ot+(nt=k>>>24)<=P);){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}L>>>=ot,P-=ot,Q.back+=ot}if(L>>>=nt,P-=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;P<b;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}Q.length+=L&(1<<Q.extra)-1,L>>>=Q.extra,P-=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)<=P);){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(!(240&At)){for(ot=nt,Qt=At,Ct=lt;At=(k=Q.distcode[Ct+((L&(1<<ot+Qt)-1)>>ot)])>>>16&255,lt=65535&k,!(ot+(nt=k>>>24)<=P);){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}L>>>=ot,P-=ot,Q.back+=ot}if(L>>>=nt,P-=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;P<b;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}Q.offset+=L&(1<<Q.extra)-1,L>>>=Q.extra,P-=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(j===0)break t;if(V=O-j,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(j<V&&(V=j),j-=V,Q.length-=V;K[Y++]=gt[rt++],--V;);Q.length===0&&(Q.mode=21);break;case 26:if(j===0)break t;K[Y++]=Q.length,j--,Q.mode=21;break;case 27:if(Q.wrap){for(;P<32;){if(q===0)break t;q--,L|=D[x++]<<P,P+=8}if(O-=j,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=j,(Q.flags?L:u(L))!==Q.check){F.msg="incorrect data check",Q.mode=30;break}P=L=0}Q.mode=28;case 28:if(Q.wrap&&Q.flags){for(;P<32;){if(q===0)break t;q--,L+=D[x++]<<P,P+=8}if(L!==(4294967295&Q.total)){F.msg="incorrect length check",Q.mode=30;break}P=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=j,F.next_in=x,F.avail_in=q,Q.hold=L,Q.bits=P,(Q.wsize||O!==F.avail_out&&Q.mode<30&&(Q.mode<27||N!==4))&&M(F,F.output,F.next_out,O-F.avail_out)?(Q.mode=31,-4):(tt-=F.avail_in,O-=F.avail_out,F.total_in+=tt,F.total_out+=O,Q.total+=O,Q.wrap&&O&&(F.adler=Q.check=Q.flags?s(Q.check,K,O,F.next_out-O):i(Q.check,K,O,F.next_out-O)),F.data_type=Q.bits+(Q.last?64:0)+(Q.mode===12?128:0)+(Q.mode===20||Q.mode===15?256:0),(tt==0&&O===0||N===4)&&J===l&&(J=-5),J)},t.inflateEnd=function(F){if(!F||!F.state)return c;var N=F.state;return N.window&&(N.window=null),F.state=null,l},t.inflateGetHeader=function(F,N){var Q;return F&&F.state&&2&(Q=F.state).wrap?((Q.head=N).done=!1,l):c},t.inflateSetDictionary=function(F,N){var Q,D=N.length;return F&&F.state?(Q=F.state).wrap!==0&&Q.mode!==11?c:Q.mode===11&&i(1,N,D,0)!==Q.check?-3:M(F,N,D,D)?(Q.mode=31,-4):(Q.havedict=1,l):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(h,A,t){"use strict";var e=h("../utils/common"),i=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],s=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],o=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];A.exports=function(a,r,l,c,p,g,d,u){var I,f,C,m,y,w,E,v,S,M=u.bits,F=0,N=0,Q=0,D=0,K=0,x=0,Y=0,q=0,j=0,L=0,P=null,tt=0,O=new e.Buf16(16),V=new e.Buf16(16),rt=null,gt=0;for(F=0;F<=15;F++)O[F]=0;for(N=0;N<c;N++)O[r[l+N]]++;for(K=M,D=15;1<=D&&O[D]===0;D--);if(D<K&&(K=D),D===0)return p[g++]=20971520,p[g++]=20971520,u.bits=1,0;for(Q=1;Q<D&&O[Q]===0;Q++);for(K<Q&&(K=Q),F=q=1;F<=15;F++)if(q<<=1,(q-=O[F])<0)return-1;if(0<q&&(a===0||D!==1))return-1;for(V[1]=0,F=1;F<15;F++)V[F+1]=V[F]+O[F];for(N=0;N<c;N++)r[l+N]!==0&&(d[V[r[l+N]]++]=N);if(w=a===0?(P=rt=d,19):a===1?(P=i,tt-=257,rt=s,gt-=257,256):(P=n,rt=o,-1),F=Q,y=g,Y=N=L=0,C=-1,m=(j=1<<(x=K))-1,a===1&&852<j||a===2&&592<j)return 1;for(;;){for(E=F-Y,S=d[N]<w?(v=0,d[N]):d[N]>w?(v=rt[gt+d[N]],P[tt+d[N]]):(v=96,0),I=1<<F-Y,Q=f=1<<x;p[y+(L>>Y)+(f-=I)]=E<<24|v<<16|S|0,f!==0;);for(I=1<<F-1;L&I;)I>>=1;if(I!==0?(L&=I-1,L+=I):L=0,N++,--O[F]==0){if(F===D)break;F=r[l+d[N]]}if(K<F&&(L&m)!==C){for(Y===0&&(Y=K),y+=Q,q=1<<(x=F-Y);x+Y<D&&!((q-=O[x+Y])<=0);)x++,q<<=1;if(j+=1<<x,a===1&&852<j||a===2&&592<j)return 1;p[C=L&m]=K<<24|x<<16|y-g|0}}return L!==0&&(p[y+L]=F-Y<<24|64<<16|0),u.bits=K,0}},{"../utils/common":41}],51:[function(h,A,t){"use strict";A.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(h,A,t){"use strict";var e=h("../utils/common"),i=0,s=1;function n(k){for(var H=k.length;0<=--H;)k[H]=0}var o=0,a=29,r=256,l=r+1+a,c=30,p=19,g=2*l+1,d=15,u=16,I=7,f=256,C=16,m=17,y=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],E=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],v=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],M=new Array(2*(l+2));n(M);var F=new Array(2*c);n(F);var N=new Array(512);n(N);var Q=new Array(256);n(Q);var D=new Array(a);n(D);var K,x,Y,q=new Array(c);function j(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 P(k){return k<256?N[k]:N[256+(k>>>7)]}function tt(k,H){k.pending_buf[k.pending++]=255&H,k.pending_buf[k.pending++]=H>>>8&255}function O(k,H,z){k.bi_valid>u-z?(k.bi_buf|=H<<k.bi_valid&65535,tt(k,k.bi_buf),k.bi_buf=H>>u-k.bi_valid,k.bi_valid+=z-u):(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,Z=new Array(d+1),et=0;for(W=1;W<=d;W++)Z[W]=et=et+z[W-1]<<1;for(R=0;R<=H;R++){var _=k[2*R+1];_!==0&&(k[2*R]=rt(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<p;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,Z=2*z;return k[R]<k[Z]||k[R]===k[Z]&&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,Z,et,_=0;if(k.last_lit!==0)for(;W=k.pending_buf[k.d_buf+2*_]<<8|k.pending_buf[k.d_buf+2*_+1],R=k.pending_buf[k.l_buf+_],_++,W===0?V(k,R,H):(V(k,(Z=Q[R])+r+1,H),(et=w[Z])!==0&&O(k,R-=D[Z],et),V(k,Z=P(--W),z),(et=E[Z])!==0&&O(k,W-=q[Z],et)),_<k.last_lit;);V(k,f,H)}function Ct(k,H){var z,W,R,Z=H.dyn_tree,et=H.stat_desc.static_tree,_=H.stat_desc.has_stree,it=H.stat_desc.elems,ft=-1;for(k.heap_len=0,k.heap_max=g,z=0;z<it;z++)Z[2*z]!==0?(k.heap[++k.heap_len]=ft=z,k.depth[z]=0):Z[2*z+1]=0;for(;k.heap_len<2;)Z[2*(R=k.heap[++k.heap_len]=ft<2?++ft:0)]=1,k.depth[R]=0,k.opt_len--,_&&(k.static_len-=et[2*R+1]);for(H.max_code=ft,z=k.heap_len>>1;1<=z;z--)ot(k,Z,z);for(R=it;z=k.heap[1],k.heap[1]=k.heap[k.heap_len--],ot(k,Z,1),W=k.heap[1],k.heap[--k.heap_max]=z,k.heap[--k.heap_max]=W,Z[2*R]=Z[2*z]+Z[2*W],k.depth[R]=(k.depth[z]>=k.depth[W]?k.depth[z]:k.depth[W])+1,Z[2*z+1]=Z[2*W+1]=R,k.heap[1]=R++,ot(k,Z,1),2<=k.heap_len;);k.heap[--k.heap_max]=k.heap[1],function(ht,Pt){var _e,Kt,je,yt,ki,Rs,Wt=Pt.dyn_tree,Gn=Pt.max_code,la=Pt.stat_desc.static_tree,ca=Pt.stat_desc.has_stree,da=Pt.stat_desc.extra_bits,Ln=Pt.stat_desc.extra_base,ti=Pt.stat_desc.max_length,Si=0;for(yt=0;yt<=d;yt++)ht.bl_count[yt]=0;for(Wt[2*ht.heap[ht.heap_max]+1]=0,_e=ht.heap_max+1;_e<g;_e++)ti<(yt=Wt[2*Wt[2*(Kt=ht.heap[_e])+1]+1]+1)&&(yt=ti,Si++),Wt[2*Kt+1]=yt,Gn<Kt||(ht.bl_count[yt]++,ki=0,Ln<=Kt&&(ki=da[Kt-Ln]),Rs=Wt[2*Kt],ht.opt_len+=Rs*(yt+ki),ca&&(ht.static_len+=Rs*(la[2*Kt+1]+ki)));if(Si!==0){do{for(yt=ti-1;ht.bl_count[yt]===0;)yt--;ht.bl_count[yt]--,ht.bl_count[yt+1]+=2,ht.bl_count[ti]--,Si-=2}while(0<Si);for(yt=ti;yt!==0;yt--)for(Kt=ht.bl_count[yt];Kt!==0;)Gn<(je=ht.heap[--_e])||(Wt[2*je+1]!==yt&&(ht.opt_len+=(yt-Wt[2*je+1])*Wt[2*je],Wt[2*je+1]=yt),Kt--)}}(k,H),gt(Z,ft,k.bl_count)}function B(k,H,z){var W,R,Z=-1,et=H[1],_=0,it=7,ft=4;for(et===0&&(it=138,ft=3),H[2*(z+1)+1]=65535,W=0;W<=z;W++)R=et,et=H[2*(W+1)+1],++_<it&&R===et||(_<ft?k.bl_tree[2*R]+=_:R!==0?(R!==Z&&k.bl_tree[2*R]++,k.bl_tree[2*C]++):_<=10?k.bl_tree[2*m]++:k.bl_tree[2*y]++,Z=R,ft=(_=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4))}function J(k,H,z){var W,R,Z=-1,et=H[1],_=0,it=7,ft=4;for(et===0&&(it=138,ft=3),W=0;W<=z;W++)if(R=et,et=H[2*(W+1)+1],!(++_<it&&R===et)){if(_<ft)for(;V(k,R,k.bl_tree),--_!=0;);else R!==0?(R!==Z&&(V(k,R,k.bl_tree),_--),V(k,C,k.bl_tree),O(k,_-3,2)):_<=10?(V(k,m,k.bl_tree),O(k,_-3,3)):(V(k,y,k.bl_tree),O(k,_-11,7));Z=R,ft=(_=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,Z,et,_){At(R),_&&(tt(R,et),tt(R,~et)),e.arraySet(R.pending_buf,R.window,Z,et,R.pending),R.pending+=et}(k,H,z,!0)}t._tr_init=function(k){G||(function(){var H,z,W,R,Z,et=new Array(d+1);for(R=W=0;R<a-1;R++)for(D[R]=W,H=0;H<1<<w[R];H++)Q[W++]=R;for(Q[W-1]=R,R=Z=0;R<16;R++)for(q[R]=Z,H=0;H<1<<E[R];H++)N[Z++]=R;for(Z>>=7;R<c;R++)for(q[R]=Z<<7,H=0;H<1<<E[R]-7;H++)N[256+Z++]=R;for(z=0;z<=d;z++)et[z]=0;for(H=0;H<=143;)M[2*H+1]=8,H++,et[8]++;for(;H<=255;)M[2*H+1]=9,H++,et[9]++;for(;H<=279;)M[2*H+1]=7,H++,et[7]++;for(;H<=287;)M[2*H+1]=8,H++,et[8]++;for(gt(M,l+1,et),H=0;H<c;H++)F[2*H+1]=5,F[2*H]=rt(H,5);K=new j(M,w,r+1,l,d),x=new j(F,E,0,c,d),Y=new j(new Array(0),v,0,p,I)}(),G=!0),k.l_desc=new L(k.dyn_ltree,K),k.d_desc=new L(k.dyn_dtree,x),k.bl_desc=new L(k.bl_tree,Y),k.bi_buf=0,k.bi_valid=0,nt(k)},t._tr_stored_block=b,t._tr_flush_block=function(k,H,z,W){var R,Z,et=0;0<k.level?(k.strm.data_type===2&&(k.strm.data_type=function(_){var it,ft=4093624447;for(it=0;it<=31;it++,ft>>>=1)if(1&ft&&_.dyn_ltree[2*it]!==0)return i;if(_.dyn_ltree[18]!==0||_.dyn_ltree[20]!==0||_.dyn_ltree[26]!==0)return s;for(it=32;it<r;it++)if(_.dyn_ltree[2*it]!==0)return s;return i}(k)),Ct(k,k.l_desc),Ct(k,k.d_desc),et=function(_){var it;for(B(_,_.dyn_ltree,_.l_desc.max_code),B(_,_.dyn_dtree,_.d_desc.max_code),Ct(_,_.bl_desc),it=p-1;3<=it&&_.bl_tree[2*S[it]+1]===0;it--);return _.opt_len+=3*(it+1)+5+5+4,it}(k),R=k.opt_len+3+7>>>3,(Z=k.static_len+3+7>>>3)<=R&&(R=Z)):R=Z=z+5,z+4<=R&&H!==-1?b(k,H,z,W):k.strategy===4||Z===R?(O(k,2+(W?1:0),3),Qt(k,M,F)):(O(k,4+(W?1:0),3),function(_,it,ft,ht){var Pt;for(O(_,it-257,5),O(_,ft-1,5),O(_,ht-4,4),Pt=0;Pt<ht;Pt++)O(_,_.bl_tree[2*S[Pt]+1],3);J(_,_.dyn_ltree,it-1),J(_,_.dyn_dtree,ft-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*P(H)]++),k.last_lit===k.lit_bufsize-1},t._tr_align=function(k){O(k,2,3),V(k,f,M),function(H){H.bi_valid===16?(tt(H,H.bi_buf),H.bi_buf=0,H.bi_valid=0):8<=H.bi_valid&&(H.pending_buf[H.pending++]=255&H.bi_buf,H.bi_buf>>=8,H.bi_valid-=8)}(k)}},{"../utils/common":41}],53:[function(h,A,t){"use strict";A.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(h,A,t){(function(e){(function(i,s){"use strict";if(!i.setImmediate){var n,o,a,r,l=1,c={},p=!1,g=i.document,d=Object.getPrototypeOf&&Object.getPrototypeOf(i);d=d&&d.setTimeout?d:i,n={}.toString.call(i.process)==="[object process]"?function(C){process.nextTick(function(){I(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){I(C.data)},function(C){a.port2.postMessage(C)}):g&&"onreadystatechange"in g.createElement("script")?(o=g.documentElement,function(C){var m=g.createElement("script");m.onreadystatechange=function(){I(C),m.onreadystatechange=null,o.removeChild(m),m=null},o.appendChild(m)}):function(C){setTimeout(I,0,C)},d.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var m=new Array(arguments.length-1),y=0;y<m.length;y++)m[y]=arguments[y+1];var w={callback:C,args:m};return c[l]=w,n(l),l++},d.clearImmediate=u}function u(C){delete c[C]}function I(C){if(p)setTimeout(I,0,C);else{var m=c[C];if(m){p=!0;try{(function(y){var w=y.callback,E=y.args;switch(E.length){case 0:w();break;case 1:w(E[0]);break;case 2:w(E[0],E[1]);break;case 3:w(E[0],E[1],E[2]);break;default:w.apply(s,E)}})(m)}finally{u(C),p=!1}}}}function f(C){C.source===i&&typeof C.data=="string"&&C.data.indexOf(r)===0&&I(+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 Ur={};bi(Ur,{default:()=>Us});module.exports=Ca(Ur);var $=require("obsidian");Et();var bt=require("obsidian");var Bt=require("obsidian");Et();function xi(h){let A=(h.dateDisplayTimezone||"").trim();return A?{timeZone:A}:{}}function $t(h,A){try{return new Intl.DateTimeFormat(void 0,A).format(new Date(h))}catch{let{timeZone:t,...e}=A;return new Intl.DateTimeFormat(void 0,e).format(new Date(h))}}function Xt(h,A){let t=xi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Vn(h,A,!0);case"us":return $t(h,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return $t(h,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return $t(h,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return $t(h,{...t,dateStyle:"medium",timeStyle:"short"})}}function Yn(h,A){let t=xi(A);switch(A.dateDisplayFormat??"locale"){case"iso":return Vn(h,A,!1);case"us":return $t(h,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return $t(h,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return $t(h,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(h).getFullYear()===e.getFullYear();return $t(h,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function zn(h,A){let t=xi(A),e=A.dateDisplayFormat==="iso"||A.dateDisplayFormat==="eu";return $t(h,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function Vn(h,A,t){let e=xi(A),i=new Intl.DateTimeFormat("en-CA",{...e,year:"numeric",month:"2-digit",day:"2-digit",...t?{hour:"2-digit",minute:"2-digit",hourCycle:"h23"}:{}}).formatToParts(new Date(h)),s=o=>i.find(a=>a.type===o)?.value??"",n=`${s("year")}-${s("month")}-${s("day")}`;return t?`${n} ${s("hour")}:${s("minute")}`:n}function ve(h,A,t){let e=h.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(A>99?"99+":String(A))}var gi={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},Ui=class extends Bt.ItemView{constructor(t,e){super(t);this.plugin=e;this.activePanel="pinned";this.taskFilter="all";this.taskAssignFilter="all";this.taskFolderFilter="all";this.expanded=new Set;this.renderTimer=null;this.sharedAuthorFilter="all";this.sharedContribOnly=!1}setActivePanel(t){this.activePanel=t,this.containerEl.isConnected&&this.render()}getViewType(){return ne}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(gi)){let p=gi[c],g=r.createEl("button",{cls:"stashpad-panels-bar-btn"});(0,Bt.setIcon)(g.createSpan({cls:"stashpad-panels-bar-btn-icon"}),p.icon),g.createSpan({cls:"stashpad-panels-bar-btn-text",text:p.label}),this.activePanel===c&&g.addClass("is-active"),g.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=g=>{g.stopPropagation(),this.openPinnedOptionsMenu(g)};let a=this.plugin.listPinnedNotes();if(a.length===0){e.createDiv({cls:"stashpad-pinned-empty"}).setText("No pinned notes yet \u2014 right-click a note and choose \u201CPin to sidebar.\u201D");return}if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")!=="folder"){a.forEach((g,d)=>this.renderPinnedRow(e,g,d));return}let l=new Map;a.forEach((g,d)=>{let u=l.get(g.folder);u||(u=[],l.set(g.folder,u)),u.push({pin:g,idx:d})});let c=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,p=Array.from(l.keys());c&&l.has(c)&&(p.splice(p.indexOf(c),1),p.unshift(c));for(let g of p){let d=g.split("/").pop()||g,u=e.createDiv({cls:"stashpad-pinned-group-header"});g===c&&u.addClass("is-active-folder"),u.createSpan({cls:"stashpad-pinned-group-name",text:d});let I=l.get(g)??[];for(let{pin:f,idx:C}of I)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,p=this.expanded.has(`${e.folder}|${e.id}`),g=t.createDiv({cls:"stashpad-pinned-row"});a&&g.addClass("has-color"),r&&g.addClass("is-completed"),g.draggable=!0,g.dataset.pinIdx=String(i),g.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(i)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),g.addClass("is-dragging")}),g.addEventListener("dragend",()=>g.removeClass("is-dragging")),g.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=g.getBoundingClientRect(),y=C.clientY-m.top<m.height/2;g.toggleClass("drop-before",y),g.toggleClass("drop-after",!y)}),g.addEventListener("dragleave",()=>{g.removeClass("drop-before"),g.removeClass("drop-after")}),g.addEventListener("drop",C=>{C.preventDefault(),g.removeClass("drop-before"),g.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===i)return;let y=g.getBoundingClientRect(),w=C.clientY-y.top<y.height/2;this.reorderPin(m,w?i:i+1)});let d=g.createSpan({cls:"stashpad-pinned-toggle"});c&&(ve(d,l,p),d.onclick=C=>{C.stopPropagation();let m=`${e.folder}|${e.id}`;this.expanded.has(m)?this.expanded.delete(m):this.expanded.add(m),this.render()});let u=g.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let I=g.createSpan({cls:"stashpad-pinned-label",text:o});I.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(g.createSpan({cls:"stashpad-pinned-folder",text:f}),g.oncontextmenu=C=>{C.preventDefault();let m=new Bt.Menu;m.addItem(y=>y.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),m.showAtMouseEvent(C)},c&&p){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,p)=>p!==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,p=this.childrenOf(e,r).length,g=p>0,d=this.expanded.has(`${e}|${r}`),u=t.createDiv({cls:"stashpad-pinned-subrow"});c&&u.addClass("is-completed"),u.style.paddingLeft=`${s*16}px`;let I=u.createSpan({cls:"stashpad-pinned-toggle"});g&&(ve(I,p,d),I.onclick=m=>{m.stopPropagation();let y=`${e}|${r}`;this.expanded.has(y)?this.expanded.delete(y):this.expanded.add(y),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(f,"file-text"),l&&(f.style.color=l);let C=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});C.onclick=()=>this.openPinFromPanel({folder:e,id:r}),g&&d&&this.renderPinnedSubtree(t,e,r,s+1)}}findFileFor(t){for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==t.folder)continue;if(this.app.metadataCache.getFileCache(e)?.frontmatter?.id===t.id)return e}return null}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===T&&(a==null||a===T)){if(o.id===T)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.created??"",l=a?.created??"";return r.localeCompare(l)}),i}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new Bt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Ht(),hi));new s(this.app,i,e).open()}openNotificationsFromPanel(){this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")}async openHomeFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.navigateTo=="function"&&t.navigateTo(T)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===ct)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(ct);return i.length>0?(this.app.workspace.revealLeaf(i[0]),i[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===ct?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let c of s){let p=c.authorId;p&&!n.has(p)&&n.set(p,c.authorDisplay||p)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(c,p,g)=>{let d=o.createEl("button",{cls:"stashpad-shared-chip",text:c});return p&&d.addClass("is-active"),d.onclick=g,d};if(a("All",this.sharedAuthorFilter==="all",()=>{this.sharedAuthorFilter="all",this.render()}),a("Mine",this.sharedAuthorFilter==="mine",()=>{this.sharedAuthorFilter="mine",this.render()}),a("Others",this.sharedAuthorFilter==="others",()=>{this.sharedAuthorFilter="others",this.render()}),n.size>1){let c=o.createEl("select",{cls:"stashpad-shared-author-select"}),p=c.createEl("option",{text:"Any author"});p.value="__any__";for(let[d,u]of n){let I=c.createEl("option",{text:u});I.value=d}let g=["all","mine","others"].includes(this.sharedAuthorFilter)?"__any__":this.sharedAuthorFilter;c.value=g,c.onchange=()=>{let d=c.value;d==="__any__"?this.sharedAuthorFilter="all":this.sharedAuthorFilter=d,this.render()}}let r=o.createEl("button",{cls:"stashpad-shared-chip",text:"Has contributors"});this.sharedContribOnly&&r.addClass("is-active"),r.onclick=()=>{this.sharedContribOnly=!this.sharedContribOnly,this.render()};let l=s.filter(c=>{if(this.sharedContribOnly&&c.contributorCount===0)return!1;switch(this.sharedAuthorFilter){case"all":return!0;case"mine":return c.authorId===i;case"others":return c.authorId!==i;default:return c.authorId===this.sharedAuthorFilter}});if(l.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let c of l){let p=e.createDiv({cls:"stashpad-pinned-row stashpad-shared-row"}),g=p.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(g,"users"),c.color&&(g.style.color=c.color);let d=p.createSpan({cls:"stashpad-pinned-label",text:c.title});d.onclick=()=>this.openSharedFromPanel(c.folder,c.id);let u=c.folder.split("/").pop()||c.folder;p.createSpan({cls:"stashpad-pinned-folder",text:u}),c.authorDisplay&&p.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===i?`you \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:`by ${c.authorDisplay}${c.contributorCount>0?` \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),i=new Set(e),s=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};r.id===T&&s.set(a,this.extractAuthorId(r.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a)||a.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof r.id!="string"||r.id===T)continue;let l=this.extractAuthorId(r.author),c=Array.isArray(r.contributors)?r.contributors.filter(m=>typeof m=="string"):[],p=s.get(a)??null;if(!(c.length>0||p===t&&(l!==null&&l!==t)))continue;let f=this.titleFromFile(o),C=typeof r.color=="string"?r.color:null;n.push({file:o,folder:a,id:r.id,title:f,color:C,authorId:l,authorDisplay:this.extractAuthorDisplay(r.author)||(l??""),contributorCount:c.length})}return n.sort((o,a)=>{let r=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},l=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},c=r.modified??r.created??"";return(l.modified??l.created??"").localeCompare(c)}),n}extractAuthorId(t){if(typeof t!="string")return null;let e=t.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return e?e[1]:null}extractAuthorDisplay(t){if(typeof t!="string")return"";let e=t.match(/\|([^\]]+)\]\]/);if(e)return e[1].trim();let i=t.match(/_authors\/([^\]|]+)-[a-z0-9]{4,12}/i);return i?i[1].replace(/[-_]/g," ").trim():""}async openSharedFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}renderTasksPanel(t){let e=t.createDiv({cls:"stashpad-panel-tasks"}),i=this.collectTasks();if(i.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks yet \u2014 press H on a note to mark it a task, or D to give it a due date.");return}let s=(this.plugin.settings.authorId??"").trim(),n=x=>!!s&&x.assignedTo.some(Y=>Y.id===s),o=x=>{let Y=this.taskAssignFilter;if(Y.startsWith("person:")){let q=Y.slice(7);return x.assignedTo.some(j=>j.id===q)}switch(Y){case"mine":return n(x);case"others":return x.assignedTo.length>0&&!n(x);case"byme":return!!s&&x.assignedBy?.id===s;case"unassigned":return x.assignedTo.length===0;default:return!0}},a=new Map;for(let x of i){for(let Y of x.assignedTo)Y.id!==s&&a.set(Y.id,Y.name);x.assignedBy&&x.assignedBy.id!==s&&a.set(x.assignedBy.id,x.assignedBy.name)}let r=[...a.entries()].map(([x,Y])=>({id:x,name:Y})).sort((x,Y)=>x.name.localeCompare(Y.name)),l=e.createDiv({cls:"stashpad-task-assign-bar"});l.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let c=l.createEl("select",{cls:"stashpad-task-assign-select"}),p=x=>{let Y={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return x.startsWith("person:")?a.get(x.slice(7))??"Person":Y[x]??x},g=x=>{let Y=c.createEl("option",{text:p(x),value:x});this.taskAssignFilter===x&&(Y.selected=!0)};for(let x of["all","mine","others","byme","unassigned"])g(x);if(r.length>0){let x=c.createEl("optgroup");x.setAttr("label","By person");for(let Y of r){let q=x.createEl("option",{text:Y.name,value:`person:${Y.id}`});this.taskAssignFilter===`person:${Y.id}`&&(q.selected=!0)}}c.onchange=()=>{this.taskAssignFilter=c.value,this.render()};let d=[...new Set(i.map(x=>x.folder))].sort((x,Y)=>x.localeCompare(Y));this.taskFolderFilter!=="all"&&!d.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let u=e.createDiv({cls:"stashpad-task-assign-bar"});u.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let I=u.createEl("select",{cls:"stashpad-task-assign-select"}),f=I.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let x of d){let Y=I.createEl("option",{text:x.split("/").pop()||x,value:x});this.taskFolderFilter===x&&(Y.selected=!0)}I.onchange=()=>{this.taskFolderFilter=I.value,this.render()};let C=x=>this.taskFolderFilter==="all"||x.folder===this.taskFolderFilter,m=i.filter(x=>o(x)&&C(x));if(m.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let y=new Date;y.setHours(0,0,0,0);let w=y.getTime(),E=w+24*60*60*1e3,v={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let x of m){if(x.completed){v.completed.push(x);continue}if(x.due==null){v.nodate.push(x);continue}x.due<w?v.overdue.push(x):x.due<E?v.today.push(x):v.upcoming.push(x)}let S=(x,Y)=>x.due==null&&Y.due==null?x.title.localeCompare(Y.title):x.due==null?1:Y.due==null?-1:x.due-Y.due,M=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],F=e.createDiv({cls:"stashpad-task-filters"}),N=m.length,Q=(x,Y,q)=>{let j=F.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===x&&j.addClass("is-active"),j.createSpan({cls:"stashpad-task-filter-label",text:Y}),j.createSpan({cls:"stashpad-task-filter-count",text:String(q)}),j.onclick=()=>{this.taskFilter=x,this.render()}};Q("all","All",N),Q("overdue","Overdue",v.overdue.length),Q("today","Today",v.today.length),Q("upcoming","Upcoming",v.upcoming.length),Q("nodate","No date",v.nodate.length),Q("completed","Done",v.completed.length);let D=this.taskFilter==="all"?M:M.filter(x=>x.key===this.taskFilter),K=!1;for(let x of D){let Y=v[x.key];if(Y.length!==0){if(K=!0,Y.sort(x.key==="completed"?(q,j)=>S(j,q):S),this.taskFilter==="all"){let q=e.createDiv({cls:`stashpad-task-section-header is-${x.key}`});(0,Bt.setIcon)(q.createSpan({cls:"stashpad-task-section-icon"}),x.icon),q.createSpan({cls:"stashpad-task-section-name",text:x.label}),q.createSpan({cls:"stashpad-task-section-count",text:String(Y.length)})}for(let q of Y)this.renderTaskRow(e,q,x.key==="today")}}if(!K&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${D[0]?.label??this.taskFilter}".`);return}K||e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks to show.")}renderTaskRow(t,e,i){let s=t.createDiv({cls:"stashpad-pinned-row stashpad-task-row"});e.color&&s.addClass("has-color"),e.completed&&s.addClass("is-completed");let n=s.createSpan({cls:"stashpad-pinned-icon stashpad-task-checkbox"});(0,Bt.setIcon)(n,e.completed?"check-square":"square"),e.color&&(n.style.color=e.color),n.title=e.completed?"Mark not done":"Mark done",n.onclick=a=>{a.stopPropagation(),this.toggleTaskCompleted(e)};let o=s.createSpan({cls:"stashpad-pinned-label",text:e.title});if(o.onclick=()=>this.openTaskFromPanel(e.folder,e.id),s.createSpan({cls:"stashpad-task-folder",text:e.folder.split("/").pop()||e.folder}),e.due!=null){let a=s.createSpan({cls:"stashpad-task-due",text:this.formatDueShort(e.due,i)});e.due<Date.now()&&!e.completed&&a.addClass("is-overdue")}else e.dueRaw&&s.createSpan({cls:"stashpad-task-due",text:e.dueRaw});if(e.assignedTo.length>0){let a=(this.plugin.settings.authorId??"").trim(),r=s.createSpan({cls:"stashpad-task-assignees"});for(let l of e.assignedTo){let c=r.createSpan({cls:"stashpad-task-assignee"});a&&l.id===a&&c.addClass("is-me"),c.setText(this.initials(l.name)),c.title=a&&l.id===a?`${l.name} (you)`:l.name}}s.oncontextmenu=a=>{a.preventDefault();let r=new Bt.Menu;r.addItem(l=>l.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),r.showAtMouseEvent(a)}}formatDueShort(t,e){return e?zn(t,this.plugin.settings):Yn(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new Bt.Notice(`Couldn't update task: ${e.message}`);return}this.scheduleRender()}initials(t){let e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}collectTasks(){let t=this.plugin.discoverStashpadFolders(),e=new Set(t),i=[];for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a||a===T)continue;let r=o.completed===!0,l=Me(o,"task")||o.task===!0||o.completed!==void 0,c=typeof o.due=="string"||typeof o.due=="number"?String(o.due):null,p=null;if(c){let g=Date.parse(c);Number.isNaN(g)||(p=g)}!l&&!r&&p==null&&!c||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:l,completed:r,due:p,dueRaw:c,color:typeof o.color=="string"?o.color:null,assignedTo:Qe(o),assignedBy:ae(o.assignedBy)})}return i}};async function Ri(h){let A=h.workspace.getLeavesOfType(ne);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new Bt.Notice("Stashpad: couldn't open the panels view.");return}await t.setViewState({type:ne,active:!0}),h.workspace.revealLeaf(t)}var Oo=require("obsidian");Et();var X=require("obsidian");ui();var qi=require("obsidian");Et();var Ge=class extends qi.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!=="/"&&ei.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof qi.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();Ht();var ke=require("obsidian"),Zs={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."}},Sa={info:4e3,success:4e3,warning:6e3,error:1e4},so=5e3,Oi=class{constructor(A){this.app=A;this.history=[];this.nextId=1;this.historyLimit=so;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??Sa[t];return new ke.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:so,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 Ki(h,A,t){let e=h.vault.getAbstractFileByPath(A);if(!(e instanceof ke.TFile))return[];let i=[{label:"Reveal",keepOpen:!0,onClick:()=>{let s=h.workspace.getLeavesOfType("file-explorer")[0];if(!s)return;h.workspace.revealLeaf(s),s.view?.revealInFolder?.(e)}}];if(!t){let s=ke.Platform.isMacOS?"Finder":ke.Platform.isWin?"File Explorer":"file manager";i.push({label:`Show in ${s}`,keepOpen:!0,onClick:()=>{try{let n=window.require?.("electron")?.shell,a=h.vault.adapter?.getFullPath?.(A);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var _s=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function Ii(h){if(!h)return"(none)";let A=h.replace(/\bMod\b/g,_s?"Cmd":"Ctrl");return _s&&(A=A.replace(/\bAlt\b/g,"Option")),A}function no(h,A,t={allowSingleKey:!0}){let e=h.placeholder,i=h.value;h.placeholder="Press a key\u2026 (Backspace to cancel)",h.value="",h.classList.add("is-recording");let s=!1,n=()=>{h.placeholder=e,h.classList.remove("is-recording"),s||(h.value=i),h.removeEventListener("keydown",o,!0),h.removeEventListener("blur",a)},o=r=>{if(r.key==="Control"||r.key==="Shift"||r.key==="Alt"||r.key==="Meta"||r.key==="OS")return;let l=!!r.code&&(/^Key[A-Z]$/.test(r.code)||/^Digit\d$/.test(r.code));if((r.key==="Dead"||r.key==="Process"||r.key==="Unidentified")&&!l)return;if(r.preventDefault(),r.stopPropagation(),r.key==="Backspace"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.shiftKey){n();return}let c=[];_s?(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 p=Da(r.key,r.code);if(!p||c.length===0&&!t.allowSingleKey)return;c.push(p);let g=c.join("+");s=!0,n(),A(g)},a=()=>n();return h.addEventListener("keydown",o,!0),h.addEventListener("blur",a),n}function Da(h,A){if(!h)return"";if(A){let t=/^Key([A-Z])$/.exec(A);if(t)return t[1];let e=/^Digit(\d)$/.exec(A);if(e)return e[1]}return h.length===1?h.toUpperCase():h}Ue();Gt();function Se(h,A,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(l){try{r(e.next(l))}catch(c){n(c)}}function a(l){try{r(e.throw(l))}catch(c){n(c)}}function r(l){l.done?s(l.value):i(l.value).then(o,a)}r((e=e.apply(h,A||[])).next())})}var mt=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 Se(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(A())}finally{t()}})}},js;function ba(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var nn=ba(),tn=(js=nn.Buffer)!==null&&js!==void 0?js:null,Na=nn.TextEncoder?new nn.TextEncoder:null;function co(h,A){return(h&15)+(h>>6|h>>3&8)<<4|(A&15)+(A>>6|A>>3&8)}function ho(h,A){let t=A.length>>1;for(let e=0;e<t;e++){let i=e<<1;h[e]=co(A.charCodeAt(i),A.charCodeAt(i+1))}}function xa(h,A){if(h.length!==A.length*2)return!1;for(let t=0;t<A.length;t++){let e=t<<1;if(A[t]!==co(h.charCodeAt(e),h.charCodeAt(e+1)))return!1}return!0}var oo=87,ao=48;function on(h,A,t){let e=0;for(let i=0;i<t;i++){let s=A[i]>>>4;h[e++]=s>9?s+oo:s+ao,s=A[i]&15,h[e++]=s>9?s+oo:s+ao}return String.fromCharCode.apply(null,h)}var _t=tn!==null?h=>{if(typeof h=="string"){let A=tn.from(h,"utf8");return new Uint8Array(A.buffer,A.byteOffset,A.length)}if(tn.isBuffer(h))return new Uint8Array(h.buffer,h.byteOffset,h.length);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")}:h=>{if(typeof h=="string")return Na.encode(h);if(ArrayBuffer.isView(h))return new Uint8Array(h.buffer,h.byteOffset,h.byteLength);throw new Error("Invalid data type!")},Lt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ci=new Uint8Array(256);for(let h=0;h<Lt.length;h++)Ci[Lt.charCodeAt(h)]=h;function ro(h,A=!0){let t=h.length,e=t%3,i=[],s=t-e;for(let n=0;n<s;n+=3){let o=(h[n]<<16&16711680)+(h[n+1]<<8&65280)+(h[n+2]&255),a=Lt.charAt(o>>18&63)+Lt.charAt(o>>12&63)+Lt.charAt(o>>6&63)+Lt.charAt(o&63);i.push(a)}if(e===1){let n=h[t-1],o=Lt.charAt(n>>2),a=Lt.charAt(n<<4&63);i.push(`${o}${a}`),A&&i.push("==")}else if(e===2){let n=(h[t-2]<<8)+h[t-1],o=Lt.charAt(n>>10),a=Lt.charAt(n>>4&63),r=Lt.charAt(n<<2&63);i.push(`${o}${a}${r}`),A&&i.push("=")}return i.join("")}function Ma(h){let A=Math.floor(h.length*.75),t=h.length;return h[t-1]==="="&&(A-=1,h[t-2]==="="&&(A-=1)),A}function Ta(h){let A=Ma(h),t=h.length,e=new Uint8Array(A),i=0;for(let s=0;s<t;s+=4){let n=Ci[h.charCodeAt(s)],o=Ci[h.charCodeAt(s+1)],a=Ci[h.charCodeAt(s+2)],r=Ci[h.charCodeAt(s+3)];e[i]=n<<2|o>>4,i+=1,e[i]=(o&15)<<4|a>>2,i+=1,e[i]=(a&3)<<6|r&63,i+=1}return e}var Yi=16*1024,fi=4,Ha=new mt,en=new Map;function go(h,A){return Se(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=(E,v=0)=>{e.set(E,v)},n=()=>e,o=()=>t.exports,a=E=>{t.exports.Hash_SetMemorySize(E);let v=t.exports.Hash_GetBuffer(),S=t.exports.memory.buffer;e=new Uint8Array(S,v,E)},r=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),l=Ha.dispatch(()=>Se(this,void 0,void 0,function*(){if(!en.has(h.name)){let v=Ta(h.data),S=WebAssembly.compile(v);en.set(h.name,S)}let E=yield en.get(h.name);t=yield WebAssembly.instantiate(E,{})})),c=()=>Se(this,void 0,void 0,function*(){t||(yield l);let E=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,E,Yi)}),p=(E=null)=>{i=!0,t.exports.Hash_Init(E)},g=E=>{let v=0;for(;v<E.length;){let S=E.subarray(v,v+Yi);v+=S.length,e.set(S),t.exports.Hash_Update(S.length)}},d=E=>{if(!i)throw new Error("update() called before init()");let v=_t(E);g(v)},u=new Uint8Array(A*2),I=(E,v=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(v),E==="binary"?e.slice(0,A):on(u,e,A)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let E=t.exports.Hash_GetState(),v=r(),S=t.exports.memory.buffer,M=new Uint8Array(S,E,v),F=new Uint8Array(fi+v);return ho(F,h.hash),F.set(M,fi),F},C=E=>{if(!(E instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let v=t.exports.Hash_GetState(),S=r(),M=fi+S,F=t.exports.memory.buffer;if(E.length!==M)throw new Error(`Bad state length (expected ${M} bytes, got ${E.length})`);if(!xa(h.hash,E.subarray(0,fi)))throw new Error("This state was written by an incompatible hash implementation");let N=E.subarray(fi);new Uint8Array(F,v,S).set(N),i=!0},m=E=>typeof E=="string"?E.length<Yi/4:E.byteLength<Yi,y=m;switch(h.name){case"argon2":case"scrypt":y=()=>!0;break;case"blake2b":case"blake2s":y=(E,v)=>v<=512&&m(E);break;case"blake3":y=(E,v)=>v===0&&m(E);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":y=()=>!1;break}let w=(E,v=null,S=null)=>{if(!y(E,v))return p(v),d(E),I("hex",S);let M=_t(E);return e.set(M),t.exports.Hash_Calculate(M.length,v,S),on(u,e,A)};return yield c(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:p,update:d,digest:I,save:f,load:C,calculate:w,hashLength:A}})}var cA=new mt;var Pa="argon2",Ua="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",Ra="e4cdc523",Ga={name:Pa,data:Ua,hash:Ra},La="blake2b",Ja="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=",qa="c6f286e6",Oa={name:La,data:Ja,hash:qa},dA=new mt;function Ao(h){return!Number.isInteger(h)||h<8||h>512||h%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function Ka(h,A){return h|A<<16}function an(h=512,A=null){if(Ao(h))return Promise.reject(Ao(h));let t=null,e=h;if(A!==null){if(t=_t(A),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=Ka(h,t.length)}let i=h/8;return go(Oa,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 Ya(h,A,t){let e=[`m=${A.memorySize}`,`t=${A.iterations}`,`p=${A.parallelism}`].join(",");return`$argon2${A.hashType}$v=19$${e}$${ro(h,!1)}$${ro(t,!1)}`}var lo=new DataView(new ArrayBuffer(4));function Zt(h){return lo.setInt32(0,h,!0),new Uint8Array(lo.buffer)}function sn(h,A,t){return Se(this,void 0,void 0,function*(){if(t<=64){let a=yield an(t*8);return a.update(Zt(t)),a.update(A),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);h.init(),h.update(Zt(t)),h.update(A);let s=h.digest("binary");i.set(s.subarray(0,32),0);for(let a=1;a<e;a++)h.init(),h.update(s),s=h.digest("binary"),i.set(s.subarray(0,32),a*32);let n=t-32*e,o;return n===64?(o=h,o.init()):o=yield an(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function za(h){switch(h){case"d":return 0;case"i":return 1;default:return 2}}function Va(h){return Se(this,void 0,void 0,function*(){var A;let{parallelism:t,iterations:e,hashLength:i}=h,s=_t(h.password),n=_t(h.salt),o=19,a=za(h.hashType),{memorySize:r}=h,l=_t((A=h.secret)!==null&&A!==void 0?A:""),[c,p]=yield Promise.all([go(Ga,1024),an(512)]);c.setMemorySize(r*1024+1024);let g=new Uint8Array(24),d=new DataView(g.buffer);d.setInt32(0,t,!0),d.setInt32(4,i,!0),d.setInt32(8,r,!0),d.setInt32(12,e,!0),d.setInt32(16,o,!0),d.setInt32(20,a,!0),c.writeMemory(g,r*1024),p.init(),p.update(g),p.update(Zt(s.length)),p.update(s),p.update(Zt(n.length)),p.update(n),p.update(Zt(l.length)),p.update(l),p.update(Zt(0));let I=Math.floor(r/(t*4))*4,f=new Uint8Array(72),C=p.digest("binary");f.set(C);for(let w=0;w<t;w++){f.set(Zt(0),64),f.set(Zt(w),68);let E=w*I,v=yield sn(p,f,1024);c.writeMemory(v,E*1024),E+=1,f.set(Zt(1),64),v=yield sn(p,f,1024),c.writeMemory(v,E*1024)}let m=new Uint8Array(1024);ho(m,c.calculate(new Uint8Array([]),r));let y=yield sn(p,m,i);if(h.outputType==="hex"){let w=new Uint8Array(i*2);return on(w,y,i)}return h.outputType==="encoded"?Ya(n,h,y):y})}var Wa=h=>{var A;if(!h||typeof h!="object")throw new Error("Invalid options parameter. It requires an object.");if(!h.password)throw new Error("Password must be specified");if(h.password=_t(h.password),h.password.length<1)throw new Error("Password must be specified");if(!h.salt)throw new Error("Salt must be specified");if(h.salt=_t(h.salt),h.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(h.secret=_t((A=h.secret)!==null&&A!==void 0?A:""),!Number.isInteger(h.iterations)||h.iterations<1)throw new Error("Iterations should be a positive number");if(!Number.isInteger(h.parallelism)||h.parallelism<1)throw new Error("Parallelism should be a positive number");if(!Number.isInteger(h.hashLength)||h.hashLength<4)throw new Error("Hash length should be at least 4 bytes.");if(!Number.isInteger(h.memorySize))throw new Error("Memory size should be specified.");if(h.memorySize<8*h.parallelism)throw new Error("Memory size should be at least 8 * parallelism.");if(h.outputType===void 0&&(h.outputType="hex"),!["hex","binary","encoded"].includes(h.outputType))throw new Error(`Insupported output type ${h.outputType}. Valid values: ['hex', 'binary', 'encoded']`)};function rn(h){return Se(this,void 0,void 0,function*(){return Wa(h),Va(Object.assign(Object.assign({},h),{hashType:"id"}))})}var hA=new mt;var gA=new mt;var pA=new mt;var uA=new mt;var IA=new Uint8Array(8);var fA=new mt;var CA=new mt;var mA=new mt;var BA=new mt;var QA=new mt;var yA=new mt;var EA=new mt;var wA=new mt;var vA=new mt;var FA=new mt;var kA=new mt;var SA=new Uint8Array(8);var DA=new mt;var bA=new Uint8Array(8);var NA=new mt;var xA=new Uint8Array(8);var MA=new mt;var TA=new mt;var HA=new mt;Ht();var Jt=new Uint8Array([83,84,65,83,72,69,78,67]),cn=2,dn=1,hn=2,Io=3,$a=32,Le=12,An=32,Xa=6e5,Za=47104,_a=3,ja=1,wt=h=>h;function qt(h){if(h.length<Jt.length+1)return!1;for(let A=0;A<Jt.length;A++)if(h[A]!==Jt[A])return!1;return!0}function po(h,A,t){h[A]=t>>>24&255,h[A+1]=t>>>16&255,h[A+2]=t>>>8&255,h[A+3]=t&255}function uo(h,A){return h[A]*16777216+(h[A+1]<<16)+(h[A+2]<<8)+h[A+3]}async function ln(h,A,t){if(t.id===hn)return await rn({password:h,salt:A,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:An,outputType:"binary"});if(t.id===dn){let e=await crypto.subtle.importKey("raw",wt(new TextEncoder().encode(h)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:wt(A),iterations:t.a,hash:"SHA-256"},e,An*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function zi(h){return crypto.subtle.importKey("raw",wt(h),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var fo={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function Je(h,A){let t=crypto.getRandomValues(new Uint8Array($a)),e=crypto.getRandomValues(new Uint8Array(Le)),i,s,n;try{i={id:hn,a:Za,b:_a,c:ja},n=await ln(A,t,i),s="argon2id"}catch(c){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",c),i={id:dn,a:Xa,b:0,c:0},n=await ln(A,t,i),s="pbkdf2"}let o=Co(i,t,e),a=await zi(n),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(e),additionalData:wt(o)},a,wt(h))),l=new Uint8Array(o.length+r.length);return l.set(o,0),l.set(r,o.length),{data:l,kdf:s}}var mi=null;async function Vi(){if(mi!==null)return mi;try{await rn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),mi=!0}catch{mi=!1}return mi}function Co(h,A,t){let e=new Uint8Array(Jt.length+1+1+4+4+1+1+A.length+t.length),i=0;return e.set(Jt,i),i+=Jt.length,e[i++]=cn,e[i++]=h.id,po(e,i,h.a),i+=4,po(e,i,h.b),i+=4,e[i++]=h.c,e[i++]=A.length,e.set(A,i),i+=A.length,e.set(t,i),i+=t.length,e}async function jt(h,A){if(!qt(h))throw new Error("Not an encrypted Stashpad file.");let t=h[Jt.length];if(t===1)return tr(h,A);if(t!==cn)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=Jt.length+1,i={id:h[e++],a:0,b:0,c:0};if(i.a=uo(h,e),e+=4,i.b=uo(h,e),e+=4,i.c=h[e++],i.id===hn){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===dn&&i.a>1e7)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let s=h[e++];if(s<8||s>64)throw new Error("Unsupported KDF parameters (file may be corrupted or malicious).");let n=h.slice(e,e+s);e+=s;let o=h.slice(e,e+Le);e+=Le;let a=h.slice(0,e),r=h.slice(e),l=await ln(A,n,i),c=await zi(l),p=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(o),additionalData:wt(a)},c,wt(r));return new Uint8Array(p)}async function tr(h,A){let t=Jt.length+1,e=h.slice(t,t+16);t+=16;let i=h.slice(t,t+12);t+=12;let s=h.slice(t),n=await crypto.subtle.importKey("raw",wt(new TextEncoder().encode(A)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:wt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(i)},o,wt(s));return new Uint8Array(a)}async function Bi(h,A){if(A.length!==An)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Le)),i=Co({id:Io,a:0,b:0,c:0},new Uint8Array(0),t),s=await zi(A),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:wt(t),additionalData:wt(i)},s,wt(h))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function re(h,A){if(!qt(h))throw new Error("Not an encrypted Stashpad file.");let t=h[Jt.length];if(t!==cn)throw new Error(`Unsupported encrypted version (${t}).`);let e=Jt.length+1;if(h[e++]!==Io)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=h[e++];e+=s;let n=h.slice(e,e+Le);e+=Le;let o=h.slice(0,e),a=h.slice(e),r=await zi(A),l=await crypto.subtle.decrypt({name:"AES-GCM",iv:wt(n),additionalData:wt(o)},r,wt(a));return new Uint8Array(l)}async function qe(h,A,t={}){if(!qt(A))return A;if(t.secretId){let i=h.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await jt(A,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new ai(h,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await jt(A,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Gt();var Wi={name:"ECDH",namedCurve:"P-256"},er="stashpad-vault-dek-wrap",ir=new TextEncoder;function gn(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function pn(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}async function mo(){let h=await crypto.subtle.generateKey(Wi,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",h.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",h.privateKey))}}function Bo(h){return crypto.subtle.importKey("spki",h,Wi,!1,[])}function sr(h){return crypto.subtle.importKey("pkcs8",h,Wi,!1,["deriveBits"])}async function Qo(h,A){let t=await crypto.subtle.deriveBits({name:"ECDH",public:A},h,256),e=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:ir.encode(er)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function $i(h,A,t){let e=await crypto.subtle.generateKey(Wi,!0,["deriveBits"]),i=await Qo(e.privateKey,await Bo(A)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,h)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:gn(o),iv:gn(s),ct:gn(n)}}async function yo(h,A){let t=await Qo(await sr(A),await Bo(pn(h.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:pn(h.iv)},t,pn(h.ct)))}var Eo=".stashpad/keys.json",nr=".stashpad",Qi="_keys";function un(h){return{v:2,keyId:h,identities:[],slots:[],joinRequests:[]}}var Xi=class{constructor(A){this.app=A}get a(){return this.app.vault.adapter}validate(A){let t=A;return!!t&&t.v===2&&typeof t.keyId=="string"&&Array.isArray(t.identities)&&Array.isArray(t.slots)&&Array.isArray(t.joinRequests)}async readValid(A){try{if(!await this.a.exists(A))return null;let t=JSON.parse(await this.a.read(A));return this.validate(t)?t:null}catch{return null}}async load(){let A=await this.readValid(Eo);if(A)return A;try{let e=((await this.a.list(Qi)).files||[]).filter(i=>/\/keys-\d+\.json$/.test(i)).sort();for(let i of e.reverse()){let s=await this.readValid(i);if(s)return s}}catch{}return null}async exists(){return await this.load()!==null}async ensureDir(A){try{await this.a.exists(A)||await this.a.mkdir(A)}catch{}}async save(A){let t=JSON.stringify(A,null,2);await this.ensureDir(nr),await this.a.write(Eo,t),await this.ensureDir(Qi);for(let e=4;e>=1;e--){let i=`${Qi}/keys-${e}.json`,s=`${Qi}/keys-${e+1}.json`;try{await this.a.exists(i)&&await this.a.write(s,await this.a.read(i))}catch{}}try{await this.a.write(`${Qi}/keys-1.json`,t)}catch{}}};var Zi="stashpad-vault-encryption";function yi(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function _i(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function te(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}var or=32,ji=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;this.kf=null;this.keyfiles=new Xi(A)}argonProbe(){return Vi()}async init(){await this.refresh()}async refresh(){this.kf=await this.keyfiles.load()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}keychainId(){let A=this.app.appId||"default";return`${Zi}-${A}`}isRemembered(){try{return!!this.secretStore()?.getSecret(this.keychainId())}catch{return!1}}async remember(A){try{await this.secretStore()?.setSecret(this.keychainId(),A)}catch(t){console.warn("[Stashpad] couldn't save password to keychain",t)}}async forgetKeychain(){let A=this.secretStore();if(A)try{A.removeSecret?await A.removeSecret(this.keychainId()):await A.setSecret(this.keychainId(),"")}catch(t){console.warn("[Stashpad] couldn't clear keychain",t)}}async tryAutoUnlock(){if(!this.isConfigured()||this.isUnlocked())return this.isUnlocked();if(this.accessState()!=="member"&&!this.hasSharedPassword())return!1;let A=this.secretStore(),t=null;try{t=A?.getSecret(this.keychainId())??null}catch{t=null}if(t)return this.unlock(t);let e=null;try{e=A?.getSecret(Zi)??null}catch{e=null}if(!e)return!1;let i=await this.unlock(e);if(i){await this.remember(e);try{A?.removeSecret?await A.removeSecret(Zi):await A?.setSecret(Zi,"")}catch{}}return i}isConfigured(){return!!this.kf||!!this.load().wrappedKey}isUnlocked(){return this.sessionKey!==null}kdf(){return this.load().identityPrivKdf??this.load().kdf}hasIdentity(){return!!this.load().identityPrivWrapped&&!!this.load().identityId}mySlot(){let A=this.load().identityId;return A?this.kf?.slots.find(t=>t.recipientId===A)??null:null}accessState(){let A=this.load();return!this.kf&&A.wrappedKey?"member":this.kf?this.hasIdentity()&&this.mySlot()?"member":A.identityId&&this.kf.joinRequests.some(t=>t.id===A.identityId)?"pending":"outsider":"none"}amIMember(){return this.accessState()==="member"}async setup(A,t=!1,e){if(await this.refresh(),this.isConfigured())throw new Error("Encryption is already set up in this vault.");if(!A)throw new Error("Password required.");let i=crypto.getRandomValues(new Uint8Array(or)),s=await this.mintIdentity(A,e),n=un(pt(8));n.identities.push(this.identityRecord(s)),n.slots.push(await $i(i,te(s.pub),s.id)),await this.keyfiles.save(n),this.kf=n,this.sessionKey=i,t?await this.remember(A):await this.forgetKeychain(),this.armIdle()}async unlock(A,t=!1){await this.refresh();let e=this.load();if(!this.kf&&e.wrappedKey){let s;try{s=await jt(te(e.wrappedKey),A)}catch{return!1}let n=await this.mintIdentity(A,e.identityLabel??void 0),o=un(pt(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await $i(s,te(n.pub),n.id)),await this.keyfiles.save(o),this.kf=o,this.sessionKey=s,t&&await this.remember(A),this.armIdle(),!0}let i=this.hasIdentity()?this.mySlot():null;if(i)try{let s=await jt(te(e.identityPrivWrapped),A);try{let n=await yo(i,s);return s.fill(0),this.sessionKey=n,t&&await this.remember(A),this.armIdle(),!0}catch{s.fill(0)}}catch{}for(let s of this.kf?.passwordSlots??[])try{let n=await jt(te(s.wrapped),A);return this.sessionKey=n,t&&await this.remember(A),this.armIdle(),!0}catch{}return!1}hasSharedPassword(){return(this.kf?.passwordSlots?.length??0)>0}async setSharedPassword(A){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(!A)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let t=await Je(this.sessionKey,A);this.kf.passwordSlots=[{id:pt(8),label:"Shared password",wrapped:_i(t.data),kdf:t.kdf,createdAt:new Date().toISOString()}],await this.keyfiles.save(this.kf)}async removeSharedPassword(){await this.refresh(),!(!this.kf||!this.kf.passwordSlots?.length)&&(this.kf.passwordSlots=[],await this.keyfiles.save(this.kf))}async verifyPassword(A){let t=this.load();try{if(t.identityPrivWrapped)return(await jt(te(t.identityPrivWrapped),A)).fill(0),!0;if(t.wrappedKey)return(await jt(te(t.wrappedKey),A)).fill(0),!0}catch{}return!1}async changePassword(A,t,e=!1){let i=this.load();if(!t)throw new Error("New password required.");if(!i.identityPrivWrapped&&!await this.unlock(A,!1))return!1;let s=this.load(),n;try{n=await jt(te(s.identityPrivWrapped),A)}catch{return!1}let o=await Je(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:_i(o.data),identityPrivKdf:o.kdf}),e?await this.remember(t):await this.forgetKeychain(),this.armIdle(),!0}async requestAccess(A,t,e=!1){if(await this.refresh(),!this.kf)throw new Error("This vault has no encryption set up yet.");if(this.amIMember())return;if(!t)throw new Error("Password required.");let i=this.hasIdentity()?{id:this.load().identityId,label:this.load().identityLabel??A,pub:this.load().identityPub}:await this.mintIdentity(t,A);A&&i.label!==A&&(await this.save({...this.load(),identityLabel:A}),i.label=A);let s={id:i.id,label:i.label,pubKey:i.pub,requestedAt:new Date().toISOString()};this.kf.joinRequests=[...this.kf.joinRequests.filter(n=>n.id!==i.id),s],await this.keyfiles.save(this.kf),e?await this.remember(t):await this.forgetKeychain()}pendingJoinRequests(){return this.kf?.joinRequests??[]}members(){return this.kf?.identities??[]}myIdentityId(){return this.load().identityId}async approveJoinRequest(A,t){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(await this.refresh(),!this.kf)return!1;let e=this.kf.joinRequests.find(i=>i.id===A);return e?(this.kf.slots=[...this.kf.slots.filter(i=>i.recipientId!==e.id),await $i(this.sessionKey,te(e.pubKey),e.id)],this.kf.identities=[...this.kf.identities.filter(i=>i.id!==e.id),{id:e.id,label:t??e.label,pubKey:e.pubKey,addedAt:new Date().toISOString()}],this.kf.joinRequests=this.kf.joinRequests.filter(i=>i.id!==A),await this.keyfiles.save(this.kf),!0):!1}async removeMember(A){await this.refresh(),this.kf&&(this.kf.slots=this.kf.slots.filter(t=>t.recipientId!==A),this.kf.identities=this.kf.identities.filter(t=>t.id!==A),this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==A),await this.keyfiles.save(this.kf))}async denyJoinRequest(A){await this.refresh(),this.kf&&(this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==A),await this.keyfiles.save(this.kf))}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null,this.clearIdle()}async clear(){this.lock(),await this.forgetKeychain();try{let A=this.app.vault.adapter;for(let t of[".stashpad/keys.json"])try{await A.exists(t)&&await A.remove(t)}catch{}try{let t=await A.list("_keys");for(let e of t.files||[])if(/\/keys-\d+\.json$/.test(e))try{await A.remove(e)}catch{}}catch{}}catch{}this.kf=null,await this.save(yi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(A,t){let e=await mo(),i=await Je(e.privKeyPkcs8,A);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??pt(8),o=t??s.identityLabel??"This device",a=_i(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:a,identityPrivWrapped:_i(i.data),identityPrivKdf:i.kdf}),{id:n,label:o,pub:a}}identityRecord(A){return{id:A.id,label:A.label,pubKey:A.pub,addedAt:new Date().toISOString()}}armIdle(){this.clearIdle();let A=this.idleMinutes();A>0&&(this.idleTimer=window.setTimeout(()=>this.lock(),A*6e4))}clearIdle(){this.idleTimer!=null&&(window.clearTimeout(this.idleTimer),this.idleTimer=null)}dispose(){this.lock()}};var Cn=Gs(ts()),es=require("obsidian");Gt();Et();var Ae="stash",ko=1;function vo(h){let t=(h.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var fn=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function De(h,A){let t=new Cn.default,e=ar([...A.rootNotes,...A.allDescendants]),i=new Map,s=[];for(let o of e){let a=await h.vault.read(o.file),r=a,l=So(a);for(let c of l){let p=h.metadataCache.getFirstLinkpathDest(c,o.file.path);if(!p){s.push(`Missing attachment "${c}" in ${o.file.path}`);continue}let g=p.name;i.has(g)||i.set(g,await h.vault.readBinary(p)),r=rr(r,c,g)}r=cr(r,h,o.file.path),t.file(`notes/${o.file.name}`,r)}for(let[o,a]of i)t.file(`attachments/${o}`,a);let n={stashSchema:ko,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 Vt(h,A,t,e,i={}){let s=await Cn.default.loadAsync(A),n=s.file("manifest.json");if(!n)throw new Error("Not a valid .stash package: missing manifest.json");let o=JSON.parse(await n.async("string"));if(typeof o.stashSchema!="number"||o.stashSchema>ko)throw new Error(`Unsupported .stash schema: v${o.stashSchema}`);await Fo(h,t);let a=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("notes/")&&v.name.endsWith(".md")),r=[];for(let v of a){let S=await v.async("string"),{fm:M,body:F}=Dt(S),N=vo(v.name.slice(6))||`${M.id||"imported-"+pt(4)}.md`;r.push({originalName:N,fm:M,body:F})}let l=new Map,c=0;for(let v of r){let S=v.fm.id;S&&(i.forceNewIds?l.set(S,pt(6)):e.has(S)||l.has(S)?(l.set(S,`${S}-${pt(4)}-Imported`),c++):l.set(S,S))}let p=new Date().toISOString(),g=[],d=`${t}/_attachments`,u=0,I=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("attachments/")),f=new Map,C=null;if(i.dedupeExisting){C=new Map;for(let v of h.vault.getFiles())C.has(v.name)||C.set(v.name,v.path)}let m=(v,S)=>{if(v.length!==S.length)return!1;for(let M=0;M<v.length;M++)if(v[M]!==S[M])return!1;return!0},y=!1;for(let v of I){let S=vo(v.name.slice(12));if(!S)continue;let M=new Uint8Array(await v.async("arraybuffer")),F=[],N=C?.get(S);N&&F.push(N);let Q=`${d}/${S}`;await h.vault.adapter.exists(Q)&&F.push(Q);let D=null;for(let x of F)try{if(m(new Uint8Array(await h.vault.adapter.readBinary(x)),M)){D=x;break}}catch{}if(D){f.set(S,D);continue}let K=Q;for(let x=1;await h.vault.adapter.exists(K);x++)K=`${d}/${Ar(S,x)}`;f.set(S,K),y||(await Fo(h,d),y=!0),await h.vault.createBinary(K,M.buffer),u++}let w=0;for(let v of r){let S=v.fm.id;if(!S){g.push(`Skipped ${v.originalName} \u2014 no id in frontmatter`);continue}let M=l.get(S),F=v.fm.parent??null,N=F;!F||F===T?N=i.reparentRootsTo??F??T:l.has(F)?N=l.get(F):N=e.has(F)?F:i.reparentRootsTo??T;let Q=lr(v.body,f,d),D={...v.fm,id:M,parent:N,import_date:p};Array.isArray(D.attachments)&&(D.attachments=D.attachments.map(q=>{let j=Do(Be(q));return Yt(f.get(j)??`${d}/${j}`)}));let K=le(D,Q),x=M===S?v.originalName:hr(v.originalName,S,M),Y=`${t}/${x}`;await h.vault.adapter.exists(Y)&&(x=`${x.replace(/\.md$/,"")}-${pt(4)}.md`,Y=`${t}/${x}`),await h.vault.create(Y,K),w++}let E;if(o.colorAliases&&typeof o.colorAliases=="object"){let v={};for(let[S,M]of Object.entries(o.colorAliases)){let F=String(S).trim().toLowerCase(),N=String(M??"").trim();/^#([0-9a-f]{6})$/.test(F)&&N&&(v[F]=N.slice(0,60))}Object.keys(v).length&&(E=v)}return{notesWritten:w,attachmentsWritten:u,collisionsRenamed:c,warnings:g,colorAliases:E,idRemap:Object.fromEntries(l)}}function ar(h){let A=new Set,t=[];for(let e of h)A.has(e.id)||(A.add(e.id),t.push(e));return t}function So(h){let A=new Set,t;for(fn.lastIndex=0;(t=fn.exec(h))!==null;)A.add(t[1]);return[...A]}async function is(h,A){let t=await h.vault.read(A),e=[],i=new Set;for(let s of So(t)){let n=h.metadataCache.getFirstLinkpathDest(s,A.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function rr(h,A,t){return h.replace(new RegExp(`!\\[\\[${dr(A)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function Ar(h,A){let t=h.lastIndexOf(".");return t>0?`${h.slice(0,t)}-${A}${h.slice(t)}`:`${h}-${A}`}function lr(h,A,t){return h.replace(fn,(e,i,s)=>{if(i.includes("/"))return e;let n=A.get(i)??`${t}/${i}`;return e.replace(i,n)})}function cr(h,A,t){let e=Dt(h);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return h;let i=e.fm.attachments.map(n=>{let o=A.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:Do(n)}),s={...e.fm,attachments:i};return le(s,e.body)}function dr(h){return h.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Do(h){let A=h.lastIndexOf("/");return A<0?h:h.slice(A+1)}function hr(h,A,t){return h.includes(A)?h.replace(A,t):h.replace(/\.md$/,`-${t}.md`)}function Dt(h){if(!h.startsWith("---"))return{fm:{},body:h};let A=h.indexOf(` ----`,3);if(A<0)return{fm:{},body:h};let t=h.slice(3,A).replace(/^\n/,""),e=h.slice(A+4),i={};try{i=(0,es.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` -`)?e.slice(1):e;return{fm:i,body:s}}function le(h,A){return`--- -${(0,es.stringifyYaml)(h).trimEnd()} +`}function zi(d,l){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:`${l.indexed.length} indexed`}),i.createEl("li",{text:`${l.nonIndex.length+l.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(),l.previewPath){let a=d.vault.getAbstractFileByPath(l.previewPath);a instanceof St.TFile&&await d.workspace.getLeaf("tab").openFile(a)}n?.hide()},n=new St.Notice(t,0),n}var St,lo,Ii,fi=Ce(()=>{"use strict";St=require("obsidian");Lt();Ue();Qt();lo=/^(\d+-\d+|\d+|[A-Za-z0-9]+(?:\.[A-Za-z0-9]+)+)\s+(.+)$/;Ii=class extends St.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 St.Setting(t);(i||s)&&r.addButton(A=>{A.setButtonText(this.previewRan?"Re-run preview":"Run preview first"),A.setCta(),A.onClick(async()=>{try{let c=await Yi(this.app,this.plugin,this.settings);if(c.error==="no-dest"){new St.Notice("Set a Designated Stashpad folder for Index first.",5e3),this.close();return}if(c.error==="no-home"){new St.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,zi(this.app,c),this.contentEl.empty(),this.titleEl.empty(),this.onOpen()}catch(c){new St.Notice(`Preview failed: ${c?.message??c}`,8e3)}})}),r.addButton(A=>{A.setButtonText(i?"Build anyway":"Build"),!i&&!s&&A.setCta(),A.onClick(async()=>{this.close(),await this.onBuild()})}),r.addButton(A=>{A.setButtonText("Cancel"),A.onClick(()=>this.close())})}onClose(){this.contentEl.empty()}}});var vi=Ha((Mo,yn)=>{(function(d){typeof Mo=="object"&&typeof yn<"u"?yn.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(l,t,e){function i(o,a){if(!t[o]){if(!l[o]){var r=typeof require=="function"&&require;if(!a&&r)return r(o,!0);if(s)return s(o,!0);var A=new Error("Cannot find module '"+o+"'");throw A.code="MODULE_NOT_FOUND",A}var c=t[o]={exports:{}};l[o][0].call(c.exports,function(g){var p=l[o][1][g];return i(p||g)},c,c.exports,d,l,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,l,t){"use strict";var e=d("./utils"),i=d("./support"),s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";t.encode=function(n){for(var o,a,r,A,c,g,p,h=[],u=0,I=n.length,f=I,m=e.getTypeOf(n)!=="string";u<n.length;)f=I-u,r=m?(o=n[u++],a=u<I?n[u++]:0,u<I?n[u++]:0):(o=n.charCodeAt(u++),a=u<I?n.charCodeAt(u++):0,u<I?n.charCodeAt(u++):0),A=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(A)+s.charAt(c)+s.charAt(g)+s.charAt(p));return h.join("")},t.decode=function(n){var o,a,r,A,c,g,p=0,h=0,u="data:";if(n.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var I,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(I=i.uint8array?new Uint8Array(0|f):new Array(0|f);p<n.length;)o=s.indexOf(n.charAt(p++))<<2|(A=s.indexOf(n.charAt(p++)))>>4,a=(15&A)<<4|(c=s.indexOf(n.charAt(p++)))>>2,r=(3&c)<<6|(g=s.indexOf(n.charAt(p++))),I[h++]=o,c!==64&&(I[h++]=a),g!==64&&(I[h++]=r);return I}},{"./support":30,"./utils":32}],2:[function(d,l,t){"use strict";var e=d("./external"),i=d("./stream/DataWorker"),s=d("./stream/Crc32Probe"),n=d("./stream/DataLengthProbe");function o(a,r,A,c,g){this.compressedSize=a,this.uncompressedSize=r,this.crc32=A,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,A){return a.pipe(new s).pipe(new n("uncompressedSize")).pipe(r.compressWorker(A)).pipe(new n("compressedSize")).withStreamInfo("compression",r)},l.exports=o},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(d,l,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,l,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}();l.exports=function(s,n){return s!==void 0&&s.length?e.getTypeOf(s)!=="string"?function(o,a,r,A){var c=i,g=A+r;o^=-1;for(var p=A;p<g;p++)o=o>>>8^c[255&(o^a[p])];return-1^o}(0|n,s,s.length,0):function(o,a,r,A){var c=i,g=A+r;o^=-1;for(var p=A;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,l,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,l,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:d("lie"),l.exports={Promise:e}},{lie:37}],7:[function(d,l,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,A){n.call(this,"FlateWorker/"+r),this._pako=null,this._pakoAction=r,this._pakoOptions=A,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(A){r.push({data:A,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,l,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,u,I){var f,m,C=c.file,y=c.compression,w=I!==o.utf8encode,E=s.transformTo("string",I(C.name)),v=s.transformTo("string",o.utf8encode(C.name)),D=C.comment,x=s.transformTo("string",I(D)),F=s.transformTo("string",o.utf8encode(D)),N=v.length!==C.name.length,Q=F.length!==D.length,S="",O="",M="",Y=C.dir,q=C.date,j={crc32:0,compressedSize:0,uncompressedSize:0};g&&!p||(j.crc32=c.crc32,j.compressedSize=c.compressedSize,j.uncompressedSize=c.uncompressedSize);var L=0;g&&(L|=8),w||!N&&!Q||(L|=2048);var P=0,tt=0;Y&&(P|=16),u==="UNIX"?(tt=798,P|=function($,rt){var pt=$;return $||(pt=rt?16893:33204),(65535&pt)<<16}(C.unixPermissions,Y)):(tt=20,P|=function($){return 63&($||0)}(C.dosPermissions)),f=q.getUTCHours(),f<<=6,f|=q.getUTCMinutes(),f<<=5,f|=q.getUTCSeconds()/2,m=q.getUTCFullYear()-1980,m<<=4,m|=q.getUTCMonth()+1,m<<=5,m|=q.getUTCDate(),N&&(O=e(1,1)+e(a(E),4)+v,S+="up"+e(O.length,2)+O),Q&&(M=e(1,1)+e(a(x),4)+F,S+="uc"+e(M.length,2)+M);var K="";return K+=` +\0`,K+=e(L,2),K+=y.magic,K+=e(f,2),K+=e(m,2),K+=e(j.crc32,4),K+=e(j.compressedSize,4),K+=e(j.uncompressedSize,4),K+=e(E.length,2),K+=e(S.length,2),{fileRecord:r.LOCAL_FILE_HEADER+K+E+S,dirRecord:r.CENTRAL_FILE_HEADER+e(tt,2)+K+e(x.length,2)+"\0\0\0\0"+e(P,4)+e(h,4)+E+S+x}}var s=d("../utils"),n=d("../stream/GenericWorker"),o=d("../utf8"),a=d("../crc32"),r=d("../signature");function A(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(A,n),A.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}}))},A.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},A.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},A.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(u,I,f,m,C){var y=s.transformTo("string",C(m));return r.CENTRAL_DIRECTORY_END+"\0\0\0\0"+e(u,2)+e(u,2)+e(I,4)+e(f,4)+e(y.length,2)+y}(this.dirRecords.length,p,c,this.zipComment,this.encodeFileName);this.push({data:h,meta:{percent:100}})},A.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},A.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},A.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))},A.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},A.prototype.lock=function(){n.prototype.lock.call(this);for(var c=this._sources,g=0;g<c.length;g++)c[g].lock()},l.exports=A},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(d,l,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(A,c){r++;var g=function(I,f){var m=I||f,C=e[m];if(!C)throw new Error(m+" is not a valid compression method !");return C}(c.options.compression,n.compression),p=c.options.compressionOptions||n.compressionOptions||{},h=c.dir,u=c.date;c._compressWorker(g,p).withStreamInfo("file",{name:A,dir:h,date:u,comment:c.comment||"",unixPermissions:c.unixPermissions,dosPermissions:c.dosPermissions}).pipe(a)}),a.entriesCount=r}catch(A){a.error(A)}return a}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(d,l,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"),l.exports=e},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(d,l,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(A){return new i.Promise(function(c,g){var p=A.decompressed.getContentWorker().pipe(new o);p.on("error",function(h){g(h)}).on("end",function(){p.streamInfo.crc32!==A.decompressed.crc32?g(new Error("Corrupted zip : CRC32 mismatch")):c()}).resume()})}l.exports=function(A,c){var g=this;return c=e.extend(c||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:s.utf8decode}),a.isNode&&a.isStream(A)?i.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):e.prepareContent("the loaded zip file",A,!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)],u=p.files;if(c.checkCRC32)for(var I=0;I<u.length;I++)h.push(r(u[I]));return i.Promise.all(h)}).then(function(p){for(var h=p.shift(),u=h.files,I=0;I<u.length;I++){var f=u[I],m=f.fileNameStr,C=e.resolve(f.fileNameStr);g.file(C,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(C).unsafeOriginalName=m)}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,l,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)},l.exports=s},{"../stream/GenericWorker":28,"../utils":32}],13:[function(d,l,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,A){a.push(r)||a._helper.pause(),o&&o(A)}).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()},l.exports=i},{"../utils":32,"readable-stream":16}],14:[function(d,l,t){"use strict";l.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,l,t){"use strict";function e(C,y,w){var E,v=s.getTypeOf(y),D=s.extend(w||{},a);D.date=D.date||new Date,D.compression!==null&&(D.compression=D.compression.toUpperCase()),typeof D.unixPermissions=="string"&&(D.unixPermissions=parseInt(D.unixPermissions,8)),D.unixPermissions&&16384&D.unixPermissions&&(D.dir=!0),D.dosPermissions&&16&D.dosPermissions&&(D.dir=!0),D.dir&&(C=u(C)),D.createFolders&&(E=h(C))&&I.call(this,E,!0);var x=v==="string"&&D.binary===!1&&D.base64===!1;w&&w.binary!==void 0||(D.binary=!x),(y instanceof r&&y.uncompressedSize===0||D.dir||!y||y.length===0)&&(D.base64=!1,D.binary=!0,y="",D.compression="STORE",v="string");var F=null;F=y instanceof r||y instanceof n?y:g.isNode&&g.isStream(y)?new p(C,y):s.prepareContent(C,y,D.binary,D.optimizedBinaryString,D.base64);var N=new A(C,F,D);this.files[C]=N}var i=d("./utf8"),s=d("./utils"),n=d("./stream/GenericWorker"),o=d("./stream/StreamHelper"),a=d("./defaults"),r=d("./compressedObject"),A=d("./zipObject"),c=d("./generate"),g=d("./nodejsUtils"),p=d("./nodejs/NodejsStreamInputAdapter"),h=function(C){C.slice(-1)==="/"&&(C=C.substring(0,C.length-1));var y=C.lastIndexOf("/");return 0<y?C.substring(0,y):""},u=function(C){return C.slice(-1)!=="/"&&(C+="/"),C},I=function(C,y){return y=y!==void 0?y:a.createFolders,C=u(C),this.files[C]||e.call(this,C,null,{dir:!0,createFolders:y}),this.files[C]};function f(C){return Object.prototype.toString.call(C)==="[object RegExp]"}var m={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(C){var y,w,E;for(y in this.files)E=this.files[y],(w=y.slice(this.root.length,y.length))&&y.slice(0,this.root.length)===this.root&&C(w,E)},filter:function(C){var y=[];return this.forEach(function(w,E){C(w,E)&&y.push(E)}),y},file:function(C,y,w){if(arguments.length!==1)return C=this.root+C,e.call(this,C,y,w),this;if(f(C)){var E=C;return this.filter(function(D,x){return!x.dir&&E.test(D)})}var v=this.files[this.root+C];return v&&!v.dir?v:null},folder:function(C){if(!C)return this;if(f(C))return this.filter(function(v,D){return D.dir&&C.test(v)});var y=this.root+C,w=I.call(this,y),E=this.clone();return E.root=w.name,E},remove:function(C){C=this.root+C;var y=this.files[C];if(y||(C.slice(-1)!=="/"&&(C+="/"),y=this.files[C]),y&&!y.dir)delete this.files[C];else for(var w=this.filter(function(v,D){return D.name.slice(0,C.length)===C}),E=0;E<w.length;E++)delete this.files[w[E].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(C){var y,w={};try{if((w=s.extend(C||{},{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 E=w.comment||this.comment||"";y=c.generateWorker(this,w,E)}catch(v){(y=new n("error")).error(v)}return new o(y,w.type||"string",w.mimeType)},generateAsync:function(C,y){return this.generateInternalStream(C).accumulate(y)},generateNodeStream:function(C,y){return(C=C||{}).type||(C.type="nodebuffer"),this.generateInternalStream(C).toNodejsStream(y)}};l.exports=m},{"./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,l,t){"use strict";l.exports=d("stream")},{stream:void 0}],17:[function(d,l,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),A=this.length-4;0<=A;--A)if(this.data[A]===n&&this.data[A+1]===o&&this.data[A+2]===a&&this.data[A+3]===r)return A-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),A=this.readData(4);return n===A[0]&&o===A[1]&&a===A[2]&&r===A[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},l.exports=i},{"../utils":32,"./DataReader":18}],18:[function(d,l,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))}},l.exports=i},{"../utils":32}],19:[function(d,l,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},l.exports=i},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(d,l,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},l.exports=i},{"../utils":32,"./DataReader":18}],21:[function(d,l,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},l.exports=i},{"../utils":32,"./ArrayReader":17}],22:[function(d,l,t){"use strict";var e=d("../utils"),i=d("../support"),s=d("./ArrayReader"),n=d("./StringReader"),o=d("./NodeBufferReader"),a=d("./Uint8ArrayReader");l.exports=function(r){var A=e.getTypeOf(r);return e.checkSupport(A),A!=="string"||i.uint8array?A==="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,l,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,l,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})},l.exports=s},{"../utils":32,"./GenericWorker":28}],25:[function(d,l,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)},l.exports=s},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(d,l,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)},l.exports=s},{"../utils":32,"./GenericWorker":28}],27:[function(d,l,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}})},l.exports=s},{"../utils":32,"./GenericWorker":28}],28:[function(d,l,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}},l.exports=e},{}],29:[function(d,l,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 A(g,p){return new a.Promise(function(h,u){var I=[],f=g._internalType,m=g._outputType,C=g._mimeType;g.on("data",function(y,w){I.push(y),p&&p(w)}).on("error",function(y){I=[],u(y)}).on("end",function(){try{var y=function(w,E,v){switch(w){case"blob":return e.newBlob(e.transformTo("arraybuffer",E),v);case"base64":return n.encode(E);default:return e.transformTo(w,E)}}(m,function(w,E){var v,D=0,x=null,F=0;for(v=0;v<E.length;v++)F+=E[v].length;switch(w){case"string":return E.join("");case"array":return Array.prototype.concat.apply([],E);case"uint8array":for(x=new Uint8Array(F),v=0;v<E.length;v++)x.set(E[v],D),D+=E[v].length;return x;case"nodebuffer":return Buffer.concat(E);default:throw new Error("concat : unsupported type '"+w+"'")}}(f,I),C);h(y)}catch(w){u(w)}I=[]}).resume()})}function c(g,p,h){var u=p;switch(p){case"blob":case"arraybuffer":u="uint8array";break;case"base64":u="string"}try{this._internalType=u,this._outputType=p,this._mimeType=h,e.checkSupport(u),this._worker=g.pipe(new i(u)),g.lock()}catch(I){this._worker=new s("error"),this._worker.error(I)}}c.prototype={accumulate:function(g){return A(this,g)},on:function(g,p){var h=this;return g==="data"?this._worker.on(g,function(u){p.call(h,u.data,u.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)}},l.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(d,l,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,l,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 A(){n.call(this,"utf-8 encode")}t.utf8encode=function(c){return i.nodebuffer?s.newBufferFrom(c,"utf-8"):function(g){var p,h,u,I,f,m=g.length,C=0;for(I=0;I<m;I++)(64512&(h=g.charCodeAt(I)))==55296&&I+1<m&&(64512&(u=g.charCodeAt(I+1)))==56320&&(h=65536+(h-55296<<10)+(u-56320),I++),C+=h<128?1:h<2048?2:h<65536?3:4;for(p=i.uint8array?new Uint8Array(C):new Array(C),I=f=0;f<C;I++)(64512&(h=g.charCodeAt(I)))==55296&&I+1<m&&(64512&(u=g.charCodeAt(I+1)))==56320&&(h=65536+(h-55296<<10)+(u-56320),I++),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,u,I,f=g.length,m=new Array(2*f);for(p=h=0;p<f;)if((u=g[p++])<128)m[h++]=u;else if(4<(I=o[u]))m[h++]=65533,p+=I-1;else{for(u&=I===2?31:I===3?15:7;1<I&&p<f;)u=u<<6|63&g[p++],I--;1<I?m[h++]=65533:u<65536?m[h++]=u:(u-=65536,m[h++]=55296|u>>10&1023,m[h++]=56320|1023&u)}return m.length!==h&&(m.subarray?m=m.subarray(0,h):m.length=h),e.applyFromCharCode(m)}(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(I,f){var m;for((f=f||I.length)>I.length&&(f=I.length),m=f-1;0<=m&&(192&I[m])==128;)m--;return m<0||m===0?f:m+o[I[m]]>f?m:f}(g),u=g;h!==g.length&&(i.uint8array?(u=g.subarray(0,h),this.leftOver=g.subarray(h,g.length)):(u=g.slice(0,h),this.leftOver=g.slice(h,g.length))),this.push({data:t.utf8decode(u),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(A,n),A.prototype.processChunk=function(c){this.push({data:t.utf8encode(c.data),meta:c.meta})},t.Utf8EncodeWorker=A},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(d,l,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 u=0;u<p.length;++u)h[u]=255&p.charCodeAt(u);return h}d("setimmediate"),t.newBlob=function(p,h){t.checkSupport("blob");try{return new Blob([p],{type:h})}catch{try{var u=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return u.append(p),u.getBlob(h)}catch{throw new Error("Bug : can't construct the Blob.")}}};var r={stringifyByChunk:function(p,h,u){var I=[],f=0,m=p.length;if(m<=u)return String.fromCharCode.apply(null,p);for(;f<m;)h==="array"||h==="nodebuffer"?I.push(String.fromCharCode.apply(null,p.slice(f,Math.min(f+u,m)))):I.push(String.fromCharCode.apply(null,p.subarray(f,Math.min(f+u,m)))),f+=u;return I.join("")},stringifyByChar:function(p){for(var h="",u=0;u<p.length;u++)h+=String.fromCharCode(p[u]);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 A(p){var h=65536,u=t.getTypeOf(p),I=!0;if(u==="uint8array"?I=r.applyCanBeUsed.uint8array:u==="nodebuffer"&&(I=r.applyCanBeUsed.nodebuffer),I)for(;1<h;)try{return r.stringifyByChunk(p,u,h)}catch{h=Math.floor(h/2)}return r.stringifyByChar(p)}function c(p,h){for(var u=0;u<p.length;u++)h[u]=p[u];return h}t.applyFromCharCode=A;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:A,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 A(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:A,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:A,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 u=t.getTypeOf(h);return g[u][p](h)},t.resolve=function(p){for(var h=p.split("/"),u=[],I=0;I<h.length;I++){var f=h[I];f==="."||f===""&&I!==0&&I!==h.length-1||(f===".."?u.pop():u.push(f))}return u.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,u,I="";for(u=0;u<(p||"").length;u++)I+="\\x"+((h=p.charCodeAt(u))<16?"0":"")+h.toString(16).toUpperCase();return I},t.delay=function(p,h,u){setImmediate(function(){p.apply(u||null,h||[])})},t.inherits=function(p,h){function u(){}u.prototype=h.prototype,p.prototype=new u},t.extend=function(){var p,h,u={};for(p=0;p<arguments.length;p++)for(h in arguments[p])Object.prototype.hasOwnProperty.call(arguments[p],h)&&u[h]===void 0&&(u[h]=arguments[p][h]);return u},t.prepareContent=function(p,h,u,I,f){return n.Promise.resolve(h).then(function(m){return e.blob&&(m instanceof Blob||["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(m))!==-1)&&typeof FileReader<"u"?new n.Promise(function(C,y){var w=new FileReader;w.onload=function(E){C(E.target.result)},w.onerror=function(E){y(E.target.error)},w.readAsArrayBuffer(m)}):m}).then(function(m){var C=t.getTypeOf(m);return C?(C==="arraybuffer"?m=t.transformTo("uint8array",m):C==="string"&&(f?m=i.decode(m):u&&I!==!0&&(m=function(y){return a(y,e.uint8array?new Uint8Array(y.length):new Array(y.length))}(m))),m):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,l,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 A=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+i.pretty(A)+", expected "+i.pretty(r)+")")}},isSignature:function(r,A){var c=this.reader.index;this.reader.setIndex(r);var g=this.reader.readString(4)===A;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),A=o.uint8array?"uint8array":"array",c=i.transformTo(A,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,A,c,g=this.zip64EndOfCentralSize-44;0<g;)r=this.reader.readInt(2),A=this.reader.readInt(4),c=this.reader.readData(A),this.zip64ExtensibleData[r]={id:r,length:A,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,A;for(r=0;r<this.files.length;r++)A=this.files[r],this.reader.setIndex(A.localHeaderOffset),this.checkSignature(s.LOCAL_FILE_HEADER),A.readLocalPart(this.reader),A.handleUTF8(),A.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 A=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=A-c;if(0<g)this.isSignature(A,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()}},l.exports=a},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(d,l,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 A(c,g){this.options=c,this.loadOptions=g}A.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 u in a)if(Object.prototype.hasOwnProperty.call(a,u)&&a[u].magic===h)return a[u];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,u=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4<u;)g=c.readInt(2),p=c.readInt(2),h=c.readData(p),this.extraFields[g]={id:g,length:p,value:h};c.setIndex(u)},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 u=i.transformTo(c,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(u)}}},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}},l.exports=A},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(d,l,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 u=(h=g.toLowerCase())==="string"||h==="text";h!=="binarystring"&&h!=="text"||(h="string"),p=this._decompressWorker();var I=!this._dataBinary;I&&!u&&(p=p.pipe(new n.Utf8EncodeWorker)),!I&&u&&(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"],A=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]]=A;l.exports=e},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(d,l,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 A=new e.MessageChannel;A.port1.onmessage=g,i=function(){A.port2.postMessage(0)}}var c=[];function g(){var p,h;s=!0;for(var u=c.length;u;){for(h=c,c=[],p=-1;++p<u;)h[p]();u=c.length}s=!1}l.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,l,t){"use strict";var e=d("immediate");function i(){}var s={},n=["REJECTED"],o=["FULFILLED"],a=["PENDING"];function r(u){if(typeof u!="function")throw new TypeError("resolver must be a function");this.state=a,this.queue=[],this.outcome=void 0,u!==i&&p(this,u)}function A(u,I,f){this.promise=u,typeof I=="function"&&(this.onFulfilled=I,this.callFulfilled=this.otherCallFulfilled),typeof f=="function"&&(this.onRejected=f,this.callRejected=this.otherCallRejected)}function c(u,I,f){e(function(){var m;try{m=I(f)}catch(C){return s.reject(u,C)}m===u?s.reject(u,new TypeError("Cannot resolve promise with itself")):s.resolve(u,m)})}function g(u){var I=u&&u.then;if(u&&(typeof u=="object"||typeof u=="function")&&typeof I=="function")return function(){I.apply(u,arguments)}}function p(u,I){var f=!1;function m(w){f||(f=!0,s.reject(u,w))}function C(w){f||(f=!0,s.resolve(u,w))}var y=h(function(){I(C,m)});y.status==="error"&&m(y.value)}function h(u,I){var f={};try{f.value=u(I),f.status="success"}catch(m){f.status="error",f.value=m}return f}(l.exports=r).prototype.finally=function(u){if(typeof u!="function")return this;var I=this.constructor;return this.then(function(f){return I.resolve(u()).then(function(){return f})},function(f){return I.resolve(u()).then(function(){throw f})})},r.prototype.catch=function(u){return this.then(null,u)},r.prototype.then=function(u,I){if(typeof u!="function"&&this.state===o||typeof I!="function"&&this.state===n)return this;var f=new this.constructor(i);return this.state!==a?c(f,this.state===o?u:I,this.outcome):this.queue.push(new A(f,u,I)),f},A.prototype.callFulfilled=function(u){s.resolve(this.promise,u)},A.prototype.otherCallFulfilled=function(u){c(this.promise,this.onFulfilled,u)},A.prototype.callRejected=function(u){s.reject(this.promise,u)},A.prototype.otherCallRejected=function(u){c(this.promise,this.onRejected,u)},s.resolve=function(u,I){var f=h(g,I);if(f.status==="error")return s.reject(u,f.value);var m=f.value;if(m)p(u,m);else{u.state=o,u.outcome=I;for(var C=-1,y=u.queue.length;++C<y;)u.queue[C].callFulfilled(I)}return u},s.reject=function(u,I){u.state=n,u.outcome=I;for(var f=-1,m=u.queue.length;++f<m;)u.queue[f].callRejected(I);return u},r.resolve=function(u){return u instanceof this?u:s.resolve(new this(i),u)},r.reject=function(u){var I=new this(i);return s.reject(I,u)},r.all=function(u){var I=this;if(Object.prototype.toString.call(u)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=u.length,m=!1;if(!f)return this.resolve([]);for(var C=new Array(f),y=0,w=-1,E=new this(i);++w<f;)v(u[w],w);return E;function v(D,x){I.resolve(D).then(function(F){C[x]=F,++y!==f||m||(m=!0,s.resolve(E,C))},function(F){m||(m=!0,s.reject(E,F))})}},r.race=function(u){var I=this;if(Object.prototype.toString.call(u)!=="[object Array]")return this.reject(new TypeError("must be an array"));var f=u.length,m=!1;if(!f)return this.resolve([]);for(var C=-1,y=new this(i);++C<f;)w=u[C],I.resolve(w).then(function(E){m||(m=!0,s.resolve(y,E))},function(E){m||(m=!0,s.reject(y,E))});var w;return y}},{immediate:36}],38:[function(d,l,t){"use strict";var e={};(0,d("./lib/utils/common").assign)(e,d("./lib/deflate"),d("./lib/inflate"),d("./lib/zlib/constants")),l.exports=e},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(d,l,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,A=-1,c=0,g=8;function p(u){if(!(this instanceof p))return new p(u);this.options=i.assign({level:A,method:g,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},u||{});var I=this.options;I.raw&&0<I.windowBits?I.windowBits=-I.windowBits:I.gzip&&0<I.windowBits&&I.windowBits<16&&(I.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,I.level,I.method,I.windowBits,I.memLevel,I.strategy);if(f!==r)throw new Error(n[f]);if(I.header&&e.deflateSetHeader(this.strm,I.header),I.dictionary){var m;if(m=typeof I.dictionary=="string"?s.string2buf(I.dictionary):a.call(I.dictionary)==="[object ArrayBuffer]"?new Uint8Array(I.dictionary):I.dictionary,(f=e.deflateSetDictionary(this.strm,m))!==r)throw new Error(n[f]);this._dict_set=!0}}function h(u,I){var f=new p(I);if(f.push(u,!0),f.err)throw f.msg||n[f.err];return f.result}p.prototype.push=function(u,I){var f,m,C=this.strm,y=this.options.chunkSize;if(this.ended)return!1;m=I===~~I?I:I===!0?4:0,typeof u=="string"?C.input=s.string2buf(u):a.call(u)==="[object ArrayBuffer]"?C.input=new Uint8Array(u):C.input=u,C.next_in=0,C.avail_in=C.input.length;do{if(C.avail_out===0&&(C.output=new i.Buf8(y),C.next_out=0,C.avail_out=y),(f=e.deflate(C,m))!==1&&f!==r)return this.onEnd(f),!(this.ended=!0);C.avail_out!==0&&(C.avail_in!==0||m!==4&&m!==2)||(this.options.to==="string"?this.onData(s.buf2binstring(i.shrinkBuf(C.output,C.next_out))):this.onData(i.shrinkBuf(C.output,C.next_out)))}while((0<C.avail_in||C.avail_out===0)&&f!==1);return m===4?(f=e.deflateEnd(this.strm),this.onEnd(f),this.ended=!0,f===r):m!==2||(this.onEnd(r),!(C.avail_out=0))},p.prototype.onData=function(u){this.chunks.push(u)},p.prototype.onEnd=function(u){u===r&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=i.flattenChunks(this.chunks)),this.chunks=[],this.err=u,this.msg=this.strm.msg},t.Deflate=p,t.deflate=h,t.deflateRaw=function(u,I){return(I=I||{}).raw=!0,h(u,I)},t.gzip=function(u,I){return(I=I||{}).gzip=!0,h(u,I)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(d,l,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"),A=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 u=e.inflateInit2(this.strm,h.windowBits);if(u!==n.Z_OK)throw new Error(o[u]);this.header=new r,e.inflateGetHeader(this.strm,this.header)}function g(p,h){var u=new c(h);if(u.push(p,!0),u.err)throw u.msg||o[u.err];return u.result}c.prototype.push=function(p,h){var u,I,f,m,C,y,w=this.strm,E=this.options.chunkSize,v=this.options.dictionary,D=!1;if(this.ended)return!1;I=h===~~h?h:h===!0?n.Z_FINISH:n.Z_NO_FLUSH,typeof p=="string"?w.input=s.binstring2buf(p):A.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(E),w.next_out=0,w.avail_out=E),(u=e.inflate(w,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&v&&(y=typeof v=="string"?s.string2buf(v):A.call(v)==="[object ArrayBuffer]"?new Uint8Array(v):v,u=e.inflateSetDictionary(this.strm,y)),u===n.Z_BUF_ERROR&&D===!0&&(u=n.Z_OK,D=!1),u!==n.Z_STREAM_END&&u!==n.Z_OK)return this.onEnd(u),!(this.ended=!0);w.next_out&&(w.avail_out!==0&&u!==n.Z_STREAM_END&&(w.avail_in!==0||I!==n.Z_FINISH&&I!==n.Z_SYNC_FLUSH)||(this.options.to==="string"?(f=s.utf8border(w.output,w.next_out),m=w.next_out-f,C=s.buf2string(w.output,f),w.next_out=m,w.avail_out=E-m,m&&i.arraySet(w.output,w.output,f,m,0),this.onData(C)):this.onData(i.shrinkBuf(w.output,w.next_out)))),w.avail_in===0&&w.avail_out===0&&(D=!0)}while((0<w.avail_in||w.avail_out===0)&&u!==n.Z_STREAM_END);return u===n.Z_STREAM_END&&(I=n.Z_FINISH),I===n.Z_FINISH?(u=e.inflateEnd(this.strm),this.onEnd(u),this.ended=!0,u===n.Z_OK):I!==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,l,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,A){if(o.subarray&&n.subarray)n.set(o.subarray(a,a+r),A);else for(var c=0;c<r;c++)n[A+c]=o[a+c]},flattenChunks:function(n){var o,a,r,A,c,g;for(o=r=0,a=n.length;o<a;o++)r+=n[o].length;for(g=new Uint8Array(r),o=A=0,a=n.length;o<a;o++)c=n[o],g.set(c,A),A+=c.length;return g}},s={arraySet:function(n,o,a,r,A){for(var c=0;c<r;c++)n[A+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,l,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,A){if(A<65537&&(r.subarray&&s||!r.subarray&&i))return String.fromCharCode.apply(null,e.shrinkBuf(r,A));for(var c="",g=0;g<A;g++)c+=String.fromCharCode(r[g]);return c}n[254]=n[254]=1,t.string2buf=function(r){var A,c,g,p,h,u=r.length,I=0;for(p=0;p<u;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<u&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),I+=c<128?1:c<2048?2:c<65536?3:4;for(A=new e.Buf8(I),p=h=0;h<I;p++)(64512&(c=r.charCodeAt(p)))==55296&&p+1<u&&(64512&(g=r.charCodeAt(p+1)))==56320&&(c=65536+(c-55296<<10)+(g-56320),p++),c<128?A[h++]=c:(c<2048?A[h++]=192|c>>>6:(c<65536?A[h++]=224|c>>>12:(A[h++]=240|c>>>18,A[h++]=128|c>>>12&63),A[h++]=128|c>>>6&63),A[h++]=128|63&c);return A},t.buf2binstring=function(r){return a(r,r.length)},t.binstring2buf=function(r){for(var A=new e.Buf8(r.length),c=0,g=A.length;c<g;c++)A[c]=r.charCodeAt(c);return A},t.buf2string=function(r,A){var c,g,p,h,u=A||r.length,I=new Array(2*u);for(c=g=0;c<u;)if((p=r[c++])<128)I[g++]=p;else if(4<(h=n[p]))I[g++]=65533,c+=h-1;else{for(p&=h===2?31:h===3?15:7;1<h&&c<u;)p=p<<6|63&r[c++],h--;1<h?I[g++]=65533:p<65536?I[g++]=p:(p-=65536,I[g++]=55296|p>>10&1023,I[g++]=56320|1023&p)}return a(I,g)},t.utf8border=function(r,A){var c;for((A=A||r.length)>r.length&&(A=r.length),c=A-1;0<=c&&(192&r[c])==128;)c--;return c<0||c===0?A:c+n[r[c]]>A?c:A}},{"./common":41}],43:[function(d,l,t){"use strict";l.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,l,t){"use strict";l.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,l,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}();l.exports=function(i,s,n,o){var a=e,r=o+n;i^=-1;for(var A=o;A<r;A++)i=i>>>8^a[255&(i^s[A])];return-1^i}},{}],46:[function(d,l,t){"use strict";var e,i=d("../utils/common"),s=d("./trees"),n=d("./adler32"),o=d("./crc32"),a=d("./messages"),r=0,A=4,c=0,g=-2,p=-1,h=4,u=2,I=8,f=9,m=286,C=30,y=19,w=2*m+1,E=15,v=3,D=258,x=D+v+1,F=42,N=113,Q=1,S=2,O=3,M=4;function Y(B,J){return B.msg=a[J],J}function q(B){return(B<<1)-(4<B?9:0)}function j(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 P(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 K(B,J){B.pending_buf[B.pending++]=J>>>8&255,B.pending_buf[B.pending++]=255&J}function $(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-x?B.strstart-(B.w_size-x):0,Z=B.window,et=B.w_mask,_=B.prev,it=B.strstart+D,ft=Z[H+z-1],ht=Z[H+z];B.prev_length>=B.good_match&&(k>>=2),W>B.lookahead&&(W=B.lookahead);do if(Z[(G=J)+z]===ht&&Z[G+z-1]===ft&&Z[G]===Z[H]&&Z[++G]===Z[H+1]){H+=2,G++;do;while(Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&Z[++H]===Z[++G]&&H<it);if(b=D-(it-H),H=it-D,z<b){if(B.match_start=J,W<=(z=b))break;ft=Z[H+z-1],ht=Z[H+z]}}while((J=_[J&et])>R&&--k!=0);return z<=B.lookahead?z:B.lookahead}function rt(B){var J,G,b,k,H,z,W,R,Z,et,_=B.w_size;do{if(k=B.window_size-B.lookahead-B.strstart,B.strstart>=_+(_-x)){for(i.arraySet(B.window,B.window,_,_,0),B.match_start-=_,B.strstart-=_,B.block_start-=_,J=G=B.hash_size;b=B.head[--J],B.head[J]=_<=b?b-_:0,--G;);for(J=G=_;b=B.prev[--J],B.prev[J]=_<=b?b-_:0,--G;);k+=_}if(B.strm.avail_in===0)break;if(z=B.strm,W=B.window,R=B.strstart+B.lookahead,Z=k,et=void 0,et=z.avail_in,Z<et&&(et=Z),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<x&&B.strm.avail_in!==0)}function pt(B,J){for(var G,b;;){if(B.lookahead<x){if(rt(B),B.lookahead<x&&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-x&&(B.match_length=$(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&&(P(B,!1),B.strm.avail_out===0))return Q}return B.insert=B.strstart<v-1?B.strstart:v-1,J===A?(P(B,!0),B.strm.avail_out===0?O:M):B.last_lit&&(P(B,!1),B.strm.avail_out===0)?Q:S}function nt(B,J){for(var G,b,k;;){if(B.lookahead<x){if(rt(B),B.lookahead<x&&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-x&&(B.match_length=$(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&&(P(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]))&&P(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===A?(P(B,!0),B.strm.avail_out===0?O:M):B.last_lit&&(P(B,!1),B.strm.avail_out===0)?Q:S}function lt(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 At(){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=I,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*C+1)),this.bl_tree=new i.Buf16(2*(2*y+1)),j(this.dyn_ltree),j(this.dyn_dtree),j(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new i.Buf16(E+1),this.heap=new i.Buf16(2*m+1),j(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new i.Buf16(2*m+1),j(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 at(B){var J;return B&&B.state?(B.total_in=B.total_out=0,B.data_type=u,(J=B.state).pending=0,J.pending_out=0,J.wrap<0&&(J.wrap=-J.wrap),J.status=J.wrap?F:N,B.adler=J.wrap===2?0:1,J.last_flush=r,s._tr_init(J),c):Y(B,g)}function yt(B){var J=at(B);return J===c&&function(G){G.window_size=2*G.w_size,j(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 mt(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!==I||b<8||15<b||J<0||9<J||H<0||h<H)return Y(B,g);b===8&&(b=9);var W=new At;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,yt(B)}e=[new lt(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,P(B,!1),B.strm.avail_out===0)||B.strstart-B.block_start>=B.w_size-x&&(P(B,!1),B.strm.avail_out===0))return Q}return B.insert=0,J===A?(P(B,!0),B.strm.avail_out===0?O:M):(B.strstart>B.block_start&&(P(B,!1),B.strm.avail_out),Q)}),new lt(4,4,8,4,pt),new lt(4,5,16,8,pt),new lt(4,6,32,32,pt),new lt(4,4,16,16,nt),new lt(8,16,32,32,nt),new lt(8,16,128,128,nt),new lt(8,32,128,256,nt),new lt(32,128,258,1024,nt),new lt(32,258,258,4096,nt)],t.deflateInit=function(B,J){return mt(B,J,I,15,8,0)},t.deflateInit2=mt,t.deflateReset=yt,t.deflateResetKeep=at,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!==A)return Y(B,B.avail_out===0?-5:g);if(b.strm=B,G=b.last_flush,b.last_flush=J,b.status===F)if(b.wrap===2)B.adler=0,tt(b,31),tt(b,139),tt(b,8),b.gzhead?(tt(b,(b.gzhead.text?1:0)+(b.gzhead.hcrc?2:0)+(b.gzhead.extra?4:0)+(b.gzhead.name?8:0)+(b.gzhead.comment?16:0)),tt(b,255&b.gzhead.time),tt(b,b.gzhead.time>>8&255),tt(b,b.gzhead.time>>16&255),tt(b,b.gzhead.time>>24&255),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,255&b.gzhead.os),b.gzhead.extra&&b.gzhead.extra.length&&(tt(b,255&b.gzhead.extra.length),tt(b,b.gzhead.extra.length>>8&255)),b.gzhead.hcrc&&(B.adler=o(B.adler,b.pending_buf,b.pending,0)),b.gzindex=0,b.status=69):(tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,0),tt(b,b.level===9?2:2<=b.strategy||b.level<2?4:0),tt(b,3),b.status=N);else{var z=I+(b.w_bits-8<<4)<<8;z|=(2<=b.strategy||b.level<2?0:b.level<6?1:b.level===6?2:3)<<6,b.strstart!==0&&(z|=32),z+=31-z%31,b.status=N,K(b,z),b.strstart!==0&&(K(b,B.adler>>>16),K(b,65535&B.adler)),B.adler=1}if(b.status===69)if(b.gzhead.extra){for(k=b.pending;b.gzindex<(65535&b.gzhead.extra.length)&&(b.pending!==b.pending_buf_size||(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending!==b.pending_buf_size));)tt(b,255&b.gzhead.extra[b.gzindex]),b.gzindex++;b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),b.gzindex===b.gzhead.extra.length&&(b.gzindex=0,b.status=73)}else b.status=73;if(b.status===73)if(b.gzhead.name){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.name.length?255&b.gzhead.name.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.gzindex=0,b.status=91)}else b.status=91;if(b.status===91)if(b.gzhead.comment){k=b.pending;do{if(b.pending===b.pending_buf_size&&(b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),L(B),k=b.pending,b.pending===b.pending_buf_size)){H=1;break}H=b.gzindex<b.gzhead.comment.length?255&b.gzhead.comment.charCodeAt(b.gzindex++):0,tt(b,H)}while(H!==0);b.gzhead.hcrc&&b.pending>k&&(B.adler=o(B.adler,b.pending_buf,b.pending-k,k)),H===0&&(b.status=103)}else b.status=103;if(b.status===103&&(b.gzhead.hcrc?(b.pending+2>b.pending_buf_size&&L(B),b.pending+2<=b.pending_buf_size&&(tt(b,255&B.adler),tt(b,B.adler>>8&255),B.adler=0,b.status=N)):b.status=N),b.pending!==0){if(L(B),B.avail_out===0)return b.last_flush=-1,c}else if(B.avail_in===0&&q(J)<=q(G)&&J!==A)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,Z){for(var et;;){if(R.lookahead===0&&(rt(R),R.lookahead===0)){if(Z===r)return Q;break}if(R.match_length=0,et=s._tr_tally(R,0,R.window[R.strstart]),R.lookahead--,R.strstart++,et&&(P(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,Z===A?(P(R,!0),R.strm.avail_out===0?O:M):R.last_lit&&(P(R,!1),R.strm.avail_out===0)?Q:S}(b,J):b.strategy===3?function(R,Z){for(var et,_,it,ft,ht=R.window;;){if(R.lookahead<=D){if(rt(R),R.lookahead<=D&&Z===r)return Q;if(R.lookahead===0)break}if(R.match_length=0,R.lookahead>=v&&0<R.strstart&&(_=ht[it=R.strstart-1])===ht[++it]&&_===ht[++it]&&_===ht[++it]){ft=R.strstart+D;do;while(_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&_===ht[++it]&&it<ft);R.match_length=D-(ft-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&&(P(R,!1),R.strm.avail_out===0))return Q}return R.insert=0,Z===A?(P(R,!0),R.strm.avail_out===0?O:M):R.last_lit&&(P(R,!1),R.strm.avail_out===0)?Q:S}(b,J):e[b.level].func(b,J);if(W!==O&&W!==M||(b.status=666),W===Q||W===O)return B.avail_out===0&&(b.last_flush=-1),c;if(W===S&&(J===1?s._tr_align(b):J!==5&&(s._tr_stored_block(b,0,0,!1),J===3&&(j(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!==A?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)):(K(b,B.adler>>>16),K(b,65535&B.adler)),L(B),0<b.wrap&&(b.wrap=-b.wrap),b.pending!==0?c:1)},t.deflateEnd=function(B){var J;return B&&B.state?(J=B.state.status)!==F&&J!==69&&J!==73&&J!==91&&J!==103&&J!==N&&J!==666?Y(B,g):(B.state=null,J===N?Y(B,-3):c):g},t.deflateSetDictionary=function(B,J){var G,b,k,H,z,W,R,Z,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&&(j(G.head),G.strstart=0,G.block_start=0,G.insert=0),Z=new i.Buf8(G.w_size),i.arraySet(Z,J,et-G.w_size,G.w_size,0),J=Z,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,l,t){"use strict";l.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,l,t){"use strict";l.exports=function(e,i){var s,n,o,a,r,A,c,g,p,h,u,I,f,m,C,y,w,E,v,D,x,F,N,Q,S;s=e.state,n=e.next_in,Q=e.input,o=n+(e.avail_in-5),a=e.next_out,S=e.output,r=a-(i-e.avail_out),A=a+(e.avail_out-257),c=s.dmax,g=s.wsize,p=s.whave,h=s.wnext,u=s.window,I=s.hold,f=s.bits,m=s.lencode,C=s.distcode,y=(1<<s.lenbits)-1,w=(1<<s.distbits)-1;t:do{f<15&&(I+=Q[n++]<<f,f+=8,I+=Q[n++]<<f,f+=8),E=m[I&y];e:for(;;){if(I>>>=v=E>>>24,f-=v,(v=E>>>16&255)===0)S[a++]=65535&E;else{if(!(16&v)){if(!(64&v)){E=m[(65535&E)+(I&(1<<v)-1)];continue e}if(32&v){s.mode=12;break t}e.msg="invalid literal/length code",s.mode=30;break t}D=65535&E,(v&=15)&&(f<v&&(I+=Q[n++]<<f,f+=8),D+=I&(1<<v)-1,I>>>=v,f-=v),f<15&&(I+=Q[n++]<<f,f+=8,I+=Q[n++]<<f,f+=8),E=C[I&w];i:for(;;){if(I>>>=v=E>>>24,f-=v,!(16&(v=E>>>16&255))){if(!(64&v)){E=C[(65535&E)+(I&(1<<v)-1)];continue i}e.msg="invalid distance code",s.mode=30;break t}if(x=65535&E,f<(v&=15)&&(I+=Q[n++]<<f,(f+=8)<v&&(I+=Q[n++]<<f,f+=8)),c<(x+=I&(1<<v)-1)){e.msg="invalid distance too far back",s.mode=30;break t}if(I>>>=v,f-=v,(v=a-r)<x){if(p<(v=x-v)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break t}if(N=u,(F=0)===h){if(F+=g-v,v<D){for(D-=v;S[a++]=u[F++],--v;);F=a-x,N=S}}else if(h<v){if(F+=g+h-v,(v-=h)<D){for(D-=v;S[a++]=u[F++],--v;);if(F=0,h<D){for(D-=v=h;S[a++]=u[F++],--v;);F=a-x,N=S}}}else if(F+=h-v,v<D){for(D-=v;S[a++]=u[F++],--v;);F=a-x,N=S}for(;2<D;)S[a++]=N[F++],S[a++]=N[F++],S[a++]=N[F++],D-=3;D&&(S[a++]=N[F++],1<D&&(S[a++]=N[F++]))}else{for(F=a-x;S[a++]=S[F++],S[a++]=S[F++],S[a++]=S[F++],2<(D-=3););D&&(S[a++]=S[F++],1<D&&(S[a++]=S[F++]))}break}}break}}while(n<o&&a<A);n-=D=f>>3,I&=(1<<(f-=D<<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<A?A-a+257:257-(a-A),s.hold=I,s.bits=f}},{}],49:[function(d,l,t){"use strict";var e=d("../utils/common"),i=d("./adler32"),s=d("./crc32"),n=d("./inffast"),o=d("./inftrees"),a=1,r=2,A=0,c=-2,g=1,p=852,h=592;function u(F){return(F>>>24&255)+(F>>>8&65280)+((65280&F)<<8)+((255&F)<<24)}function I(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new e.Buf16(320),this.work=new e.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(F){var N;return F&&F.state?(N=F.state,F.total_in=F.total_out=N.total=0,F.msg="",N.wrap&&(F.adler=1&N.wrap),N.mode=g,N.last=0,N.havedict=0,N.dmax=32768,N.head=null,N.hold=0,N.bits=0,N.lencode=N.lendyn=new e.Buf32(p),N.distcode=N.distdyn=new e.Buf32(h),N.sane=1,N.back=-1,A):c}function m(F){var N;return F&&F.state?((N=F.state).wsize=0,N.whave=0,N.wnext=0,f(F)):c}function C(F,N){var Q,S;return F&&F.state?(S=F.state,N<0?(Q=0,N=-N):(Q=1+(N>>4),N<48&&(N&=15)),N&&(N<8||15<N)?c:(S.window!==null&&S.wbits!==N&&(S.window=null),S.wrap=Q,S.wbits=N,m(F))):c}function y(F,N){var Q,S;return F?(S=new I,(F.state=S).window=null,(Q=C(F,N))!==A&&(F.state=null),Q):c}var w,E,v=!0;function D(F){if(v){var N;for(w=new e.Buf32(512),E=new e.Buf32(32),N=0;N<144;)F.lens[N++]=8;for(;N<256;)F.lens[N++]=9;for(;N<280;)F.lens[N++]=7;for(;N<288;)F.lens[N++]=8;for(o(a,F.lens,0,288,w,0,F.work,{bits:9}),N=0;N<32;)F.lens[N++]=5;o(r,F.lens,0,32,E,0,F.work,{bits:5}),v=!1}F.lencode=w,F.lenbits=9,F.distcode=E,F.distbits=5}function x(F,N,Q,S){var O,M=F.state;return M.window===null&&(M.wsize=1<<M.wbits,M.wnext=0,M.whave=0,M.window=new e.Buf8(M.wsize)),S>=M.wsize?(e.arraySet(M.window,N,Q-M.wsize,M.wsize,0),M.wnext=0,M.whave=M.wsize):(S<(O=M.wsize-M.wnext)&&(O=S),e.arraySet(M.window,N,Q-S,O,M.wnext),(S-=O)?(e.arraySet(M.window,N,Q-S,S,0),M.wnext=S,M.whave=M.wsize):(M.wnext+=O,M.wnext===M.wsize&&(M.wnext=0),M.whave<M.wsize&&(M.whave+=O))),0}t.inflateReset=m,t.inflateReset2=C,t.inflateResetKeep=f,t.inflateInit=function(F){return y(F,15)},t.inflateInit2=y,t.inflate=function(F,N){var Q,S,O,M,Y,q,j,L,P,tt,K,$,rt,pt,nt,lt,At,at,yt,mt,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,O=F.output,j=F.avail_out,M=F.next_in,S=F.input,q=F.avail_in,L=Q.hold,P=Q.bits,tt=q,K=j,J=A;t:for(;;)switch(Q.mode){case g:if(Q.wrap===0){Q.mode=13;break}for(;P<16;){if(q===0)break t;q--,L+=S[M++]<<P,P+=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),P=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(P-=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,P=L=0;break;case 2:for(;P<16;){if(q===0)break t;q--,L+=S[M++]<<P,P+=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)),P=L=0,Q.mode=3;case 3:for(;P<32;){if(q===0)break t;q--,L+=S[M++]<<P,P+=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)),P=L=0,Q.mode=4;case 4:for(;P<16;){if(q===0)break t;q--,L+=S[M++]<<P,P+=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)),P=L=0,Q.mode=5;case 5:if(1024&Q.flags){for(;P<16;){if(q===0)break t;q--,L+=S[M++]<<P,P+=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)),P=L=0}else Q.head&&(Q.head.extra=null);Q.mode=6;case 6:if(1024&Q.flags&&(q<($=Q.length)&&($=q),$&&(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,S,M,$,B)),512&Q.flags&&(Q.check=s(Q.check,S,$,M)),q-=$,M+=$,Q.length-=$),Q.length))break t;Q.length=0,Q.mode=7;case 7:if(2048&Q.flags){if(q===0)break t;for($=0;B=S[M+$++],Q.head&&B&&Q.length<65536&&(Q.head.name+=String.fromCharCode(B)),B&&$<q;);if(512&Q.flags&&(Q.check=s(Q.check,S,$,M)),q-=$,M+=$,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($=0;B=S[M+$++],Q.head&&B&&Q.length<65536&&(Q.head.comment+=String.fromCharCode(B)),B&&$<q;);if(512&Q.flags&&(Q.check=s(Q.check,S,$,M)),q-=$,M+=$,B)break t}else Q.head&&(Q.head.comment=null);Q.mode=9;case 9:if(512&Q.flags){for(;P<16;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(L!==(65535&Q.check)){F.msg="header crc mismatch",Q.mode=30;break}P=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(;P<32;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}F.adler=Q.check=u(L),P=L=0,Q.mode=11;case 11:if(Q.havedict===0)return F.next_out=Y,F.avail_out=j,F.next_in=M,F.avail_in=q,Q.hold=L,Q.bits=P,2;F.adler=Q.check=1,Q.mode=12;case 12:if(N===5||N===6)break t;case 13:if(Q.last){L>>>=7&P,P-=7&P,Q.mode=27;break}for(;P<3;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}switch(Q.last=1&L,P-=1,3&(L>>>=1)){case 0:Q.mode=14;break;case 1:if(D(Q),Q.mode=20,N!==6)break;L>>>=2,P-=2;break t;case 2:Q.mode=17;break;case 3:F.msg="invalid block type",Q.mode=30}L>>>=2,P-=2;break;case 14:for(L>>>=7&P,P-=7&P;P<32;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if((65535&L)!=(L>>>16^65535)){F.msg="invalid stored block lengths",Q.mode=30;break}if(Q.length=65535&L,P=L=0,Q.mode=15,N===6)break t;case 15:Q.mode=16;case 16:if($=Q.length){if(q<$&&($=q),j<$&&($=j),$===0)break t;e.arraySet(O,S,M,$,Y),q-=$,M+=$,j-=$,Y+=$,Q.length-=$;break}Q.mode=12;break;case 17:for(;P<14;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(Q.nlen=257+(31&L),L>>>=5,P-=5,Q.ndist=1+(31&L),L>>>=5,P-=5,Q.ncode=4+(15&L),L>>>=4,P-=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(;P<3;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}Q.lens[z[Q.have++]]=7&L,L>>>=3,P-=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(;lt=(k=Q.lencode[L&(1<<Q.lenbits)-1])>>>16&255,At=65535&k,!((nt=k>>>24)<=P);){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(At<16)L>>>=nt,P-=nt,Q.lens[Q.have++]=At;else{if(At===16){for(b=nt+2;P<b;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(L>>>=nt,P-=nt,Q.have===0){F.msg="invalid bit length repeat",Q.mode=30;break}B=Q.lens[Q.have-1],$=3+(3&L),L>>>=2,P-=2}else if(At===17){for(b=nt+3;P<b;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}P-=nt,B=0,$=3+(7&(L>>>=nt)),L>>>=3,P-=3}else{for(b=nt+7;P<b;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}P-=nt,B=0,$=11+(127&(L>>>=nt)),L>>>=7,P-=7}if(Q.have+$>Q.nlen+Q.ndist){F.msg="invalid bit length repeat",Q.mode=30;break}for(;$--;)Q.lens[Q.have++]=B}}if(Q.mode===30)break;if(Q.lens[256]===0){F.msg="invalid code -- missing end-of-block",Q.mode=30;break}if(Q.lenbits=9,G={bits:Q.lenbits},J=o(a,Q.lens,0,Q.nlen,Q.lencode,0,Q.work,G),Q.lenbits=G.bits,J){F.msg="invalid literal/lengths set",Q.mode=30;break}if(Q.distbits=6,Q.distcode=Q.distdyn,G={bits:Q.distbits},J=o(r,Q.lens,Q.nlen,Q.ndist,Q.distcode,0,Q.work,G),Q.distbits=G.bits,J){F.msg="invalid distances set",Q.mode=30;break}if(Q.mode=20,N===6)break t;case 20:Q.mode=21;case 21:if(6<=q&&258<=j){F.next_out=Y,F.avail_out=j,F.next_in=M,F.avail_in=q,Q.hold=L,Q.bits=P,n(F,K),Y=F.next_out,O=F.output,j=F.avail_out,M=F.next_in,S=F.input,q=F.avail_in,L=Q.hold,P=Q.bits,Q.mode===12&&(Q.back=-1);break}for(Q.back=0;lt=(k=Q.lencode[L&(1<<Q.lenbits)-1])>>>16&255,At=65535&k,!((nt=k>>>24)<=P);){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(lt&&!(240<)){for(at=nt,yt=lt,mt=At;lt=(k=Q.lencode[mt+((L&(1<<at+yt)-1)>>at)])>>>16&255,At=65535&k,!(at+(nt=k>>>24)<=P);){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}L>>>=at,P-=at,Q.back+=at}if(L>>>=nt,P-=nt,Q.back+=nt,Q.length=At,lt===0){Q.mode=26;break}if(32<){Q.back=-1,Q.mode=12;break}if(64<){F.msg="invalid literal/length code",Q.mode=30;break}Q.extra=15<,Q.mode=22;case 22:if(Q.extra){for(b=Q.extra;P<b;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}Q.length+=L&(1<<Q.extra)-1,L>>>=Q.extra,P-=Q.extra,Q.back+=Q.extra}Q.was=Q.length,Q.mode=23;case 23:for(;lt=(k=Q.distcode[L&(1<<Q.distbits)-1])>>>16&255,At=65535&k,!((nt=k>>>24)<=P);){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(!(240<)){for(at=nt,yt=lt,mt=At;lt=(k=Q.distcode[mt+((L&(1<<at+yt)-1)>>at)])>>>16&255,At=65535&k,!(at+(nt=k>>>24)<=P);){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}L>>>=at,P-=at,Q.back+=at}if(L>>>=nt,P-=nt,Q.back+=nt,64<){F.msg="invalid distance code",Q.mode=30;break}Q.offset=At,Q.extra=15<,Q.mode=24;case 24:if(Q.extra){for(b=Q.extra;P<b;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}Q.offset+=L&(1<<Q.extra)-1,L>>>=Q.extra,P-=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(j===0)break t;if($=K-j,Q.offset>$){if(($=Q.offset-$)>Q.whave&&Q.sane){F.msg="invalid distance too far back",Q.mode=30;break}rt=$>Q.wnext?($-=Q.wnext,Q.wsize-$):Q.wnext-$,$>Q.length&&($=Q.length),pt=Q.window}else pt=O,rt=Y-Q.offset,$=Q.length;for(j<$&&($=j),j-=$,Q.length-=$;O[Y++]=pt[rt++],--$;);Q.length===0&&(Q.mode=21);break;case 26:if(j===0)break t;O[Y++]=Q.length,j--,Q.mode=21;break;case 27:if(Q.wrap){for(;P<32;){if(q===0)break t;q--,L|=S[M++]<<P,P+=8}if(K-=j,F.total_out+=K,Q.total+=K,K&&(F.adler=Q.check=Q.flags?s(Q.check,O,K,Y-K):i(Q.check,O,K,Y-K)),K=j,(Q.flags?L:u(L))!==Q.check){F.msg="incorrect data check",Q.mode=30;break}P=L=0}Q.mode=28;case 28:if(Q.wrap&&Q.flags){for(;P<32;){if(q===0)break t;q--,L+=S[M++]<<P,P+=8}if(L!==(4294967295&Q.total)){F.msg="incorrect length check",Q.mode=30;break}P=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=j,F.next_in=M,F.avail_in=q,Q.hold=L,Q.bits=P,(Q.wsize||K!==F.avail_out&&Q.mode<30&&(Q.mode<27||N!==4))&&x(F,F.output,F.next_out,K-F.avail_out)?(Q.mode=31,-4):(tt-=F.avail_in,K-=F.avail_out,F.total_in+=tt,F.total_out+=K,Q.total+=K,Q.wrap&&K&&(F.adler=Q.check=Q.flags?s(Q.check,O,K,F.next_out-K):i(Q.check,O,K,F.next_out-K)),F.data_type=Q.bits+(Q.last?64:0)+(Q.mode===12?128:0)+(Q.mode===20||Q.mode===15?256:0),(tt==0&&K===0||N===4)&&J===A&&(J=-5),J)},t.inflateEnd=function(F){if(!F||!F.state)return c;var N=F.state;return N.window&&(N.window=null),F.state=null,A},t.inflateGetHeader=function(F,N){var Q;return F&&F.state&&2&(Q=F.state).wrap?((Q.head=N).done=!1,A):c},t.inflateSetDictionary=function(F,N){var Q,S=N.length;return F&&F.state?(Q=F.state).wrap!==0&&Q.mode!==11?c:Q.mode===11&&i(1,N,S,0)!==Q.check?-3:x(F,N,S,S)?(Q.mode=31,-4):(Q.havedict=1,A):c},t.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(d,l,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];l.exports=function(a,r,A,c,g,p,h,u){var I,f,m,C,y,w,E,v,D,x=u.bits,F=0,N=0,Q=0,S=0,O=0,M=0,Y=0,q=0,j=0,L=0,P=null,tt=0,K=new e.Buf16(16),$=new e.Buf16(16),rt=null,pt=0;for(F=0;F<=15;F++)K[F]=0;for(N=0;N<c;N++)K[r[A+N]]++;for(O=x,S=15;1<=S&&K[S]===0;S--);if(S<O&&(O=S),S===0)return g[p++]=20971520,g[p++]=20971520,u.bits=1,0;for(Q=1;Q<S&&K[Q]===0;Q++);for(O<Q&&(O=Q),F=q=1;F<=15;F++)if(q<<=1,(q-=K[F])<0)return-1;if(0<q&&(a===0||S!==1))return-1;for($[1]=0,F=1;F<15;F++)$[F+1]=$[F]+K[F];for(N=0;N<c;N++)r[A+N]!==0&&(h[$[r[A+N]]++]=N);if(w=a===0?(P=rt=h,19):a===1?(P=i,tt-=257,rt=s,pt-=257,256):(P=n,rt=o,-1),F=Q,y=p,Y=N=L=0,m=-1,C=(j=1<<(M=O))-1,a===1&&852<j||a===2&&592<j)return 1;for(;;){for(E=F-Y,D=h[N]<w?(v=0,h[N]):h[N]>w?(v=rt[pt+h[N]],P[tt+h[N]]):(v=96,0),I=1<<F-Y,Q=f=1<<M;g[y+(L>>Y)+(f-=I)]=E<<24|v<<16|D|0,f!==0;);for(I=1<<F-1;L&I;)I>>=1;if(I!==0?(L&=I-1,L+=I):L=0,N++,--K[F]==0){if(F===S)break;F=r[A+h[N]]}if(O<F&&(L&C)!==m){for(Y===0&&(Y=O),y+=Q,q=1<<(M=F-Y);M+Y<S&&!((q-=K[M+Y])<=0);)M++,q<<=1;if(j+=1<<M,a===1&&852<j||a===2&&592<j)return 1;g[m=L&C]=O<<24|M<<16|y-p|0}}return L!==0&&(g[y+L]=F-Y<<24|64<<16|0),u.bits=O,0}},{"../utils/common":41}],51:[function(d,l,t){"use strict";l.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,l,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,A=r+1+a,c=30,g=19,p=2*A+1,h=15,u=16,I=7,f=256,m=16,C=17,y=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],E=[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],D=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],x=new Array(2*(A+2));n(x);var F=new Array(2*c);n(F);var N=new Array(512);n(N);var Q=new Array(256);n(Q);var S=new Array(a);n(S);var O,M,Y,q=new Array(c);function j(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 P(k){return k<256?N[k]:N[256+(k>>>7)]}function tt(k,H){k.pending_buf[k.pending++]=255&H,k.pending_buf[k.pending++]=H>>>8&255}function K(k,H,z){k.bi_valid>u-z?(k.bi_buf|=H<<k.bi_valid&65535,tt(k,k.bi_buf),k.bi_buf=H>>u-k.bi_valid,k.bi_valid+=z-u):(k.bi_buf|=H<<k.bi_valid&65535,k.bi_valid+=z)}function $(k,H,z){K(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 pt(k,H,z){var W,R,Z=new Array(h+1),et=0;for(W=1;W<=h;W++)Z[W]=et=et+z[W-1]<<1;for(R=0;R<=H;R++){var _=k[2*R+1];_!==0&&(k[2*R]=rt(Z[_]++,_))}}function nt(k){var H;for(H=0;H<A;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 lt(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 At(k,H,z,W){var R=2*H,Z=2*z;return k[R]<k[Z]||k[R]===k[Z]&&W[H]<=W[z]}function at(k,H,z){for(var W=k.heap[z],R=z<<1;R<=k.heap_len&&(R<k.heap_len&&At(H,k.heap[R+1],k.heap[R],k.depth)&&R++,!At(H,W,k.heap[R],k.depth));)k.heap[z]=k.heap[R],z=R,R<<=1;k.heap[z]=W}function yt(k,H,z){var W,R,Z,et,_=0;if(k.last_lit!==0)for(;W=k.pending_buf[k.d_buf+2*_]<<8|k.pending_buf[k.d_buf+2*_+1],R=k.pending_buf[k.l_buf+_],_++,W===0?$(k,R,H):($(k,(Z=Q[R])+r+1,H),(et=w[Z])!==0&&K(k,R-=S[Z],et),$(k,Z=P(--W),z),(et=E[Z])!==0&&K(k,W-=q[Z],et)),_<k.last_lit;);$(k,f,H)}function mt(k,H){var z,W,R,Z=H.dyn_tree,et=H.stat_desc.static_tree,_=H.stat_desc.has_stree,it=H.stat_desc.elems,ft=-1;for(k.heap_len=0,k.heap_max=p,z=0;z<it;z++)Z[2*z]!==0?(k.heap[++k.heap_len]=ft=z,k.depth[z]=0):Z[2*z+1]=0;for(;k.heap_len<2;)Z[2*(R=k.heap[++k.heap_len]=ft<2?++ft:0)]=1,k.depth[R]=0,k.opt_len--,_&&(k.static_len-=et[2*R+1]);for(H.max_code=ft,z=k.heap_len>>1;1<=z;z--)at(k,Z,z);for(R=it;z=k.heap[1],k.heap[1]=k.heap[k.heap_len--],at(k,Z,1),W=k.heap[1],k.heap[--k.heap_max]=z,k.heap[--k.heap_max]=W,Z[2*R]=Z[2*z]+Z[2*W],k.depth[R]=(k.depth[z]>=k.depth[W]?k.depth[z]:k.depth[W])+1,Z[2*z+1]=Z[2*W+1]=R,k.heap[1]=R++,at(k,Z,1),2<=k.heap_len;);k.heap[--k.heap_max]=k.heap[1],function(ht,Pt){var je,Yt,ti,Et,Ni,Ys,Wt=Pt.dyn_tree,$n=Pt.max_code,ka=Pt.stat_desc.static_tree,Sa=Pt.stat_desc.has_stree,Da=Pt.stat_desc.extra_bits,Wn=Pt.stat_desc.extra_base,ei=Pt.stat_desc.max_length,Mi=0;for(Et=0;Et<=h;Et++)ht.bl_count[Et]=0;for(Wt[2*ht.heap[ht.heap_max]+1]=0,je=ht.heap_max+1;je<p;je++)ei<(Et=Wt[2*Wt[2*(Yt=ht.heap[je])+1]+1]+1)&&(Et=ei,Mi++),Wt[2*Yt+1]=Et,$n<Yt||(ht.bl_count[Et]++,Ni=0,Wn<=Yt&&(Ni=Da[Yt-Wn]),Ys=Wt[2*Yt],ht.opt_len+=Ys*(Et+Ni),Sa&&(ht.static_len+=Ys*(ka[2*Yt+1]+Ni)));if(Mi!==0){do{for(Et=ei-1;ht.bl_count[Et]===0;)Et--;ht.bl_count[Et]--,ht.bl_count[Et+1]+=2,ht.bl_count[ei]--,Mi-=2}while(0<Mi);for(Et=ei;Et!==0;Et--)for(Yt=ht.bl_count[Et];Yt!==0;)$n<(ti=ht.heap[--je])||(Wt[2*ti+1]!==Et&&(ht.opt_len+=(Et-Wt[2*ti+1])*Wt[2*ti],Wt[2*ti+1]=Et),Yt--)}}(k,H),pt(Z,ft,k.bl_count)}function B(k,H,z){var W,R,Z=-1,et=H[1],_=0,it=7,ft=4;for(et===0&&(it=138,ft=3),H[2*(z+1)+1]=65535,W=0;W<=z;W++)R=et,et=H[2*(W+1)+1],++_<it&&R===et||(_<ft?k.bl_tree[2*R]+=_:R!==0?(R!==Z&&k.bl_tree[2*R]++,k.bl_tree[2*m]++):_<=10?k.bl_tree[2*C]++:k.bl_tree[2*y]++,Z=R,ft=(_=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4))}function J(k,H,z){var W,R,Z=-1,et=H[1],_=0,it=7,ft=4;for(et===0&&(it=138,ft=3),W=0;W<=z;W++)if(R=et,et=H[2*(W+1)+1],!(++_<it&&R===et)){if(_<ft)for(;$(k,R,k.bl_tree),--_!=0;);else R!==0?(R!==Z&&($(k,R,k.bl_tree),_--),$(k,m,k.bl_tree),K(k,_-3,2)):_<=10?($(k,C,k.bl_tree),K(k,_-3,3)):($(k,y,k.bl_tree),K(k,_-11,7));Z=R,ft=(_=0)===et?(it=138,3):R===et?(it=6,3):(it=7,4)}}n(q);var G=!1;function b(k,H,z,W){K(k,(o<<1)+(W?1:0),3),function(R,Z,et,_){lt(R),_&&(tt(R,et),tt(R,~et)),e.arraySet(R.pending_buf,R.window,Z,et,R.pending),R.pending+=et}(k,H,z,!0)}t._tr_init=function(k){G||(function(){var H,z,W,R,Z,et=new Array(h+1);for(R=W=0;R<a-1;R++)for(S[R]=W,H=0;H<1<<w[R];H++)Q[W++]=R;for(Q[W-1]=R,R=Z=0;R<16;R++)for(q[R]=Z,H=0;H<1<<E[R];H++)N[Z++]=R;for(Z>>=7;R<c;R++)for(q[R]=Z<<7,H=0;H<1<<E[R]-7;H++)N[256+Z++]=R;for(z=0;z<=h;z++)et[z]=0;for(H=0;H<=143;)x[2*H+1]=8,H++,et[8]++;for(;H<=255;)x[2*H+1]=9,H++,et[9]++;for(;H<=279;)x[2*H+1]=7,H++,et[7]++;for(;H<=287;)x[2*H+1]=8,H++,et[8]++;for(pt(x,A+1,et),H=0;H<c;H++)F[2*H+1]=5,F[2*H]=rt(H,5);O=new j(x,w,r+1,A,h),M=new j(F,E,0,c,h),Y=new j(new Array(0),v,0,g,I)}(),G=!0),k.l_desc=new L(k.dyn_ltree,O),k.d_desc=new L(k.dyn_dtree,M),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,Z,et=0;0<k.level?(k.strm.data_type===2&&(k.strm.data_type=function(_){var it,ft=4093624447;for(it=0;it<=31;it++,ft>>>=1)if(1&ft&&_.dyn_ltree[2*it]!==0)return i;if(_.dyn_ltree[18]!==0||_.dyn_ltree[20]!==0||_.dyn_ltree[26]!==0)return s;for(it=32;it<r;it++)if(_.dyn_ltree[2*it]!==0)return s;return i}(k)),mt(k,k.l_desc),mt(k,k.d_desc),et=function(_){var it;for(B(_,_.dyn_ltree,_.l_desc.max_code),B(_,_.dyn_dtree,_.d_desc.max_code),mt(_,_.bl_desc),it=g-1;3<=it&&_.bl_tree[2*D[it]+1]===0;it--);return _.opt_len+=3*(it+1)+5+5+4,it}(k),R=k.opt_len+3+7>>>3,(Z=k.static_len+3+7>>>3)<=R&&(R=Z)):R=Z=z+5,z+4<=R&&H!==-1?b(k,H,z,W):k.strategy===4||Z===R?(K(k,2+(W?1:0),3),yt(k,x,F)):(K(k,4+(W?1:0),3),function(_,it,ft,ht){var Pt;for(K(_,it-257,5),K(_,ft-1,5),K(_,ht-4,4),Pt=0;Pt<ht;Pt++)K(_,_.bl_tree[2*D[Pt]+1],3);J(_,_.dyn_ltree,it-1),J(_,_.dyn_dtree,ft-1)}(k,k.l_desc.max_code+1,k.d_desc.max_code+1,et+1),yt(k,k.dyn_ltree,k.dyn_dtree)),nt(k),W&<(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*P(H)]++),k.last_lit===k.lit_bufsize-1},t._tr_align=function(k){K(k,2,3),$(k,f,x),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,l,t){"use strict";l.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,l,t){(function(e){(function(i,s){"use strict";if(!i.setImmediate){var n,o,a,r,A=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(m){process.nextTick(function(){I(m)})}:function(){if(i.postMessage&&!i.importScripts){var m=!0,C=i.onmessage;return i.onmessage=function(){m=!1},i.postMessage("","*"),i.onmessage=C,m}}()?(r="setImmediate$"+Math.random()+"$",i.addEventListener?i.addEventListener("message",f,!1):i.attachEvent("onmessage",f),function(m){i.postMessage(r+m,"*")}):i.MessageChannel?((a=new MessageChannel).port1.onmessage=function(m){I(m.data)},function(m){a.port2.postMessage(m)}):p&&"onreadystatechange"in p.createElement("script")?(o=p.documentElement,function(m){var C=p.createElement("script");C.onreadystatechange=function(){I(m),C.onreadystatechange=null,o.removeChild(C),C=null},o.appendChild(C)}):function(m){setTimeout(I,0,m)},h.setImmediate=function(m){typeof m!="function"&&(m=new Function(""+m));for(var C=new Array(arguments.length-1),y=0;y<C.length;y++)C[y]=arguments[y+1];var w={callback:m,args:C};return c[A]=w,n(A),A++},h.clearImmediate=u}function u(m){delete c[m]}function I(m){if(g)setTimeout(I,0,m);else{var C=c[m];if(C){g=!0;try{(function(y){var w=y.callback,E=y.args;switch(E.length){case 0:w();break;case 1:w(E[0]);break;case 2:w(E[0],E[1]);break;case 3:w(E[0],E[1],E[2]);break;default:w.apply(s,E)}})(C)}finally{u(m),g=!1}}}}function f(m){m.source===i&&typeof m.data=="string"&&m.data.indexOf(r)===0&&I(+m.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 ol={};Hi(ol,{default:()=>Ks});module.exports=Pa(ol);var X=require("obsidian");Qt();var bt=require("obsidian");var Bt=require("obsidian");Qt();function Ri(d){let l=(d.dateDisplayTimezone||"").trim();return l?{timeZone:l}:{}}function Xt(d,l){try{return new Intl.DateTimeFormat(void 0,l).format(new Date(d))}catch{let{timeZone:t,...e}=l;return new Intl.DateTimeFormat(void 0,e).format(new Date(d))}}function Zt(d,l){let t=Ri(l);switch(l.dateDisplayFormat??"locale"){case"iso":return io(d,l,!0);case"us":return Xt(d,{...t,month:"numeric",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});case"eu":return Xt(d,{...t,day:"numeric",month:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",hourCycle:"h23"});case"long":return Xt(d,{...t,dateStyle:"full",timeStyle:"short"});case"locale":default:return Xt(d,{...t,dateStyle:"medium",timeStyle:"short"})}}function to(d,l){let t=Ri(l);switch(l.dateDisplayFormat??"locale"){case"iso":return io(d,l,!1);case"us":return Xt(d,{...t,month:"numeric",day:"numeric",year:"numeric"});case"eu":return Xt(d,{...t,day:"numeric",month:"numeric",year:"numeric"});case"long":return Xt(d,{...t,dateStyle:"full"});case"locale":default:{let e=new Date,i=new Date(d).getFullYear()===e.getFullYear();return Xt(d,i?{...t,month:"short",day:"numeric"}:{...t,month:"short",day:"numeric",year:"numeric"})}}}function eo(d,l){let t=Ri(l),e=l.dateDisplayFormat==="iso"||l.dateDisplayFormat==="eu";return Xt(d,{...t,hour:e?"2-digit":"numeric",minute:"2-digit",...e?{hourCycle:"h23"}:{}})}function io(d,l,t){let e=Ri(l),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 ke(d,l,t){let e=d.createSpan({cls:"stashpad-count-badge"});t&&e.addClass("is-expanded"),e.setText(l>99?"99+":String(l))}var ui={pinned:{label:"Pinned",icon:"pin"},shared:{label:"Shared",icon:"users"},tasks:{label:"Tasks",icon:"check-circle-2"}},Oi=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 ae}getDisplayText(){return"Stashpad panels"}getIcon(){return"panel-left"}async onOpen(){this.render(),this.registerEvent(this.app.metadataCache.on("changed",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("rename",()=>this.scheduleRender())),this.registerEvent(this.app.vault.on("delete",()=>this.scheduleRender())),this.registerEvent(this.app.workspace.on("active-leaf-change",t=>{t&&t.view.getViewType()===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(ui)){let g=ui[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 A=t.createDiv({cls:"stashpad-panels-body"});this.activePanel==="pinned"?this.renderPinnedPanel(A):this.activePanel==="shared"?this.renderSharedPanel(A):this.activePanel==="tasks"&&this.renderTasksPanel(A)}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new 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 A=new Map;a.forEach((p,h)=>{let u=A.get(p.folder);u||(u=[],A.set(p.folder,u)),u.push({pin:p,idx:h})});let c=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,g=Array.from(A.keys());c&&A.has(c)&&(g.splice(g.indexOf(c),1),g.unshift(c));for(let p of g){let h=p.split("/").pop()||p,u=e.createDiv({cls:"stashpad-pinned-group-header"});p===c&&u.addClass("is-active-folder"),u.createSpan({cls:"stashpad-pinned-group-name",text:h});let I=A.get(p)??[];for(let{pin:f,idx:m}of I)this.renderPinnedRow(e,f,m)}}renderPinnedRow(t,e,i){let s=this.findFileFor(e);if(!s)return;let n=this.app.metadataCache.getFileCache(s)?.frontmatter??{},o=this.titleFromFile(s),a=typeof n.color=="string"?n.color:null,r=n.completed===!0,A=this.childrenOf(e.folder,e.id).length,c=A>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",m=>{m.dataTransfer?.setData("text/plain",String(i)),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),p.addClass("is-dragging")}),p.addEventListener("dragend",()=>p.removeClass("is-dragging")),p.addEventListener("dragover",m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="move");let C=p.getBoundingClientRect(),y=m.clientY-C.top<C.height/2;p.toggleClass("drop-before",y),p.toggleClass("drop-after",!y)}),p.addEventListener("dragleave",()=>{p.removeClass("drop-before"),p.removeClass("drop-after")}),p.addEventListener("drop",m=>{m.preventDefault(),p.removeClass("drop-before"),p.removeClass("drop-after");let C=parseInt(m.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===i)return;let y=p.getBoundingClientRect(),w=m.clientY-y.top<y.height/2;this.reorderPin(C,w?i:i+1)});let h=p.createSpan({cls:"stashpad-pinned-toggle"});c&&(ke(h,A,g),h.onclick=m=>{m.stopPropagation();let C=`${e.folder}|${e.id}`;this.expanded.has(C)?this.expanded.delete(C):this.expanded.add(C),this.render()});let u=p.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(u,c?"folder-tree":"file-text"),a&&(u.style.color=a);let I=p.createSpan({cls:"stashpad-pinned-label",text:o});I.onclick=()=>this.openPinFromPanel(e);let f=e.folder.split("/").pop()||e.folder;if(p.createSpan({cls:"stashpad-pinned-folder",text:f}),p.oncontextmenu=m=>{m.preventDefault();let C=new Bt.Menu;C.addItem(y=>y.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>{this.plugin.unpinNote(e)})),C.showAtMouseEvent(m)},c&&g){let m=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinnedSubtree(m,e.folder,e.id,1)}}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],A;!a&&!r?A=Date.now():a?r?A=(a.pinnedAt+r.pinnedAt)/2:A=a.pinnedAt+1e3:A=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=A})}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 A=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}`),u=t.createDiv({cls:"stashpad-pinned-subrow"});c&&u.addClass("is-completed"),u.style.paddingLeft=`${s*16}px`;let I=u.createSpan({cls:"stashpad-pinned-toggle"});p&&(ke(I,g,h),I.onclick=C=>{C.stopPropagation();let y=`${e}|${r}`;this.expanded.has(y)?this.expanded.delete(y):this.expanded.add(y),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,Bt.setIcon)(f,"file-text"),A&&(f.style.color=A);let m=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(o)});m.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===T&&(a==null||a===T)){if(o.id===T)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter,a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=o?.created??"",A=a?.created??"";return r.localeCompare(A)}),i}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}async openSearchFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.openSearchModal=="function"&&t.openSearchModal()}async openLogFromPanel(){let t=this.app.vault.adapter,e=this.plugin.pluginPrivatePath("log.jsonl");if(!await t.exists(e)){new Bt.Notice("No log yet \u2014 make some changes first.");return}let i=await t.read(e),{LogModal:s}=await Promise.resolve().then(()=>(Ht(),gi));new s(this.app,i,e).open()}openNotificationsFromPanel(){this.app.commands?.executeCommandById?.("stashpad:stashpad-open-notification-history")}async openHomeFromPanel(){let t=await this.resolveTargetStashpad();t&&typeof t.navigateTo=="function"&&t.navigateTo(T)}async openPinFromPanel(t){await this.plugin.revealNoteByRef(t.folder,t.id)}async resolveTargetStashpad(){let t=this.plugin.lastActiveStashpadLeaf;if(t&&t.view.getViewType()===ct)return this.app.workspace.revealLeaf(t),t.view;let e=this.findActiveStashpad();if(e)return e;let i=this.app.workspace.getLeavesOfType(ct);return i.length>0?(this.app.workspace.revealLeaf(i[0]),i[0].view):(await this.plugin.activateView({reveal:!0}),this.findActiveStashpad())}findActiveStashpad(){let t=this.app.workspace.activeLeaf;return t&&t.view.getViewType()===ct?t.view:null}renderSharedPanel(t){let e=t.createDiv({cls:"stashpad-panel-shared"}),i=(this.plugin.settings.authorId??"").trim();if(!i){e.createDiv({cls:"stashpad-shared-empty"}).setText("Set an author name in Stashpad settings to populate Shared.");return}let s=this.collectSharedNotes(i),n=new Map;for(let c of s){let g=c.authorId;g&&!n.has(g)&&n.set(g,c.authorDisplay||g)}let o=e.createDiv({cls:"stashpad-shared-filters"}),a=(c,g,p)=>{let 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,u]of n){let I=c.createEl("option",{text:u});I.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 A=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(A.length===0){e.createDiv({cls:"stashpad-shared-empty"}).setText("No shared notes match the current filters.");return}for(let c of A){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 u=c.folder.split("/").pop()||c.folder;g.createSpan({cls:"stashpad-pinned-folder",text:u}),c.authorDisplay&&g.createSpan({cls:"stashpad-shared-meta"}).setText(c.authorId===i?`you \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:`by ${c.authorDisplay}${c.contributorCount>0?` \xB7 ${c.contributorCount} contributor${c.contributorCount===1?"":"s"}`:""}`)}}collectSharedNotes(t){let e=this.plugin.discoverStashpadFolders(),i=new Set(e),s=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};r.id===T&&s.set(a,this.extractAuthorId(r.author))}let n=[];for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!i.has(a)||a.endsWith("/_authors")||o.path.includes("/_authors/"))continue;let r=this.app.metadataCache.getFileCache(o)?.frontmatter??{};if(typeof r.id!="string"||r.id===T)continue;let A=this.extractAuthorId(r.author),c=Array.isArray(r.contributors)?r.contributors.filter(C=>typeof C=="string"):[],g=s.get(a)??null;if(!(c.length>0||g===t&&(A!==null&&A!==t)))continue;let f=this.titleFromFile(o),m=typeof r.color=="string"?r.color:null;n.push({file:o,folder:a,id:r.id,title:f,color:m,authorId:A,authorDisplay:this.extractAuthorDisplay(r.author)||(A??""),contributorCount:c.length})}return n.sort((o,a)=>{let r=this.app.metadataCache.getFileCache(o.file)?.frontmatter??{},A=this.app.metadataCache.getFileCache(a.file)?.frontmatter??{},c=r.modified??r.created??"";return(A.modified??A.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=M=>!!s&&M.assignedTo.some(Y=>Y.id===s),o=M=>{let Y=this.taskAssignFilter;if(Y.startsWith("person:")){let q=Y.slice(7);return M.assignedTo.some(j=>j.id===q)}switch(Y){case"mine":return n(M);case"others":return M.assignedTo.length>0&&!n(M);case"byme":return!!s&&M.assignedBy?.id===s;case"unassigned":return M.assignedTo.length===0;default:return!0}},a=new Map;for(let M of i){for(let Y of M.assignedTo)Y.id!==s&&a.set(Y.id,Y.name);M.assignedBy&&M.assignedBy.id!==s&&a.set(M.assignedBy.id,M.assignedBy.name)}let r=[...a.entries()].map(([M,Y])=>({id:M,name:Y})).sort((M,Y)=>M.name.localeCompare(Y.name)),A=e.createDiv({cls:"stashpad-task-assign-bar"});A.createSpan({cls:"stashpad-task-assign-label",text:"Assignment"});let c=A.createEl("select",{cls:"stashpad-task-assign-select"}),g=M=>{let Y={all:"Everyone",mine:"Assigned to me",others:"Assigned to others",byme:"Assigned by me",unassigned:"Unassigned"};return M.startsWith("person:")?a.get(M.slice(7))??"Person":Y[M]??M},p=M=>{let Y=c.createEl("option",{text:g(M),value:M});this.taskAssignFilter===M&&(Y.selected=!0)};for(let M of["all","mine","others","byme","unassigned"])p(M);if(r.length>0){let M=c.createEl("optgroup");M.setAttr("label","By person");for(let Y of r){let q=M.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(M=>M.folder))].sort((M,Y)=>M.localeCompare(Y));this.taskFolderFilter!=="all"&&!h.includes(this.taskFolderFilter)&&(this.taskFolderFilter="all");let u=e.createDiv({cls:"stashpad-task-assign-bar"});u.createSpan({cls:"stashpad-task-assign-label",text:"Folder"});let I=u.createEl("select",{cls:"stashpad-task-assign-select"}),f=I.createEl("option",{text:"All folders",value:"all"});this.taskFolderFilter==="all"&&(f.selected=!0);for(let M of h){let Y=I.createEl("option",{text:M.split("/").pop()||M,value:M});this.taskFolderFilter===M&&(Y.selected=!0)}I.onchange=()=>{this.taskFolderFilter=I.value,this.render()};let m=M=>this.taskFolderFilter==="all"||M.folder===this.taskFolderFilter,C=i.filter(M=>o(M)&&m(M));if(C.length===0){e.createDiv({cls:"stashpad-tasks-empty"}).setText("No tasks match the current filters.");return}let y=new Date;y.setHours(0,0,0,0);let w=y.getTime(),E=w+24*60*60*1e3,v={overdue:[],today:[],upcoming:[],nodate:[],completed:[]};for(let M of C){if(M.completed){v.completed.push(M);continue}if(M.due==null){v.nodate.push(M);continue}M.due<w?v.overdue.push(M):M.due<E?v.today.push(M):v.upcoming.push(M)}let D=(M,Y)=>M.due==null&&Y.due==null?M.title.localeCompare(Y.title):M.due==null?1:Y.due==null?-1:M.due-Y.due,x=[{key:"overdue",label:"Overdue",icon:"alert-circle"},{key:"today",label:"Due today",icon:"calendar-clock"},{key:"upcoming",label:"Upcoming",icon:"calendar"},{key:"nodate",label:"No date",icon:"inbox"},{key:"completed",label:"Completed",icon:"check-circle-2"}],F=e.createDiv({cls:"stashpad-task-filters"}),N=C.length,Q=(M,Y,q)=>{let j=F.createEl("button",{cls:"stashpad-task-filter"});this.taskFilter===M&&j.addClass("is-active"),j.createSpan({cls:"stashpad-task-filter-label",text:Y}),j.createSpan({cls:"stashpad-task-filter-count",text:String(q)}),j.onclick=()=>{this.taskFilter=M,this.render()}};Q("all","All",N),Q("overdue","Overdue",v.overdue.length),Q("today","Today",v.today.length),Q("upcoming","Upcoming",v.upcoming.length),Q("nodate","No date",v.nodate.length),Q("completed","Done",v.completed.length);let S=this.taskFilter==="all"?x:x.filter(M=>M.key===this.taskFilter),O=!1;for(let M of S){let Y=v[M.key];if(Y.length!==0){if(O=!0,Y.sort(M.key==="completed"?(q,j)=>D(j,q):D),this.taskFilter==="all"){let q=e.createDiv({cls:`stashpad-task-section-header is-${M.key}`});(0,Bt.setIcon)(q.createSpan({cls:"stashpad-task-section-icon"}),M.icon),q.createSpan({cls:"stashpad-task-section-name",text:M.label}),q.createSpan({cls:"stashpad-task-section-count",text:String(Y.length)})}for(let q of Y)this.renderTaskRow(e,q,M.key==="today")}}if(!O&&this.taskFilter!=="all"){e.createDiv({cls:"stashpad-tasks-empty"}).setText(`Nothing in "${S[0]?.label??this.taskFilter}".`);return}O||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 A of e.assignedTo){let c=r.createSpan({cls:"stashpad-task-assignee"});a&&A.id===a&&c.addClass("is-me"),c.setText(this.initials(A.name)),c.title=a&&A.id===a?`${A.name} (you)`:A.name}}s.oncontextmenu=a=>{a.preventDefault();let r=new Bt.Menu;r.addItem(A=>A.setTitle("Open").setIcon("arrow-right").onClick(()=>{this.openTaskFromPanel(e.folder,e.id)})),r.showAtMouseEvent(a)}}formatDueShort(t,e){return e?eo(t,this.plugin.settings):to(t,this.plugin.settings)}async openTaskFromPanel(t,e){await this.plugin.revealNoteByRef(t,e)}async toggleTaskCompleted(t){try{await this.app.fileManager.processFrontMatter(t.file,e=>{e.completed=e.completed!==!0})}catch(e){new Bt.Notice(`Couldn't update task: ${e.message}`);return}this.scheduleRender()}initials(t){let e=t.trim().split(/\s+/).filter(Boolean);return e.length===0?"?":e.length===1?e[0].slice(0,2).toUpperCase():(e[0][0]+e[e.length-1][0]).toUpperCase()}collectTasks(){let t=this.plugin.discoverStashpadFolders(),e=new Set(t),i=[];for(let s of this.app.vault.getMarkdownFiles()){let n=s.parent?.path?.replace(/\/+$/,"")??"";if(!e.has(n))continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a||a===T)continue;let r=o.completed===!0,A=Me(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)}!A&&!r&&g==null&&!c||i.push({file:s,folder:n,id:a,title:this.titleFromFile(s),task:A,completed:r,due:g,dueRaw:c,color:typeof o.color=="string"?o.color:null,assignedTo:Ee(o),assignedBy:le(o.assignedBy)})}return i}};async function Ki(d){let l=d.workspace.getLeavesOfType(ae);if(l.length>0){d.workspace.revealLeaf(l[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:ae,active:!0}),d.workspace.revealLeaf(t)}var _o=require("obsidian");Qt();var V=require("obsidian");fi();var $i=require("obsidian");Qt();var Ge=class extends $i.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!=="/"&&ii.has(o.name))){o.path!=="/"&&i(o.path)&&s.push(o);for(let a of o.children)a instanceof $i.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()}};Qt();Ht();var De=require("obsidian"),nn={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."}},za={info:4e3,success:4e3,warning:6e3,error:1e4},po=5e3,Wi=class{constructor(l){this.app=l;this.history=[];this.nextId=1;this.historyLimit=po;this.changeListeners=new Set;this.muted=new Set;this.defaultAuthorId=null}setDefaultAuthorId(l){this.defaultAuthorId=l||null}show(l){let t=l.kind??"info",e=l.category??"system",i={id:this.nextId++,ts:Date.now(),message:l.message,kind:t,category:e,authorId:l.authorId??this.defaultAuthorId??void 0,affectedIds:l.affectedIds?l.affectedIds.slice():[],affectedPaths:l.affectedPaths?l.affectedPaths.slice():[],affectedAuthorIds:l.affectedAuthorIds?l.affectedAuthorIds.slice():[],folder:l.folder,actionLabels:(l.actions??[]).map(o=>o.label)};if(this.pushHistory(i),this.muted.has(e))return null;let s=this.buildContent(l,t),n=l.duration??za[t];return new De.Notice(s,n)}onChange(l){return this.changeListeners.add(l),()=>this.changeListeners.delete(l)}recent(){return this.history.slice().reverse()}clearHistory(){this.history=[],this.emit()}setMuted(l,t){t?this.muted.add(l):this.muted.delete(l)}isMuted(l){return this.muted.has(l)}loadMutedFromList(l){this.muted=new Set(l)}mutedList(){return Array.from(this.muted)}loadHistory(l){let t=this.applyLimit(l.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(l){this.historyLimit=Number.isFinite(l)?l:po,this.history=this.applyLimit(this.history),this.emit()}applyLimit(l){return this.historyLimit<=0||l.length<=this.historyLimit?l:l.slice(l.length-this.historyLimit)}pushHistory(l){this.history.push(l),this.history=this.applyLimit(this.history),this.emit()}emit(){for(let l of this.changeListeners)try{l()}catch(t){console.warn("[Stashpad] notification listener failed",t)}}buildContent(l,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=l.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),l.actions&&l.actions.length>0){let o=document.createElement("div");o.className="stashpad-notice-actions";for(let a of l.actions){let r=document.createElement("button");r.className="stashpad-notice-action",r.textContent=a.label,r.addEventListener("click",A=>{if(A.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 Xi(d,l,t){let e=d.vault.getAbstractFileByPath(l);if(!(e instanceof De.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=De.Platform.isMacOS?"Finder":De.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?.(l);a&&n?.showItemInFolder&&n.showItemInFolder(a)}catch(n){console.warn("[Stashpad] showItemInFolder failed",n)}}})}return i}var on=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function mi(d){if(!d)return"(none)";let l=d.replace(/\bMod\b/g,on?"Cmd":"Ctrl");return on&&(l=l.replace(/\bAlt\b/g,"Option")),l}function go(d,l,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 A=!!r.code&&(/^Key[A-Z]$/.test(r.code)||/^Digit\d$/.test(r.code));if((r.key==="Dead"||r.key==="Process"||r.key==="Unidentified")&&!A)return;if(r.preventDefault(),r.stopPropagation(),r.key==="Backspace"&&!r.metaKey&&!r.ctrlKey&&!r.altKey&&!r.shiftKey){n();return}let c=[];on?(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=Va(r.key,r.code);if(!g||c.length===0&&!t.allowSingleKey)return;c.push(g);let p=c.join("+");s=!0,n(),l(p)},a=()=>n();return d.addEventListener("keydown",o,!0),d.addEventListener("blur",a),n}function Va(d,l){if(!d)return"";if(l){let t=/^Key([A-Z])$/.exec(l);if(t)return t[1];let e=/^Digit(\d)$/.exec(l);if(e)return e[1]}return d.length===1?d.toUpperCase():d}Ue();Lt();function be(d,l,t,e){function i(s){return s instanceof t?s:new t(function(n){n(s)})}return new(t||(t=Promise))(function(s,n){function o(A){try{r(e.next(A))}catch(c){n(c)}}function a(A){try{r(e.throw(A))}catch(c){n(c)}}function r(A){A.done?s(A.value):i(A.value).then(o,a)}r((e=e.apply(d,l||[])).next())})}var Ct=class{constructor(){this.mutex=Promise.resolve()}lock(){let l=()=>{};return this.mutex=this.mutex.then(()=>new Promise(l)),new Promise(t=>{l=t})}dispatch(l){return be(this,void 0,void 0,function*(){let t=yield this.lock();try{return yield Promise.resolve(l())}finally{t()}})}},an;function $a(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global}var cn=$a(),rn=(an=cn.Buffer)!==null&&an!==void 0?an:null,Wa=cn.TextEncoder?new cn.TextEncoder:null;function Bo(d,l){return(d&15)+(d>>6|d>>3&8)<<4|(l&15)+(l>>6|l>>3&8)}function Qo(d,l){let t=l.length>>1;for(let e=0;e<t;e++){let i=e<<1;d[e]=Bo(l.charCodeAt(i),l.charCodeAt(i+1))}}function Xa(d,l){if(d.length!==l.length*2)return!1;for(let t=0;t<l.length;t++){let e=t<<1;if(l[t]!==Bo(d.charCodeAt(e),d.charCodeAt(e+1)))return!1}return!0}var uo=87,Io=48;function dn(d,l,t){let e=0;for(let i=0;i<t;i++){let s=l[i]>>>4;d[e++]=s>9?s+uo:s+Io,s=l[i]&15,d[e++]=s>9?s+uo:s+Io}return String.fromCharCode.apply(null,d)}var jt=rn!==null?d=>{if(typeof d=="string"){let l=rn.from(d,"utf8");return new Uint8Array(l.buffer,l.byteOffset,l.length)}if(rn.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 Wa.encode(d);if(ArrayBuffer.isView(d))return new Uint8Array(d.buffer,d.byteOffset,d.byteLength);throw new Error("Invalid data type!")},Jt="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Bi=new Uint8Array(256);for(let d=0;d<Jt.length;d++)Bi[Jt.charCodeAt(d)]=d;function fo(d,l=!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=Jt.charAt(o>>18&63)+Jt.charAt(o>>12&63)+Jt.charAt(o>>6&63)+Jt.charAt(o&63);i.push(a)}if(e===1){let n=d[t-1],o=Jt.charAt(n>>2),a=Jt.charAt(n<<4&63);i.push(`${o}${a}`),l&&i.push("==")}else if(e===2){let n=(d[t-2]<<8)+d[t-1],o=Jt.charAt(n>>10),a=Jt.charAt(n>>4&63),r=Jt.charAt(n<<2&63);i.push(`${o}${a}${r}`),l&&i.push("=")}return i.join("")}function Za(d){let l=Math.floor(d.length*.75),t=d.length;return d[t-1]==="="&&(l-=1,d[t-2]==="="&&(l-=1)),l}function _a(d){let l=Za(d),t=d.length,e=new Uint8Array(l),i=0;for(let s=0;s<t;s+=4){let n=Bi[d.charCodeAt(s)],o=Bi[d.charCodeAt(s+1)],a=Bi[d.charCodeAt(s+2)],r=Bi[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 Zi=16*1024,Ci=4,ja=new Ct,ln=new Map;function yo(d,l){return be(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=(E,v=0)=>{e.set(E,v)},n=()=>e,o=()=>t.exports,a=E=>{t.exports.Hash_SetMemorySize(E);let v=t.exports.Hash_GetBuffer(),D=t.exports.memory.buffer;e=new Uint8Array(D,v,E)},r=()=>new DataView(t.exports.memory.buffer).getUint32(t.exports.STATE_SIZE,!0),A=ja.dispatch(()=>be(this,void 0,void 0,function*(){if(!ln.has(d.name)){let v=_a(d.data),D=WebAssembly.compile(v);ln.set(d.name,D)}let E=yield ln.get(d.name);t=yield WebAssembly.instantiate(E,{})})),c=()=>be(this,void 0,void 0,function*(){t||(yield A);let E=t.exports.Hash_GetBuffer(),v=t.exports.memory.buffer;e=new Uint8Array(v,E,Zi)}),g=(E=null)=>{i=!0,t.exports.Hash_Init(E)},p=E=>{let v=0;for(;v<E.length;){let D=E.subarray(v,v+Zi);v+=D.length,e.set(D),t.exports.Hash_Update(D.length)}},h=E=>{if(!i)throw new Error("update() called before init()");let v=jt(E);p(v)},u=new Uint8Array(l*2),I=(E,v=null)=>{if(!i)throw new Error("digest() called before init()");return i=!1,t.exports.Hash_Final(v),E==="binary"?e.slice(0,l):dn(u,e,l)},f=()=>{if(!i)throw new Error("save() can only be called after init() and before digest()");let E=t.exports.Hash_GetState(),v=r(),D=t.exports.memory.buffer,x=new Uint8Array(D,E,v),F=new Uint8Array(Ci+v);return Qo(F,d.hash),F.set(x,Ci),F},m=E=>{if(!(E instanceof Uint8Array))throw new Error("load() expects an Uint8Array generated by save()");let v=t.exports.Hash_GetState(),D=r(),x=Ci+D,F=t.exports.memory.buffer;if(E.length!==x)throw new Error(`Bad state length (expected ${x} bytes, got ${E.length})`);if(!Xa(d.hash,E.subarray(0,Ci)))throw new Error("This state was written by an incompatible hash implementation");let N=E.subarray(Ci);new Uint8Array(F,v,D).set(N),i=!0},C=E=>typeof E=="string"?E.length<Zi/4:E.byteLength<Zi,y=C;switch(d.name){case"argon2":case"scrypt":y=()=>!0;break;case"blake2b":case"blake2s":y=(E,v)=>v<=512&&C(E);break;case"blake3":y=(E,v)=>v===0&&C(E);break;case"xxhash64":case"xxhash3":case"xxhash128":case"crc64":y=()=>!1;break}let w=(E,v=null,D=null)=>{if(!y(E,v))return g(v),h(E),I("hex",D);let x=jt(E);return e.set(x),t.exports.Hash_Calculate(x.length,v,D),dn(u,e,l)};return yield c(),{getMemory:n,writeMemory:s,getExports:o,setMemorySize:a,init:g,update:h,digest:I,save:f,load:m,calculate:w,hashLength:l}})}var Nl=new Ct;var tr="argon2",er="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",ir="e4cdc523",sr={name:tr,data:er,hash:ir},nr="blake2b",or="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=",ar="c6f286e6",rr={name:nr,data:or,hash:ar},Ml=new Ct;function mo(d){return!Number.isInteger(d)||d<8||d>512||d%8!==0?new Error("Invalid variant! Valid values: 8, 16, ..., 512"):null}function lr(d,l){return d|l<<16}function hn(d=512,l=null){if(mo(d))return Promise.reject(mo(d));let t=null,e=d;if(l!==null){if(t=jt(l),t.length>64)return Promise.reject(new Error("Max key length is 64 bytes"));e=lr(d,t.length)}let i=d/8;return yo(rr,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 Ar(d,l,t){let e=[`m=${l.memorySize}`,`t=${l.iterations}`,`p=${l.parallelism}`].join(",");return`$argon2${l.hashType}$v=19$${e}$${fo(d,!1)}$${fo(t,!1)}`}var Co=new DataView(new ArrayBuffer(4));function _t(d){return Co.setInt32(0,d,!0),new Uint8Array(Co.buffer)}function An(d,l,t){return be(this,void 0,void 0,function*(){if(t<=64){let a=yield hn(t*8);return a.update(_t(t)),a.update(l),a.digest("binary")}let e=Math.ceil(t/32)-2,i=new Uint8Array(t);d.init(),d.update(_t(t)),d.update(l);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 hn(n*8),o.update(s),s=o.digest("binary"),i.set(s.subarray(0,n),e*32),i})}function cr(d){switch(d){case"d":return 0;case"i":return 1;default:return 2}}function dr(d){return be(this,void 0,void 0,function*(){var l;let{parallelism:t,iterations:e,hashLength:i}=d,s=jt(d.password),n=jt(d.salt),o=19,a=cr(d.hashType),{memorySize:r}=d,A=jt((l=d.secret)!==null&&l!==void 0?l:""),[c,g]=yield Promise.all([yo(sr,1024),hn(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(A.length)),g.update(A),g.update(_t(0));let I=Math.floor(r/(t*4))*4,f=new Uint8Array(72),m=g.digest("binary");f.set(m);for(let w=0;w<t;w++){f.set(_t(0),64),f.set(_t(w),68);let E=w*I,v=yield An(g,f,1024);c.writeMemory(v,E*1024),E+=1,f.set(_t(1),64),v=yield An(g,f,1024),c.writeMemory(v,E*1024)}let C=new Uint8Array(1024);Qo(C,c.calculate(new Uint8Array([]),r));let y=yield An(g,C,i);if(d.outputType==="hex"){let w=new Uint8Array(i*2);return dn(w,y,i)}return d.outputType==="encoded"?Ar(n,d,y):y})}var hr=d=>{var l;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=jt(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=jt(d.salt),d.salt.length<8)throw new Error("Salt should be at least 8 bytes long");if(d.secret=jt((l=d.secret)!==null&&l!==void 0?l:""),!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 pn(d){return be(this,void 0,void 0,function*(){return hr(d),dr(Object.assign(Object.assign({},d),{hashType:"id"}))})}var Tl=new Ct;var Hl=new Ct;var Pl=new Ct;var Ul=new Ct;var Rl=new Uint8Array(8);var Gl=new Ct;var Ll=new Ct;var Jl=new Ct;var ql=new Ct;var Ol=new Ct;var Kl=new Ct;var Yl=new Ct;var zl=new Ct;var Vl=new Ct;var $l=new Ct;var Wl=new Ct;var Xl=new Uint8Array(8);var Zl=new Ct;var _l=new Uint8Array(8);var jl=new Ct;var tA=new Uint8Array(8);var eA=new Ct;var iA=new Ct;var sA=new Ct;Ht();var qt=new Uint8Array([83,84,65,83,72,69,78,67]),In=2,fn=1,mn=2,vo=3,pr=32,Le=12,gn=32,gr=6e5,ur=47104,Ir=3,fr=1,vt=d=>d;function Ot(d){if(d.length<qt.length+1)return!1;for(let l=0;l<qt.length;l++)if(d[l]!==qt[l])return!1;return!0}function Eo(d,l,t){d[l]=t>>>24&255,d[l+1]=t>>>16&255,d[l+2]=t>>>8&255,d[l+3]=t&255}function wo(d,l){return d[l]*16777216+(d[l+1]<<16)+(d[l+2]<<8)+d[l+3]}async function un(d,l,t){if(t.id===mn)return await pn({password:d,salt:l,parallelism:t.c,iterations:t.b,memorySize:t.a,hashLength:gn,outputType:"binary"});if(t.id===fn){let e=await crypto.subtle.importKey("raw",vt(new TextEncoder().encode(d)),"PBKDF2",!1,["deriveBits"]),i=await crypto.subtle.deriveBits({name:"PBKDF2",salt:vt(l),iterations:t.a,hash:"SHA-256"},e,gn*8);return new Uint8Array(i)}throw new Error(`Unsupported KDF id (${t.id}).`)}async function _i(d){return crypto.subtle.importKey("raw",vt(d),{name:"AES-GCM"},!1,["encrypt","decrypt"])}var Fo={argon2id:{label:"Argon2id",strong:!0},pbkdf2:{label:"PBKDF2 (fallback)",strong:!1}};async function Je(d,l){let t=crypto.getRandomValues(new Uint8Array(pr)),e=crypto.getRandomValues(new Uint8Array(Le)),i,s,n;try{i={id:mn,a:ur,b:Ir,c:fr},n=await un(l,t,i),s="argon2id"}catch(c){console.warn("[Stashpad] Argon2id unavailable \u2014 encrypting with PBKDF2 fallback.",c),i={id:fn,a:gr,b:0,c:0},n=await un(l,t,i),s="pbkdf2"}let o=ko(i,t,e),a=await _i(n),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:vt(e),additionalData:vt(o)},a,vt(d))),A=new Uint8Array(o.length+r.length);return A.set(o,0),A.set(r,o.length),{data:A,kdf:s}}var Qi=null;async function ji(){if(Qi!==null)return Qi;try{await pn({password:"x",salt:new Uint8Array(16),parallelism:1,iterations:1,memorySize:8,hashLength:16,outputType:"binary"}),Qi=!0}catch{Qi=!1}return Qi}function ko(d,l,t){let e=new Uint8Array(qt.length+1+1+4+4+1+1+l.length+t.length),i=0;return e.set(qt,i),i+=qt.length,e[i++]=In,e[i++]=d.id,Eo(e,i,d.a),i+=4,Eo(e,i,d.b),i+=4,e[i++]=d.c,e[i++]=l.length,e.set(l,i),i+=l.length,e.set(t,i),i+=t.length,e}async function te(d,l){if(!Ot(d))throw new Error("Not an encrypted Stashpad file.");let t=d[qt.length];if(t===1)return mr(d,l);if(t!==In)throw new Error(`Unsupported encrypted .stash version (${t}).`);let e=qt.length+1,i={id:d[e++],a:0,b:0,c:0};if(i.a=wo(d,e),e+=4,i.b=wo(d,e),e+=4,i.c=d[e++],i.id===mn){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===fn&&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+Le);e+=Le;let a=d.slice(0,e),r=d.slice(e),A=await un(l,n,i),c=await _i(A),g=await crypto.subtle.decrypt({name:"AES-GCM",iv:vt(o),additionalData:vt(a)},c,vt(r));return new Uint8Array(g)}async function mr(d,l){let t=qt.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",vt(new TextEncoder().encode(l)),"PBKDF2",!1,["deriveKey"]),o=await crypto.subtle.deriveKey({name:"PBKDF2",salt:vt(e),iterations:21e4,hash:"SHA-256"},n,{name:"AES-GCM",length:256},!1,["decrypt"]),a=await crypto.subtle.decrypt({name:"AES-GCM",iv:vt(i)},o,vt(s));return new Uint8Array(a)}async function yi(d,l){if(l.length!==gn)throw new Error("Encryption key must be 32 bytes.");let t=crypto.getRandomValues(new Uint8Array(Le)),i=ko({id:vo,a:0,b:0,c:0},new Uint8Array(0),t),s=await _i(l),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:vt(t),additionalData:vt(i)},s,vt(d))),o=new Uint8Array(i.length+n.length);return o.set(i,0),o.set(n,i.length),o}async function Ae(d,l){if(!Ot(d))throw new Error("Not an encrypted Stashpad file.");let t=d[qt.length];if(t!==In)throw new Error(`Unsupported encrypted version (${t}).`);let e=qt.length+1;if(d[e++]!==vo)throw new Error("Not a raw-key (.stashenc) envelope.");e+=9;let s=d[e++];e+=s;let n=d.slice(e,e+Le);e+=Le;let o=d.slice(0,e),a=d.slice(e),r=await _i(l),A=await crypto.subtle.decrypt({name:"AES-GCM",iv:vt(n),additionalData:vt(o)},r,vt(a));return new Uint8Array(A)}async function qe(d,l,t={}){if(!Ot(l))return l;if(t.secretId){let i=d.secretStorage,s=null;try{s=i?.getSecret(t.secretId)??null}catch{s=null}if(s)try{return await te(l,s)}catch{}}let e;for(;;){let i=await new Promise(s=>{new ri(d,e,!!t.allowLater,s).open()});if(i.kind==="cancel")return null;if(i.kind==="later")return t.onLater?.(),null;try{return await te(l,i.value)}catch{e="Wrong password or corrupted file. Try again."}}}Lt();var ts={name:"ECDH",namedCurve:"P-256"},Cr="stashpad-vault-dek-wrap",Br=new TextEncoder;function Cn(d){let l="";for(let t=0;t<d.length;t++)l+=String.fromCharCode(d[t]);return btoa(l)}function Bn(d){let l=atob(d),t=new Uint8Array(l.length);for(let e=0;e<l.length;e++)t[e]=l.charCodeAt(e);return t}async function So(){let d=await crypto.subtle.generateKey(ts,!0,["deriveBits"]);return{pubKeySpki:new Uint8Array(await crypto.subtle.exportKey("spki",d.publicKey)),privKeyPkcs8:new Uint8Array(await crypto.subtle.exportKey("pkcs8",d.privateKey))}}function Do(d){return crypto.subtle.importKey("spki",d,ts,!1,[])}function Qr(d){return crypto.subtle.importKey("pkcs8",d,ts,!1,["deriveBits"])}async function bo(d,l){let t=await crypto.subtle.deriveBits({name:"ECDH",public:l},d,256),e=await crypto.subtle.importKey("raw",t,"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(0),info:Br.encode(Cr)},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function es(d,l,t){let e=await crypto.subtle.generateKey(ts,!0,["deriveBits"]),i=await bo(e.privateKey,await Do(l)),s=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:s},i,d)),o=new Uint8Array(await crypto.subtle.exportKey("spki",e.publicKey));return{recipientId:t,ephPub:Cn(o),iv:Cn(s),ct:Cn(n)}}async function xo(d,l){let t=await bo(await Qr(l),await Do(Bn(d.ephPub)));return new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:Bn(d.iv)},t,Bn(d.ct)))}var No=".stashpad/keys.json",yr=".stashpad",Ei="_keys";function Qn(d){return{v:2,keyId:d,identities:[],slots:[],joinRequests:[]}}var is=class{constructor(l){this.app=l}get a(){return this.app.vault.adapter}validate(l){let t=l;return!!t&&t.v===2&&typeof t.keyId=="string"&&Array.isArray(t.identities)&&Array.isArray(t.slots)&&Array.isArray(t.joinRequests)}async readValid(l){try{if(!await this.a.exists(l))return null;let t=JSON.parse(await this.a.read(l));return this.validate(t)?t:null}catch{return null}}async load(){let l=await this.readValid(No);if(l)return l;try{let e=((await this.a.list(Ei)).files||[]).filter(i=>/\/keys-\d+\.json$/.test(i)).sort();for(let i of e.reverse()){let s=await this.readValid(i);if(s)return s}}catch{}return null}async exists(){return await this.load()!==null}async ensureDir(l){try{await this.a.exists(l)||await this.a.mkdir(l)}catch{}}async save(l){let t=JSON.stringify(l,null,2);await this.ensureDir(yr),await this.a.write(No,t),await this.ensureDir(Ei);for(let e=4;e>=1;e--){let i=`${Ei}/keys-${e}.json`,s=`${Ei}/keys-${e+1}.json`;try{await this.a.exists(i)&&await this.a.write(s,await this.a.read(i))}catch{}}try{await this.a.write(`${Ei}/keys-1.json`,t)}catch{}}};var ss="stashpad-vault-encryption";function wi(){return{wrappedKey:null,kdf:null,identityId:null,identityLabel:null,identityPub:null,identityPrivWrapped:null,identityPrivKdf:null}}function ns(d){let l="";for(let t=0;t<d.length;t++)l+=String.fromCharCode(d[t]);return btoa(l)}function ee(d){let l=atob(d),t=new Uint8Array(l.length);for(let e=0;e<l.length;e++)t[e]=l.charCodeAt(e);return t}var Er=32,os=class{constructor(l,t,e,i=()=>0){this.app=l;this.load=t;this.save=e;this.idleMinutes=i;this.sessionKey=null;this.idleTimer=null;this.kf=null;this.keyfiles=new is(l)}argonProbe(){return ji()}async init(){await this.refresh()}async refresh(){this.kf=await this.keyfiles.load()}secretStore(){return this.app.secretStorage??null}keychainAvailable(){return!!this.secretStore()}keychainId(){let l=this.app.appId||"default";return`${ss}-${l}`}isRemembered(){try{return!!this.secretStore()?.getSecret(this.keychainId())}catch{return!1}}async remember(l){try{await this.secretStore()?.setSecret(this.keychainId(),l)}catch(t){console.warn("[Stashpad] couldn't save password to keychain",t)}}async forgetKeychain(){let l=this.secretStore();if(l)try{l.removeSecret?await l.removeSecret(this.keychainId()):await l.setSecret(this.keychainId(),"")}catch(t){console.warn("[Stashpad] couldn't clear keychain",t)}}async tryAutoUnlock(){if(!this.isConfigured()||this.isUnlocked())return this.isUnlocked();if(this.accessState()!=="member"&&!this.hasSharedPassword())return!1;let l=this.secretStore(),t=null;try{t=l?.getSecret(this.keychainId())??null}catch{t=null}if(t)return this.unlock(t);let e=null;try{e=l?.getSecret(ss)??null}catch{e=null}if(!e)return!1;let i=await this.unlock(e);if(i){await this.remember(e);try{l?.removeSecret?await l.removeSecret(ss):await l?.setSecret(ss,"")}catch{}}return i}isConfigured(){return!!this.kf||!!this.load().wrappedKey}isUnlocked(){return this.sessionKey!==null}kdf(){return this.load().identityPrivKdf??this.load().kdf}hasIdentity(){return!!this.load().identityPrivWrapped&&!!this.load().identityId}mySlot(){let l=this.load().identityId;return l?this.kf?.slots.find(t=>t.recipientId===l)??null:null}accessState(){let l=this.load();return!this.kf&&l.wrappedKey?"member":this.kf?this.hasIdentity()&&this.mySlot()?"member":l.identityId&&this.kf.joinRequests.some(t=>t.id===l.identityId)?"pending":"outsider":"none"}amIMember(){return this.accessState()==="member"}async setup(l,t=!1,e){if(await this.refresh(),this.isConfigured())throw new Error("Encryption is already set up in this vault.");if(!l)throw new Error("Password required.");let i=crypto.getRandomValues(new Uint8Array(Er)),s=await this.mintIdentity(l,e),n=Qn(gt(8));n.identities.push(this.identityRecord(s)),n.slots.push(await es(i,ee(s.pub),s.id)),await this.keyfiles.save(n),this.kf=n,this.sessionKey=i,t?await this.remember(l):await this.forgetKeychain(),this.armIdle()}async unlock(l,t=!1){await this.refresh();let e=this.load();if(!this.kf&&e.wrappedKey){let s;try{s=await te(ee(e.wrappedKey),l)}catch{return!1}let n=await this.mintIdentity(l,e.identityLabel??void 0),o=Qn(gt(8));return o.identities.push(this.identityRecord(n)),o.slots.push(await es(s,ee(n.pub),n.id)),await this.keyfiles.save(o),this.kf=o,this.sessionKey=s,t&&await this.remember(l),this.armIdle(),!0}let i=this.hasIdentity()?this.mySlot():null;if(i)try{let s=await te(ee(e.identityPrivWrapped),l);try{let n=await xo(i,s);return s.fill(0),this.sessionKey=n,t&&await this.remember(l),this.armIdle(),!0}catch{s.fill(0)}}catch{}for(let s of this.kf?.passwordSlots??[])try{let n=await te(ee(s.wrapped),l);return this.sessionKey=n,t&&await this.remember(l),this.armIdle(),!0}catch{}return!1}hasSharedPassword(){return(this.kf?.passwordSlots?.length??0)>0}async setSharedPassword(l){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(!l)throw new Error("Password required.");if(await this.refresh(),!this.kf)throw new Error("Encryption is not set up.");let t=await Je(this.sessionKey,l);this.kf.passwordSlots=[{id:gt(8),label:"Shared password",wrapped:ns(t.data),kdf:t.kdf,createdAt:new Date().toISOString()}],await this.keyfiles.save(this.kf)}async removeSharedPassword(){await this.refresh(),!(!this.kf||!this.kf.passwordSlots?.length)&&(this.kf.passwordSlots=[],await this.keyfiles.save(this.kf))}async verifyPassword(l){let t=this.load();try{if(t.identityPrivWrapped)return(await te(ee(t.identityPrivWrapped),l)).fill(0),!0;if(t.wrappedKey)return(await te(ee(t.wrappedKey),l)).fill(0),!0}catch{}return!1}async changePassword(l,t,e=!1){let i=this.load();if(!t)throw new Error("New password required.");if(!i.identityPrivWrapped&&!await this.unlock(l,!1))return!1;let s=this.load(),n;try{n=await te(ee(s.identityPrivWrapped),l)}catch{return!1}let o=await Je(n,t);return n.fill(0),await this.save({...s,identityPrivWrapped:ns(o.data),identityPrivKdf:o.kdf}),e?await this.remember(t):await this.forgetKeychain(),this.armIdle(),!0}async requestAccess(l,t,e=!1){if(await this.refresh(),!this.kf)throw new Error("This vault has no encryption set up yet.");if(this.amIMember())return;if(!t)throw new Error("Password required.");let i=this.hasIdentity()?{id:this.load().identityId,label:this.load().identityLabel??l,pub:this.load().identityPub}:await this.mintIdentity(t,l);l&&i.label!==l&&(await this.save({...this.load(),identityLabel:l}),i.label=l);let s={id:i.id,label:i.label,pubKey:i.pub,requestedAt:new Date().toISOString()};this.kf.joinRequests=[...this.kf.joinRequests.filter(n=>n.id!==i.id),s],await this.keyfiles.save(this.kf),e?await this.remember(t):await this.forgetKeychain()}pendingJoinRequests(){return this.kf?.joinRequests??[]}members(){return this.kf?.identities??[]}myIdentityId(){return this.load().identityId}async approveJoinRequest(l,t){if(!this.sessionKey)throw new Error("Unlock encryption first.");if(await this.refresh(),!this.kf)return!1;let e=this.kf.joinRequests.find(i=>i.id===l);return e?(this.kf.slots=[...this.kf.slots.filter(i=>i.recipientId!==e.id),await es(this.sessionKey,ee(e.pubKey),e.id)],this.kf.identities=[...this.kf.identities.filter(i=>i.id!==e.id),{id:e.id,label:t??e.label,pubKey:e.pubKey,addedAt:new Date().toISOString()}],this.kf.joinRequests=this.kf.joinRequests.filter(i=>i.id!==l),await this.keyfiles.save(this.kf),!0):!1}async removeMember(l){await this.refresh(),this.kf&&(this.kf.slots=this.kf.slots.filter(t=>t.recipientId!==l),this.kf.identities=this.kf.identities.filter(t=>t.id!==l),this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==l),await this.keyfiles.save(this.kf))}async denyJoinRequest(l){await this.refresh(),this.kf&&(this.kf.joinRequests=this.kf.joinRequests.filter(t=>t.id!==l),await this.keyfiles.save(this.kf))}lock(){this.sessionKey&&this.sessionKey.fill(0),this.sessionKey=null,this.clearIdle()}async clear(){this.lock(),await this.forgetKeychain();try{let l=this.app.vault.adapter;for(let t of[".stashpad/keys.json"])try{await l.exists(t)&&await l.remove(t)}catch{}try{let t=await l.list("_keys");for(let e of t.files||[])if(/\/keys-\d+\.json$/.test(e))try{await l.remove(e)}catch{}}catch{}}catch{}this.kf=null,await this.save(wi())}getSessionKey(){return this.sessionKey&&this.armIdle(),this.sessionKey?this.sessionKey.slice():null}async mintIdentity(l,t){let e=await So(),i=await Je(e.privKeyPkcs8,l);e.privKeyPkcs8.fill(0);let s=this.load(),n=s.identityId??gt(8),o=t??s.identityLabel??"This device",a=ns(e.pubKeySpki);return await this.save({...s,identityId:n,identityLabel:o,identityPub:a,identityPrivWrapped:ns(i.data),identityPrivKdf:i.kdf}),{id:n,label:o,pub:a}}identityRecord(l){return{id:l.id,label:l.label,pubKey:l.pub,addedAt:new Date().toISOString()}}armIdle(){this.clearIdle();let l=this.idleMinutes();l>0&&(this.idleTimer=window.setTimeout(()=>this.lock(),l*6e4))}clearIdle(){this.idleTimer!=null&&(window.clearTimeout(this.idleTimer),this.idleTimer=null)}dispose(){this.lock()}};var wn=Pi(vi()),as=require("obsidian");Lt();Qt();var ie="stash",Po=1;function To(d){let t=(d.split(/[\\/]/).pop()??"").trim();return!t||t==="."||t===".."||t.includes("/")||t.includes("\\")||t.includes("..")?"":t}var En=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g;async function ce(d,l){let t=new wn.default,e=wr([...l.rootNotes,...l.allDescendants]),i=new Map,s=[];for(let o of e){let a=await d.vault.read(o.file),r=a,A=Uo(a);for(let c of A){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=vr(r,c,p)}r=Sr(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:Po,exportedAt:new Date().toISOString(),sourceFolder:l.sourceFolder,noteCount:e.length,rootIds:l.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,l,t,e,i={}){let s=await wn.default.loadAsync(l),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>Po)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 D=await v.async("string"),{fm:x,body:F}=wt(D),N=To(v.name.slice(6))||`${x.id||"imported-"+gt(4)}.md`;r.push({originalName:N,fm:x,body:F})}let A=new Map,c=0;for(let v of r){let D=v.fm.id;D&&(i.forceNewIds?A.set(D,gt(6)):e.has(D)||A.has(D)?(A.set(D,`${D}-${gt(4)}-Imported`),c++):A.set(D,D))}let g=new Date().toISOString(),p=[],h=`${t}/_attachments`,u=0,I=Object.values(s.files).filter(v=>!v.dir&&v.name.startsWith("attachments/")),f=new Map,m=null;if(i.dedupeExisting){m=new Map;for(let v of d.vault.getFiles())m.has(v.name)||m.set(v.name,v.path)}let C=(v,D)=>{if(v.length!==D.length)return!1;for(let x=0;x<v.length;x++)if(v[x]!==D[x])return!1;return!0},y=!1;for(let v of I){let D=To(v.name.slice(12));if(!D)continue;let x=new Uint8Array(await v.async("arraybuffer")),F=[],N=m?.get(D);N&&F.push(N);let Q=`${h}/${D}`;await d.vault.adapter.exists(Q)&&F.push(Q);let S=null;for(let M of F)try{if(C(new Uint8Array(await d.vault.adapter.readBinary(M)),x)){S=M;break}}catch{}if(S){f.set(D,S);continue}let O=Q;for(let M=1;await d.vault.adapter.exists(O);M++)O=`${h}/${Fr(D,M)}`;f.set(D,O),y||(await Ho(d,h),y=!0),await d.vault.createBinary(O,x.buffer),u++}let w=0;for(let v of r){let D=v.fm.id;if(!D){p.push(`Skipped ${v.originalName} \u2014 no id in frontmatter`);continue}let x=A.get(D),F=v.fm.parent??null,N=F;!F||F===T?N=i.reparentRootsTo??F??T:A.has(F)?N=A.get(F):N=e.has(F)?F:i.reparentRootsTo??T;let Q=kr(v.body,f,h),S={...v.fm,id:x,parent:N,import_date:g};Array.isArray(S.attachments)&&(S.attachments=S.attachments.map(q=>{let j=Ro(ye(q));return zt(f.get(j)??`${h}/${j}`)}));let O=de(S,Q),M=x===D?v.originalName:br(v.originalName,D,x),Y=`${t}/${M}`;await d.vault.adapter.exists(Y)&&(M=`${M.replace(/\.md$/,"")}-${gt(4)}.md`,Y=`${t}/${M}`),await d.vault.create(Y,O),w++}let E;if(o.colorAliases&&typeof o.colorAliases=="object"){let v={};for(let[D,x]of Object.entries(o.colorAliases)){let F=String(D).trim().toLowerCase(),N=String(x??"").trim();/^#([0-9a-f]{6})$/.test(F)&&N&&(v[F]=N.slice(0,60))}Object.keys(v).length&&(E=v)}return{notesWritten:w,attachmentsWritten:u,collisionsRenamed:c,warnings:p,colorAliases:E,idRemap:Object.fromEntries(A)}}function wr(d){let l=new Set,t=[];for(let e of d)l.has(e.id)||(l.add(e.id),t.push(e));return t}function Uo(d){let l=new Set,t;for(En.lastIndex=0;(t=En.exec(d))!==null;)l.add(t[1]);return[...l]}async function rs(d,l){let t=await d.vault.read(l),e=[],i=new Set;for(let s of Uo(t)){let n=d.metadataCache.getFirstLinkpathDest(s,l.path);n&&!i.has(n.path)&&(i.add(n.path),e.push(n))}return e}function vr(d,l,t){return d.replace(new RegExp(`!\\[\\[${Dr(l)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,i)=>`![[${t}${i??""}]]`)}function Fr(d,l){let t=d.lastIndexOf(".");return t>0?`${d.slice(0,t)}-${l}${d.slice(t)}`:`${d}-${l}`}function kr(d,l,t){return d.replace(En,(e,i,s)=>{if(i.includes("/"))return e;let n=l.get(i)??`${t}/${i}`;return e.replace(i,n)})}function Sr(d,l,t){let e=wt(d);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return d;let i=e.fm.attachments.map(n=>{let o=l.metadataCache.getFirstLinkpathDest(n,t);return o?o.name:Ro(n)}),s={...e.fm,attachments:i};return de(s,e.body)}function Dr(d){return d.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ro(d){let l=d.lastIndexOf("/");return l<0?d:d.slice(l+1)}function br(d,l,t){return d.includes(l)?d.replace(l,t):d.replace(/\.md$/,`-${t}.md`)}function wt(d){if(!d.startsWith("---"))return{fm:{},body:d};let l=d.indexOf(` +---`,3);if(l<0)return{fm:{},body:d};let t=d.slice(3,l).replace(/^\n/,""),e=d.slice(l+4),i={};try{i=(0,as.parseYaml)(t)??{}}catch{i={}}let s=e.startsWith(` +`)?e.slice(1):e;return{fm:i,body:s}}function de(d,l){return`--- +${(0,as.stringifyYaml)(d).trimEnd()} --- -${A}`}async function Fo(h,A){if(!(!A||await h.vault.adapter.exists(A)))try{await h.vault.createFolder(A)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}var ce="stashenc",gr="stashmeta";function de(h){return h.replace(/\.stashenc$/,`.${gr}`)}async function bo(h,A){try{return JSON.parse(await h.vault.adapter.read(de(A)))}catch{return null}}async function be(h,A,t){let e=A.replace(/\/+$/,""),i=[];for(let l of h.vault.getMarkdownFiles()){if((l.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let c;try{c=Dt(await h.vault.read(l)).fm}catch{continue}typeof c.id=="string"&&i.push({id:c.id,file:l,parent:typeof c.parent=="string"?c.parent:null,created:typeof c.created=="string"?c.created:""})}let s=i.find(l=>l.id===t);if(!s)return null;let n=new Map;for(let l of i){if(!l.parent)continue;let c=n.get(l.parent)??[];c.push(l),n.set(l.parent,c)}let o=[],a=new Set([t]),r=[t];for(;r.length;){let l=[];for(let c of r)for(let p of n.get(c)??[])a.has(p.id)||(a.add(p.id),o.push(p),l.push(p.id));r=l}return{rootNote:s,descendants:o,parentId:s.parent}}function mn(h){if(!h)return null;let A=h.replace(/\/+$/,"");return!A||A.startsWith("/")||A.includes("\\")||/^[a-zA-Z]:/.test(A)||A.split("/").some(t=>t===".."||t===".")?null:A}async function Bn(h,A,t){await h.vault.adapter.writeBinary(A,t);let e;try{e=new Uint8Array(await h.vault.adapter.readBinary(A))}catch(s){throw new Error(`Couldn't read back the encrypted file to verify it (${s.message}). Nothing was deleted.`)}let i=e.length===t.length;if(i){for(let s=0;s<t.length;s++)if(e[s]!==t[s]){i=!1;break}}if(!i){try{await h.vault.adapter.remove(A)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function ss(h){return h.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||h.basename}function Oe(h){return(h.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function No(h,A,t){let e=new Set(A.map(a=>a.file.path)),i=new Map;for(let a of A)for(let r of await is(h,a.file))i.set(r.path,r);let s=new Set,n=h.metadataCache.resolvedLinks??{};for(let a of Object.keys(n))if(!e.has(a))for(let r of Object.keys(n[a]??{}))i.has(r)&&s.add(r);let o=[];for(let a of A){let r=t?.get(a.file.path);if(r!=null)try{let l=await h.vault.adapter.stat(a.file.path);if(l&&l.mtime!==r){console.warn("[Stashpad] note changed since it was bundled \u2014 keeping plaintext",a.file.path),o.push(a.file.path);continue}}catch{}try{await h.vault.delete(a.file)}catch(l){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,l),o.push(a.file.path)}}for(let[a,r]of i)if(!s.has(a))try{await h.vault.delete(r)}catch(l){console.warn("[Stashpad] couldn't delete exclusive attachment",a,l),o.push(a)}return{unpurged:o}}async function xo(h,A,t,e,i=null,s=!1,n){let o=await be(h,A,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:r,parentId:l}=o,c=[a,...r],p=new Map;for(let E of c)try{let v=await h.vault.adapter.stat(E.file.path);v&&p.set(E.file.path,v.mtime)}catch{}let g=await De(h,{rootNotes:[{id:a.id,file:a.file}],allDescendants:r.map(E=>({id:E.id,file:E.file})),sourceFolder:A}),d=await Bi(g,e),u=await re(d,e);if(u.length!==g.length)throw new Error("Encryption self-check failed (size mismatch).");for(let E=0;E<g.length;E++)if(u[E]!==g[E])throw new Error("Encryption self-check failed (content mismatch).");let I=(n??A).replace(/\/+$/,"");n&&!await h.vault.adapter.exists(I)&&await h.vault.adapter.mkdir(I);let f=Oe(s?t:ss(a.file)),C=`${I}/${f}.${ce}`;for(let E=1;await h.vault.adapter.exists(C);E++)C=`${I}/${f} (${E}).${ce}`;await Bn(h,C,d);let m=c,y={v:1,parentId:l,title:s?"":ss(a.file),count:m.length,created:a.created,rootId:t,prevSibling:i};try{await h.vault.adapter.write(de(C),JSON.stringify(y))}catch(E){console.warn("[Stashpad] couldn't write lock sidecar",E)}let{unpurged:w}=await No(h,m,p);return{blobPath:C,noteCount:m.length,rootId:t,parentId:l,title:y.title,created:a.created,unpurged:w}}async function Mo(h,A,t,e,i){let s=new Uint8Array(await h.vault.adapter.readBinary(A));if(!qt(s))throw new Error("Not an encrypted bundle.");let n=await re(s,t),o=mn(i)??A.replace(/\/[^/]*$/,""),a=await Vt(h,n,o,e,{dedupeExisting:!0});await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(de(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ut="_deleted";function pr(h){let A="";for(let t=0;t<h.length;t++)A+=String.fromCharCode(h[t]);return btoa(A)}function ur(h){let A=atob(h),t=new Uint8Array(A.length);for(let e=0;e<A.length;e++)t[e]=A.charCodeAt(e);return t}async function Qn(h,A,t,e){let i=mn(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=mn(new TextDecoder().decode(await re(ur(t.originalFolderEnc),e)))}catch{i=null}if(i)return await h.vault.adapter.exists(i)||await h.vault.adapter.mkdir(i),i;let s=A.replace(/\/[^/]*$/,"");if(s===Ut||s.startsWith(`${Ut}/`))throw new Error("This deleted note's origin folder is unknown (missing or tampered sidecar) \u2014 can't restore it safely. The encrypted copy was kept.");return s}async function yn(h){let A=[""];for(;A.length;){let t=A.shift(),e;try{e=await h.vault.adapter.list(t||"/")}catch{continue}if(e.files.some(i=>i.endsWith(`.${ce}`)))return!0;for(let i of e.folders)i===".obsidian"||i.endsWith("/.obsidian")||A.push(i)}return!1}async function To(h,A,t,e,i,s=!1){let n=await be(h,A,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:a,parentId:r}=n,l=[o,...a],c=new Map;for(let E of l)try{let v=await h.vault.adapter.stat(E.file.path);v&&c.set(E.file.path,v.mtime)}catch{}let p=await De(h,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(E=>({id:E.id,file:E.file})),sourceFolder:A}),g=await Bi(p,e),d=await re(g,e);if(d.length!==p.length)throw new Error("Encryption self-check failed (size).");for(let E=0;E<p.length;E++)if(d[E]!==p[E])throw new Error("Encryption self-check failed (content).");await h.vault.adapter.exists(Ut)||await h.vault.adapter.mkdir(Ut);let u=A.replace(/\/+$/,""),I=u.split("/").pop()||"vault",f=Oe(s?t:`${I} ${ss(o.file)}`),C=`${Ut}/${f}.${ce}`;for(let E=1;await h.vault.adapter.exists(C);E++)C=`${Ut}/${f} (${E}).${ce}`;await Bn(h,C,g);let m=l,y={v:1,kind:"deleted",originalFolder:s?"":u,...s?{originalFolderEnc:pr(await Bi(new TextEncoder().encode(u),e))}:{},parentId:r,title:s?"":ss(o.file),count:m.length,created:o.created,rootId:t,deletedAt:i};try{await h.vault.adapter.write(de(C),JSON.stringify(y))}catch(E){console.warn("[Stashpad] couldn't write deleted sidecar",E)}let{unpurged:w}=await No(h,m,c);return{blobPath:C,noteCount:m.length,rootId:t,originalFolder:u,title:y.title,unpurged:w}}async function Ho(h,A,t,e){let i=new Uint8Array(await h.vault.adapter.readBinary(A));if(!qt(i))throw new Error("Not an encrypted bundle.");let s=await ns(h,A),n=await Qn(h,A,s,t),o=await re(i,t),a=await Vt(h,o,n,e,{dedupeExisting:!0});await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(de(A))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function ns(h,A){try{return JSON.parse(await h.vault.adapter.read(de(A)))}catch{return null}}var Ot=".trash";async function Ir(h,A){let t=[],e=[A];for(;e.length;){let i=e.shift(),s;try{s=await h.vault.adapter.list(i)}catch{continue}t.push(...s.files),e.push(...s.folders)}return t}function fr(h){let A=h.split("/").filter(Boolean);if(A.length===0)return null;for(let t of A)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return A.join("/")}async function Po(h,A,t,e=!1){if(!await h.vault.adapter.exists(Ot))return null;let i=await Ir(h,Ot);if(i.length===0)return null;let{default:s}=await Promise.resolve().then(()=>Gs(ts())),n=new s,o=new Map;for(let u of i){let I=u.slice(Ot.length+1);n.file(`files/${I}`,await h.vault.adapter.readBinary(u));try{let f=await h.vault.adapter.stat(u);f&&o.set(u,f.mtime)}catch{}}let a=new Uint8Array(await n.generateAsync({type:"arraybuffer"})),r=await Bi(a,A),l=await re(r,A);if(l.length!==a.length)throw new Error("Encryption self-check failed (size).");for(let u=0;u<a.length;u++)if(l[u]!==a[u])throw new Error("Encryption self-check failed (content).");await h.vault.adapter.exists(Ut)||await h.vault.adapter.mkdir(Ut);let c=Oe(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),p=`${Ut}/${c}.${ce}`;for(let u=1;await h.vault.adapter.exists(p);u++)p=`${Ut}/${c} (${u}).${ce}`;await Bn(h,p,r);let g={v:1,kind:"rawtrash",originalFolder:Ot,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await h.vault.adapter.write(de(p),JSON.stringify(g))}catch(u){console.warn("[Stashpad] couldn't write backfill sidecar",u)}let d=[];for(let u of i){let I=o.get(u);try{if(I!=null){let f=await h.vault.adapter.stat(u);if(f&&f.mtime!==I){d.push(u);continue}}await h.vault.adapter.remove(u)}catch(f){console.warn("[Stashpad] couldn't delete trash file",u,f),d.push(u)}}return{blobPath:p,fileCount:i.length,unpurged:d}}async function Uo(h,A,t){let e=new Uint8Array(await h.vault.adapter.readBinary(A));if(!qt(e))throw new Error("Not an encrypted bundle.");let i=await re(e,t),{default:s}=await Promise.resolve().then(()=>Gs(ts())),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=fr(a.slice(6));if(!l){console.warn("[Stashpad] skipped unsafe trash entry",a);continue}let c=`${Ot}/${l}`.split("/").slice(0,-1).join("/"),p="";for(let d of c.split("/"))p=p?`${p}/${d}`:d,await h.vault.adapter.exists(p)||await h.vault.adapter.mkdir(p);let g=`${Ot}/${l}`;for(let d=1;await h.vault.adapter.exists(g);d++)g=`${Ot}/${l.replace(/(\.[^./]*)?$/,` (${d})$1`)}`;await h.vault.adapter.writeBinary(g,await r.async("arraybuffer")),o++}await h.vault.adapter.remove(A);try{await h.vault.adapter.remove(de(A))}catch{}return{filesWritten:o}}async function Ro(h){if(!await h.vault.adapter.exists(Ut))return[];try{return(await h.vault.adapter.list(Ut)).files.filter(t=>t.endsWith(`.${ce}`))}catch{return[]}}var Ei=null,os=new Set;function as(h){if(Ei!==h){Ei=h;for(let A of os)A()}}function ee(){return Ei}function Go(h){if(Ei===h){Ei=null;for(let A of os)A()}}function Lo(h){return os.add(h),()=>os.delete(h)}function Cr(){return X.Platform.isMacOS?"Finder":X.Platform.isWin?"File Explorer":"file manager"}var Ke=[{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 vn(){let h={};for(let A of Ke)h[A.id]={primary:A.defaultPrimary,secondary:A.defaultSecondary??"",preferRight:!1,useBoth:!!A.defaultUseBoth};return h}var he={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:yi(),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:vn()},Jo=JSON.parse(JSON.stringify(he)),wn=new Set;function ut(){return Jo}function Fn(h){Jo=h;for(let A of wn)A()}function qo(h){return wn.add(h),()=>wn.delete(h)}function ls(h){try{let A=h.internalPlugins?.plugins?.templates;if(!A?.enabled)return null;let t=A.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var rs=[{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"}],En=null;function mr(h,A){return En||(En=class extends X.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new En(h,A)}var As=class extends X.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if(X.SettingPage){super.display();return}let{containerEl:t}=this;t.empty();for(let e of rs){t.createEl("h2",{text:e.label});let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new X.Setting(t);typeof s.render=="function"?s.render(n):(s.name&&n.setName(s.name),s.desc&&n.setDesc(s.desc))}else this.renderTabContent(t,e.id)}}getSettingDefinitions(){return rs.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>mr(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(Zs);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 X.Notice("No log yet \u2014 make some changes first.");return}let a=await n.read(o);new He(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=Zs[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 ci(this.app,this.plugin.notifications,async n=>{let o=this.app.vault.adapter,a=this.plugin.pluginPrivatePath("log.jsonl");if(!await o.exists(a)){new X.Notice("No log yet \u2014 make some changes first.");return}let r=await o.read(a);new He(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 p=>{a(p),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 Ge(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||he.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 X.Notice(`"${a}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=a,await t()})})},["folder","path","location","notes"])),i.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,"")||he.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:p,attachmentsLinked:g}=await this.plugin.rebootstrapAllFolders(),d=[];d.push(`rebootstrapped ${o.length} folder${o.length===1?"":"s"}`),p>0&&d.push(`imported ${p} loose file${p===1?"":"s"}`),g>0&&d.push(`linked attachments on ${g} note${g===1?"":"s"}`),r>0?d.push(`updated frontmatter on ${r} of ${a} notes`):a>0&&d.push(`frontmatter already in sync (${a} notes checked)`),l>0&&d.push(`renamed ${l} note${l===1?"":"s"} to match body`),c>0&&d.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new X.Notice(`Stashpad: ${d.join("; ")}.`)}catch(o){new X.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=ls(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: ${Xt(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:zt).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=[...zt],n&&(n.value=zt.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 X.Setting(s).setName("Cross-Stashpad search scope").setDesc("Toggle each Stashpad's pill to choose whether its notes contribute to cross-folder search. Excluded folders are still valid move destinations \u2014 their notes just don't appear in search results from elsewhere."),n.length===0)s.createEl("p",{cls:"setting-item-description"}).setText('No Stashpads found in this vault yet. A Stashpad is just a folder that contains a Stashpad-shaped note (frontmatter has both `id` and `parent`). Easiest way: open Stashpad (ribbon icon or command "Reveal or open Stashpad") \u2014 it auto-creates the default folder on first use. Or create one below.');else{let a=s.createDiv({cls:"stashpad-folder-list"});for(let r of n)this.renderFolderScopeRow(a,r)}let o=null;new X.Setting(s).setName("Create a new Stashpad").setDesc("Type a vault-relative folder path. The folder is created (with intermediates) and seeded with a Home note so Stashpad recognizes it.").addText(a=>{a.setPlaceholder("my-stashpad"),o=a.inputEl}).addButton(a=>a.setButtonText("Create").setCta().onClick(async()=>{let r=(o?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!r){new X.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(r),new X.Notice(`Created Stashpad "${r}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(r,2e3),this.update?.()}catch(l){new X.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 X.Setting(s).setName("Folder panel placement").setDesc("Folders you've pinned, downranked, or hidden in the Stashpad folder panel. Pin/downrank from a folder's right-click menu in the panel; restore here or from the panel's \u201CHidden\u201D section."),this.renderFolderPlacementList(s)},["folder","panel","pin","pinned","downrank","hide","hidden","restore","placement"])),i.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");let s=i.createDiv({cls:"stashpad-beta-row"});s.createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),s.createEl("span",{cls:"stashpad-beta-note",text:"Encryption is in beta \u2014 keep your own backups of anything important."}),i.createEl("p",{cls:"setting-item-description"}).setText("\u26A0\uFE0F Encryption protects what you lock in this vault. Each device unlocks with its own password (which never leaves the device); the vault key is shared with collaborators by approving their device \u2014 no shared password. If everyone with access loses their password, anything encrypted is gone for good. While encrypting, avoid a sync/cloud service writing the vault mid-operation \u2014 it can corrupt files.");let n=()=>t.argonProbe(),o=()=>this.plugin.settings.authorName?.trim()||"This device",a=t.accessState();t.refresh().then(()=>{t.accessState()!==a&&this.update?.()});let r=a;if(r==="none"){new X.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(g=>g.setButtonText("Set up password\u2026").setCta().onClick(()=>{new xt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:d,remember:u})=>{if(!d)return"Enter a password.";try{await t.setup(d,u,o())}catch(I){return I.message}return new X.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}if(r==="outsider"&&!t.isUnlocked()){t.hasSharedPassword()&&new X.Setting(i).setName("This vault is encrypted").setDesc("Enter the shared password (ask whoever set it up \u2014 they'll send it via a password manager or secure message).").addButton(g=>g.setButtonText("Unlock with shared password\u2026").setCta().onClick(()=>{new xt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:d,remember:u})=>await t.unlock(d,u)?(new X.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password (or the keyfile hasn't synced here yet)."}).open()})),new X.Setting(i).setName(t.hasSharedPassword()?"Or request device approval":"This vault is encrypted by a collaborator").setDesc("Request access \u2014 pick a password for THIS device, then ask an existing member to approve it. Once approved (and the keyfile syncs to you), you'll unlock with that password. No shared secret.").addButton(g=>g.setButtonText("Request access\u2026").onClick(()=>{new xt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:d,remember:u})=>{if(!d)return"Choose a password for this device.";try{await t.requestAccess(o(),d,u)}catch(I){return I.message}return new X.Notice("Access requested. An existing member can now approve this device."),this.update?.(),null}}).open()}));return}if(r==="pending"){new X.Setting(i).setName("Access requested \u2014 waiting for approval").setDesc("An existing member needs to approve this device. After they do and the keyfile syncs here, reopen this page to unlock with the password you chose.").addButton(g=>g.setButtonText("Try unlock now").setCta().onClick(()=>{new xt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:d,remember:u})=>await t.unlock(d,u)?(new X.Notice("Encryption unlocked."),this.update?.(),null):"Not approved yet (or wrong password). Ask a member to approve this device, then try again."}).open()})).addButton(g=>g.setButtonText("Cancel request").onClick(async()=>{let d=t.myIdentityId();d&&await t.denyJoinRequest(d),new X.Notice("Access request cancelled."),this.update?.()}));return}let l=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",c=t.isRemembered()?" \xB7 remembered on this device":"";if(new X.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${l?` \xB7 ${l}`:""}${c}`),t.isUnlocked()?new X.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(g=>g.setButtonText("Lock now").onClick(()=>{t.lock(),new X.Notice("Encryption locked."),this.update?.()})):new X.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(g=>g.setButtonText("Unlock\u2026").setCta().onClick(()=>{new xt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:d,remember:u})=>await t.unlock(d,u)?(new X.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),t.keychainAvailable()&&t.isRemembered()&&new X.Setting(i).setName("Forget password on this device").setDesc("Drops ONLY the copy saved in this device's keychain \u2014 your encryption stays set up and nothing is decrypted or deleted. You'll just re-type the password next session. (To turn encryption off entirely, use \u201CRemove encryption\u201D below.)").addButton(g=>g.setButtonText("Forget on this device").onClick(async()=>{await t.forgetKeychain(),new X.Notice("Removed from this device's keychain \u2014 encryption still set up."),this.update?.()})),t.amIMember()&&new X.Setting(i).setName("Change this device's password").setDesc("Re-wraps THIS device's key under a new password \u2014 doesn't re-encrypt files or affect other people.").addButton(g=>g.setButtonText("Change\u2026").onClick(()=>{new xt(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:d,next:u,remember:I})=>await t.changePassword(d,u,I)?(new X.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),t.amIMember()&&new X.Setting(i).setName("Remove encryption").setDesc("Erases the key from this vault. Refused while any locked notes exist \u2014 decrypt everything first (locked notes have NO plaintext copy; losing the key loses them forever).").addButton(g=>{g.setButtonText("Remove\u2026").onClick(async()=>{if(await yn(this.app)){new X.Notice(`Can't remove encryption: locked/encrypted-deleted notes still exist and would be lost forever. Run "Decrypt (unlock) ALL locked notes in the vault" and empty the encrypted trash first.`,1e4);return}new ri(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:d=>t.verifyPassword(d),onConfirm:async()=>{if(await yn(this.app)){new X.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}await t.clear(),new X.Notice("Encryption removed."),this.update?.()}}).open()}),g.setWarning?.(!0)}),new X.Setting(i).setName("Sharing").setHeading(),t.isUnlocked()?t.hasSharedPassword()?new X.Setting(i).setName("Shared password").setDesc("ON \u2014 anyone who knows it can unlock this vault (no approval). Share it via a password manager or secure message; don't send it in the clear.").addButton(g=>g.setButtonText("Change\u2026").onClick(()=>{new xt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Change shared password",intro:"Everyone who unlocks with the shared password will need the new one. Re-share it securely after changing.",onSubmit:async({next:d})=>{if(!d)return"Enter a password.";try{await t.setSharedPassword(d)}catch(u){return u.message}return new X.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(g=>{g.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new X.Notice("Shared password turned off."),this.update?.()}),g.setWarning?.(!0)}):new X.Setting(i).setName("Shared password").setDesc("OFF \u2014 set one passphrase that everyone types to unlock (the simplest way to share). Anyone who knows it can unlock; turning it off later doesn't claw back copies already synced elsewhere.").addButton(g=>g.setButtonText("Set shared password\u2026").onClick(()=>{new xt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Set shared password",intro:"One passphrase everyone types to unlock this vault. Anyone who knows it gets in \u2014 share it ONLY through a password manager or secure message, never in the clear. You can turn it off later.",onSubmit:async({next:d})=>{if(!d)return"Enter a password.";try{await t.setSharedPassword(d)}catch(u){return u.message}return new X.Notice("Shared password set \u2014 share it securely with your collaborators."),this.update?.(),null}}).open()})):i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to manage how this vault is shared."),new X.Setting(i).setName("Collaborators (device approval)").setHeading(),i.createEl("p",{cls:"setting-item-description"}).setText("Everyone who can unlock this vault, and devices waiting for access. Approving a request shares the vault key with that device \u2014 it never sees a password. Removing a member revokes future access (existing synced copies they already hold aren't clawed back \u2014 rotate the key for that, a future feature)."),new X.Setting(i).setName("Synced from the vault keyfile").addButton(g=>g.setButtonText("Refresh").onClick(async()=>{await t.refresh(),this.update?.()})),!t.isUnlocked())i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to approve or remove collaborators.");else{let g=t.myIdentityId();for(let u of t.members()){let I=u.id===g,f=new X.Setting(i).setName(`${u.label}${I?" \u2014 this device":""}`).setDesc(I?"You":"Member");I||f.addButton(C=>{C.setButtonText("Remove").onClick(async()=>{await t.removeMember(u.id),new X.Notice(`Removed ${u.label}. (Not full revocation without rotating the key.)`),this.update?.()}),C.setWarning?.(!0)})}let d=t.pendingJoinRequests();if(d.length===0)i.createEl("p",{cls:"setting-item-description"}).setText("No pending access requests.");else for(let u of d)new X.Setting(i).setName(u.label).setDesc("Wants access to this vault").addButton(I=>I.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(u.id)}catch(f){new X.Notice(f.message);return}new X.Notice(`Approved ${u.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(I=>I.setButtonText("Deny").onClick(async()=>{await t.denyJoinRequest(u.id),new X.Notice("Request denied."),this.update?.()}))}},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private","collaborator","share","team","member","approve"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{this.plugin.settings.encryptTrash=n,await this.plugin.saveSettings()})),["trash","delete","encrypt"])),e.push(this.renderDef("Encrypt trash filenames","Hide the filename + origin folder of encrypted-trashed items (opaque names on disk; shown under \u201CHidden\u201D in the trash tab). Default OFF so you can still tell what to restore when working outside the app.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFilenames).onChange(async n=>{this.plugin.settings.encryptTrashFilenames=n,await this.plugin.saveSettings()})),["trash","filename","encrypt"])),e.push(this.renderDef("Follow Obsidian's trash setting instead","OFF (recommended): encrypted-deleted notes go to Stashpad's own \u201C_deleted/\u201D store \u2014 the only trash location Stashpad fully controls, so it can encrypt, list, and restore them. ON: deletes follow Obsidian's \u201CDeleted files\u201D setting instead (system/OS trash or permanent). \u26A0\uFE0F Stashpad CANNOT encrypt or recover notes that go to the system trash \u2014 so the encrypted trash + recoverable trash view won't apply. Only turn this on if you specifically want Obsidian's native trash behavior.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFollowObsidian??!1).onChange(async n=>{this.plugin.settings.encryptTrashFollowObsidian=n||void 0,await this.plugin.saveSettings()})),["trash","obsidian","system","delete","encrypt"])),e.push(this.renderDef("Auto-lock after idle minutes","Forget the password from memory after this many idle minutes (0 = never). Re-prompts on the next encryption action.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.encryptionIdleLockMinutes??0)).onChange(async n=>{let o=Math.max(0,Math.floor(Number(n)||0));this.plugin.settings.encryptionIdleLockMinutes=o,await this.plugin.saveSettings()})),["auto-lock","idle","timeout","lock"])),e.push(this.renderDef("Hide titles of locked notes","Show a generic label on \u{1F512} locked placeholders instead of the note's title, so a glance at the vault doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.renderDef("Default archive folder",`Where the "Move selection to archive" command sends notes (they're auto-encrypted on arrival). Leaving this blank is fine \u2014 the command will just show you a list of your archive folders to pick from each time (or use the only one if you have a single archive). Mark a folder as an archive via the folder panel \u2192 right-click \u2192 "Mark as archive".`,i=>{let s=this.plugin.settings.archiveFolders??[];i.addDropdown(n=>{n.addOption("",s.length?"\u2014 pick from list each time \u2014":"\u2014 no archive folders yet \u2014");for(let a of s)n.addOption(a,a);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async a=>{this.plugin.settings.defaultArchiveFolder=a||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e}hotkeyItems(){let t={name:"Hotkeys",desc:"Each command has up to two slots. Click a slot and press a key (or chord) to bind it; press Backspace (delete on Mac) to cancel without binding; or click \u2715 to clear an existing binding. A \u21BA icon appears on any slot that differs from its shipped default \u2014 click it to revert that slot. When both slots are set, the pill on the right decides which one is active.",searchable:!1},e=Ke.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 X.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 X.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(r=>{new Ge(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 X.Setting(t).setName("Include Stashpad folders in scan").setDesc("By default, notes inside any known Stashpad folder are excluded \u2014 the index destination shouldn't index itself, and other Stashpad folders are usually already organized. Toggle on if you want them included anyway.").addToggle(r=>{r.setValue(this.plugin.settings.jdIndexIncludeStashpadFolders===!0),r.onChange(async l=>{this.plugin.settings.jdIndexIncludeStashpadFolders=l,await this.plugin.saveSettings(),this.display()})}),new X.Setting(t).setName("Designated Stashpad folder for Index").setDesc("Required. Must be a Stashpad folder. The index hierarchy is built here. New notes are created; nothing is deleted.").addText(r=>{new Ge(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 X.Setting(t).setName("Sort").setDesc("Order of entries within the same depth. Natural: numbers first then alphabetical (recommended). Created: by source file's creation time \u2014 handy when prefixes are word-only and don't carry ordering.").addDropdown(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=Re(this.app,this.plugin,this.plugin.settings),o=t.createEl("p",{cls:"setting-item-description"}),a=n.skippedStashpadNotes.length>0?` (${n.skippedStashpadNotes.length} Stashpad-folder note${n.skippedStashpadNotes.length===1?"":"s"} excluded by default)`:"";o.setText(`Preview: ${n.indexed.length} note${n.indexed.length===1?"":"s"} would be indexed, ${n.nonIndex.length} would NOT be indexed${a}.`),new X.Setting(t).setName("Actions").setDesc("Preview aggressively overwrites the designated folder's HOME note body (frontmatter preserved). Build creates Stashpad notes (existing notes with the same jdPrefix are updated, not duplicated).").addButton(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 Gi(this.app,this.plugin,this.plugin.settings);if(l.error==="no-dest"){new X.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(l.error==="no-home"){new X.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}Li(this.app,l),this.display()}catch(l){console.error("[stashpad] preview failed",l),new X.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 X.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new pi(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let p=await $s(this.app,this.plugin,this.plugin.settings);if(p.error==="no-dest"){new X.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(p.error==="dest-not-stashpad"){new X.Notice(`"${p.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder (or create one first).`,7e3);return}this.plugin.settings.jdIndexHasBuilt=!0,await this.plugin.saveSettings(),new X.Notice(`Built: ${p.created} created, ${p.updated} updated, ${p.skipped} skipped \u2192 ${p.destFolder}`,6e3),this.display()}catch(p){console.error("[stashpad] build failed",p),new X.Notice(`Build failed: ${p?.message??p}`,8e3)}}).open()})}).addButton(r=>{r.setButtonText(`Reveal in ${Cr()}`),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 X.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(l)){new X.Notice(`Folder "${l}" doesn't exist yet.`,5e3);return}try{let p=this.app.vault.adapter.basePath;if(p){let{shell:g}=window.require?.("electron")??{},d=`${p}/${l}`;g?.openPath?.(d)}else new X.Notice("Reveal in file system not supported on this platform.",4e3)}catch(p){new X.Notice(`Couldn't open folder: ${p?.message??p}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new X.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=ee()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new X.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(o=>{for(let a of e)o.addOption(a,a);o.setValue(i),o.onChange(a=>{i=a,n()})}),t.createEl("p",{cls:"setting-item-description",text:"Give each per-note color a friendly name. Filters and pickers display the alias instead of the hex code; the underlying color stays the same. The same hex in two Stashpads can have different aliases."});let s=t.createDiv({cls:"stashpad-color-aliases-list"}),n=()=>{s.empty();let o=this.plugin.collectColorsInFolder(i),a=new Map(o.map(p=>[p.hex,p.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(p=>({hex:p,count:a.get(p)??0}));c.sort((p,g)=>g.count-p.count||p.hex.localeCompare(g.hex));for(let p of c)this.renderColorAliasRow(s,i,p.hex,p.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=pt()),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 X.Setting(t).setName("Author name").setDesc("Your display name. Used in the note footer + as the author/contributor link target. Leave blank to opt out (notes won't be stamped).").addText(i=>{i.setValue(this.plugin.settings.authorName).onChange(async s=>{this.plugin.settings.authorName=s.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=pt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new X.Setting(t).setName("Author id (auto-assigned)").setDesc("Stable id appended to your name on links so coworkers with the same name don't collide. Generated once and shouldn't change. If you really need to reset it, clear and retype your author name above.").addText(i=>{i.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new X.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(i=>{i.setValue(this.plugin.settings.authorRole).onChange(async s=>{this.plugin.settings.authorRole=s.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new X.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(i=>{i.setValue(this.plugin.settings.authorDepartment).onChange(async s=>{this.plugin.settings.authorDepartment=s.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new X.Setting(t).setName("Show author in note footer").addToggle(i=>i.setValue(this.plugin.settings.showAuthor).onChange(async s=>{this.plugin.settings.showAuthor=s,await this.plugin.saveSettings()})),new X.Setting(t).setName("Show contributors in note footer").addToggle(i=>i.setValue(this.plugin.settings.showContributors).onChange(async s=>{this.plugin.settings.showContributors=s,await this.plugin.saveSettings()})),new X.Setting(t).setName("Show last edit time in note footer").addToggle(i=>i.setValue(this.plugin.settings.showLastEdit).onChange(async s=>{this.plugin.settings.showLastEdit=s,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){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 X.Setting(t).setName("Registry maintenance").setDesc("Rebuild scans the whole vault to reconstruct the list. Restore regenerates any deleted author pages across every Stashpad folder.").addButton(s=>s.setButtonText("Rebuild").onClick(async()=>{s.setDisabled(!0).setButtonText("Rebuilding\u2026");try{let n=await this.plugin.rebuildAuthorRegistry();new X.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new X.Notice(`Rebuild failed: ${n.message}`)}s.setDisabled(!1).setButtonText("Rebuild"),this.display()})).addButton(s=>s.setButtonText("Restore missing pages").onClick(async()=>{s.setDisabled(!0).setButtonText("Restoring\u2026");try{let n=await this.plugin.restoreMissingAuthorStubs();new X.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new X.Notice(`Restore failed: ${n.message}`)}s.setDisabled(!1).setButtonText("Restore missing pages")}));let e=this.plugin.authorRegistry.all();if(e.length===0){t.createEl("div",{cls:"setting-item-description",text:"No authors recorded yet. Rebuild to scan the vault."});return}let i=t.createDiv({cls:"stashpad-known-authors-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-known-author-row"}),o=n.createDiv({cls:"stashpad-known-author-main"});o.createSpan({cls:"stashpad-known-author-name",text:s.name||"(unnamed)"});let a=[];if(s.role&&a.push(s.role),s.department&&a.push(s.department),a.push(`id ${s.id}`),o.createSpan({cls:"stashpad-known-author-meta",text:` \xB7 ${a.join(" \xB7 ")}`}),s.renames&&s.renames.length>0){let 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 X.Setting(t).setName("Note templates per Stashpad").setDesc("Pick a markdown file to use as the default template for new notes in each Stashpad. The template's frontmatter becomes the new note's frontmatter (id/parent/created/attachments are always set by Stashpad). If the body contains {{body}}, that's where the user-typed body goes; otherwise the user body is followed by the template body.");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 p=l.createDiv({cls:"stashpad-note-template-suggest"});p.style.display="none";let g=a.createDiv({cls:"stashpad-note-template-warn"});g.style.display="none";let d=()=>this.app.vault.getMarkdownFiles().map(C=>C.path).filter(C=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(C)).sort(),u=()=>{p.empty();let C=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),m=w=>{let E=w.toLowerCase();return C.every(v=>E.includes(v))},y=d().filter(w=>m(w)).slice(0,12);if(y.length===0){p.style.display="none";return}p.style.display="";for(let w of y)p.createDiv({cls:"stashpad-note-template-suggest-item",text:w}).addEventListener("mousedown",async v=>{v.preventDefault(),c.value=w,await I(),p.style.display="none"})},I=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=()=>{g.empty(),g.style.display="none";let C=c.value.trim();if(!C)return;let m=this.app.vault.getAbstractFileByPath(C);if(!m||m.extension!=="md"){g.style.display="",g.setText(`\u26A0 "${C}" is not a markdown file in this vault.`);return}let y=this.app.metadataCache.getFileCache(m)?.frontmatter??{},E=oe.filter(v=>{let S=y[v];return!(S==null||typeof S=="string"&&S.trim()===""||Array.isArray(S)&&S.length===0)});E.length!==0&&(g.style.display="",g.setText(`\u26A0 Template defines ${E.join(", ")} \u2014 Stashpad always sets ${E.length===1?"this":"these"} on new notes, so the template value${E.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",u),c.addEventListener("input",u),c.addEventListener("blur",()=>{setTimeout(()=>{p.style.display="none"},150)}),c.addEventListener("change",()=>{I()}),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 p=this.plugin.settings.customPalette??[];new we(this.app,i,p,async g=>{if((g??null)===null&&s===0){await this.plugin.setColorAlias(e,i,""),n();return}if(g&&g.toLowerCase()===i){n();return}let d=await this.plugin.recolorAllInFolder(e,i,g??null);if(d>0)new X.Notice(`Recolored ${d} note${d===1?"":"s"}.`);else if(s===0){let u=this.plugin.getColorAlias(e,i);u&&(await this.plugin.setColorAlias(e,i,""),g&&await this.plugin.setColorAlias(e,g,u))}n()},async g=>{let d=(this.plugin.settings.customPalette??[]).filter(u=>u.toLowerCase()!==g.toLowerCase());return this.plugin.settings.customPalette=d,await this.plugin.saveSettings(),d}).open()};let r=o.createDiv({cls:"stashpad-color-alias-meta"});r.createSpan({cls:"stashpad-color-alias-hex",text:i}),r.createSpan({cls:"stashpad-color-alias-count",text:s===0?"\xB7 unused":`\xB7 ${s} note${s===1?"":"s"}`});let l=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,i)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,i,l.value),!l.value.trim()&&s===0&&n()};let c=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});l.value||(c.style.visibility="hidden"),c.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let i=t.createDiv({cls:"stashpad-folder-row"});i.createSpan({cls:"stashpad-folder-row-label",text:e});let s=i.createSpan({cls:"stashpad-folder-row-state"}),n=i.createDiv({cls:"stashpad-binding-pill"});n.setAttribute("role","switch"),n.setAttribute("tabindex","0");let o=n.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),r=()=>{let c=a();n.toggleClass("is-right",c),n.setAttribute("aria-checked",String(c)),o.setText(c?"X":"\u2713"),s.setText(c?"Excluded":"Included"),s.toggleClass("is-excluded",c),n.title=c?"Excluded \u2014 notes here won't appear in cross-Stashpad search. Click to include.":"Included \u2014 notes here appear in cross-Stashpad search. Click to exclude."},l=async()=>{let c=new Set(this.plugin.settings.searchExcludedFolders??[]);c.has(e)?c.delete(e):c.add(e),this.plugin.settings.searchExcludedFolders=[...c].sort(),r(),await this.plugin.saveSettings()};n.onclick=()=>void l(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},r()}renderFolderPlacementList(t){let e=this.plugin.settings,i=[{key:"folderPanelPinned",label:"Pinned",action:"Unpin"},{key:"folderPanelDownranked",label:"Downranked",action:"Reset"},{key:"folderPanelHidden",label:"Hidden",action:"Unhide"}];if(!i.some(o=>(e[o.key]??[]).length>0)){t.createEl("p",{cls:"setting-item-description"}).setText("No folders customized yet. Right-click a folder in the Stashpad folder panel to pin, downrank, or hide it.");return}let n=async o=>{e.folderPanelPinned=(e.folderPanelPinned??[]).filter(a=>a!==o),e.folderPanelDownranked=(e.folderPanelDownranked??[]).filter(a=>a!==o),e.folderPanelHidden=(e.folderPanelHidden??[]).filter(a=>a!==o),await this.plugin.saveSettings(),this.update?.()};for(let o of i){let a=[...e[o.key]??[]].sort();if(a.length===0)continue;t.createEl("div",{cls:"stashpad-folder-placement-group",text:`${o.label} (${a.length})`});let r=t.createDiv({cls:"stashpad-folder-list"});for(let l of a){let c=r.createDiv({cls:"stashpad-folder-row"});c.createSpan({cls:"stashpad-folder-row-label",text:l});let p=c.createEl("button",{text:o.action});p.onclick=()=>void n(l)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=d=>{let u=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),I=u.createEl("input",{type:"text"});I.readOnly=!0,I.placeholder="Click & press a key",I.value=Ii(i()[d]),I.classList.add("stashpad-binding-input");let f=()=>{I.size=Math.max(3,I.value.length||I.placeholder.length)};f();let C=d==="primary"?e.defaultPrimary:e.defaultSecondary??"";I.onclick=()=>{no(I,async E=>{this.plugin.settings.bindings[e.id][d]=E,I.value=Ii(E),f(),await this.plugin.saveSettings(),o(),w()})};let m=u.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});m.title="Clear this slot",m.onclick=async()=>{this.plugin.settings.bindings[e.id][d]="",I.value="",f(),await this.plugin.saveSettings(),o(),w()};let y=u.createEl("button",{cls:"stashpad-binding-revert"});(0,X.setIcon)(y,"rotate-ccw");let w=()=>{let v=i()[d]!==C;y.toggleClass("is-hidden",!v),y.title=C?`Revert to default (${Ii(C)})`:"Revert to default (no binding)"};return y.onclick=async()=>{this.plugin.settings.bindings[e.id][d]=C,I.value=Ii(C),f(),await this.plugin.saveSettings(),o(),w()},w(),I};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"}),p=c.createEl("input",{type:"checkbox"});p.title="Use both bindings simultaneously (overrides the L/R toggle)",c.createSpan({text:"Use both"}),p.onchange=async()=>{this.plugin.settings.bindings[e.id].useBoth=p.checked,await this.plugin.saveSettings(),o()},o=()=>{let d=i(),u=!!(d.primary&&d.secondary);p.checked=!!d.useBoth,p.disabled=!u,c.toggleClass("is-disabled",!u);let I=!!d.useBoth&&u;r.toggleClass("is-disabled",!u||I),r.toggleClass("is-right",d.preferRight),r.setAttribute("aria-checked",String(d.preferRight)),r.setAttribute("aria-disabled",String(!u||I)),l.setText(d.preferRight?"R":"L"),r.title=u?I?'Overridden by "Use both"':d.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let g=async()=>{let d=i();!d.primary||!d.secondary||(this.plugin.settings.bindings[e.id].preferRight=!d.preferRight,o(),await this.plugin.saveSettings())};r.onclick=()=>void g(),r.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),g())},o()}};var Ye=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=ut().inheritObsidianExclusions,t=A?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!qn(i.path)&&!On(i.path)&&!(A&&Kn(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 Oo.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 cs=class extends bt.ItemView{constructor(t,e){super(t);this.plugin=e;this.displayedPath=null;this.unsubscribeSelection=null;this.renderTimer=null;this.expanded=new Set;this.composerAutocomplete=null;this.composerInputEl=null;this.composerDraft="";this.composerDraftForId=null;this.displayedId=null;this.unsubscribeContent=null}getViewType(){return me}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 u=t.createDiv({cls:"stashpad-detail-empty"});(0,bt.setIcon)(u.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),u.createSpan({cls:"stashpad-detail-empty-text",text:"No Stashpad note selected. Cursor or click a note in a Stashpad list to inspect it here."});return}let n=s.file;this.displayedPath=n.path;let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=t.createDiv({cls:"stashpad-detail-scroll"}),r=a.createDiv({cls:"stashpad-detail-header"}),l=r.createDiv({cls:"stashpad-detail-titlerow"});l.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let c=l.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,bt.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(s.folder,s.id)};let p=r.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&p.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let u=p.createSpan({cls:"stashpad-detail-meta-color"});u.style.background=o.color,u.title=o.color}if(o.completed===!0&&p.createSpan({cls:"stashpad-detail-meta-chip is-completed",text:"\u2713 completed"}),typeof o.due=="string"||typeof o.due=="number"){let u=Date.parse(String(o.due)),I=Number.isNaN(u)?String(o.due):Xt(u,this.plugin.settings);p.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${I}`})}if(Array.isArray(o.tags))for(let u of o.tags.filter(I=>typeof I=="string"))p.createSpan({cls:"stashpad-detail-meta-tag",text:`#${u.replace(/^#/,"")}`});let g=a.createDiv({cls:"stashpad-detail-body"});try{let u=await this.app.vault.cachedRead(n),I=this.stripFrontmatter(u);await bt.MarkdownRenderer.render(this.app,I,g,n.path,this)}catch(u){g.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${u.message}`})}this.renderFooterMeta(a,n,o,s),this.renderChildren(a,s.folder,s.id),this.renderComposer(t,s);let d=this.composerInputEl;if(e&&d&&(d.focus(),i!=null)){let u=Math.min(i,d.value.length);try{d.setSelectionRange(u,u)}catch{}}}renderComposer(t,e){let i=t.createDiv({cls:"stashpad-detail-composer"}),s=i.createEl("textarea",{cls:"stashpad-detail-composer-input",attr:{placeholder:"Add a child note\u2026",rows:"2"}});this.composerInputEl=s,this.composerDraftForId===e.id?s.value=this.composerDraft:(this.composerDraft="",this.composerDraftForId=e.id),s.addEventListener("input",()=>{this.composerDraft=s.value,this.composerDraftForId=e.id}),s.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey&&!o.isComposing){if(this.composerAutocomplete?.isOpen?.())return;o.preventDefault(),this.submitComposer(e)}});let n=i.createEl("button",{cls:"stashpad-detail-composer-send",attr:{"aria-label":"Add child note"}});(0,bt.setIcon)(n.createSpan({cls:"stashpad-detail-composer-send-icon"}),"plus"),n.createSpan({cls:"stashpad-detail-composer-send-text",text:"Add child note"}),n.title="Add child note (Enter)",n.onclick=()=>void this.submitComposer(e),this.composerAutocomplete=new Ye(this.app,s),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==ct||typeof i.createNoteUnder!="function"){new bt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new bt.Notice(`Couldn't add note: ${s.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,i){let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==ct)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let r=a.createDiv({cls:"stashpad-detail-children-list"});for(let l of o)l.file&&this.renderDetailChildRow(r,s,n,e,l,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},r=typeof a.color=="string"?a.color:null,l=a.completed===!0,c=i.getChildren(n.id),p=c.length>0,g=`${s}|${n.id}`,d=this.expanded.has(g),u=t.createDiv({cls:"stashpad-detail-child-row"});l&&u.addClass("is-completed"),o>0&&(u.style.paddingLeft=`${o*16}px`),u.draggable=!0,u.dataset.id=n.id,u.addEventListener("dragstart",y=>{y.dataTransfer?.setData("text/plain",n.id),y.dataTransfer&&(y.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",y=>{y.preventDefault(),y.dataTransfer&&(y.dataTransfer.dropEffect="move");let w=u.getBoundingClientRect(),E=y.clientY-w.top<w.height/2;u.toggleClass("drop-before",E),u.toggleClass("drop-after",!E)}),u.addEventListener("dragleave",()=>{u.removeClass("drop-before"),u.removeClass("drop-after")}),u.addEventListener("drop",y=>{y.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let w=y.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let E=u.getBoundingClientRect(),v=y.clientY-E.top<E.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,v?"before":"after")}),u.oncontextmenu=y=>{y.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(y,w)};let I=u.createSpan({cls:"stashpad-detail-child-toggle"});if(p&&(ve(I,c.length,d),I.onclick=y=>{y.stopPropagation(),this.expanded.has(g)?this.expanded.delete(g):this.expanded.add(g),this.render()}),Me(a,"task")||a.task===!0||a.completed!==void 0){let y=u.createSpan({cls:"stashpad-detail-child-checkbox"});(0,bt.setIcon)(y,l?"check-square":"square"),y.title=l?"Mark not done":"Mark done",y.addEventListener("mousedown",w=>w.stopPropagation()),y.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),y.onclick=w=>{w.preventDefault(),w.stopPropagation();let E=i.get(n.id);E&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(E)}}let C=u.createSpan({cls:"stashpad-detail-child-icon"});(0,bt.setIcon)(C,p?"folder-tree":"file-text"),r&&(C.style.color=r);let m=u.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(m.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},p&&d)for(let y of c)this.renderDetailChildRow(t,e,i,s,y,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)?Xt(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==T&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new bt.Notice(`Couldn't open: ${i.message}`)}}};async function ds(h){let A=h.workspace.getLeavesOfType(me);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getRightLeaf(!1);if(!t){new bt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:me,active:!0}),h.workspace.revealLeaf(t)}var U=require("obsidian");Et();var ge=require("obsidian");Et();function Br(h,A){let t=h.vault.getAbstractFileByPath(A);if(!(t instanceof ge.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof ge.TFile?n.extension==="md"&&e.push(n):n instanceof ge.TFolder&&(ei.has(n.name)||i.push(n))}return e}var hs=class{constructor(A){this.app=A;this.nodes=new Map;this.byPath=new Map;this.listeners=new Set;this.orderProvider=null;this.synthetic=new Map;this.coalesceTimer=null;this.nodes.set(T,{id:T,parent:null,children:[],file:null,created:""})}setOrderProvider(A){this.orderProvider=A}onChange(A){return this.listeners.add(A),()=>this.listeners.delete(A)}emit(){for(let A of this.listeners)A()}rebuild(A){A!==void 0&&(this.currentFolder=A);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(T,{id:T,parent:null,children:[],file:null,created:""});let s=t?Br(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,p=this.synthetic.get(n.path),g=c??p;g&&(this.nodes.set(g.id,{...g,children:[],file:n}),this.byPath.set(n.path,g.id));continue}if(this.synthetic.delete(n.path),a===T){let l=this.nodes.get(T);l.file=n,l.created=o?.created??"",this.byPath.set(n.path,T);continue}let r=o?.parent??null;r===a&&(r=null),this.nodes.set(a,{id:a,parent:r??T,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===T)continue;let o=n.parent??T;(this.nodes.get(o)??this.nodes.get(T)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let r=this.nodes.get(o),l=this.nodes.get(a);return(r.created||"").localeCompare(l.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((r,l)=>a.set(r,l)),n.children.sort((r,l)=>{let c=a.has(r)?a.get(r):1/0,p=a.has(l)?a.get(l):1/0;return c===p?0:c-p})}}this.emit()}insertSynthetic(A){if(!A.file)return;let t=A.file.path;this.synthetic.set(t,A),this.nodes.set(A.id,A),this.byPath.set(t,A.id);let e=A.parent??T,i=this.nodes.get(e);i&&!i.children.includes(A.id)&&i.children.push(A.id),this.emit()}get(A){return this.nodes.get(A)}getRoot(){return this.nodes.get(T)}getChildren(A){let t=this.nodes.get(A);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let A=0;for(let t of this.nodes.values())t.file&&A++;return A}pathTo(A){let t=[],e=new Set,i=this.nodes.get(A);for(;i&&i.id!==T&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(A){return this.byPath.get(A)}snapshot(){let A={};for(let t of this.nodes.values())t.id===T||!t.file||(A[t.id]={parent:t.parent===T?null:t.parent,path:t.file.path});return A}hookMetadataCache(A){let t=r=>{let l=this.currentFolder;return l?typeof r!="string"?!1:r===l||r.startsWith(l+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),A())},16))},s=r=>{r instanceof ge.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof ge.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 ge.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(Te(A.path))return this.byPath.has(A.path)?this.applyDelete(A.path):!1;let t=this.app.metadataCache.getFileCache(A)?.frontmatter,e=t?.id,i=this.byPath.get(A.path);if(!e){if(i){let l=this.nodes.get(i);if(l&&l.file!==A)return l.file=A,!0}return!1}if(this.synthetic.delete(A.path),e===T){let l=this.nodes.get(T),c=t?.created??"",p=!1;return l.file!==A&&(l.file=A,p=!0),l.created!==c&&(l.created=c,p=!0),this.byPath.get(A.path)!==T&&(this.byPath.set(A.path,T),p=!0),p}let s=t?.parent??T,n=t?.created??"";if(!(s===T||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let l={id:e,parent:s,children:[],file:A,created:n};return this.nodes.set(e,l),this.byPath.set(A.path,e),this.attachToParent(l),this.resortChildrenOf(s),!0}let r=!1;if(a.file!==A&&(a.file=A,r=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??T),r=!0),a.parent!==s){let l=a.parent??T;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(l),this.resortChildrenOf(s),r=!0}return r}applyDelete(A){let t=this.byPath.get(A);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(A),this.synthetic.delete(A),!0;this.detachFromParent(e);let i=this.nodes.get(T);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=T,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(T),this.nodes.delete(t),this.byPath.delete(A),this.synthetic.delete(A),!0}applyRename(A,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||A.path===e||A.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(A);if(Te(A.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(A);this.byPath.delete(t),this.byPath.set(A.path,n);let o=this.nodes.get(n);return o&&(o.file=A),!0}detachFromParent(A){let t=this.nodes.get(A.parent??T);if(!t)return;let e=t.children.indexOf(A.id);e>=0&&t.children.splice(e,1)}attachToParent(A){let t=this.nodes.get(A.parent??T);t||(t=this.nodes.get(T)),t.children.includes(A.id)||t.children.push(A.id)}resortChildrenOf(A){let t=this.nodes.get(A);if(t&&(t.children.sort((e,i)=>{let s=this.nodes.get(e),n=this.nodes.get(i);return(s.created||"").localeCompare(n.created||"")}),this.orderProvider)){let e=this.orderProvider(A);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,a=i.has(n)?i.get(n):1/0;return o===a?0:o-a})}}}};var kn=class{constructor(){this.enabled=!1;this.buckets=new Map}record(A,t){if(!this.enabled)return;let e=this.buckets.get(A);e||(e={count:0,total:0,max:0},this.buckets.set(A,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(A,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(A,performance.now()-e)}}async timeAsync(A,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(A,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let A=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(A.length===0)return"Stashpad perf: no samples (enable profiling, then use the app).";let t=["**Stashpad performance profile**","","| label | count | total (ms) | avg (ms) | max (ms) |","| --- | ---: | ---: | ---: | ---: |"];for(let e of A)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` -`)}},Nt=new kn;var Ko=".stashpad-order.json",ze=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}/${Ko}`,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}/${Ko}`,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 wi={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"},Sn=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],Qr=new Set(Sn),Yo=".stashpad-sort.json",gs=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}/${Yo}`,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"&&Qr.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}/${Yo}`,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 pe="parentLink",Ve="children";var Is=class Is{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||!ut().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(),Is.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[pe]=="string"?n[pe]:null,a=n?.[Ve],r=Array.isArray(a)?a.filter(l=>typeof l=="string"):[];if((o??null)!==(i??null)||r.length!==s.length)return!0;for(let l=0;l<r.length;l++)if(r[l]!==s[l])return!0;return!1}async syncOne(A){let e=this.getTree().get(A);if(!e||!e.file||!this.wouldWrite(A))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await Nt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[pe]=i:delete n[pe],s.length>0?n[Ve]=s:delete n[Ve]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(A){if(A.id===T)return null;let t=this.getTree();if(!A.parent||A.parent===T){let i=t.getRoot();return i&&i.id!==A.id&&i.file?ps(i.file.path):null}let e=t.get(A.parent);return e?.file?ps(e.file.path):null}computeChildrenLinks(A){return this.getTree().getChildren(A.id).filter(e=>!!e.file).map(e=>ps(e.file.path))}};Is.PACING_MS=100;var us=Is;async function We(h,A){let t=A.endsWith("/")?A:A+"/",e=new Map,i=new Map;for(let l of h.vault.getMarkdownFiles()){if(l.path!==A&&!l.path.startsWith(t))continue;let c=h.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id:null;if(!p)continue;let g=typeof c?.parent=="string"?c.parent:T;e.set(p,{file:l,id:p,parent:g});let d=i.get(g)??[];d.push(p),i.set(g,d)}let s=l=>ps(l.file.path),n=l=>{if(l.id===T)return null;if(l.parent===T||!l.parent){let p=e.get(T);return p?s(p):null}let c=e.get(l.parent);return c?s(c):null},o=l=>{let c=i.get(l.id)??[],p=[];for(let g of c){let d=e.get(g);d&&p.push(s(d))}return p},a=0,r=0;for(let l of e.values()){a+=1;let c=n(l),p=o(l),g=h.metadataCache.getFileCache(l.file)?.frontmatter,d=g&&typeof g[pe]=="string"?g[pe]:null,u=g?.[Ve],I=Array.isArray(u)?u.filter(m=>typeof m=="string"):[],f=(d??null)===(c??null),C=I.length===p.length&&I.every((m,y)=>m===p[y]);if(!(f&&C))try{await h.fileManager.processFrontMatter(l.file,m=>{c?m[pe]=c:delete m[pe],p.length>0?m[Ve]=p:delete m[Ve]}),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 ps(h){return`[[${h.replace(/\.md$/i,"")}]]`}Gt();Ue();var fs=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();Os();var St=vt.moment;function Dn(h){let A=h.trim().toLowerCase();if(!A)return null;let t=Date.now(),e=u=>St(u).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 u=parseInt(a[1],10),I=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&u<12&&(u+=12),f==="am"&&u===12&&(u=0),u>=0&&u<24&&I>=0&&I<60&&(s=(u*3600+I*60)*1e3,n=!0,o=A.replace(a[0]," ").replace(/\s+/g," ").trim())}let r=u=>n?u+s:u;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"],p=l.indexOf(o)>=0?l.indexOf(o):c.indexOf(o);if(p>=0){let u=St().startOf("day"),f=(u.day()-p+7)%7;return r(u.subtract(f,"days").valueOf())}let g=/^(\d+)\s*([dwmy])$/.exec(o);if(g){let u=parseInt(g[1],10),I={d:"days",w:"weeks",m:"months",y:"years"}[g[2]];return r(St().subtract(u,I).startOf("day").valueOf())}let d=St(o,["YYYY-MM-DD","YYYY/MM/DD","MM-DD-YYYY","MM/DD/YYYY","M-D-YYYY","M/D/YYYY"],!0);return d.isValid()?r(d.startOf("day").valueOf()):null}function zo(h){let A={text:[],filters:{}},t=(h||"").trim();if(!t)return A;let e=/\b(in|before|after|on):\s*(?:\[([^\]]*)\]|([^]*?)(?=\s+(?:in|before|after|on):|$))/gi,i=t,s;for(;(s=e.exec(t))!=null;){let n=s[1].toLowerCase(),o=(s[2]!==void 0?s[2]:s[3]??"").trim();if(o){if(n==="in")A.filters.in=o.toLowerCase();else if(n==="before"){let a=Dn(o);a!=null&&(A.filters.before=a)}else if(n==="after"){let a=Dn(o);a!=null&&(A.filters.after=a)}else if(n==="on"){let a=Dn(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 ie=class h extends vt.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==T?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===T&&this.notes.push({node:a,title:i,body:""});for(let r of this.tree.getChildren(n))s(r.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(T))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(a=>{o.body=this.stripFm(a)})}}createdMsFor(t){if(t.node?.created){let e=Date.parse(t.node.created);if(!Number.isNaN(e))return e}return t.cross?.file?.stat?.ctime!=null?t.cross.file.stat.ctime:null}stripFm(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` ----`,3);return e===-1?t:t.slice(e+4).replace(/^\r?\n/,"")}getSuggestions(t){let e=t.trim().toLowerCase(),i=zo(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=E=>C.every(v=>E.toLowerCase().includes(v)),y=E=>{if(!o.has(E)){o.add(E);for(let v of this.tree.getChildren(E))y(v.id)}};for(let E of this.notes)!E.node||E.cross||m(E.title)&&y(E.node.id);let w=new Map;for(let E of this.notes){if(!E.cross)continue;let v=w.get(E.cross.folder)??[];v.push(E),w.set(E.cross.folder,v)}for(let[E,v]of w){let S=new Map;for(let N of v){let Q=N.cross?.parentId??null;if(!Q)continue;let D=S.get(Q)??[];D.push(N.cross.id),S.set(Q,D)}let M=new Set;a.set(E,M);let F=N=>{if(!M.has(N)){M.add(N);for(let Q of S.get(N)??[])F(Q)}};for(let N of v)m(N.title)&&F(N.cross.id)}}let r=C=>{let m=i.filters;if(o||a)if(C.cross){let y=a?.get(C.cross.folder);if(!y||!y.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 y=this.createdMsFor(C);if(y==null||m.before!=null&&y>=m.before||m.after!=null&&y<=m.after||m.on&&(y<m.on.start||y>=m.on.end))return!1}return!0},l=C=>n(C.toLowerCase()),c=this.notes.filter(C=>!C.cross),p=this.notes.filter(C=>C.cross),g=(C,m)=>({id:C.cross?`cross:${C.cross.folder}:${C.cross.id}`:C.node.id,label:C.title,node:C.node,kind:"note",bodyPreview:this.previewFromBody(C.body,m),matchLine:m,crossFolder:C.cross?.folder,crossFile:C.cross?.file,crossId:C.cross?.id}),d=C=>{let m=[];for(let y of C)if(r(y))if(this.opts.mode==="search"){if(!e){m.push(g(y,-1));continue}let w=n(y.title.toLowerCase()),E=y.body.split(/\r?\n/),v=[];for(let M=0;M<E.length;M++)l(E[M])&&v.push(M);let S=v.length>0||n(y.body.toLowerCase());if(!w&&!S)continue;if(v.length===0)m.push(g(y,-1));else{let M=[],F=-100;for(let Q of v)Q-F>5&&M.push(Q),F=Q;let N=5;for(let Q of M.slice(0,N))m.push(g(y,Q))}}else{if(e&&!n(y.title.toLowerCase())&&!n(y.body.toLowerCase()))continue;m.push(g(y,-1))}return m},u=d(c),I=[...u];if(this.opts.mode==="search"?e?!0:u.length<10:!!e){let C=d(p);this.opts.mode==="search"&&!e&&(I.length=Math.min(I.length,50)),I.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(y=>{let w=y.split("/").pop()??y;return n(`${y.toLowerCase()} ${w.toLowerCase()}`)})&&I.push(m):I.unshift(m))}if(this.opts.allowCreate&&e&&!I.some(C=>C.label.trim().toLowerCase()===e)&&I.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let C=y=>y.kind==="note"&&(y.id===T||y.crossId===T)&&n(y.label.toLowerCase()),m=I.filter(C);if(m.length>0){let y=I.filter(w=>!C(w));I.splice(0,I.length,...m,...y)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&I.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),I}loadExcludedNotes(){if(this.includeExcluded||!this.opts.excludedFolderNotes)return;this.includeExcluded=!0;for(let e of this.opts.excludedFolderNotes())this.notes.push({node:null,title:e.title,body:e.body,cross:e});for(let e of this.notes)!e.cross||e.body||!e.cross.file||this.app.vault.cachedRead(e.cross.file).then(i=>{e.body=this.stripFm(i)});let t=this.inputEl;t&&(t.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(()=>t.dispatchEvent(new Event("input",{bubbles:!0})),250))}previewFromBody(t,e){let i=t.split(/\r?\n/);if(e<0)return i.filter(a=>a.trim().length>0).slice(0,3).join(` +${l}`}async function Ho(d,l){if(!(!l||await d.vault.adapter.exists(l)))try{await d.vault.createFolder(l)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}var he="stashenc",xr="stashmeta";function pe(d){return d.replace(/\.stashenc$/,`.${xr}`)}async function Go(d,l){try{return JSON.parse(await d.vault.adapter.read(pe(l)))}catch{return null}}async function ge(d,l,t){let e=l.replace(/\/+$/,""),i=[];for(let A of d.vault.getMarkdownFiles()){if((A.parent?.path?.replace(/\/+$/,"")??"")!==e)continue;let c;try{c=wt(await d.vault.read(A)).fm}catch{continue}typeof c.id=="string"&&i.push({id:c.id,file:A,parent:typeof c.parent=="string"?c.parent:null,created:typeof c.created=="string"?c.created:""})}let s=i.find(A=>A.id===t);if(!s)return null;let n=new Map;for(let A of i){if(!A.parent)continue;let c=n.get(A.parent)??[];c.push(A),n.set(A.parent,c)}let o=[],a=new Set([t]),r=[t];for(;r.length;){let A=[];for(let c of r)for(let g of n.get(c)??[])a.has(g.id)||(a.add(g.id),o.push(g),A.push(g.id));r=A}return{rootNote:s,descendants:o,parentId:s.parent}}function vn(d){if(!d)return null;let l=d.replace(/\/+$/,"");return!l||l.startsWith("/")||l.includes("\\")||/^[a-zA-Z]:/.test(l)||l.split("/").some(t=>t===".."||t===".")?null:l}async function Fn(d,l,t){await d.vault.adapter.writeBinary(l,t);let e;try{e=new Uint8Array(await d.vault.adapter.readBinary(l))}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(l)}catch{}throw new Error("The encrypted file on disk doesn't match what was written (bad write?). Nothing was deleted.")}}function ls(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function Oe(d){return(d.replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim()||"locked").slice(0,60)}async function Lo(d,l,t){let e=new Set(l.map(a=>a.file.path)),i=new Map;for(let a of l)for(let r of await rs(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 l){let r=t?.get(a.file.path);if(r!=null)try{let A=await d.vault.adapter.stat(a.file.path);if(A&&A.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(A){console.warn("[Stashpad] couldn't delete plaintext note",a.file.path,A),o.push(a.file.path)}}for(let[a,r]of i)if(!s.has(a))try{await d.vault.delete(r)}catch(A){console.warn("[Stashpad] couldn't delete exclusive attachment",a,A),o.push(a)}return{unpurged:o}}async function Jo(d,l,t,e,i=null,s=!1,n){let o=await ge(d,l,t);if(!o)throw new Error("Couldn't find that note to lock.");let{rootNote:a,descendants:r,parentId:A}=o,c=[a,...r],g=new Map;for(let E of c)try{let v=await d.vault.adapter.stat(E.file.path);v&&g.set(E.file.path,v.mtime)}catch{}let p=await ce(d,{rootNotes:[{id:a.id,file:a.file}],allDescendants:r.map(E=>({id:E.id,file:E.file})),sourceFolder:l}),h=await yi(p,e),u=await Ae(h,e);if(u.length!==p.length)throw new Error("Encryption self-check failed (size mismatch).");for(let E=0;E<p.length;E++)if(u[E]!==p[E])throw new Error("Encryption self-check failed (content mismatch).");let I=(n??l).replace(/\/+$/,"");n&&!await d.vault.adapter.exists(I)&&await d.vault.adapter.mkdir(I);let f=Oe(s?t:ls(a.file)),m=`${I}/${f}.${he}`;for(let E=1;await d.vault.adapter.exists(m);E++)m=`${I}/${f} (${E}).${he}`;await Fn(d,m,h);let C=c,y={v:1,parentId:A,title:s?"":ls(a.file),count:C.length,created:a.created,rootId:t,prevSibling:i};try{await d.vault.adapter.write(pe(m),JSON.stringify(y))}catch(E){console.warn("[Stashpad] couldn't write lock sidecar",E)}let{unpurged:w}=await Lo(d,C,g);return{blobPath:m,noteCount:C.length,rootId:t,parentId:A,title:y.title,created:a.created,unpurged:w}}async function qo(d,l,t,e,i){let s=new Uint8Array(await d.vault.adapter.readBinary(l));if(!Ot(s))throw new Error("Not an encrypted bundle.");let n=await Ae(s,t),o=vn(i)??l.replace(/\/[^/]*$/,""),a=await $t(d,n,o,e,{dedupeExisting:!0});await d.vault.adapter.remove(l);try{await d.vault.adapter.remove(pe(l))}catch{}return{notesWritten:a.notesWritten,restoredTo:o}}var Ut="_deleted";function Nr(d){let l="";for(let t=0;t<d.length;t++)l+=String.fromCharCode(d[t]);return btoa(l)}function Mr(d){let l=atob(d),t=new Uint8Array(l.length);for(let e=0;e<l.length;e++)t[e]=l.charCodeAt(e);return t}async function kn(d,l,t,e){let i=vn(t?.originalFolder);if(!i&&t?.originalFolderEnc&&e)try{i=vn(new TextDecoder().decode(await Ae(Mr(t.originalFolderEnc),e)))}catch{i=null}if(i)return await d.vault.adapter.exists(i)||await d.vault.adapter.mkdir(i),i;let s=l.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 Sn(d){let l=[""];for(;l.length;){let t=l.shift(),e;try{e=await d.vault.adapter.list(t||"/")}catch{continue}if(e.files.some(i=>i.endsWith(`.${he}`)))return!0;for(let i of e.folders)i===".obsidian"||i.endsWith("/.obsidian")||l.push(i)}return!1}async function Oo(d,l,t,e,i,s=!1){let n=await ge(d,l,t);if(!n)throw new Error("Couldn't find that note to delete.");let{rootNote:o,descendants:a,parentId:r}=n,A=[o,...a],c=new Map;for(let E of A)try{let v=await d.vault.adapter.stat(E.file.path);v&&c.set(E.file.path,v.mtime)}catch{}let g=await ce(d,{rootNotes:[{id:o.id,file:o.file}],allDescendants:a.map(E=>({id:E.id,file:E.file})),sourceFolder:l}),p=await yi(g,e),h=await Ae(p,e);if(h.length!==g.length)throw new Error("Encryption self-check failed (size).");for(let E=0;E<g.length;E++)if(h[E]!==g[E])throw new Error("Encryption self-check failed (content).");await d.vault.adapter.exists(Ut)||await d.vault.adapter.mkdir(Ut);let u=l.replace(/\/+$/,""),I=u.split("/").pop()||"vault",f=Oe(s?t:`${I} ${ls(o.file)}`),m=`${Ut}/${f}.${he}`;for(let E=1;await d.vault.adapter.exists(m);E++)m=`${Ut}/${f} (${E}).${he}`;await Fn(d,m,p);let C=A,y={v:1,kind:"deleted",originalFolder:s?"":u,...s?{originalFolderEnc:Nr(await yi(new TextEncoder().encode(u),e))}:{},parentId:r,title:s?"":ls(o.file),count:C.length,created:o.created,rootId:t,deletedAt:i};try{await d.vault.adapter.write(pe(m),JSON.stringify(y))}catch(E){console.warn("[Stashpad] couldn't write deleted sidecar",E)}let{unpurged:w}=await Lo(d,C,c);return{blobPath:m,noteCount:C.length,rootId:t,originalFolder:u,title:y.title,unpurged:w}}async function Ko(d,l,t,e){let i=new Uint8Array(await d.vault.adapter.readBinary(l));if(!Ot(i))throw new Error("Not an encrypted bundle.");let s=await As(d,l),n=await kn(d,l,s,t),o=await Ae(i,t),a=await $t(d,o,n,e,{dedupeExisting:!0});await d.vault.adapter.remove(l);try{await d.vault.adapter.remove(pe(l))}catch{}return{notesWritten:a.notesWritten,restoredTo:n}}async function As(d,l){try{return JSON.parse(await d.vault.adapter.read(pe(l)))}catch{return null}}var Kt=".trash";async function Tr(d,l){let t=[],e=[l];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 Hr(d){let l=d.split("/").filter(Boolean);if(l.length===0)return null;for(let t of l)if(t===".."||t==="."||t.includes("\\")||/^[a-zA-Z]:/.test(t))return null;return l.join("/")}async function Yo(d,l,t,e=!1){if(!await d.vault.adapter.exists(Kt))return null;let i=await Tr(d,Kt);if(i.length===0)return null;let{default:s}=await Promise.resolve().then(()=>Pi(vi())),n=new s,o=new Map;for(let u of i){let I=u.slice(Kt.length+1);n.file(`files/${I}`,await d.vault.adapter.readBinary(u));try{let f=await d.vault.adapter.stat(u);f&&o.set(u,f.mtime)}catch{}}let a=new Uint8Array(await n.generateAsync({type:"arraybuffer"})),r=await yi(a,l),A=await Ae(r,l);if(A.length!==a.length)throw new Error("Encryption self-check failed (size).");for(let u=0;u<a.length;u++)if(A[u]!==a[u])throw new Error("Encryption self-check failed (content).");await d.vault.adapter.exists(Ut)||await d.vault.adapter.mkdir(Ut);let c=Oe(e?`trash-${t.replace(/[^0-9]/g,"").slice(0,14)}`:"Obsidian trash backfill"),g=`${Ut}/${c}.${he}`;for(let u=1;await d.vault.adapter.exists(g);u++)g=`${Ut}/${c} (${u}).${he}`;await Fn(d,g,r);let p={v:1,kind:"rawtrash",originalFolder:Kt,parentId:null,title:e?"":"Obsidian trash (backfill)",count:i.length,created:t,rootId:"",deletedAt:t};try{await d.vault.adapter.write(pe(g),JSON.stringify(p))}catch(u){console.warn("[Stashpad] couldn't write backfill sidecar",u)}let h=[];for(let u of i){let I=o.get(u);try{if(I!=null){let f=await d.vault.adapter.stat(u);if(f&&f.mtime!==I){h.push(u);continue}}await d.vault.adapter.remove(u)}catch(f){console.warn("[Stashpad] couldn't delete trash file",u,f),h.push(u)}}return{blobPath:g,fileCount:i.length,unpurged:h}}async function zo(d,l,t){let e=new Uint8Array(await d.vault.adapter.readBinary(l));if(!Ot(e))throw new Error("Not an encrypted bundle.");let i=await Ae(e,t),{default:s}=await Promise.resolve().then(()=>Pi(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 A=Hr(a.slice(6));if(!A){console.warn("[Stashpad] skipped unsafe trash entry",a);continue}let c=`${Kt}/${A}`.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=`${Kt}/${A}`;for(let h=1;await d.vault.adapter.exists(p);h++)p=`${Kt}/${A.replace(/(\.[^./]*)?$/,` (${h})$1`)}`;await d.vault.adapter.writeBinary(p,await r.async("arraybuffer")),o++}await d.vault.adapter.remove(l);try{await d.vault.adapter.remove(pe(l))}catch{}return{filesWritten:o}}async function Vo(d){if(!await d.vault.adapter.exists(Ut))return[];try{return(await d.vault.adapter.list(Ut)).files.filter(t=>t.endsWith(`.${he}`))}catch{return[]}}var Fi=null,cs=new Set;function ds(d){if(Fi!==d){Fi=d;for(let l of cs)l()}}function se(){return Fi}function $o(d){if(Fi===d){Fi=null;for(let l of cs)l()}}function Wo(d){return cs.add(d),()=>cs.delete(d)}function Pr(){return V.Platform.isMacOS?"Finder":V.Platform.isWin?"File Explorer":"file manager"}var Ke=[{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 xn(){let d={};for(let l of Ke)d[l.id]={primary:l.defaultPrimary,secondary:l.defaultSecondary??"",preferRight:!1,useBoth:!!l.defaultUseBoth};return d}var ue={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:wi(),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,okfEnabled:!1,okfTemplatePath:"",drafts:{},lastSubmitted:{},bindings:xn()},Xo=JSON.parse(JSON.stringify(ue)),bn=new Set;function ut(){return Xo}function Nn(d){Xo=d;for(let l of bn)l()}function Zo(d){return bn.add(d),()=>bn.delete(d)}function gs(d){try{let l=d.internalPlugins?.plugins?.templates;if(!l?.enabled)return null;let t=l.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var hs=[{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:"okf",label:"Open Knowledge Format (OKF)"},{id:"hotkeys",label:"Hotkeys"}],Dn=null;function Ur(d,l){return Dn||(Dn=class extends V.SettingPage{constructor(t,e){super(),this.title=t,this._renderFn=e}display(){this.containerEl.empty(),this._renderFn(this.containerEl)}}),new Dn(d,l)}var ps=class extends V.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){if(V.SettingPage){super.display();return}let{containerEl:t}=this;t.empty();for(let e of hs){t.createEl("h2",{text:e.label});let i=this.itemsForTab(e.id);if(i)for(let s of i){let n=new V.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 hs.map(t=>{let e=this.itemsForTab(t.id);return e?{type:"page",name:t.label,items:e}:{type:"page",name:t.label,page:()=>Ur(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();case"okf":return this.okfItems();default:return null}}renderTabContent(t,e){switch(e){case"authorship":this.renderAuthorshipSection(t);break;case"templates":this.renderTemplatesTab(t);break;case"jdindex":this.renderJdIndexSection(t);break}}diagnosticsItems(){let t=new Set(this.plugin.settings.mutedNotificationCategories??[]),e=Object.keys(nn);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 V.Notice("No log yet \u2014 make some changes first.");return}let a=await n.read(o);new He(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=nn[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 di(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 V.Notice("No log yet \u2014 make some changes first.");return}let r=await o.read(a);new He(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,A=>A.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 Ge(this.app,n.inputEl),n.setValue(this.plugin.settings.folder).setPlaceholder("Stashpad").onChange(async o=>{let a=(o||"").trim().replace(/^\/+|\/+$/g,"")||ue.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 V.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,"")||ue.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:A,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)`),A>0&&h.push(`renamed ${A} note${A===1?"":"s"} to match body`),c>0&&h.push(`rebuilt author registry (${c} author${c===1?"":"s"})`),new V.Notice(`Stashpad: ${h.join("; ")}.`)}catch(o){new V.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=gs(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: ${Zt(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:Vt).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(A=>A.trim().toLowerCase()).filter(Boolean),await t()})}).addExtraButton(a=>a.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...Vt],n&&(n.value=Vt.join(` +`)),await t()}))},["slug","stopwords","filename","title"])),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 V.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 V.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 V.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(r),new V.Notice(`Created Stashpad "${r}".`),o&&(o.value=""),await this.plugin.waitForStashpadFolder(r,2e3),this.update?.()}catch(A){new V.Notice(`Couldn't create: ${A.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 V.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");let s=i.createDiv({cls:"stashpad-beta-row"});s.createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),s.createEl("span",{cls:"stashpad-beta-note",text:"Encryption is in beta \u2014 keep your own backups of anything important."}),i.createEl("div",{cls:"stashpad-ai-disclaimer"}).setText("\u26A0\uFE0F AI-built, NOT human-audited. This encryption was written by an AI assistant \u2014 not designed, reviewed, or security-audited by a human, and not tested by any security professional. It may carry real security, privacy, and DATA-LOSS risks. Treat it as a best-effort nice-to-have that might buy a little time against a casual snoop \u2014 nothing is guaranteed. Do NOT rely on it for anything sensitive, and always keep your own unencrypted backups of anything important."),i.createEl("p",{cls:"setting-item-description"}).setText("\u26A0\uFE0F Encryption protects what you lock in this vault. Each device unlocks with its own password (which never leaves the device); the vault key is shared with collaborators by approving their device \u2014 no shared password. If everyone with access loses their password, anything encrypted is gone for good. While encrypting, avoid a sync/cloud service writing the vault mid-operation \u2014 it can corrupt files.");let n=()=>t.argonProbe(),o=()=>this.plugin.settings.authorName?.trim()||"This device",a=t.accessState();t.refresh().then(()=>{t.accessState()!==a&&this.update?.()});let r=a;if(r==="none"){new V.Setting(i).setName("Encryption").setDesc("Not set up yet in this vault.").addButton(p=>p.setButtonText("Set up password\u2026").setCta().onClick(()=>{new Nt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:h,remember:u})=>{if(!h)return"Enter a password.";try{await t.setup(h,u,o())}catch(I){return I.message}return new V.Notice("Encryption set up \u2014 unlocked for this session."),this.update?.(),null}}).open()}));return}if(r==="outsider"&&!t.isUnlocked()){t.hasSharedPassword()&&new V.Setting(i).setName("This vault is encrypted").setDesc("Enter the shared password (ask whoever set it up \u2014 they'll send it via a password manager or secure message).").addButton(p=>p.setButtonText("Unlock with shared password\u2026").setCta().onClick(()=>{new Nt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:h,remember:u})=>await t.unlock(h,u)?(new V.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password (or the keyfile hasn't synced here yet)."}).open()})),new V.Setting(i).setName(t.hasSharedPassword()?"Or request device approval":"This vault is encrypted by a collaborator").setDesc("Request access \u2014 pick a password for THIS device, then ask an existing member to approve it. Once approved (and the keyfile syncs to you), you'll unlock with that password. No shared secret.").addButton(p=>p.setButtonText("Request access\u2026").onClick(()=>{new Nt(this.app,{mode:"setup",offerKeychain:!0,kdfProbe:n,onSubmit:async({next:h,remember:u})=>{if(!h)return"Choose a password for this device.";try{await t.requestAccess(o(),h,u)}catch(I){return I.message}return new V.Notice("Access requested. An existing member can now approve this device."),this.update?.(),null}}).open()}));return}if(r==="pending"){new V.Setting(i).setName("Access requested \u2014 waiting for approval").setDesc("An existing member needs to approve this device. After they do and the keyfile syncs here, reopen this page to unlock with the password you chose.").addButton(p=>p.setButtonText("Try unlock now").setCta().onClick(()=>{new Nt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:h,remember:u})=>await t.unlock(h,u)?(new V.Notice("Encryption unlocked."),this.update?.(),null):"Not approved yet (or wrong password). Ask a member to approve this device, then try again."}).open()})).addButton(p=>p.setButtonText("Cancel request").onClick(async()=>{let h=t.myIdentityId();h&&await t.denyJoinRequest(h),new V.Notice("Access request cancelled."),this.update?.()}));return}let A=t.kdf()==="argon2id"?"Argon2id":t.kdf()==="pbkdf2"?"PBKDF2 (fallback)":"",c=t.isRemembered()?" \xB7 remembered on this device":"";if(new V.Setting(i).setName("Status").setDesc(`${t.isUnlocked()?"Set up \xB7 unlocked this session":"Set up \xB7 locked"}${A?` \xB7 ${A}`:""}${c}`),t.isUnlocked()?new V.Setting(i).setName("Lock now").setDesc("Forget the password from memory until you re-enter it.").addButton(p=>p.setButtonText("Lock now").onClick(()=>{t.lock(),new V.Notice("Encryption locked."),this.update?.()})):new V.Setting(i).setName("Unlock").setDesc("Enter your password to use encryption this session.").addButton(p=>p.setButtonText("Unlock\u2026").setCta().onClick(()=>{new Nt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:h,remember:u})=>await t.unlock(h,u)?(new V.Notice("Encryption unlocked."),this.update?.(),null):"Wrong password. Try again."}).open()})),t.keychainAvailable()&&t.isRemembered()&&new V.Setting(i).setName("Forget password on this device").setDesc("Drops ONLY the copy saved in this device's keychain \u2014 your encryption stays set up and nothing is decrypted or deleted. You'll just re-type the password next session. (To turn encryption off entirely, use \u201CRemove encryption\u201D below.)").addButton(p=>p.setButtonText("Forget on this device").onClick(async()=>{await t.forgetKeychain(),new V.Notice("Removed from this device's keychain \u2014 encryption still set up."),this.update?.()})),t.amIMember()&&new V.Setting(i).setName("Change this device's password").setDesc("Re-wraps THIS device's key under a new password \u2014 doesn't re-encrypt files or affect other people.").addButton(p=>p.setButtonText("Change\u2026").onClick(()=>{new Nt(this.app,{mode:"change",offerKeychain:!0,kdfProbe:n,onSubmit:async({current:h,next:u,remember:I})=>await t.changePassword(h,u,I)?(new V.Notice("Password changed."),this.update?.(),null):"Wrong current password. Try again."}).open()})),t.amIMember()&&new V.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(p=>{p.setButtonText("Remove\u2026").onClick(async()=>{if(await Sn(this.app)){new V.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 li(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:h=>t.verifyPassword(h),onConfirm:async()=>{if(await Sn(this.app)){new V.Notice("Locked notes appeared while this dialog was open \u2014 removal cancelled. Decrypt everything first.",1e4);return}await t.clear(),new V.Notice("Encryption removed."),this.update?.()}}).open()}),p.setWarning?.(!0)}),new V.Setting(i).setName("Sharing").setHeading(),t.isUnlocked()?t.hasSharedPassword()?new V.Setting(i).setName("Shared password").setDesc("ON \u2014 anyone who knows it can unlock this vault (no approval). Share it via a password manager or secure message; don't send it in the clear.").addButton(p=>p.setButtonText("Change\u2026").onClick(()=>{new Nt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Change shared password",intro:"Everyone who unlocks with the shared password will need the new one. Re-share it securely after changing.",onSubmit:async({next:h})=>{if(!h)return"Enter a password.";try{await t.setSharedPassword(h)}catch(u){return u.message}return new V.Notice("Shared password updated."),this.update?.(),null}}).open()})).addButton(p=>{p.setButtonText("Turn off").onClick(async()=>{await t.removeSharedPassword(),new V.Notice("Shared password turned off."),this.update?.()}),p.setWarning?.(!0)}):new V.Setting(i).setName("Shared password").setDesc("OFF \u2014 set one passphrase that everyone types to unlock (the simplest way to share). Anyone who knows it can unlock; turning it off later doesn't claw back copies already synced elsewhere.").addButton(p=>p.setButtonText("Set shared password\u2026").onClick(()=>{new Nt(this.app,{mode:"setup",offerKeychain:!1,kdfProbe:n,title:"Set shared password",intro:"One passphrase everyone types to unlock this vault. Anyone who knows it gets in \u2014 share it ONLY through a password manager or secure message, never in the clear. You can turn it off later.",onSubmit:async({next:h})=>{if(!h)return"Enter a password.";try{await t.setSharedPassword(h)}catch(u){return u.message}return new V.Notice("Shared password set \u2014 share it securely with your collaborators."),this.update?.(),null}}).open()})):i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to manage how this vault is shared."),new V.Setting(i).setName("Collaborators (device approval)").setHeading(),i.createEl("p",{cls:"setting-item-description"}).setText("Everyone who can unlock this vault, and devices waiting for access. Approving a request shares the vault key with that device \u2014 it never sees a password. Removing a member revokes future access (existing synced copies they already hold aren't clawed back \u2014 rotate the key for that, a future feature)."),new V.Setting(i).setName("Synced from the vault keyfile").addButton(p=>p.setButtonText("Refresh").onClick(async()=>{await t.refresh(),this.update?.()})),!t.isUnlocked())i.createEl("p",{cls:"setting-item-description"}).setText("Unlock encryption above to approve or remove collaborators.");else{let p=t.myIdentityId();for(let u of t.members()){let I=u.id===p,f=new V.Setting(i).setName(`${u.label}${I?" \u2014 this device":""}`).setDesc(I?"You":"Member");I||f.addButton(m=>{m.setButtonText("Remove").onClick(async()=>{await t.removeMember(u.id),new V.Notice(`Removed ${u.label}. (Not full revocation without rotating the key.)`),this.update?.()}),m.setWarning?.(!0)})}let h=t.pendingJoinRequests();if(h.length===0)i.createEl("p",{cls:"setting-item-description"}).setText("No pending access requests.");else for(let u of h)new V.Setting(i).setName(u.label).setDesc("Wants access to this vault").addButton(I=>I.setButtonText("Approve").setCta().onClick(async()=>{try{await t.approveJoinRequest(u.id)}catch(f){new V.Notice(f.message);return}new V.Notice(`Approved ${u.label} \u2014 they can unlock once the keyfile syncs to them.`),this.update?.()})).addButton(I=>I.setButtonText("Deny").onClick(async()=>{await t.denyJoinRequest(u.id),new V.Notice("Request denied."),this.update?.()}))}},["encryption","encrypt","password","passphrase","lock","unlock","key","security","private","collaborator","share","team","member","approve"])),e.push(this.renderDef("Encrypt items sent to trash","When ON, deleting a note sends it to Stashpad's encrypted trash (recoverable with your password) instead of a plaintext trash. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrash).onChange(async n=>{this.plugin.settings.encryptTrash=n,await this.plugin.saveSettings()})),["trash","delete","encrypt"])),e.push(this.renderDef("Encrypt trash filenames","Hide the filename + origin folder of encrypted-trashed items (opaque names on disk; shown under \u201CHidden\u201D in the trash tab). Default OFF so you can still tell what to restore when working outside the app.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFilenames).onChange(async n=>{this.plugin.settings.encryptTrashFilenames=n,await this.plugin.saveSettings()})),["trash","filename","encrypt"])),e.push(this.renderDef("Follow Obsidian's trash setting instead","OFF (recommended): encrypted-deleted notes go to Stashpad's own \u201C_deleted/\u201D store \u2014 the only trash location Stashpad fully controls, so it can encrypt, list, and restore them. ON: deletes follow Obsidian's \u201CDeleted files\u201D setting instead (system/OS trash or permanent). \u26A0\uFE0F Stashpad CANNOT encrypt or recover notes that go to the system trash \u2014 so the encrypted trash + recoverable trash view won't apply. Only turn this on if you specifically want Obsidian's native trash behavior.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.encryptTrashFollowObsidian??!1).onChange(async n=>{this.plugin.settings.encryptTrashFollowObsidian=n||void 0,await this.plugin.saveSettings()})),["trash","obsidian","system","delete","encrypt"])),e.push(this.renderDef("Auto-lock after idle minutes","Forget the password from memory after this many idle minutes (0 = never). Re-prompts on the next encryption action.",i=>i.addText(s=>s.setValue(String(this.plugin.settings.encryptionIdleLockMinutes??0)).onChange(async n=>{let o=Math.max(0,Math.floor(Number(n)||0));this.plugin.settings.encryptionIdleLockMinutes=o,await this.plugin.saveSettings()})),["auto-lock","idle","timeout","lock"])),e.push(this.renderDef("Hide titles of locked notes","Show a generic label on \u{1F512} locked placeholders instead of the note's title, so a glance at the vault doesn't reveal what's locked. Default OFF.",i=>i.addToggle(s=>s.setValue(this.plugin.settings.hideLockedTitles??!1).onChange(async n=>{this.plugin.settings.hideLockedTitles=n,await this.plugin.saveSettings(),this.plugin.refreshAllStashpadViews?.()})),["title","hide","private","lock","placeholder","visibility"])),e.push(this.renderDef("Default archive folder",`Where the "Move selection to archive" command sends notes (they're auto-encrypted on arrival). Leaving this blank is fine \u2014 the command will just show you a list of your archive folders to pick from each time (or use the only one if you have a single archive). Mark a folder as an archive via the folder panel \u2192 right-click \u2192 "Mark as archive".`,i=>{let s=this.plugin.settings.archiveFolders??[];i.addDropdown(n=>{n.addOption("",s.length?"\u2014 pick from list each time \u2014":"\u2014 no archive folders yet \u2014");for(let a of s)n.addOption(a,a);let o=this.plugin.settings.defaultArchiveFolder??"";n.setValue(s.includes(o)?o:""),n.onChange(async a=>{this.plugin.settings.defaultArchiveFolder=a||void 0,await this.plugin.saveSettings()})})},["archive","default","move","encrypt","folder"])),e}hotkeyItems(){let t={name:"Hotkeys",desc:"Each command has up to two slots. Click a slot and press a key (or chord) to bind it; press Backspace (delete on Mac) to cancel without binding; or click \u2715 to clear an existing binding. A \u21BA icon appears on any slot that differs from its shipped default \u2014 click it to revert that slot. When both slots are set, the pill on the right decides which one is active.",searchable:!1},e=Ke.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 V.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 A=>{this.plugin.settings.jdIndexScope=A==="folder"?"folder":"vault",await this.plugin.saveSettings(),this.display()})}),(this.plugin.settings.jdIndexScope??"vault")==="folder"&&new V.Setting(t).setName("Scope folder").setDesc("Vault-relative path. Leave empty to fall back to the entire vault.").addText(r=>{new Ge(this.app,r.inputEl),r.setPlaceholder("Path/To/Folder"),r.setValue(this.plugin.settings.jdIndexScopeFolder??""),r.onChange(async A=>{this.plugin.settings.jdIndexScopeFolder=(A||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new V.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 A=>{this.plugin.settings.jdIndexIncludeStashpadFolders=A,await this.plugin.saveSettings(),this.display()})}),new V.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 Ge(this.app,r.inputEl),r.setPlaceholder(s[0]??"(pick a Stashpad folder)"),r.setValue(this.plugin.settings.jdIndexStashpadFolder??""),r.onChange(async A=>{this.plugin.settings.jdIndexStashpadFolder=(A||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})}),new V.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 A=>{this.plugin.settings.jdIndexSort=A==="created"?"created":"natural",await this.plugin.saveSettings()})});let n=Re(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 V.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 A=await Yi(this.app,this.plugin,this.plugin.settings);if(A.error==="no-dest"){new V.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(A.error==="no-home"){new V.Notice(`"${this.plugin.settings.jdIndexStashpadFolder}" doesn't have a Stashpad home note. Open the folder in Stashpad first (it creates one automatically).`,7e3);return}zi(this.app,A),this.display()}catch(A){console.error("[stashpad] preview failed",A),new V.Notice(`Preview failed: ${A?.message??A}`,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 V.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}new Ii(this.app,this.plugin,this.plugin.settings,n.indexed.length,async()=>{try{let g=await en(this.app,this.plugin,this.plugin.settings);if(g.error==="no-dest"){new V.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(g.error==="dest-not-stashpad"){new V.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 V.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 V.Notice(`Build failed: ${g?.message??g}`,8e3)}}).open()})}).addButton(r=>{r.setButtonText(`Reveal in ${Pr()}`),r.setTooltip("Open the designated Stashpad folder in your OS file browser."),r.onClick(async()=>{let A=(this.plugin.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"");if(!A){new V.Notice("Set a Designated Stashpad folder for Index first.",5e3);return}if(!this.app.vault.getAbstractFileByPath(A)){new V.Notice(`Folder "${A}" doesn't exist yet.`,5e3);return}try{let g=this.app.vault.adapter.basePath;if(g){let{shell:p}=window.require?.("electron")??{},h=`${g}/${A}`;p?.openPath?.(h)}else new V.Notice("Reveal in file system not supported on this platform.",4e3)}catch(g){new V.Notice(`Couldn't open folder: ${g?.message??g}`,5e3)}})})}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new V.Setting(t).setName("Color aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let i=(()=>{let o=se()?.noteFolder;return o&&e.includes(o)?o:e[0]})();new V.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(/\/+$/,"")]??{},A=new Set([...a.keys(),...Object.keys(r)]);if(A.size===0){s.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${i}" yet. Set a per-note color (Shift+: or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...A].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=gt()),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 A=>{n(A),await this.plugin.saveSettings()})),o);return t.push(e("Show author in note footer",()=>this.plugin.settings.showAuthor,i=>{this.plugin.settings.showAuthor=i},["author","footer","show"])),t.push(e("Show contributors in note footer",()=>this.plugin.settings.showContributors,i=>{this.plugin.settings.showContributors=i},["contributors","footer","show"])),t.push(e("Show last edit time in note footer",()=>this.plugin.settings.showLastEdit,i=>{this.plugin.settings.showLastEdit=i},["last edit","modified","footer","time"])),t.push(this.sectionDef("Folders you've worked in","Folders where you've authored or contributed notes. Click one to open it.",i=>this.renderAuthoredFolders(i),["folders","authored","contributed","worked"])),t.push(this.sectionDef("Known authors","Everyone the plugin has seen, with role/department + rename history; rebuild/restore the registry.",i=>this.renderKnownAuthorsSection(i),["authors","registry","rename","known","rebuild"])),t}renderAuthoredFolders(t){let e=this.plugin.collectAuthoredFolders();if(e.length===0){t.createEl("p",{cls:"setting-item-description",text:"No authored or contributed folders yet."});return}let i=t.createDiv({cls:"stashpad-authored-folders-list"});for(let s of e){let n=i.createDiv({cls:"stashpad-authored-folder-row"}),o=n.createEl("a",{cls:"stashpad-authored-folder-link",text:s.folder});o.onclick=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"])]}okfItems(){return[this.sectionDef("Open Knowledge Format (OKF)","Turn a Stashpad folder into a browsable OKF bundle \u2014 markdown concept files with OKF frontmatter, a generated index.md, and relative-markdown cross-links \u2014 that LLMs/agents can read. Complements (never replaces) Stashpad's own frontmatter and links.",t=>this.renderOkfSection(t),["okf","open knowledge format","knowledge","catalog","index","export","bundle","tarball","agent","google"])]}appendCode(t,e){e.split(/`([^`]+)`/g).forEach((i,s)=>{s%2===1?t.createEl("code",{text:i}):i&&t.appendText(i)})}codeDesc(t){let e=document.createDocumentFragment();return this.appendCode(e,t),e}renderOkfSection(t){if(t.createDiv({cls:"stashpad-beta-row"}).createEl("span",{cls:"stashpad-beta-badge",text:"BETA"}),new V.Setting(t).setName("Enable OKF").setDesc(this.codeDesc("Master switch. When on, you choose which folders use OKF by assigning the OKF template to them in Settings \u2192 Templates (all / some / none \u2014 your call). Those folders then get OKF frontmatter and a maintained `index.md`. Turning this off leaves existing OKF files in place; it just stops maintaining them.")).addToggle(i=>i.setValue(this.plugin.settings.okfEnabled).onChange(async s=>{if(this.plugin.settings.okfEnabled=s,await this.plugin.saveSettings(),s)try{await this.plugin.ensureOkfTemplate()}catch(n){console.warn("[Stashpad] OKF template create failed",n)}new V.Notice(s?`OKF on. Next: assign the template "${this.plugin.okfTemplatePathOrDefault()}" to a folder \u2014 use \u201CCreate template + open Templates\u201D below. Heads-up: OKF frontmatter + index.md refresh automatically but NOT instantly (a few seconds after changes); hit Rebuild for an immediate pass.`:"OKF disabled.",s?0:4e3),this.update?.()})),this.plugin.settings.okfEnabled){let i=this.plugin.okfTemplatePathOrDefault(),s=this.plugin.okfActiveFolders().length,n=t.createEl("div",{cls:"setting-item-description stashpad-okf-howto"});n.createEl("p",{text:"How to use OKF in a folder:"});let o=n.createEl("ol");if(this.appendCode(o.createEl("li"),`Open Templates and set a folder's template to \`${i}\` (archive folders are skipped).`),this.appendCode(o.createEl("li"),"Hit Rebuild below to write OKF frontmatter (`okfParent`/`okfChildren` + `okfType`/`okfTitle`/`okfTimestamp`) and generate that folder's `index.md`."),this.appendCode(o.createEl("li"),"Right-click a note (or a selection) \u2192 \u201CExport as OKF\u2026\u201D to save a `.zip` / `.tar.gz` bundle (or `.stash`)."),n.createEl("p",{cls:"stashpad-okf-soon",text:"OKF frontmatter + index.md refresh automatically a few seconds after you add, move, or delete notes \u2014 NOT instantly. Use Rebuild for an immediate pass."}),s===0){let a=t.createEl("p",{cls:"stashpad-okf-cta"});this.appendCode(a,"\u{1F449} No folder is using OKF yet. Click \u201CCreate template + open Templates\u201D below, then set a folder's template to `"+i+"`.")}else n.createEl("p",{cls:"stashpad-okf-soon",text:`Currently ${s} folder${s===1?"":"s"} actively using OKF.`});new V.Setting(t).setName("Assign OKF to folders").setDesc(this.codeDesc(`Creates the OKF template if needed (never duplicates it), then opens Templates \u2014 set a folder's template to \`${i}\` there.`)).addButton(a=>{a.setButtonText("Create template + open Templates").setCta(),a.onClick(async()=>{let r;try{r=await this.plugin.ensureOkfTemplate()}catch(A){new V.Notice(`Couldn't create the OKF template: ${A.message}`);return}new V.Notice(`OKF template ready at "${r}" \u2014 set a folder's template to that path.`),this.update?.(),this.openSettingsPage("Templates")})}),new V.Setting(t).setName("Rebuild OKF frontmatter").setDesc(this.codeDesc("Write/refresh OKF fields for every folder using the OKF template \u2014 `okfParent`/`okfChildren` relative links (managed) plus `okfType`/`okfTitle`/`okfTimestamp` defaults (yours to edit after). Heads-up: adding, moving, or deleting notes already auto-refreshes the folder, but NOT instantly \u2014 it waits ~a few seconds after you stop. Use this button for an immediate rebuild (e.g. right after first assigning the template). Complements Stashpad's own links; nothing is removed.")).addButton(a=>a.setButtonText("Rebuild now").onClick(async()=>{let r=await this.plugin.rebuildAllOkf();new V.Notice(r.folders===0?"No folders use the OKF template yet \u2014 assign it in Templates first.":`OKF: updated ${r.written} of ${r.checked} notes across ${r.folders} folder${r.folders===1?"":"s"}.`),this.update?.()}))}let e=new V.Setting(t).setName("Learn about OKF").setDesc("Google's open, vendor-neutral spec for sharing curated knowledge with agents.");e.addButton(i=>i.setButtonText("Spec / repo").onClick(()=>window.open("https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf"))),e.addButton(i=>i.setButtonText("Announcement").onClick(()=>window.open("https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing/")))}openSettingsPage(t){let e=()=>new V.Notice(`Open Settings \u2192 Stashpad \u2192 ${t}.`);try{let i=this.app.setting;if(!i?.openTabById){e();return}i.openTabById("stashpad"),window.setTimeout(()=>{let s=i.modalEl?.querySelector(".vertical-tab-content");if(!s){e();return}let o=Array.from(s.querySelectorAll("*")).find(a=>a.childElementCount===0&&a.textContent?.trim()===t&&!a.closest(".vertical-tab-header"))?.closest("[class*='nav'], .setting-item, button, a");o&&!o.closest(".vertical-tab-header")?o.click():e()},60)}catch{e()}}renderAuthorshipSection(t){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 V.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=gt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new V.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 V.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 V.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 V.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 V.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 V.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 V.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 V.Notice(`Author registry rebuilt: ${n.total} author(s).`)}catch(n){new V.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 V.Notice(n.created>0?`Restored ${n.created} author page(s).`:"No missing author pages.")}catch(n){new V.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"}),A=s.renames.map(c=>`${c.from} \u2192 ${c.to}`).join(", ");r.setText(`Renamed: ${A}`)}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;if(new V.Setting(t).setName("Note templates per Stashpad").setDesc("Pick a markdown file to use as the default template for new notes in each Stashpad. The template's frontmatter becomes the new note's frontmatter (id/parent/created/attachments are always set by Stashpad). If the body contains {{body}}, that's where the user-typed body goes; otherwise the user body is followed by the template body."),this.plugin.settings.okfEnabled){let n=this.plugin.okfTemplatePathOrDefault();this.appendCode(t.createEl("p",{cls:"setting-item-description"}),`\u{1F4A1} OKF tip: type \`${n}\` into a folder's template field below to turn that folder into an OKF bundle (OKF frontmatter + a maintained \`index.md\`). Assign it to all, some, or none of your folders \u2014 it's per-folder. Manage OKF itself in Settings \u2192 OKF.`)}let i=t.createDiv({cls:"stashpad-note-templates-list"}),s=n=>{let o=n.replace(/\/+$/,""),a=i.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(n);let A=a.createDiv({cls:"stashpad-note-template-input-wrap"}),c=A.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=A.createDiv({cls:"stashpad-note-template-suggest"});g.style.display="none";let p=[],h=[],u=-1,I=()=>g.style.display!=="none"&&p.length>0,f=x=>{u=x,h.forEach((F,N)=>F.toggleClass("is-active",N===x)),x>=0&&h[x]&&h[x].scrollIntoView({block:"nearest"})},m=()=>{g.style.display="none",u=-1},C=async x=>{c.value=x,await v(),m()},y=a.createDiv({cls:"stashpad-note-template-warn"});y.style.display="none";let w=()=>this.app.vault.getMarkdownFiles().map(x=>x.path).filter(x=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(x)).sort(),E=()=>{g.empty(),h=[];let x=c.value.trim().toLowerCase().split(/\s+/).filter(Boolean),F=N=>{let Q=N.toLowerCase();return x.every(S=>Q.includes(S))};if(p=w().filter(N=>F(N)).slice(0,12),p.length===0){m();return}g.style.display="",p.forEach((N,Q)=>{let S=g.createDiv({cls:"stashpad-note-template-suggest-item",text:N});h.push(S),S.addEventListener("mousemove",()=>f(Q)),S.addEventListener("mousedown",async O=>{O.preventDefault(),await C(N)})}),u=u>=0&&u<p.length?u:-1,u>=0&&f(u)},v=async()=>{let x=c.value.trim(),F={...this.plugin.settings.noteTemplates??{}};x?F[o]=x:delete F[o],this.plugin.settings.noteTemplates=F,await this.plugin.saveSettings(),D()},D=()=>{y.empty(),y.style.display="none";let x=c.value.trim();if(!x)return;let F=this.app.vault.getAbstractFileByPath(x);if(!F||F.extension!=="md"){y.style.display="",y.setText(`\u26A0 "${x}" is not a markdown file in this vault.`);return}let N=this.app.metadataCache.getFileCache(F)?.frontmatter??{},S=re.filter(O=>{let M=N[O];return!(M==null||typeof M=="string"&&M.trim()===""||Array.isArray(M)&&M.length===0)});S.length!==0&&(y.style.display="",y.setText(`\u26A0 Template defines ${S.join(", ")} \u2014 Stashpad always sets ${S.length===1?"this":"these"} on new notes, so the template value${S.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",E),c.addEventListener("input",()=>{u=-1,E()}),c.addEventListener("blur",()=>{setTimeout(m,150)}),c.addEventListener("change",()=>{v()}),c.addEventListener("keydown",x=>{if(x.key==="ArrowDown")x.preventDefault(),I()?f((u+1)%p.length):(E(),p.length&&f(0));else if(x.key==="ArrowUp"){if(!I())return;x.preventDefault(),f((u-1+p.length)%p.length)}else if(x.key==="Enter")I()&&u>=0&&(x.preventDefault(),C(p[u]));else if(x.key==="Escape")I()&&(x.preventDefault(),m());else if(x.key==="Tab"&&!x.shiftKey){if(!I())return;let F=p[u>=0?u:0],N=c.value,Q;if(F.toLowerCase().startsWith(N.toLowerCase())){let S=F.indexOf("/",N.length);Q=S>=0?F.slice(0,S+1):F}else Q=F;Q&&Q!==N&&(x.preventDefault(),c.value=Q,u=-1,E(),p.length===1&&f(0))}}),D()};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 Fe(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 V.Notice(`Recolored ${h} note${h===1?"":"s"}.`);else if(s===0){let u=this.plugin.getColorAlias(e,i);u&&(await this.plugin.setColorAlias(e,i,""),p&&await this.plugin.setColorAlias(e,p,u))}n()},async p=>{let h=(this.plugin.settings.customPalette??[]).filter(u=>u.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 A=o.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});A.value=this.plugin.getColorAlias(e,i)??"",A.onchange=async()=>{await this.plugin.setColorAlias(e,i,A.value),!A.value.trim()&&s===0&&n()};let c=o.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});A.value||(c.style.visibility="hidden"),c.onclick=async()=>{await this.plugin.setColorAlias(e,i,""),s===0?n():(A.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."},A=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 A(),n.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),A())},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 A of a){let c=r.createDiv({cls:"stashpad-folder-row"});c.createSpan({cls:"stashpad-folder-row-label",text:A});let g=c.createEl("button",{text:o.action});g.onclick=()=>void n(A)}}}renderBindingRow(t,e){t.setName(e.label).setDesc(e.desc);let i=()=>this.plugin.settings.bindings[e.id],s,n,o=()=>{},a=h=>{let u=t.controlEl.createDiv({cls:"stashpad-binding-slot"}),I=u.createEl("input",{type:"text"});I.readOnly=!0,I.placeholder="Click & press a key",I.value=mi(i()[h]),I.classList.add("stashpad-binding-input");let f=()=>{I.size=Math.max(3,I.value.length||I.placeholder.length)};f();let m=h==="primary"?e.defaultPrimary:e.defaultSecondary??"";I.onclick=()=>{go(I,async E=>{this.plugin.settings.bindings[e.id][h]=E,I.value=mi(E),f(),await this.plugin.saveSettings(),o(),w()})};let C=u.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});C.title="Clear this slot",C.onclick=async()=>{this.plugin.settings.bindings[e.id][h]="",I.value="",f(),await this.plugin.saveSettings(),o(),w()};let y=u.createEl("button",{cls:"stashpad-binding-revert"});(0,V.setIcon)(y,"rotate-ccw");let w=()=>{let v=i()[h]!==m;y.toggleClass("is-hidden",!v),y.title=m?`Revert to default (${mi(m)})`:"Revert to default (no binding)"};return y.onclick=async()=>{this.plugin.settings.bindings[e.id][h]=m,I.value=mi(m),f(),await this.plugin.saveSettings(),o(),w()},w(),I};s=a("primary"),n=a("secondary");let r=t.controlEl.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let A=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(),u=!!(h.primary&&h.secondary);g.checked=!!h.useBoth,g.disabled=!u,c.toggleClass("is-disabled",!u);let I=!!h.useBoth&&u;r.toggleClass("is-disabled",!u||I),r.toggleClass("is-right",h.preferRight),r.setAttribute("aria-checked",String(h.preferRight)),r.setAttribute("aria-disabled",String(!u||I)),A.setText(h.preferRight?"R":"L"),r.title=u?I?'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 Ye=class{constructor(l,t){this.app=l;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 l=this.detectTrigger();if(!l){this.close();return}this.openFor(l)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=l=>{l.key==="Escape"&&(!this.state||!this.items.length||(l.preventDefault(),l.stopPropagation(),l.stopImmediatePropagation(),this.close()))};this.onKeyDown=l=>{!this.state||!this.items.length||(l.key==="ArrowDown"?(l.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):l.key==="ArrowUp"?(l.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):l.key==="Enter"||l.key==="Tab"?(l.preventDefault(),l.stopPropagation(),this.commit()):l.key==="Escape"&&(l.preventDefault(),l.stopPropagation(),l.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let l=this.ta.ownerDocument??document;l.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>l.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 l of this.vaultListeners)l();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;let l=ut().inheritObsidianExclusions,t=l?this.app.vault.getConfig?.("userIgnoreFilters"):void 0;this.fileIndex=this.app.vault.getFiles().filter(i=>!Zn(i.path)&&!_n(i.path)&&!(l&&jn(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 l=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=l.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(l){this.buildIndex();let t=l.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 l.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(l){if(this.state=l,this.items=this.buildItems(l),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let l=new _o.Scope(this.app.scope);l.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=l,this.app.keymap?.pushScope(l)}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 l=this.popupEl;l.empty();for(let t=0;t<this.items.length;t++){let e=this.items[t],i=l.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 l=this.popupEl.children;for(let e=0;e<l.length;e++)l[e].toggleClass("is-active",e===this.activeIdx);let t=l[this.activeIdx];t&&t.scrollIntoView({block:"nearest"})}position(){if(!this.popupEl)return;let l=this.ta.getBoundingClientRect(),t=this.popupEl.offsetHeight||200,e=l.top-t-4,i=l.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,l.width)}px`}commit(){if(!this.state||!this.items.length)return;let l=this.items[this.activeIdx];if(!l)return;let t=this.ta.value.slice(0,this.state.replaceStart),e=this.ta.value.slice(this.state.replaceEnd),i=l.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()}};Qt();var us=class extends bt.ItemView{constructor(t,e){super(t);this.plugin=e;this.displayedPath=null;this.unsubscribeSelection=null;this.renderTimer=null;this.expanded=new Set;this.composerAutocomplete=null;this.composerInputEl=null;this.composerDraft="";this.composerDraftForId=null;this.displayedId=null;this.unsubscribeContent=null}getViewType(){return Qe}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 u=t.createDiv({cls:"stashpad-detail-empty"});(0,bt.setIcon)(u.createSpan({cls:"stashpad-detail-empty-icon"}),"panel-right"),u.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"}),A=r.createDiv({cls:"stashpad-detail-titlerow"});A.createDiv({cls:"stashpad-detail-title",text:this.titleFor(n)});let c=A.createEl("button",{cls:"stashpad-detail-open-btn",attr:{"aria-label":"Open in Stashpad tab"}});(0,bt.setIcon)(c,"arrow-up-right"),c.title="Open this note in a new Stashpad tab",c.onclick=()=>{this.openInStashpad(s.folder,s.id)};let g=r.createDiv({cls:"stashpad-detail-metarow"});if(s.folder&&g.createSpan({cls:"stashpad-detail-meta-chip",text:s.folder.split("/").pop()||s.folder}),typeof o.color=="string"&&o.color){let u=g.createSpan({cls:"stashpad-detail-meta-color"});u.style.background=o.color,u.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 u=Date.parse(String(o.due)),I=Number.isNaN(u)?String(o.due):Zt(u,this.plugin.settings);g.createSpan({cls:"stashpad-detail-meta-chip is-due",text:`due ${I}`})}if(Array.isArray(o.tags))for(let u of o.tags.filter(I=>typeof I=="string"))g.createSpan({cls:"stashpad-detail-meta-tag",text:`#${u.replace(/^#/,"")}`});let p=a.createDiv({cls:"stashpad-detail-body"});try{let u=await this.app.vault.cachedRead(n),I=this.stripFrontmatter(u);await bt.MarkdownRenderer.render(this.app,I,p,n.path,this)}catch(u){p.createDiv({cls:"stashpad-detail-error",text:`Couldn't read \`${n.path}\`: ${u.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 u=Math.min(i,h.value.length);try{h.setSelectionRange(u,u)}catch{}}}renderComposer(t,e){let i=t.createDiv({cls:"stashpad-detail-composer"}),s=i.createEl("textarea",{cls:"stashpad-detail-composer-input",attr:{placeholder:"Add a child note\u2026",rows:"2"}});this.composerInputEl=s,this.composerDraftForId===e.id?s.value=this.composerDraft:(this.composerDraft="",this.composerDraftForId=e.id),s.addEventListener("input",()=>{this.composerDraft=s.value,this.composerDraftForId=e.id}),s.addEventListener("keydown",o=>{if(o.key==="Enter"&&!o.shiftKey&&!o.isComposing){if(this.composerAutocomplete?.isOpen?.())return;o.preventDefault(),this.submitComposer(e)}});let n=i.createEl("button",{cls:"stashpad-detail-composer-send",attr:{"aria-label":"Add child note"}});(0,bt.setIcon)(n.createSpan({cls:"stashpad-detail-composer-send-icon"}),"plus"),n.createSpan({cls:"stashpad-detail-composer-send-text",text:"Add child note"}),n.title="Add child note (Enter)",n.onclick=()=>void this.submitComposer(e),this.composerAutocomplete=new Ye(this.app,s),this.composerAutocomplete.attach()}async submitComposer(t){let e=(this.composerInputEl?.value??"").trim();if(!e)return;let i=this.plugin.lastActiveStashpadLeaf?.view;if(!i||i.getViewType?.()!==ct||typeof i.createNoteUnder!="function"){new bt.Notice("Open a Stashpad view to add notes.");return}try{await i.createNoteUnder(e,t.id)}catch(s){new bt.Notice(`Couldn't add note: ${s.message}`);return}this.composerDraft="",this.composerDraftForId=t.id,this.composerInputEl&&(this.composerInputEl.value=""),await this.render(),setTimeout(()=>this.composerInputEl?.focus(),0)}renderChildren(t,e,i){let s=this.plugin.lastActiveStashpadLeaf?.view;if(!s||s.getViewType?.()!==ct)return;let n=s.tree;if(!n?.getChildren)return;let o=n.getChildren(i);if(!o||o.length===0)return;let a=t.createDiv({cls:"stashpad-detail-children"});a.createDiv({cls:"stashpad-detail-children-header",text:`Children (${o.length})`});let r=a.createDiv({cls:"stashpad-detail-children-list"});for(let A of o)A.file&&this.renderDetailChildRow(r,s,n,e,A,0)}renderDetailChildRow(t,e,i,s,n,o){if(!n.file)return;let a=this.app.metadataCache.getFileCache(n.file)?.frontmatter??{},r=typeof a.color=="string"?a.color:null,A=a.completed===!0,c=i.getChildren(n.id),g=c.length>0,p=`${s}|${n.id}`,h=this.expanded.has(p),u=t.createDiv({cls:"stashpad-detail-child-row"});A&&u.addClass("is-completed"),o>0&&(u.style.paddingLeft=`${o*16}px`),u.draggable=!0,u.dataset.id=n.id,u.addEventListener("dragstart",y=>{y.dataTransfer?.setData("text/plain",n.id),y.dataTransfer&&(y.dataTransfer.effectAllowed="move"),u.addClass("is-dragging")}),u.addEventListener("dragend",()=>u.removeClass("is-dragging")),u.addEventListener("dragover",y=>{y.preventDefault(),y.dataTransfer&&(y.dataTransfer.dropEffect="move");let w=u.getBoundingClientRect(),E=y.clientY-w.top<w.height/2;u.toggleClass("drop-before",E),u.toggleClass("drop-after",!E)}),u.addEventListener("dragleave",()=>{u.removeClass("drop-before"),u.removeClass("drop-after")}),u.addEventListener("drop",y=>{y.preventDefault(),u.removeClass("drop-before"),u.removeClass("drop-after");let w=y.dataTransfer?.getData("text/plain");if(!w||w===n.id)return;let E=u.getBoundingClientRect(),v=y.clientY-E.top<E.height/2;typeof e.reorderToTarget=="function"&&e.reorderToTarget([w],n.id,v?"before":"after")}),u.oncontextmenu=y=>{y.preventDefault();let w=i.get(n.id);w&&typeof e.openNoteMenu=="function"&&e.openNoteMenu(y,w)};let I=u.createSpan({cls:"stashpad-detail-child-toggle"});if(g&&(ke(I,c.length,h),I.onclick=y=>{y.stopPropagation(),this.expanded.has(p)?this.expanded.delete(p):this.expanded.add(p),this.render()}),Me(a,"task")||a.task===!0||a.completed!==void 0){let y=u.createSpan({cls:"stashpad-detail-child-checkbox"});(0,bt.setIcon)(y,A?"check-square":"square"),y.title=A?"Mark not done":"Mark done",y.addEventListener("mousedown",w=>w.stopPropagation()),y.addEventListener("dblclick",w=>{w.preventDefault(),w.stopPropagation()}),y.onclick=w=>{w.preventDefault(),w.stopPropagation();let E=i.get(n.id);E&&typeof e.toggleCompletedForNode=="function"&&e.toggleCompletedForNode(E)}}let m=u.createSpan({cls:"stashpad-detail-child-icon"});(0,bt.setIcon)(m,g?"folder-tree":"file-text"),r&&(m.style.color=r);let C=u.createSpan({cls:"stashpad-detail-child-title",text:this.titleFor(n.file)});if(C.onclick=()=>{e?.navigateTo&&e.navigateTo(n.id)},g&&h)for(let y of c)this.renderDetailChildRow(t,e,i,s,y,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)?Zt(e,this.plugin.settings):t}async openInStashpad(t,e){try{let i=await this.plugin.activateViewForFolder(t);e!==T&&this.plugin.navigateLeafTo(i,t,e)}catch(i){new bt.Notice(`Couldn't open: ${i.message}`)}}};async function Is(d){let l=d.workspace.getLeavesOfType(Qe);if(l.length>0){d.workspace.revealLeaf(l[0]);return}let t=d.workspace.getRightLeaf(!1);if(!t){new bt.Notice("Stashpad: couldn't open the detail panel.");return}await t.setViewState({type:Qe,active:!0}),d.workspace.revealLeaf(t)}var U=require("obsidian");Qt();var Ie=require("obsidian");Qt();function Rr(d,l){let t=d.vault.getAbstractFileByPath(l);if(!(t instanceof Ie.TFolder))return[];let e=[],i=[t];for(;i.length;){let s=i.pop();for(let n of s.children)n instanceof Ie.TFile?n.extension==="md"&&e.push(n):n instanceof Ie.TFolder&&(ii.has(n.name)||i.push(n))}return e}var fs=class{constructor(l){this.app=l;this.nodes=new Map;this.byPath=new Map;this.listeners=new Set;this.orderProvider=null;this.synthetic=new Map;this.coalesceTimer=null;this.nodes.set(T,{id:T,parent:null,children:[],file:null,created:""})}setOrderProvider(l){this.orderProvider=l}onChange(l){return this.listeners.add(l),()=>this.listeners.delete(l)}emit(){for(let l of this.listeners)l()}rebuild(l){l!==void 0&&(this.currentFolder=l);let t=this.currentFolder,e=this.byPath,i=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(T,{id:T,parent:null,children:[],file:null,created:""});let s=t?Rr(this.app,t):this.app.vault.getMarkdownFiles();for(let n of s){let o=this.app.metadataCache.getFileCache(n)?.frontmatter,a=o?.id;if(!a){let A=e.get(n.path),c=A?i.get(A):void 0,g=this.synthetic.get(n.path),p=c??g;p&&(this.nodes.set(p.id,{...p,children:[],file:n}),this.byPath.set(n.path,p.id));continue}if(this.synthetic.delete(n.path),a===T){let A=this.nodes.get(T);A.file=n,A.created=o?.created??"",this.byPath.set(n.path,T);continue}let r=o?.parent??null;r===a&&(r=null),this.nodes.set(a,{id:a,parent:r??T,children:[],file:n,created:o?.created??""}),this.byPath.set(n.path,a)}for(let n of this.nodes.values()){if(n.id===T)continue;let o=n.parent??T;(this.nodes.get(o)??this.nodes.get(T)).children.push(n.id)}for(let n of this.nodes.values())if(n.children.sort((o,a)=>{let r=this.nodes.get(o),A=this.nodes.get(a);return(r.created||"").localeCompare(A.created||"")}),this.orderProvider){let o=this.orderProvider(n.id);if(o.length>0){let a=new Map;o.forEach((r,A)=>a.set(r,A)),n.children.sort((r,A)=>{let c=a.has(r)?a.get(r):1/0,g=a.has(A)?a.get(A):1/0;return c===g?0:c-g})}}this.emit()}insertSynthetic(l){if(!l.file)return;let t=l.file.path;this.synthetic.set(t,l),this.nodes.set(l.id,l),this.byPath.set(t,l.id);let e=l.parent??T,i=this.nodes.get(e);i&&!i.children.includes(l.id)&&i.children.push(l.id),this.emit()}get(l){return this.nodes.get(l)}getRoot(){return this.nodes.get(T)}getChildren(l){let t=this.nodes.get(l);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}fileBackedCount(){let l=0;for(let t of this.nodes.values())t.file&&l++;return l}pathTo(l){let t=[],e=new Set,i=this.nodes.get(l);for(;i&&i.id!==T&&!e.has(i.id);)e.add(i.id),t.unshift(i),i=i.parent?this.nodes.get(i.parent):void 0;return t}idForPath(l){return this.byPath.get(l)}snapshot(){let l={};for(let t of this.nodes.values())t.id===T||!t.file||(l[t.id]={parent:t.parent===T?null:t.parent,path:t.file.path});return l}hookMetadataCache(l){let t=r=>{let A=this.currentFolder;return A?typeof r!="string"?!1:r===A||r.startsWith(A+"/"):!0},e=!1,i=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),l())},16))},s=r=>{r instanceof Ie.TFile&&t(r.path)&&r.extension==="md"&&(this.applyChange(r),i())},n=r=>{r instanceof Ie.TFile&&t(r.path)&&r.extension==="md"&&this.applyChange(r)&&i()},o=r=>{let A=r?.path;typeof A=="string"&&t(A)&&this.applyDelete(A)&&i()},a=(r,A)=>{if(!(r instanceof Ie.TFile))return;let c=typeof A=="string"?A: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(l){if(Te(l.path))return this.byPath.has(l.path)?this.applyDelete(l.path):!1;let t=this.app.metadataCache.getFileCache(l)?.frontmatter,e=t?.id,i=this.byPath.get(l.path);if(!e){if(i){let A=this.nodes.get(i);if(A&&A.file!==l)return A.file=l,!0}return!1}if(this.synthetic.delete(l.path),e===T){let A=this.nodes.get(T),c=t?.created??"",g=!1;return A.file!==l&&(A.file=l,g=!0),A.created!==c&&(A.created=c,g=!0),this.byPath.get(l.path)!==T&&(this.byPath.set(l.path,T),g=!0),g}let s=t?.parent??T,n=t?.created??"";if(!(s===T||this.nodes.has(s)))return this.rebuild(),!0;if(i&&i!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let A={id:e,parent:s,children:[],file:l,created:n};return this.nodes.set(e,A),this.byPath.set(l.path,e),this.attachToParent(A),this.resortChildrenOf(s),!0}let r=!1;if(a.file!==l&&(a.file=l,r=!0),a.created!==n&&(a.created=n,this.resortChildrenOf(a.parent??T),r=!0),a.parent!==s){let A=a.parent??T;this.detachFromParent(a),a.parent=s,this.attachToParent(a),this.resortChildrenOf(A),this.resortChildrenOf(s),r=!0}return r}applyDelete(l){let t=this.byPath.get(l);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(l),this.synthetic.delete(l),!0;this.detachFromParent(e);let i=this.nodes.get(T);for(let s of e.children){let n=this.nodes.get(s);n&&(n.parent=T,i.children.includes(s)||i.children.push(s))}return e.children.length>0&&this.resortChildrenOf(T),this.nodes.delete(t),this.byPath.delete(l),this.synthetic.delete(l),!0}applyRename(l,t){let e=this.currentFolder,i=!e||t===e||t.startsWith(e+"/"),s=!e||l.path===e||l.path.startsWith(e+"/");if(!i&&!s)return!1;if(i&&!s)return this.applyDelete(t);if(!i&&s)return this.applyChange(l);if(Te(l.path))return this.byPath.has(t)?this.applyDelete(t):!1;let n=this.byPath.get(t);if(!n)return this.applyChange(l);this.byPath.delete(t),this.byPath.set(l.path,n);let o=this.nodes.get(n);return o&&(o.file=l),!0}detachFromParent(l){let t=this.nodes.get(l.parent??T);if(!t)return;let e=t.children.indexOf(l.id);e>=0&&t.children.splice(e,1)}attachToParent(l){let t=this.nodes.get(l.parent??T);t||(t=this.nodes.get(T)),t.children.includes(l.id)||t.children.push(l.id)}resortChildrenOf(l){let t=this.nodes.get(l);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(l);if(e.length>0){let i=new Map;e.forEach((s,n)=>i.set(s,n)),t.children.sort((s,n)=>{let o=i.has(s)?i.get(s):1/0,a=i.has(n)?i.get(n):1/0;return o===a?0:o-a})}}}};var Mn=class{constructor(){this.enabled=!1;this.buckets=new Map}record(l,t){if(!this.enabled)return;let e=this.buckets.get(l);e||(e={count:0,total:0,max:0},this.buckets.set(l,e)),e.count+=1,e.total+=t,t>e.max&&(e.max=t)}time(l,t){if(!this.enabled)return t();let e=performance.now();try{return t()}finally{this.record(l,performance.now()-e)}}async timeAsync(l,t){if(!this.enabled)return t();let e=performance.now();try{return await t()}finally{this.record(l,performance.now()-e)}}reset(){this.buckets.clear()}hasData(){return this.buckets.size>0}report(){let l=[...this.buckets.entries()].map(([e,i])=>({label:e,...i,avg:i.total/i.count})).sort((e,i)=>i.total-e.total);if(l.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 l)t.push(`| \`${e.label}\` | ${e.count} | ${e.total.toFixed(0)} | ${e.avg.toFixed(1)} | ${e.max.toFixed(0)} |`);return t.join(` +`)}},xt=new Mn;var jo=".stashpad-order.json",ze=class{constructor(l){this.app=l;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(l){if(this.cache.has(l))return this.cache.get(l);let t=`${l}/${jo}`,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(l,i),i}async save(l){this.scheduleWrite(l)}async flush(l){let t=this.pendingTimers.get(l);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(l)),await this.writeNow(l)}scheduleWrite(l){let t=this.pendingTimers.get(l);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(l),this.writeNow(l)},150);this.pendingTimers.set(l,e)}async writeNow(l){let e=(this.writeInFlight.get(l)??Promise.resolve()).then(()=>this.doWrite(l));this.writeInFlight.set(l,e);try{await e}finally{this.writeInFlight.get(l)===e&&this.writeInFlight.delete(l)}}async doWrite(l){let t=this.cache.get(l)??{},e={};for(let[n,o]of Object.entries(t))o.length>0&&(e[n]=o);this.cache.set(l,e);let i=`${l}/${jo}`,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(l,t){return this.cache.get(l)?.[t]?.slice()??[]}setOrder(l,t,e){let i=this.cache.get(l)??{};i[t]=e.slice(),this.cache.set(l,i)}appendChild(l,t,e){let i=this.cache.get(l)??{},s=i[t]??[];s.includes(e)||s.push(e),i[t]=s,this.cache.set(l,i)}removeChild(l,t){let e=this.cache.get(l);if(e)for(let i of Object.values(e)){let s=i.indexOf(t);s>=0&&i.splice(s,1)}}invalidate(l){this.cache.delete(l)}};var ki={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"},Tn=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],Gr=new Set(Tn),ta=".stashpad-sort.json",ms=class{constructor(l){this.app=l;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(l){if(this.cache.has(l))return this.cache.get(l);let t=`${l}/${ta}`,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"&&Gr.has(o)&&(i[n]=o)}}catch(s){console.warn("Stashpad: sort load failed",s)}return this.cache.set(l,i),i}async save(l){this.scheduleWrite(l)}async flush(l){let t=this.pendingTimers.get(l);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(l)),await this.writeNow(l)}scheduleWrite(l){let t=this.pendingTimers.get(l);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(l),this.writeNow(l)},150);this.pendingTimers.set(l,e)}async writeNow(l){let e=(this.writeInFlight.get(l)??Promise.resolve()).then(()=>this.doWrite(l));this.writeInFlight.set(l,e);try{await e}finally{this.writeInFlight.get(l)===e&&this.writeInFlight.delete(l)}}async doWrite(l){let t=this.cache.get(l)??{},e=`${l}/${ta}`,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(l,t){return this.cache.get(l)?.[t]??"manual"}setMode(l,t,e){let i=this.cache.get(l)??{};e==="manual"?delete i[t]:i[t]=e,this.cache.set(l,i)}removeParent(l,t){let e=this.cache.get(l);e&&delete e[t]}invalidate(l){this.cache.delete(l)}};Qt();var fe="parentLink",Ve="children";var Qs=class Qs{constructor(l,t){this.app=l;this.getTree=t;this.pending=new Set;this.timer=null;this.activityListeners=new Set;this.errorListeners=new Set}onActivity(l){return this.activityListeners.add(l),()=>this.activityListeners.delete(l)}emitActivity(){let l=this.pending.size;for(let t of this.activityListeners)try{t(l)}catch(e){console.warn("[Stashpad] fmSync activity listener failed",e)}}schedule(l){if(!l||!ut().writeRecoveryLinks)return;let t=this.pending.size;this.pending.add(l),this.pending.size!==t&&this.emitActivity(),this.kick()}scheduleParentChange(l,t,e){this.schedule(l),t&&this.schedule(t),this.schedule(e)}scheduleSubtree(l){let t=this.getTree(),e=i=>{this.schedule(i);for(let s of t.getChildren(i))e(s.id)};e(l)}scheduleParentOfDeleted(l){l&&this.schedule(l)}async flush(){for(this.timer!=null&&(window.clearTimeout(this.timer),this.timer=null);this.pending.size>0;){let l=this.pending.values().next().value;if(l===void 0)break;this.pending.delete(l),this.emitActivity(),await this.syncOne(l)}}pendingCount(){return this.pending.size}onError(l){return this.errorListeners.add(l),()=>this.errorListeners.delete(l)}emitError(l,t){for(let e of this.errorListeners)try{e(l,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(),Qs.PACING_MS))}async tick(){this.timer=null;let l=this.pending.values().next().value;if(l!==void 0){this.pending.delete(l),this.emitActivity();try{await this.syncOne(l)}catch(t){console.warn("[Stashpad] frontmatter sync tick failed",t)}this.pending.size>0&&this.kick()}}wouldWrite(l){let e=this.getTree().get(l);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[fe]=="string"?n[fe]:null,a=n?.[Ve],r=Array.isArray(a)?a.filter(A=>typeof A=="string"):[];if((o??null)!==(i??null)||r.length!==s.length)return!0;for(let A=0;A<r.length;A++)if(r[A]!==s[A])return!0;return!1}async syncOne(l){let e=this.getTree().get(l);if(!e||!e.file||!this.wouldWrite(l))return;let i=this.computeParentLink(e),s=this.computeChildrenLinks(e);try{await xt.timeAsync("write.fmSync",()=>this.app.fileManager.processFrontMatter(e.file,n=>{i?n[fe]=i:delete n[fe],s.length>0?n[Ve]=s:delete n[Ve]}))}catch(n){console.warn("[Stashpad] frontmatter sync failed",e.file?.path,n),this.emitError(e.file.path,n)}}computeParentLink(l){if(l.id===T)return null;let t=this.getTree();if(!l.parent||l.parent===T){let i=t.getRoot();return i&&i.id!==l.id&&i.file?Cs(i.file.path):null}let e=t.get(l.parent);return e?.file?Cs(e.file.path):null}computeChildrenLinks(l){return this.getTree().getChildren(l.id).filter(e=>!!e.file).map(e=>Cs(e.file.path))}};Qs.PACING_MS=100;var Bs=Qs;async function $e(d,l){let t=l.endsWith("/")?l:l+"/",e=new Map,i=new Map;for(let A of d.vault.getMarkdownFiles()){if(A.path!==l&&!A.path.startsWith(t))continue;let c=d.metadataCache.getFileCache(A)?.frontmatter,g=typeof c?.id=="string"?c.id:null;if(!g)continue;let p=typeof c?.parent=="string"?c.parent:T;e.set(g,{file:A,id:g,parent:p});let h=i.get(p)??[];h.push(g),i.set(p,h)}let s=A=>Cs(A.file.path),n=A=>{if(A.id===T)return null;if(A.parent===T||!A.parent){let g=e.get(T);return g?s(g):null}let c=e.get(A.parent);return c?s(c):null},o=A=>{let c=i.get(A.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 A of e.values()){a+=1;let c=n(A),g=o(A),p=d.metadataCache.getFileCache(A.file)?.frontmatter,h=p&&typeof p[fe]=="string"?p[fe]:null,u=p?.[Ve],I=Array.isArray(u)?u.filter(C=>typeof C=="string"):[],f=(h??null)===(c??null),m=I.length===g.length&&I.every((C,y)=>C===g[y]);if(!(f&&m))try{await d.fileManager.processFrontMatter(A.file,C=>{c?C[fe]=c:delete C[fe],g.length>0?C[Ve]=g:delete C[Ve]}),r+=1,await new Promise(C=>setTimeout(C,50))}catch(C){console.warn("[Stashpad] rebootstrap fm sync failed",A.file.path,C)}}return{checked:a,written:r}}function Cs(d){return`[[${d.replace(/\.md$/i,"")}]]`}Lt();Ue();var ys=class{constructor(l,t){this.tree=l;this.log=t}async sweep(l){let t=await this.log.readState(),e=this.tree.snapshot(),i=n=>{if(!l)return!0;let o=l.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 Ft=require("obsidian");Qt();Ws();var Dt=Ft.moment;function Hn(d){let l=d.trim().toLowerCase();if(!l)return null;let t=Date.now(),e=u=>Dt(u).startOf("day").valueOf(),i=/\b(\d{1,2})(?::(\d{2}))?\s*(am|pm)?\b/,s=0,n=!1,o=l,a=i.exec(l);if(a&&(a[3]||a[2])){let u=parseInt(a[1],10),I=a[2]?parseInt(a[2],10):0,f=a[3];f==="pm"&&u<12&&(u+=12),f==="am"&&u===12&&(u=0),u>=0&&u<24&&I>=0&&I<60&&(s=(u*3600+I*60)*1e3,n=!0,o=l.replace(a[0]," ").replace(/\s+/g," ").trim())}let r=u=>n?u+s:u;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 A=["sunday","monday","tuesday","wednesday","thursday","friday","saturday"],c=["sun","mon","tue","wed","thu","fri","sat"],g=A.indexOf(o)>=0?A.indexOf(o):c.indexOf(o);if(g>=0){let u=Dt().startOf("day"),f=(u.day()-g+7)%7;return r(u.subtract(f,"days").valueOf())}let p=/^(\d+)\s*([dwmy])$/.exec(o);if(p){let u=parseInt(p[1],10),I={d:"days",w:"weeks",m:"months",y:"years"}[p[2]];return r(Dt().subtract(u,I).startOf("day").valueOf())}let h=Dt(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 ea(d){let l={text:[],filters:{}},t=(d||"").trim();if(!t)return l;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")l.filters.in=o.toLowerCase();else if(n==="before"){let a=Hn(o);a!=null&&(l.filters.before=a)}else if(n==="after"){let a=Hn(o);a!=null&&(l.filters.after=a)}else if(n==="on"){let a=Hn(o);if(a!=null)if(/\b\d{1,2}:\d{2}\b|\b\d{1,2}\s*(?:am|pm)\b/i.test(o))l.filters.on={start:a-6e4,end:a+6e4};else{let A=Dt(a).startOf("day").valueOf();l.filters.on={start:A,end:A+864e5}}}i=i.replace(s[0]," ")}}for(let n of i.split(/\s+/))n&&l.text.push(n.toLowerCase());return l}var ne=class d extends Ft.SuggestModal{constructor(t,e,i,s){super(t);this.tree=e;this.titleFn=i;this.opts=s;this.notes=[];this.includeExcluded=!1;this.pendingCleanups=[];this.crossFolderIndex=null;this.whenBuilderEl=null;this.whenMode="on";this.whenSingleText="";this.whenBetweenEndText="";this.setPlaceholder(s.placeholder??(s.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}onClose(){for(;this.pendingCleanups.length>0;){let t=this.pendingCleanups.pop();try{t&&t()}catch{}}try{this.opts.onClose?.()}catch{}}loadAll(){let t=this.tree.getRoot(),e=t.file?.parent?.name?.trim()??"",i=e?`Home \u2014 ${e}`:"Home",s=(n,o)=>{let a=this.tree.get(n);a?.file&&n!==T?this.notes.push({node:a,title:`${" ".repeat(o)}${this.titleFn(a)}`,body:""}):a?.file&&n===T&&this.notes.push({node:a,title:i,body:""});for(let r of this.tree.getChildren(n))s(r.id,o+1)};t.file&&this.notes.push({node:t,title:i,body:""});for(let n of this.tree.getChildren(T))s(n.id,1);for(let n of this.notes)n.node?.file&&this.app.vault.cachedRead(n.node.file).then(o=>{n.body=this.stripFm(o)});if(this.opts.crossFolderNotes){let n=this.opts.crossFolderNotes();for(let o of n)this.notes.push({node:null,title:o.title,body:o.body,cross:o});for(let o of this.notes)!o.cross||o.body||o.cross.file&&this.app.vault.cachedRead(o.cross.file).then(a=>{o.body=this.stripFm(a)})}}createdMsFor(t){if(t.node?.created){let e=Date.parse(t.node.created);if(!Number.isNaN(e))return e}return t.cross?.file?.stat?.ctime!=null?t.cross.file.stat.ctime:null}stripFm(t){if(!t.startsWith("---"))return t;let e=t.indexOf(` +---`,3);return e===-1?t:t.slice(e+4).replace(/^\r?\n/,"")}getSuggestions(t){let e=t.trim().toLowerCase(),i=ea(t),s=i.text;console.log("[Stashpad] search query parsed",{query:t,text:i.text,filters:i.filters});let n=m=>{if(!s.length)return!0;for(let C of s)if(!m.includes(C))return!1;return!0},o=null,a=null;if(i.filters.in){let m=i.filters.in.split(/\s+/).filter(Boolean);o=new Set,a=new Map;let C=E=>m.every(v=>E.toLowerCase().includes(v)),y=E=>{if(!o.has(E)){o.add(E);for(let v of this.tree.getChildren(E))y(v.id)}};for(let E of this.notes)!E.node||E.cross||C(E.title)&&y(E.node.id);let w=new Map;for(let E of this.notes){if(!E.cross)continue;let v=w.get(E.cross.folder)??[];v.push(E),w.set(E.cross.folder,v)}for(let[E,v]of w){let D=new Map;for(let N of v){let Q=N.cross?.parentId??null;if(!Q)continue;let S=D.get(Q)??[];S.push(N.cross.id),D.set(Q,S)}let x=new Set;a.set(E,x);let F=N=>{if(!x.has(N)){x.add(N);for(let Q of D.get(N)??[])F(Q)}};for(let N of v)C(N.title)&&F(N.cross.id)}}let r=m=>{let C=i.filters;if(o||a)if(m.cross){let y=a?.get(m.cross.folder);if(!y||!y.has(m.cross.id))return!1}else if(m.node){if(!o||!o.has(m.node.id))return!1}else return!1;if(C.before||C.after||C.on){let y=this.createdMsFor(m);if(y==null||C.before!=null&&y>=C.before||C.after!=null&&y<=C.after||C.on&&(y<C.on.start||y>=C.on.end))return!1}return!0},A=m=>n(m.toLowerCase()),c=this.notes.filter(m=>!m.cross),g=this.notes.filter(m=>m.cross),p=(m,C)=>({id:m.cross?`cross:${m.cross.folder}:${m.cross.id}`:m.node.id,label:m.title,node:m.node,kind:"note",bodyPreview:this.previewFromBody(m.body,C),matchLine:C,crossFolder:m.cross?.folder,crossFile:m.cross?.file,crossId:m.cross?.id}),h=m=>{let C=[];for(let y of m)if(r(y))if(this.opts.mode==="search"){if(!e){C.push(p(y,-1));continue}let w=n(y.title.toLowerCase()),E=y.body.split(/\r?\n/),v=[];for(let x=0;x<E.length;x++)A(E[x])&&v.push(x);let D=v.length>0||n(y.body.toLowerCase());if(!w&&!D)continue;if(v.length===0)C.push(p(y,-1));else{let x=[],F=-100;for(let Q of v)Q-F>5&&x.push(Q),F=Q;let N=5;for(let Q of x.slice(0,N))C.push(p(y,Q))}}else{if(e&&!n(y.title.toLowerCase())&&!n(y.body.toLowerCase()))continue;C.push(p(y,-1))}return C},u=h(c),I=[...u];if(this.opts.mode==="search"?e?!0:u.length<10:!!e){let m=h(g);this.opts.mode==="search"&&!e&&(I.length=Math.min(I.length,50)),I.push(...m)}if(this.opts.folderResults){let m=this.opts.folderResults(),C={id:"__folder_picker__",label:"Open folder in a new tab\u2026",node:null,kind:"folder-open"};m.length>0&&(e?m.some(y=>{let w=y.split("/").pop()??y;return n(`${y.toLowerCase()} ${w.toLowerCase()}`)})&&I.push(C):I.unshift(C))}if(this.opts.allowCreate&&e&&!I.some(m=>m.label.trim().toLowerCase()===e)&&I.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),i.text.join("").length>=3){let m=y=>y.kind==="note"&&(y.id===T||y.crossId===T)&&n(y.label.toLowerCase()),C=I.filter(m);if(C.length>0){let y=I.filter(w=>!m(w));I.splice(0,I.length,...C,...y)}}return this.opts.excludedFolderNotes&&!this.includeExcluded&&I.push({id:"__search_excluded__",label:"Search excluded Stashpad folders",node:null,kind:"search-excluded"}),I}loadExcludedNotes(){if(this.includeExcluded||!this.opts.excludedFolderNotes)return;this.includeExcluded=!0;for(let e of this.opts.excludedFolderNotes())this.notes.push({node:null,title:e.title,body:e.body,cross:e});for(let e of this.notes)!e.cross||e.body||!e.cross.file||this.app.vault.cachedRead(e.cross.file).then(i=>{e.body=this.stripFm(i)});let t=this.inputEl;t&&(t.dispatchEvent(new Event("input",{bubbles:!0})),setTimeout(()=>t.dispatchEvent(new Event("input",{bubbles:!0})),250))}previewFromBody(t,e){let i=t.split(/\r?\n/);if(e<0)return i.filter(a=>a.trim().length>0).slice(0,3).join(` `);let s=Math.max(0,e-2),n=Math.min(i.length,e+3);return i.slice(s,n).filter(o=>o.trim().length>0).join(` -`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let d=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),u=d.createSpan({cls:"stashpad-search-excluded-icon"});(0,vt.setIcon)(u,"folder-search"),d.createSpan({text:t.label}),e.createDiv({cls:"stashpad-suggest-preview",text:"Include folders you've excluded from search (e.g. to move a note there)."});return}t.crossFolder&&e.addClass("is-cross-folder"),e.addClass("stashpad-suggest-row");let i=e.createDiv({cls:"stashpad-suggest-body"}),s=this.notes.find(d=>t.crossFolder?d.cross?.folder===t.crossFolder&&d.cross?.id===t.crossId:d.node?.id===t.id),n=zo(this.inputEl?.value??"").text,o=this.firstLineOfBody(s?.body??"")||t.label.trim(),a=i.createDiv({cls:"stashpad-suggest-title"});this.highlightInto(a,o,n);let r=t.crossFolder??this.opts.localFolder??null;if(t.bodyPreview&&t.matchLine!=null&&t.matchLine>=0){let d=i.createDiv({cls:"stashpad-suggest-preview stashpad-suggest-snippet"});this.highlightInto(d,t.bodyPreview,n)}let l="";if(t.crossFolder?l=s?.cross?.parentBlurb??"":l=this.parentBlurbFor(t.node),l){let d=i.createDiv({cls:"stashpad-suggest-preview"});d.appendText("Parent: "),this.highlightInto(d,l,n)}let c=t.crossFolder?this.buildCrossBreadcrumb(t):this.buildLocalBreadcrumb(t.node),p=t.crossFolder??this.opts.localFolder??null;if(p||c){let d=i.createDiv({cls:"stashpad-suggest-breadcrumb"}),I=[p?p.split("/").pop()||p:"",c].filter(f=>f&&f.length>0).join(" \u203A ");I&&d.setText(I)}let g=s?this.createdMsFor(s):null;if(g!=null||r){let d=e.createDiv({cls:"stashpad-suggest-rail"});if(g!=null){let u=d.createDiv({cls:"stashpad-suggest-time"});u.setText(this.formatRelativeTime(g)),u.title=St(g).format("YYYY-MM-DD HH:mm")}r&&d.createDiv({cls:"stashpad-suggest-folder-badge",text:r.split("/").pop()||r})}}formatRelativeTime(t){let e=St(t),i=St().startOf("day").diff(St(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(l=>l&&l.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let l of s){let c=0;for(;(c=n.indexOf(l,c))!==-1;)o.push([c,c+l.length]),c+=l.length}if(!o.length){t.appendText(e);return}o.sort((l,c)=>l[0]-c[0]);let a=[];for(let l of o){let c=a[a.length-1];c&&l[0]<=c[1]?c[1]=Math.max(c[1],l[1]):a.push([l[0],l[1]])}let r=0;for(let[l,c]of a)l>r&&t.appendText(e.slice(r,l)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(l,c)}),r=c;r<e.length&&t.appendText(e.slice(r))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===T)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==T&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==T?this.tree.get(s.parent):void 0;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let r of this.notes){if(!r.cross)continue;let l=this.crossFolderIndex.get(r.cross.folder);l||(l=new Map,this.crossFolderIndex.set(r.cross.folder,l)),l.set(r.cross.id,r.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.crossId??t.id.replace(/^cross:/,""),s=e.get(i);if(!s)return"";let n=[],o=new Set([s.id]),a=s.parentId?e.get(s.parentId):null;for(;a&&!o.has(a.id);)o.add(a.id),n.unshift(a.title),a=a.parentId?e.get(a.parentId):null;return n.join(" \u203A ")}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let i of e){let s=i.trim();if(s)return s}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===T)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!vt.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(vt.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",l=>{if(l.key==="["){l.preventDefault();let c=t.selectionStart??t.value.length,p=t.selectionEnd??c,g=t.value.slice(0,c),d=t.value.slice(c,p),u=t.value.slice(p);t.value=`${g}[${d}]${u}`;let I=c+1+d.length;t.setSelectionRange(I,I),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 p=t.value.slice(0,c-1),g=t.value.slice(c+1);t.value=`${p}${g}`,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,p=this.inputEl;if(!c)return!0;let g=Array.from(c.querySelectorAll('input, button, select, textarea, a[href], [tabindex]:not([tabindex="-1"])')).filter(I=>!I.hasAttribute("disabled")&&I.tabIndex!==-1&&I.offsetParent!==null);if(g.length===0)return!0;let d=document.activeElement,u=d?g.indexOf(d):-1;if(l.shiftKey){if(u<=0)return l.preventDefault(),g[g.length-1].focus(),!1}else if(u===g.length-1)return l.preventDefault(),(p??g[0]).focus(),!1;return!0}),this.app.keymap?.pushScope(a),this.pendingCleanups.push(()=>{try{this.app.keymap?.popScope(a)}catch{}})}appendFilterToInput(t,e,i){let s=t.value,o=`${s.length>0&&!/\s$/.test(s)?" ":""}${e}: [`,a="]",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 I of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=I.label,this.whenMode===I.id&&f.addClass("is-active"),f.addEventListener("mousedown",C=>C.preventDefault()),f.addEventListener("click",C=>{if(C.preventDefault(),this.whenMode===I.id)return;let m=this.whenMode;m!=="between"&&I.id==="between"?this.whenBetweenEndText="":m==="between"&&I.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=I.id;for(let y in a)a[y].toggleClass("is-active",y===I.id);u()}),a[I.id]=f,n.appendChild(f)}s.appendChild(n);let r=document.createElement("div");r.className="stashpad-when-body",s.appendChild(r);let l=(I,f,C="single")=>{let m=St().format("YYYY-MM-DD"),y=!f||f===m;if(C==="betweenStart")return"00:00";if(C==="betweenEnd")return"23:59";switch(I){case"after":return"00:00";case"on":return y?St().format("HH:mm"):"23:59";case"before":return y?St().format("HH:mm"):"23:59";default:return"23:59"}},c=(I,f)=>{I.addEventListener("keydown",C=>{C.key==="Enter"?(C.preventDefault(),C.stopPropagation(),f()):C.key==="Escape"&&(C.preventDefault(),C.stopPropagation(),this.closeWhenBuilder())})},p=(I,f)=>{let C=I.selectionStart??I.value.length,m=I.selectionEnd??I.value.length,w=`${C>0&&!/\s$/.test(I.value.slice(0,C))?" ":""}${f}`,E=I.value.slice(0,C)+w+I.value.slice(m);I.value=E;let v=C+w.length;I.setSelectionRange(v,v),I.focus(),I.dispatchEvent(new Event("input",{bubbles:!0}))},g=(I,f)=>{let m=I.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return m?m[1]:null},d=(I,f,C,m)=>{let y=r.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=y.createDiv({cls:"stashpad-when-icon-slot"}),E=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});E.type="button",E.title="Pick date",(0,vt.setIcon)(E,"calendar-days");let v=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});v.tabIndex=-1;let S=y.createDiv({cls:"stashpad-when-icon-slot"}),M=S.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});M.type="button",M.title="Pick time",(0,vt.setIcon)(M,"clock");let F=y.createDiv({cls:"stashpad-when-icon-slot"}),N=F.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});N.type="button",N.title="Pick day",(0,vt.setIcon)(N,"calendar");let Q=y.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=y.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:I}});K.value=f(),K.addEventListener("input",()=>C(K.value));let x=y.createEl("button",{cls:"stashpad-when-clear"});x.type="button",x.textContent="\xD7",x.title="Clear";for(let P of[E,M,N,D,x])P.addEventListener("mousedown",tt=>tt.preventDefault());let Y=null,q=(P,tt)=>{Y&&Y();let O=P.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!==P&&!P.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",P=>{P.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(),p(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 Ct=lt.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});Ct.type="button";let B=()=>{let J=parseInt(ot.value,10);!Number.isFinite(J)||J<1||(p(K,gt(J,Qt.value)),O())};Ct.addEventListener("mousedown",J=>J.preventDefault()),Ct.addEventListener("click",J=>{J.preventDefault(),B()}),V(B),ot.focus(),ot.select()})});let j=(P,tt,O,V,rt)=>{q(tt,(gt,nt,At)=>{Mi(gt,{seedH:O,seedM:V,seedPeriod:rt,close:nt,setOnEnter:At,onFinalize:lt=>p(P,$n(lt))})})};N.addEventListener("click",P=>{P.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",Ct=>Ct.preventDefault()),Qt.addEventListener("click",Ct=>{Ct.preventDefault(),p(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],Ct=gt.createEl("button",{cls:"stashpad-when-pop-chip",text:Qt.slice(0,3)});Ct.type="button",Ct.title=Qt,ot===lt&&Ct.addClass("is-today"),Ct.addEventListener("mousedown",B=>B.preventDefault()),Ct.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");p(K,H)}else p(K,Qt);O()})}})});let L=(P,tt)=>{P.value||(P.value=tt);let O=P;if(typeof O.showPicker=="function")try{O.showPicker();return}catch{}P.focus(),P.click()};return E.addEventListener("click",P=>{P.preventDefault(),L(v,St().format("YYYY-MM-DD"))}),v.addEventListener("change",()=>{v.value&&p(K,v.value)}),M.addEventListener("click",P=>{P.preventDefault();let tt=K.selectionStart??K.value.length,O=g(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";j(K,S,lt,At,ot)}),x.addEventListener("click",P=>{P.preventDefault(),K.value="",C(""),K.focus()}),K},u=()=>{if(r.empty(),this.whenMode==="between"){let I=d("start (date / day / timeframe)",()=>this.whenSingleText,E=>{this.whenSingleText=E},"betweenStart"),f=d("end (date / day / timeframe)",()=>this.whenBetweenEndText,E=>{this.whenBetweenEndText=E},"betweenEnd"),C=r.createDiv({cls:"stashpad-when-actions"}),m=C.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",E=>E.preventDefault());let y=()=>{let E=I.value.trim(),v=f.value.trim();E&&this.appendFilterToInput(t,"after",E),v&&this.appendFilterToInput(t,"before",v),this.closeWhenBuilder()};m.addEventListener("click",E=>{E.preventDefault(),y()});let w=C.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",E=>E.preventDefault()),w.addEventListener("click",E=>{E.preventDefault(),this.closeWhenBuilder()}),c(I,y),c(f,y),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}else{let I=d("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),f=r.createDiv({cls:"stashpad-when-actions"}),C=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",w=>w.preventDefault());let m=()=>{let w=I.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};C.addEventListener("click",w=>{w.preventDefault(),m()});let y=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});y.type="button",y.addEventListener("mousedown",w=>w.preventDefault()),y.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),c(I,m),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}};u(),e.parentElement?.insertBefore(s,e.nextSibling),this.whenBuilderEl=s}closeWhenBuilder(){if(!this.whenBuilderEl)return;this.whenBuilderEl.remove(),this.whenBuilderEl=null,this.modalEl?.removeClass("is-when-builder-open")}selectSuggestion(t,e){if(t&&t.kind==="search-excluded"){this.loadExcludedNotes();return}super.selectSuggestion(t,e)}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}if(t.kind==="folder-open"&&t.id==="__folder_picker__"){let e=this.opts.folderResults?.()??[];if(!e.length)return;let i=this.inputEl?.value??"",s=!1,n=g=>{s=!0;let d=g.split("/").pop()??g;this.opts.onPick({id:`folder:${g}`,label:`Open folder \u201C${d}\u201D in a new tab`,node:null,kind:"folder-open",folder:g})},o=new bn(this.app,e,n),a=o.onClose.bind(o),r=this.tree,l=this.titleFn,c=this.opts,p=this.app;o.onClose=()=>{if(a(),!s){let g=new h(p,r,l,c);g.open(),setTimeout(()=>{let d=g.inputEl;d&&(i&&(d.value=i,d.dispatchEvent(new Event("input",{bubbles:!0}))),d.focus(),d.setSelectionRange(d.value.length,d.value.length))},0)}},o.open();return}this.opts.onPick(t)}},bn=class extends vt.FuzzySuggestModal{constructor(t,e,i){super(t);this.folders=e;this.onChosen=i;this.setPlaceholder("Open which folder?")}getItems(){return this.folders}getItemText(t){let e=t.split("/").pop()??t;return e===t?t:`${e} \u2014 ${t}`}onChooseItem(t){this.onChosen(t)}};var Vo=require("obsidian");Et();var Cs=class extends Vo.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:yr(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(A){return this.commands.filter(t=>Ni(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 yr(h){return h.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||h}Ht();var Nn=require("obsidian");function Er(h,A){return!A||h.metaKey||h.ctrlKey||h.altKey?!1:h.key.toLowerCase()===A.toLowerCase()}function $e(h,A){return A?A.includes("+")?wr(h,A):Er(h,A):!1}function st(h,A){if(!A)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=A;return t&&e?s?$e(h,t)||$e(h,e):i?$e(h,e):$e(h,t):$e(h,t)||$e(h,e)}function vi(h){if(!h)return"";let A=Nn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return h.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?A?"Cmd":"Ctrl":e.toLowerCase()==="alt"?A?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function wr(h,A){if(!A)return!1;let t=A.split("+").map(p=>p.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),i=new Set(t.slice(0,-1).map(p=>p.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=Nn.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?h.metaKey:h.ctrlKey;return s&&!c||n&&!h.ctrlKey||o&&!h.metaKey||a!==h.altKey||r!==h.shiftKey||!s&&(!n&&h.ctrlKey||!o&&h.metaKey)?!1:h.key.toLowerCase()===e}var Ne=require("obsidian");Ht();var Rt=class Rt{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 Ne.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 Ne.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=A.scope==="selection"?this.host.getActionTargets().map(g=>g.file).filter(g=>!!g):this.fileBackedNotesInFolder();if(i.length===0){new Ne.Notice(A.scope==="selection"?"No notes selected.":"No notes in this folder.");return}let s=[],n=[];for(let g of i){let d=this.host.app.metadataCache.getFileCache(g)?.frontmatter,u=typeof d?.author=="string"?d.author:"";if(!u.trim()){s.push(g.path);continue}if(u.includes(e)||!A.contributorMode)continue;(Array.isArray(d?.contributors)?d.contributors.filter(f=>typeof f=="string"):[]).some(f=>f.includes(e))||n.push(g.path)}let o=s.length+n.length;if(o===0){new Ne.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(A.scope==="folder"){let g=[`Stamp yourself as author on ${s.length} unauthored note(s)`];if(n.length&&g.push(`and as a contributor on ${n.length} already-authored note(s)`),!await new Promise(u=>{new Ft(this.host.app,"Claim authorship",`${g.join(" ")}? -Existing authors are never overwritten. This can be undone.`,"Claim",u).open()}))return}let a=this.host.noteFolder,r=t.link,l=new Set,c=async()=>{await this.pacedFrontmatter(s,(g,d)=>{typeof g.author=="string"&&g.author.trim()||(g.author=r),Array.isArray(g.contributors)&&g.contributors.some(u=>typeof u=="string"&&u.includes(e))&&(g.contributors=g.contributors.filter(u=>!(typeof u=="string"&&u.includes(e))),l.add(d))}),await this.pacedFrontmatter(n,g=>{let d=Array.isArray(g.contributors)?g.contributors.filter(u=>typeof u=="string"):[];d.some(u=>u.includes(e))||d.push(r),g.contributors=d})};this.ensureAuthorFile(t),await c(),this.host.plugin.getUndoStack(a).push({label:`Claim authorship (${o} note${o===1?"":"s"})`,undo:async()=>{await this.pacedFrontmatter(s,(g,d)=>{if(typeof g.author=="string"&&g.author.includes(e)&&delete g.author,l.has(d)){let u=Array.isArray(g.contributors)?g.contributors.filter(I=>typeof I=="string"):[];u.some(I=>I.includes(e))||u.push(r),g.contributors=u}}),await this.pacedFrontmatter(n,g=>{Array.isArray(g.contributors)&&(g.contributors=g.contributors.filter(d=>!(typeof d=="string"&&d.includes(e))))}),this.host.debouncedRender()},redo:async()=>{l.clear(),await c(),this.host.debouncedRender()}});let p=[];s.length&&p.push(`authored ${s.length}`),n.length&&p.push(`contributing to ${n.length}`),new Ne.Notice(`Claimed authorship: ${p.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=Rt.EXTERNAL_WRITE_GRACE_MS*20,e=Rt.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<Rt.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=Rt.CONTRIB_DEBOUNCE_MS+(e?Rt.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<Rt.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(g=>typeof g=="string"):[],l=`-${s.id}`,c=a.includes(l),p=r.some(g=>g.includes(l));!c&&!p&&r.push(s.link),o.contributors=r})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Rt.CONTRIB_DEBOUNCE_MS=4e3,Rt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Rt.EXTERNAL_WRITE_GRACE_MS=1500,Rt.EXTERNAL_QUIESCENCE_MS=5e3;var ms=Rt;var Bs=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 Wo=require("obsidian");var Qs=class{constructor(A,t,e){this.host=A;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(A){let t=this.renderCache.get(A.path);if(t&&t.mtime===A.stat.mtime)return Nt.record("render.row.cacheHit",0),t;let e=await Nt.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(A)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await Nt.timeAsync("render.row.markdown",()=>Wo.MarkdownRenderer.render(this.host.app,s,o,A.path,this.component));let a=o.innerHTML,r={mtime:A.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(A.path,r),r}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(A=>{for(let t of A){if(!t.isIntersecting)continue;let e=t.target,i=this.lazyBodies.get(e);this.bodyObserver?.unobserve(e),this.lazyBodies.delete(e),i&&i()}},{root:this.host.contentEl,rootMargin:"1400px 0px"})}dispose(){this.bodyObserver?.disconnect(),this.bodyObserver=null}isArmed(){return!!this.bodyObserver}hasFreshRenderCache(A){let t=this.renderCache.get(A.path);return!!t&&t.mtime===A.stat.mtime}defer(A,t){this.lazyBodies.set(A,t),this.bodyObserver?.observe(A)}splitAttachments(A){let t=[];return{text:A.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` +`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}if(t.kind==="folder-open"){e.addClass("is-folder-open"),e.createDiv({cls:"stashpad-suggest-title",text:t.label}),t.folder?e.createDiv({cls:"stashpad-suggest-preview",text:t.folder}):e.createDiv({cls:"stashpad-suggest-preview",text:"Click to choose a folder\u2026"});return}if(t.kind==="search-excluded"){e.addClass("is-search-excluded");let h=e.createDiv({cls:"stashpad-suggest-title stashpad-search-excluded-row"}),u=h.createSpan({cls:"stashpad-search-excluded-icon"});(0,Ft.setIcon)(u,"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=ea(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 A="";if(t.crossFolder?A=s?.cross?.parentBlurb??"":A=this.parentBlurbFor(t.node),A){let h=i.createDiv({cls:"stashpad-suggest-preview"});h.appendText("Parent: "),this.highlightInto(h,A,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"}),I=[g?g.split("/").pop()||g:"",c].filter(f=>f&&f.length>0).join(" \u203A ");I&&h.setText(I)}let p=s?this.createdMsFor(s):null;if(p!=null||r){let h=e.createDiv({cls:"stashpad-suggest-rail"});if(p!=null){let u=h.createDiv({cls:"stashpad-suggest-time"});u.setText(this.formatRelativeTime(p)),u.title=Dt(p).format("YYYY-MM-DD HH:mm")}r&&h.createDiv({cls:"stashpad-suggest-folder-badge",text:r.split("/").pop()||r})}}formatRelativeTime(t){let e=Dt(t),i=Dt().startOf("day").diff(Dt(t).startOf("day"),"days");return i===0?e.format("h:mm a"):i===1?"yesterday":i>1&&i<7?`${i}d ago`:i>=7&&i<30?`${Math.floor(i/7)}w ago`:i>=30&&i<365?e.format("MMM D"):e.format("MMM D, YYYY")}highlightInto(t,e,i){if(!e)return;let s=i.filter(A=>A&&A.length>0);if(!s.length){t.appendText(e);return}let n=e.toLowerCase(),o=[];for(let A of s){let c=0;for(;(c=n.indexOf(A,c))!==-1;)o.push([c,c+A.length]),c+=A.length}if(!o.length){t.appendText(e);return}o.sort((A,c)=>A[0]-c[0]);let a=[];for(let A of o){let c=a[a.length-1];c&&A[0]<=c[1]?c[1]=Math.max(c[1],A[1]):a.push([A[0],A[1]])}let r=0;for(let[A,c]of a)A>r&&t.appendText(e.slice(r,A)),t.createSpan({cls:"stashpad-suggest-match",text:e.slice(A,c)}),r=c;r<e.length&&t.appendText(e.slice(r))}buildLocalBreadcrumb(t){if(!t||!t.parent||t.parent===T)return"";let e=[],i=new Set([t.id]),s=this.tree.get(t.parent);for(;s&&s.id!==T&&!i.has(s.id);)i.add(s.id),e.unshift(this.titleFn(s)),s=s.parent&&s.parent!==T?this.tree.get(s.parent):void 0;return e.join(" \u203A ")}buildCrossBreadcrumb(t){if(!t.crossFolder)return"";if(!this.crossFolderIndex){this.crossFolderIndex=new Map;for(let r of this.notes){if(!r.cross)continue;let A=this.crossFolderIndex.get(r.cross.folder);A||(A=new Map,this.crossFolderIndex.set(r.cross.folder,A)),A.set(r.cross.id,r.cross)}}let e=this.crossFolderIndex.get(t.crossFolder);if(!e)return"";let i=t.crossId??t.id.replace(/^cross:/,""),s=e.get(i);if(!s)return"";let n=[],o=new Set([s.id]),a=s.parentId?e.get(s.parentId):null;for(;a&&!o.has(a.id);)o.add(a.id),n.unshift(a.title),a=a.parentId?e.get(a.parentId):null;return n.join(" \u203A ")}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let i of e){let s=i.trim();if(s)return s}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===T)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let i=this.notes.find(s=>s.node?.id===e.id);return i?this.firstLineOfBody(i.body):""}onOpen(){if(super.onOpen(),this.opts.showFilterChips&&!Ft.Platform.isMobile){let t=this.inputEl,e=this.resultContainerEl;if(!t||!e)return;this.mountFilterChipRow(t,e);return}if(Ft.Platform.isMobile){let t=this.inputEl;t&&t.focus()}}mountFilterChipRow(t,e){t.addEventListener("keydown",A=>{if(A.key==="["){A.preventDefault();let c=t.selectionStart??t.value.length,g=t.selectionEnd??c,p=t.value.slice(0,c),h=t.value.slice(c,g),u=t.value.slice(g);t.value=`${p}[${h}]${u}`;let I=c+1+h.length;t.setSelectionRange(I,I),t.dispatchEvent(new Event("input",{bubbles:!0}));return}if(A.key==="]"){let c=t.selectionStart??-1;c>=0&&t.value[c]==="]"&&(A.preventDefault(),t.setSelectionRange(c+1,c+1));return}if(A.key==="Backspace"&&!A.metaKey&&!A.ctrlKey&&!A.altKey&&t.selectionStart===t.selectionEnd){let c=t.selectionStart??-1;if(c>0&&t.value[c-1]==="["&&t.value[c]==="]"){A.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",A=>{A.preventDefault()}),n.addEventListener("click",A=>{A.preventDefault(),this.appendFilterToInput(t,"in","")}),n.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),A.stopPropagation(),n.click())}),i.appendChild(n);let o=document.createElement("button");o.className="stashpad-search-filter-chip stashpad-search-filter-when",o.type="button",o.textContent="when:[date / day / timeframe]",o.title="Open the time-filter builder (Before / On / After / Between).",o.addEventListener("mousedown",A=>{A.preventDefault()}),o.addEventListener("click",A=>{A.preventDefault(),this.toggleWhenBuilder(t,i)}),o.addEventListener("keydown",A=>{(A.key==="Enter"||A.key===" ")&&(A.preventDefault(),A.stopPropagation(),o.click())}),i.appendChild(o),e.parentElement?.insertBefore(i,e);let a=new Ft.Scope(this.scope),r=A=>{let c=document.activeElement;return c?.classList?.contains("stashpad-search-filter-chip")?(A.preventDefault(),c.click(),!1):A.key==="Enter"&&!A.isComposing?(A.preventDefault(),this.selectActiveSuggestion?.(A),!1):!0};a.register([],"Enter",r),a.register([]," ",r),a.register(["Mod"],"f",A=>{A.preventDefault();let c=this.inputEl;return c&&(c.focus(),c.select()),!1}),a.register([],"Tab",A=>{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(I=>!I.hasAttribute("disabled")&&I.tabIndex!==-1&&I.offsetParent!==null);if(p.length===0)return!0;let h=document.activeElement,u=h?p.indexOf(h):-1;if(A.shiftKey){if(u<=0)return A.preventDefault(),p[p.length-1].focus(),!1}else if(u===p.length-1)return A.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 A=s.length+o.length+r.length;if(t.setSelectionRange(A,A+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 I of o){let f=document.createElement("button");f.type="button",f.className="stashpad-when-tab",f.textContent=I.label,this.whenMode===I.id&&f.addClass("is-active"),f.addEventListener("mousedown",m=>m.preventDefault()),f.addEventListener("click",m=>{if(m.preventDefault(),this.whenMode===I.id)return;let C=this.whenMode;C!=="between"&&I.id==="between"?this.whenBetweenEndText="":C==="between"&&I.id!=="between"&&(!this.whenSingleText&&this.whenBetweenEndText&&(this.whenSingleText=this.whenBetweenEndText),this.whenBetweenEndText=""),this.whenMode=I.id;for(let y in a)a[y].toggleClass("is-active",y===I.id);u()}),a[I.id]=f,n.appendChild(f)}s.appendChild(n);let r=document.createElement("div");r.className="stashpad-when-body",s.appendChild(r);let A=(I,f,m="single")=>{let C=Dt().format("YYYY-MM-DD"),y=!f||f===C;if(m==="betweenStart")return"00:00";if(m==="betweenEnd")return"23:59";switch(I){case"after":return"00:00";case"on":return y?Dt().format("HH:mm"):"23:59";case"before":return y?Dt().format("HH:mm"):"23:59";default:return"23:59"}},c=(I,f)=>{I.addEventListener("keydown",m=>{m.key==="Enter"?(m.preventDefault(),m.stopPropagation(),f()):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),this.closeWhenBuilder())})},g=(I,f)=>{let m=I.selectionStart??I.value.length,C=I.selectionEnd??I.value.length,w=`${m>0&&!/\s$/.test(I.value.slice(0,m))?" ":""}${f}`,E=I.value.slice(0,m)+w+I.value.slice(C);I.value=E;let v=m+w.length;I.setSelectionRange(v,v),I.focus(),I.dispatchEvent(new Event("input",{bubbles:!0}))},p=(I,f)=>{let C=I.slice(0,f).match(/(\d{4}-\d{2}-\d{2})(?!.*\d{4}-\d{2}-\d{2})/);return C?C[1]:null},h=(I,f,m,C)=>{let y=r.createDiv({cls:"stashpad-when-input-wrap has-icons"}),w=y.createDiv({cls:"stashpad-when-icon-slot"}),E=w.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-cal"});E.type="button",E.title="Pick date",(0,Ft.setIcon)(E,"calendar-days");let v=w.createEl("input",{cls:"stashpad-when-native",attr:{type:"date"}});v.tabIndex=-1;let D=y.createDiv({cls:"stashpad-when-icon-slot"}),x=D.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-clock"});x.type="button",x.title="Pick time",(0,Ft.setIcon)(x,"clock");let F=y.createDiv({cls:"stashpad-when-icon-slot"}),N=F.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-day"});N.type="button",N.title="Pick day",(0,Ft.setIcon)(N,"calendar");let Q=y.createDiv({cls:"stashpad-when-icon-slot"}),S=Q.createEl("button",{cls:"stashpad-when-icon stashpad-when-icon-tf"});S.type="button",S.title="Pick timeframe",(0,Ft.setIcon)(S,"history");let O=y.createEl("input",{cls:"stashpad-when-input",attr:{type:"text",placeholder:I}});O.value=f(),O.addEventListener("input",()=>m(O.value));let M=y.createEl("button",{cls:"stashpad-when-clear"});M.type="button",M.textContent="\xD7",M.title="Clear";for(let P of[E,x,N,S,M])P.addEventListener("mousedown",tt=>tt.preventDefault());let Y=null,q=(P,tt)=>{Y&&Y();let K=P.createDiv({cls:"stashpad-when-popover"}),$=new Ft.Scope(this.scope),rt=null,pt=at=>{rt=at},nt=!1,lt=at=>{!K.contains(at.target)&&at.target!==P&&!P.contains(at.target)&&At()},At=()=>{if(!nt){nt=!0,K.remove(),document.removeEventListener("mousedown",lt,!0);try{this.app.keymap?.popScope($)}catch{}Y===At&&(Y=null)}};Y=At,$.register([],"Escape",at=>(at.preventDefault(),At(),!1)),$.register([],"Enter",at=>(at.preventDefault(),rt&&rt(),!1));try{tt(K,At,pt)}catch(at){console.error("[stashpad] popover fill threw:",at),K.remove(),Y=null;return}this.app.keymap?.pushScope($),this.pendingCleanups.push(At),setTimeout(()=>document.addEventListener("mousedown",lt,!0),0)};S.addEventListener("click",P=>{P.preventDefault(),q(Q,(tt,K,$)=>{let rt=this.whenMode==="on",pt=(J,G)=>{if(!rt)return`${J}${G}`;let b={d:"days",w:"weeks",m:"months",y:"years"}[G];return Dt().subtract(J,b).format("YYYY-MM-DD")},nt=tt.createDiv({cls:"stashpad-when-pop-row"}),lt=[{label:"Last 7d",n:7,unit:"d"},{label:"Last 30d",n:30,unit:"d"},{label:"This week",n:1,unit:"w"},{label:"This month",n:1,unit:"m"}];for(let J of lt){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(O,pt(J.n,J.unit)),K()})}let At=tt.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-builder"});At.createSpan({text:"Last",cls:"stashpad-when-pop-label"});let at=At.createEl("input",{cls:"stashpad-when-pop-number",attr:{type:"number",min:"1",max:"999",value:"7"}}),yt=At.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=yt.createEl("option",{text:J.label});G.value=J.v}let mt=At.createEl("button",{cls:"stashpad-when-pop-chip stashpad-when-pop-go",text:"Insert"});mt.type="button";let B=()=>{let J=parseInt(at.value,10);!Number.isFinite(J)||J<1||(g(O,pt(J,yt.value)),K())};mt.addEventListener("mousedown",J=>J.preventDefault()),mt.addEventListener("click",J=>{J.preventDefault(),B()}),$(B),at.focus(),at.select()})});let j=(P,tt,K,$,rt)=>{q(tt,(pt,nt,lt)=>{Gi(pt,{seedH:K,seedM:$,seedPeriod:rt,close:nt,setOnEnter:lt,onFinalize:At=>g(P,no(At))})})};N.addEventListener("click",P=>{P.preventDefault(),q(F,(tt,K,$)=>{let rt=tt.createDiv({cls:"stashpad-when-pop-row"});for(let at of["Today","Yesterday"]){let yt=rt.createEl("button",{cls:"stashpad-when-pop-chip",text:at});yt.type="button",yt.addEventListener("mousedown",mt=>mt.preventDefault()),yt.addEventListener("click",mt=>{mt.preventDefault(),g(O,at),K()})}let pt=tt.createDiv({cls:"stashpad-when-pop-row stashpad-when-pop-days"}),nt=["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],At=(Dt().day()+6)%7;for(let at=0;at<nt.length;at++){let yt=nt[at],mt=pt.createEl("button",{cls:"stashpad-when-pop-chip",text:yt.slice(0,3)});mt.type="button",mt.title=yt,at===At&&mt.addClass("is-today"),mt.addEventListener("mousedown",B=>B.preventDefault()),mt.addEventListener("click",B=>{if(B.preventDefault(),C==="betweenEnd"){let J=at,G=Dt().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(O,H)}else g(O,yt);K()})}})});let L=(P,tt)=>{P.value||(P.value=tt);let K=P;if(typeof K.showPicker=="function")try{K.showPicker();return}catch{}P.focus(),P.click()};return E.addEventListener("click",P=>{P.preventDefault(),L(v,Dt().format("YYYY-MM-DD"))}),v.addEventListener("change",()=>{v.value&&g(O,v.value)}),x.addEventListener("click",P=>{P.preventDefault();let tt=O.selectionStart??O.value.length,K=p(O.value,tt),$=A(this.whenMode,K,C),[rt,pt]=$.split(":"),nt=parseInt(rt,10),lt=parseInt(pt,10),At=nt%12;At===0&&(At=12);let at=nt>=12?"pm":"am";j(O,D,At,lt,at)}),M.addEventListener("click",P=>{P.preventDefault(),O.value="",m(""),O.focus()}),O},u=()=>{if(r.empty(),this.whenMode==="between"){let I=h("start (date / day / timeframe)",()=>this.whenSingleText,E=>{this.whenSingleText=E},"betweenStart"),f=h("end (date / day / timeframe)",()=>this.whenBetweenEndText,E=>{this.whenBetweenEndText=E},"betweenEnd"),m=r.createDiv({cls:"stashpad-when-actions"}),C=m.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});C.type="button",C.addEventListener("mousedown",E=>E.preventDefault());let y=()=>{let E=I.value.trim(),v=f.value.trim();E&&this.appendFilterToInput(t,"after",E),v&&this.appendFilterToInput(t,"before",v),this.closeWhenBuilder()};C.addEventListener("click",E=>{E.preventDefault(),y()});let w=m.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});w.type="button",w.addEventListener("mousedown",E=>E.preventDefault()),w.addEventListener("click",E=>{E.preventDefault(),this.closeWhenBuilder()}),c(I,y),c(f,y),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}else{let I=h("date / day / timeframe",()=>this.whenSingleText,w=>{this.whenSingleText=w},"single"),f=r.createDiv({cls:"stashpad-when-actions"}),m=f.createEl("button",{cls:"stashpad-when-insert",text:"Insert"});m.type="button",m.addEventListener("mousedown",w=>w.preventDefault());let C=()=>{let w=I.value.trim();w&&this.appendFilterToInput(t,this.whenMode,w),this.closeWhenBuilder()};m.addEventListener("click",w=>{w.preventDefault(),C()});let y=f.createEl("button",{cls:"stashpad-when-cancel",text:"Cancel"});y.type="button",y.addEventListener("mousedown",w=>w.preventDefault()),y.addEventListener("click",w=>{w.preventDefault(),this.closeWhenBuilder()}),c(I,C),I.focus(),I.setSelectionRange(I.value.length,I.value.length)}};u(),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 Pn(this.app,e,n),a=o.onClose.bind(o),r=this.tree,A=this.titleFn,c=this.opts,g=this.app;o.onClose=()=>{if(a(),!s){let p=new d(g,r,A,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)}},Pn=class extends Ft.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 ia=require("obsidian");Qt();var Es=class extends ia.SuggestModal{constructor(l){super(l),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:Lr(t[e]?.name??e)})).sort((e,i)=>e.name.localeCompare(i.name))}getSuggestions(l){return this.commands.filter(t=>Ui(l,t.name))}renderSuggestion(l,t){t.createDiv({text:l.name,cls:"stashpad-cmd-palette-name"})}onChooseSuggestion(l){this.app.commands?.executeCommandById?.(l.id)}};function Lr(d){return d.replace(/^(?:\s*Stashpad:\s*)+/i,"").trim()||d}Ht();var Un=require("obsidian");function Jr(d,l){return!l||d.metaKey||d.ctrlKey||d.altKey?!1:d.key.toLowerCase()===l.toLowerCase()}function We(d,l){return l?l.includes("+")?qr(d,l):Jr(d,l):!1}function st(d,l){if(!l)return!1;let{primary:t,secondary:e,preferRight:i,useBoth:s}=l;return t&&e?s?We(d,t)||We(d,e):i?We(d,e):We(d,t):We(d,t)||We(d,e)}function Si(d){if(!d)return"";let l=Un.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return d.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?l?"Cmd":"Ctrl":e.toLowerCase()==="alt"?l?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function qr(d,l){if(!l)return!1;let t=l.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=Un.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 xe=require("obsidian");Ht();var Rt=class Rt{constructor(l){this.host=l;this.knownBodies=new Map;this.contribTimers=new Map;this.recentSelfWrites=new Map;this.lastExternalModify=new Map}dispose(){for(let l of this.contribTimers.values())clearTimeout(l);this.contribTimers.clear(),this.knownBodies.clear(),this.recentSelfWrites.clear(),this.lastExternalModify.clear()}currentAuthorLink(){let l=(this.host.plugin.settings.authorName??"").trim(),t=(this.host.plugin.settings.authorId??"").trim();if(!l||!t)return null;let e=l.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.host.noteFolder}/_authors/${e}-${t}.md`,s=l.replace(/[\[\]|]/g,"").trim()||e;return{link:`[[${i}|${s}]]`,path:i,name:l,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 l=this.host.noteFolder.replace(/\/+$/,"");return this.host.app.vault.getMarkdownFiles().filter(t=>{let e=t.parent?.path?.replace(/\/+$/,"")??"";if(e!==l&&!e.startsWith(l+"/")||t.path.includes("/_authors/"))return!1;let i=this.host.app.metadataCache.getFileCache(t)?.frontmatter;return typeof i?.id=="string"&&!!i.id})}async pacedFrontmatter(l,t){for(let s=0;s<l.length;s++){let n=this.host.app.vault.getAbstractFileByPath(l[s]);if(n instanceof xe.TFile){this.recentSelfWrites.set(n.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(n,o=>t(o,l[s]))}catch(o){console.warn("[Stashpad] claim: frontmatter write failed",l[s],o)}}(s+1)%25===0&&await new Promise(o=>setTimeout(o,30))}}async claimAuthorship(l){let t=this.currentAuthorLink();if(!t){new xe.Notice("Set your author name in Stashpad settings first.");return}let e=`-${t.id}`,i=l.scope==="selection"?this.host.getActionTargets().map(p=>p.file).filter(p=>!!p):this.fileBackedNotesInFolder();if(i.length===0){new xe.Notice(l.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,u=typeof h?.author=="string"?h.author:"";if(!u.trim()){s.push(p.path);continue}if(u.includes(e)||!l.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 xe.Notice("Nothing to claim \u2014 those notes are already authored by you.");return}if(l.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(u=>{new kt(this.host.app,"Claim authorship",`${p.join(" ")}? +Existing authors are never overwritten. This can be undone.`,"Claim",u).open()}))return}let a=this.host.noteFolder,r=t.link,A=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(u=>typeof u=="string"&&u.includes(e))&&(p.contributors=p.contributors.filter(u=>!(typeof u=="string"&&u.includes(e))),A.add(h))}),await this.pacedFrontmatter(n,p=>{let h=Array.isArray(p.contributors)?p.contributors.filter(u=>typeof u=="string"):[];h.some(u=>u.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,A.has(h)){let u=Array.isArray(p.contributors)?p.contributors.filter(I=>typeof I=="string"):[];u.some(I=>I.includes(e))||u.push(r),p.contributors=u}}),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()=>{A.clear(),await c(),this.host.debouncedRender()}});let g=[];s.length&&g.push(`authored ${s.length}`),n.length&&g.push(`contributing to ${n.length}`),new xe.Notice(`Claimed authorship: ${g.join(", ")}. Undo available.`),this.host.debouncedRender()}async ensureAuthorFile(l){try{l.id&&this.host.plugin.authorRegistry.record({id:l.id,name:l.name});let t=`${this.host.noteFolder}/_authors`;if(await this.host.ensureFolder(t),await this.host.app.vault.adapter.exists(l.path))return;let e=l.id===(this.host.plugin.settings.authorId??"").trim(),i=this.host.plugin.buildAuthorStub({id:l.id,name:l.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(l.path,i)}catch(t){console.warn("[Stashpad] ensureAuthorFile failed",t)}}collectAuthorIds(l){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 l){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 l=Date.now(),t=Rt.EXTERNAL_WRITE_GRACE_MS*20,e=Rt.EXTERNAL_QUIESCENCE_MS*12;for(let[i,s]of this.recentSelfWrites)l-s>t&&this.recentSelfWrites.delete(i);for(let[i,s]of this.lastExternalModify)l-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(l){let t=Date.now(),e=this.recentSelfWrites.get(l.path);e!==void 0&&t-e<Rt.EXTERNAL_WRITE_GRACE_MS||this.lastExternalModify.set(l.path,t),this.scheduleContribution(l)}scheduleContribution(l){let t=this.contribTimers.get(l.path);t&&clearTimeout(t);let e=this.isFileActivelyEdited(l),i=Rt.CONTRIB_DEBOUNCE_MS+(e?Rt.CONTRIB_ACTIVE_EDITOR_BONUS_MS:0),s=setTimeout(()=>{if(this.contribTimers.delete(l.path),this.isFileActivelyEdited(l)){this.scheduleContribution(l);return}let n=this.lastExternalModify.get(l.path);if(n!==void 0&&Date.now()-n<Rt.EXTERNAL_QUIESCENCE_MS){this.scheduleContribution(l);return}this.maybeRecordContribution(l)},i);this.contribTimers.set(l.path,s)}isFileActivelyEdited(l){try{let t=this.host.app.workspace.activeLeaf;if(!t)return!1;let e=t.view;if(!e||e.getViewType?.()!=="markdown"||e.file?.path!==l.path)return!1;let i=e.containerEl??null;return!!i&&i.contains(document.activeElement)}catch{return!1}}async maybeRecordContribution(l){let t="";try{t=await this.host.app.vault.cachedRead(l)}catch{return}let e=this.host.stripFrontmatter(t),i=this.knownBodies.get(l.path);if(this.knownBodies.set(l.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(l.path,Date.now());try{await this.host.app.fileManager.processFrontMatter(l,o=>{o.modified=n;let a=typeof o.author=="string"?o.author:"",r=Array.isArray(o.contributors)?o.contributors.filter(p=>typeof p=="string"):[],A=`-${s.id}`,c=a.includes(A),g=r.some(p=>p.includes(A));!c&&!g&&r.push(s.link),o.contributors=r})}catch(o){console.warn("[Stashpad] maybeRecordContribution failed",o)}}};Rt.CONTRIB_DEBOUNCE_MS=4e3,Rt.CONTRIB_ACTIVE_EDITOR_BONUS_MS=2e3,Rt.EXTERNAL_WRITE_GRACE_MS=1500,Rt.EXTERNAL_QUIESCENCE_MS=5e3;var ws=Rt;var vs=class{constructor(l){this.host=l;this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0}attachRowDnD(l,t,e){l.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=l.offsetHeight,l.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 A,c="before";a&&a.classList.contains("stashpad-note")?(A=a.dataset.id,c="before"):r&&r.classList.contains("stashpad-note")&&(A=r.dataset.id,c="after"),A&&this.host.reorderToTarget(o,A,c)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",s.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(l,12,12)}catch{}}}),l.addEventListener("dragend",()=>{l.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),l.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let s=this.dropZone(i,l);this.clearDropIndicators(),s==="drop-into"?(this.removeDragPlaceholder(),l.addClass("drop-into")):(l.removeClass("drop-into"),this.placePlaceholder(l,s==="drop-above"?"before":"after"))}),l.addEventListener("dragleave",i=>{let s=l.getBoundingClientRect();(i.clientX<s.left||i.clientX>s.right||i.clientY<s.top||i.clientY>s.bottom)&&l.removeClass("drop-into")}),l.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let s=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,l);this.clearDropIndicators(),this.removeDragPlaceholder(),l.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(l){l.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(l.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")}}),l.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(l,t){if(!this.dragPlaceholder||!this.host.listEl)return;let e=t==="before"?l:l.nextSibling;if(t==="before"&&this.dragPlaceholder.nextSibling===l||t==="after"&&this.dragPlaceholder.previousSibling===l)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 l=this.dragPlaceholder;l.style.height="0px",l.style.opacity="0",setTimeout(()=>{l.parentElement&&l.remove()},150)}dropZone(l,t){let e=t.getBoundingClientRect(),i=l.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 l of Array.from(this.host.listEl.querySelectorAll(".drop-into")))l.removeClass("drop-into")}};var sa=require("obsidian");var Fs=class{constructor(l,t,e){this.host=l;this.component=t;this.bodyObserver=null;this.lazyBodies=new WeakMap;this.renderCache=e??new Map}async getOrComputeRender(l){let t=this.renderCache.get(l.path);if(t&&t.mtime===l.stat.mtime)return xt.record("render.row.cacheHit",0),t;let e=await xt.timeAsync("render.row.read",()=>this.host.app.vault.cachedRead(l)),i=this.host.stripFrontmatter(e),{text:s,attachments:n}=this.splitAttachments(i),o=createDiv({cls:"stashpad-note-text"});await xt.timeAsync("render.row.markdown",()=>sa.MarkdownRenderer.render(this.host.app,s,o,l.path,this.component));let a=o.innerHTML,r={mtime:l.stat.mtime,text:s,attachments:n,html:a};return this.renderCache.set(l.path,r),r}arm(){this.bodyObserver?.disconnect(),this.lazyBodies=new WeakMap,this.bodyObserver=new IntersectionObserver(l=>{for(let t of l){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(l){let t=this.renderCache.get(l.path);return!!t&&t.mtime===l.stat.mtime}defer(l,t){this.lazyBodies.set(l,t),this.bodyObserver?.observe(l)}splitAttachments(l){let t=[];return{text:l.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,s)=>(t.push(s),"")).replace(/\n{3,}/g,` -`).trim(),attachments:t}}};function Xo(h,A,t){return h.tree.getChildren(A).slice().sort((i,s)=>vr(h,i,s,t)).map(i=>i.id)}function vr(h,A,t,e){switch(e){case"created-asc":return(A.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(A.created||"");case"modified-asc":case"modified-desc":{let i=$o(h,A)||A.created||"",s=$o(h,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=h.titleForNode(A),s=h.titleForNode(t),n={numeric:!0,sensitivity:"base"};return e==="title-az"?i.localeCompare(s,void 0,n):s.localeCompare(i,void 0,n)}default:return 0}}function $o(h,A){if(!A.file)return"";let t=h.app.metadataCache.getFileCache(A.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Xe=require("obsidian");var Zo=require("obsidian");function ue(h,A,t){h.empty();try{(0,Zo.setIcon)(h,A)}catch{}let e=h.querySelector("svg");e&&e.querySelector("path, line, circle, rect, polyline, polygon, ellipse")||(h.empty(),h.createSpan({cls:"stashpad-icon-fallback",text:t}))}function _o(h){if(h instanceof Element&&h.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let A=new Set([document]);h instanceof Element&&h.ownerDocument&&A.add(h.ownerDocument);for(let t of A)if(t.body?.querySelector(".modal-bg")||t.body?.querySelector(".modal-container .modal")||t.body?.querySelector(".suggestion-container")||t.body?.querySelector(".menu.mod-active"))return!0;return!1}function jo(h){let A=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(h))!=null;)A.push({lang:e[3].trim(),code:e[4]});return A}function Fi(h){return h.split("/").map(A=>A.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function ta(h,A,t){let e=new Set(A),i=h.filter(n=>!e.has(n)),s=h.findIndex(n=>e.has(n));if(s<0)return h.slice();switch(t){case"top":return[...A,...i];case"bottom":return[...i,...A];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...A),o}case"down":{let n=(()=>{let l=-1;return h.forEach((c,p)=>{e.has(c)&&(l=p)}),l})(),o=0;for(let l=0;l<Math.min(h.length,n+2);l++)e.has(h[l])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...A),r}}}function xn(h,A){if(h.length!==A.length)return!1;for(let t=0;t<h.length;t++)if(h[t]!==A[t])return!1;return!0}async function Mn(h){let A=h.getActionTargets();if(!A.length)return;let t=ut().prefixTimestampsOnCopy,e=[];for(let i of A){if(!i.file)continue;let s=await h.app.vault.cachedRead(i.file),n=h.stripFrontmatter(s).trim();e.push(t?`${h.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(e.join(` +`).trim(),attachments:t}}};function oa(d,l,t){return d.tree.getChildren(l).slice().sort((i,s)=>Or(d,i,s,t)).map(i=>i.id)}function Or(d,l,t,e){switch(e){case"created-asc":return(l.created||"").localeCompare(t.created||"");case"created-desc":return(t.created||"").localeCompare(l.created||"");case"modified-asc":case"modified-desc":{let i=na(d,l)||l.created||"",s=na(d,t)||t.created||"";return e==="modified-asc"?i.localeCompare(s):s.localeCompare(i)}case"title-az":case"title-za":{let i=d.titleForNode(l),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 na(d,l){if(!l.file)return"";let t=d.app.metadataCache.getFileCache(l.file)?.frontmatter;return(typeof t?.modified=="string"?t.modified:"")||""}var Xe=require("obsidian");var aa=require("obsidian");function me(d,l,t){d.empty();try{(0,aa.setIcon)(d,l)}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 ra(d){if(d instanceof Element&&d.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt"))return!0;let l=new Set([document]);d instanceof Element&&d.ownerDocument&&l.add(d.ownerDocument);for(let t of l)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 la(d){let l=[],t=/^([ \t]*)(`{3,})[ \t]*([^\n`]*)\n([\s\S]*?)\n\1\2[ \t]*$/gm,e;for(;(e=t.exec(d))!=null;)l.push({lang:e[3].trim(),code:e[4]});return l}function Di(d){return d.split("/").map(l=>l.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function Aa(d,l,t){let e=new Set(l),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[...l,...i];case"bottom":return[...i,...l];case"up":{let n=Math.max(0,s-1),o=i.slice();return o.splice(n,0,...l),o}case"down":{let n=(()=>{let A=-1;return d.forEach((c,g)=>{e.has(c)&&(A=g)}),A})(),o=0;for(let A=0;A<Math.min(d.length,n+2);A++)e.has(d[A])||o++;let a=Math.min(i.length,o),r=i.slice();return r.splice(a,0,...l),r}}}function Rn(d,l){if(d.length!==l.length)return!1;for(let t=0;t<d.length;t++)if(d[t]!==l[t])return!1;return!0}async function Gn(d){let l=d.getActionTargets();if(!l.length)return;let t=ut().prefixTimestampsOnCopy,e=[];for(let i of l){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(` -`)),h.plugin.notifications.show({message:`Copied ${h.titleList(A)} to clipboard`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}async function ea(h){let A=h.getActionTargets();if(!A.length||!A[0].file){new Xe.Notice("Nothing to copy from.");return}let t=A[0],e=await h.app.vault.cachedRead(t.file),i=h.stripFrontmatter(e),s=jo(i);if(s.length===0){h.plugin.notifications.show({message:`No codeblock found in "${h.titleForNode(t)}".`,kind:"info",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}if(s.length===1){await navigator.clipboard.writeText(s[0].code),h.plugin.notifications.show({message:`Copied codeblock${s[0].lang?` (${s[0].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder});return}let n=s.map((a,r)=>({kind:"one",idx:r,label:`${r+1}. ${a.lang||"(no language)"} \u2014 ${a.code.split(` +`)),d.plugin.notifications.show({message:`Copied ${d.titleList(l)} to clipboard`,kind:"success",category:"system",affectedIds:l.map(i=>i.id),folder:d.noteFolder})}async function ca(d){let l=d.getActionTargets();if(!l.length||!l[0].file){new Xe.Notice("Nothing to copy from.");return}let t=l[0],e=await d.app.vault.cachedRead(t.file),i=d.stripFrontmatter(e),s=la(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(` -`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends Xe.SuggestModal{getSuggestions(a){let r=a.trim().toLowerCase();if(!r)return n;let l=r.split(/\s+/).filter(Boolean);return n.filter(c=>{let p=c.label.toLowerCase();return l.every(g=>p.includes(g))})}renderSuggestion(a,r){r.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let r=a.kind==="all"?s.map(l=>l.code).join(` +`)?"\u2026":""}`}));n.push({kind:"all",idx:-1,label:`Copy all ${s.length} blocks (joined with blank lines)`});let o=new class extends Xe.SuggestModal{getSuggestions(a){let r=a.trim().toLowerCase();if(!r)return n;let A=r.split(/\s+/).filter(Boolean);return n.filter(c=>{let g=c.label.toLowerCase();return A.every(p=>g.includes(p))})}renderSuggestion(a,r){r.createDiv({cls:"stashpad-suggest-title",text:a.label})}async onChooseSuggestion(a){let r=a.kind==="all"?s.map(A=>A.code).join(` -`):s[a.idx].code;await navigator.clipboard.writeText(r),h.plugin.notifications.show({message:a.kind==="all"?`Copied all ${s.length} codeblocks from "${h.titleForNode(t)}".`:`Copied codeblock${s[a.idx].lang?` (${s[a.idx].lang})`:""} from "${h.titleForNode(t)}".`,kind:"success",category:"system",affectedIds:[t.id],folder:h.noteFolder})}}(h.app);o.setPlaceholder(`${s.length} codeblocks in "${h.titleForNode(t)}" \u2014 pick one to copy.`),o.open()}async function ia(h){let A=h.getActionTargets();if(A.length===0){let n=h.tree.get(h.focusId);n?.file&&(A=[n])}if(A.length===0){new Xe.Notice("Nothing to copy.");return}let t=ut().prefixTimestampsOnCopy,e=[],i=async(n,o)=>{if(n.file){let a=await h.app.vault.cachedRead(n.file),r=h.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),l=t?`${h.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${l}${r}`)}for(let a of h.tree.getChildren(n.id))await i(a,o+1)};for(let n of A)await i(n,0);let s=e.join(` -`);await navigator.clipboard.writeText(s),h.plugin.clearNoteClipboard(),h.plugin.noteClipboard={mode:"copy",folder:h.noteFolder,ids:A.map(n=>n.id),text:s},h.render(),h.plugin.notifications.show({message:`Copied tree of ${h.titleList(A)} (${e.length} entries) \u2014 paste in the list to clone, in a note to drop the outline in`,kind:"success",category:"system",affectedIds:A.map(n=>n.id),folder:h.noteFolder})}async function sa(h){let A=h.getActionTargets();if(A.length===0){let i=h.tree.get(h.focusId);i?.file&&(A=[i])}if(A.length===0){new Xe.Notice("Nothing to copy.");return}let t=[],e=(i,s)=>{if(!i.file)return;let n=" ".repeat(s);t.push(`${n}- ![[${i.file.basename}]]`);for(let o of h.tree.getChildren(i.id))e(o,s+1)};for(let i of A)e(i,0);await navigator.clipboard.writeText(t.join(` -`)),h.plugin.notifications.show({message:`Copied outline of ${h.titleList(A)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:A.map(i=>i.id),folder:h.noteFolder})}var Ie=require("obsidian");Et();Ti();Ht();function kr(h){return h.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function na(h,A){let t=Dr(h,A);if(t.length===0){new Ie.Notice("Nothing to export.");return}let e=br(h,t);if(e.length===0){new Ie.Notice("No exportable notes (no files attached).");return}let i=(h.noteFolder.split("/").pop()||h.noteFolder).trim(),s=t.length===1?h.titleForNode(t[0]):`${i}-${t.length}notes`;new oi(h.app,s,e.length,(n,o,a)=>{Sr(h,t,e,n,o,a)},Vi).open()}async function Sr(h,A,t,e,i,s=!1){try{let n=await De(h.app,{rootNotes:A.filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),allDescendants:t.filter(d=>!A.some(u=>u.id===d.id)).filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),sourceFolder:h.noteFolder}),o="";if(i){let d=await Je(n,i);n=d.data;let u=fo[d.kdf];o=u.strong?` (encrypted \xB7 ${u.label})`:` (encrypted \xB7 ${u.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,Ie.moment)().format("YYYYMMDD-HHmmss"),r=kr(e),l=(h.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${h.noteFolder}/${l}`;await h.ensureFolder(c);let p=`${r}-${a}`,g=`${c}/${p}.${Ae}`;if(await h.app.vault.createBinary(g,n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)),s&&i){let d=h.app.secretStorage;try{d?.setSecret(ii(p),i)}catch(u){console.warn("[Stashpad] couldn't save export passphrase to secret storage",u)}}await h.log.append({type:"stash_export",id:A[0].id,payload:{path:g,noteCount:t.length,rootIds:A.map(d=>d.id)}}),h.plugin.notifications.show({message:`Exported ${t.length} note${t.length===1?"":"s"}${o} \u2192 \`${g}\``,kind:i&&o.includes("weaker")?"warning":"success",category:"export",affectedPaths:[g],folder:h.noteFolder,actions:h.actionsForFile(g),duration:0})}catch(n){h.plugin.notifications.show({message:`Stashpad: export failed +`):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 da(d){let l=d.getActionTargets();if(l.length===0){let n=d.tree.get(d.focusId);n?.file&&(l=[n])}if(l.length===0){new Xe.Notice("Nothing to copy.");return}let t=ut().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(" "),A=t?`${d.formatTimeInline(n.created)} `:"";e.push(`${" ".repeat(o)}- ${A}${r}`)}for(let a of d.tree.getChildren(n.id))await i(a,o+1)};for(let n of l)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:l.map(n=>n.id),text:s},d.render(),d.plugin.notifications.show({message:`Copied tree of ${d.titleList(l)} (${e.length} entries) \u2014 paste in the list to clone, in a note to drop the outline in`,kind:"success",category:"system",affectedIds:l.map(n=>n.id),folder:d.noteFolder})}async function ha(d){let l=d.getActionTargets();if(l.length===0){let i=d.tree.get(d.focusId);i?.file&&(l=[i])}if(l.length===0){new Xe.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 l)e(i,0);await navigator.clipboard.writeText(t.join(` +`)),d.plugin.notifications.show({message:`Copied outline of ${d.titleList(l)} (${t.length} entr${t.length===1?"y":"ies"})`,kind:"success",category:"system",affectedIds:l.map(i=>i.id),folder:d.noteFolder})}var Gt=require("obsidian");Qt();Li();Ht();function Yr(d){return d.replace(/[^\w.\-]+/g,"_").replace(/^\.+/,"").slice(0,60)||"stash-export"}async function pa(d,l){let t=ua(d,l);if(t.length===0){new Gt.Notice("Nothing to export.");return}let e=Ia(d,t);if(e.length===0){new Gt.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 ai(d.app,s,e.length,(n,o,a)=>{zr(d,t,e,n,o,a)},ji).open()}async function ga(d,l){let t=ua(d,l);if(t.length===0){new Gt.Notice("Nothing to export.");return}let e=Ia(d,t);if(e.length===0){new Gt.Notice("No exportable notes.");return}let i=(d.noteFolder.split("/").pop()||d.noteFolder).trim(),s=t.length===1?d.titleForNode(t[0]):`${i}-okf`;new pi(d.app,s,e.length,(n,o)=>{(async()=>{try{let a=await d.plugin.exportOkf(d.noteFolder,t.map(r=>r.id),n,o);if(!a.length){new Gt.Notice("Nothing exported.");return}d.plugin.notifications.show({message:`Exported OKF \u2014 ${a.length} file${a.length===1?"":"s"} \u2192 \`${d.noteFolder}/${d.plugin.settings.exportFolder||"_exports"}\``,kind:"success",category:"export",affectedPaths:a,folder:d.noteFolder,duration:0}),await d.log.append({type:"stash_export",id:t[0].id,payload:{okf:!0,paths:a,noteCount:e.length,rootIds:t.map(r=>r.id)}})}catch(a){new Gt.Notice(`OKF export failed: ${a.message}`),console.error(a)}})()}).open()}async function zr(d,l,t,e,i,s=!1){try{let n=await ce(d.app,{rootNotes:l.filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),allDescendants:t.filter(h=>!l.some(u=>u.id===h.id)).filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),sourceFolder:d.noteFolder}),o="";if(i){let h=await Je(n,i);n=h.data;let u=Fo[h.kdf];o=u.strong?` (encrypted \xB7 ${u.label})`:` (encrypted \xB7 ${u.label} \u2014 Argon2id unavailable on this device, this export is weaker)`}let a=(0,Gt.moment)().format("YYYYMMDD-HHmmss"),r=Yr(e),A=(d.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${d.noteFolder}/${A}`;await d.ensureFolder(c);let g=`${r}-${a}`,p=`${c}/${g}.${ie}`;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(si(g),i)}catch(u){console.warn("[Stashpad] couldn't save export passphrase to secret storage",u)}}await d.log.append({type:"stash_export",id:l[0].id,payload:{path:p,noteCount:t.length,rootIds:l.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 Dr(h,A){if(A?.file)return[A];if(h.selection.size>0)return[...h.selection].map(e=>h.tree.get(e)).filter(e=>!!e?.file);if(h.cursorIdx>=0&&h.currentChildren[h.cursorIdx])return[h.currentChildren[h.cursorIdx]];let t=h.tree.get(h.focusId);return t?.file?[t]:[]}function br(h,A){let t=new Set,e=[],i=s=>{if(!t.has(s.id)){t.add(s.id),s.file&&e.push(s);for(let n of h.tree.getChildren(s.id))i(n)}};for(let s of A)i(s);return e}async function oa(h){let A=h.app.vault.getFiles().filter(e=>e.extension===Ae);if(A.length===0){new Ie.Notice("No .stash files found in this vault.");return}let t=new class extends Ie.FuzzySuggestModal{getItems(){return A}getItemText(e){return e.path}onChooseItem(e){Tn(h,e)}}(h.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Tn(h,A){try{let t=new Uint8Array(await h.app.vault.readBinary(A)),e=await qe(h.app,t,{secretId:ii(A.basename)});if(!e)return;let i=await Vt(h.app,e,h.noteFolder,Nr(h));h.tree.rebuild(h.noteFolder),h.render(),await h.log.append({type:"stash_import",id:T,payload:{from:A.path,into:h.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await h.app.fileManager.trashFile(A)}catch{}h.plugin.importService.clearPendingEncrypted(A.path);let s=[`Imported ${i.notesWritten} note${i.notesWritten===1?"":"s"}`];i.attachmentsWritten&&s.push(`+ ${i.attachmentsWritten} attachment${i.attachmentsWritten===1?"":"s"}`),i.collisionsRenamed&&s.push(`(${i.collisionsRenamed} id collision${i.collisionsRenamed===1?"":"s"} renamed)`),h.plugin.notifications.show({message:s.join(" "),kind:"success",category:"import",folder:h.noteFolder})}catch(t){h.plugin.notifications.show({message:`Stashpad: import failed -File: \`${A.name}\` +Check disk space + write permissions on the export folder.`,kind:"error",category:"export"}),console.error(n)}}function ua(d,l){if(l?.file)return[l];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 Ia(d,l){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 l)i(s);return e}async function fa(d){let l=d.app.vault.getFiles().filter(e=>e.extension===ie);if(l.length===0){new Gt.Notice("No .stash files found in this vault.");return}let t=new class extends Gt.FuzzySuggestModal{getItems(){return l}getItemText(e){return e.path}onChooseItem(e){Ln(d,e)}}(d.app);t.setPlaceholder("Pick a .stash file to import\u2026"),t.open()}async function Ln(d,l){try{let t=new Uint8Array(await d.app.vault.readBinary(l)),e=await qe(d.app,t,{secretId:si(l.basename)});if(!e)return;let i=await $t(d.app,e,d.noteFolder,Vr(d));d.tree.rebuild(d.noteFolder),d.render(),await d.log.append({type:"stash_import",id:T,payload:{from:l.path,into:d.noteFolder,noteCount:i.notesWritten,attachmentsWritten:i.attachmentsWritten,collisionsRenamed:i.collisionsRenamed}});try{await d.app.fileManager.trashFile(l)}catch{}d.plugin.importService.clearPendingEncrypted(l.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: \`${l.name}\` Error: ${t.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[A.path],actions:h.actionsForFile(A.path)}),console.error(t)}}function Nr(h){let A=new Set,t=e=>{if(A.add(e),!!h.tree.get(e))for(let s of h.tree.getChildren(e))t(s.id)};return t(T),A}var Mr=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),ys={nested:"Nested",flat:"Flat",everything:"Everything"},Es=[{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"}],ws=class extends U.ItemView{constructor(t,e){super(t);this.focusId=T;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.pendingCursorId=null;this.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.nextDestinationFolder=null;this.nextDestinationLabel=null;this.inListPicker=null;this.pickerEscapeAt=0;this.composerExitAt=0;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.scrollListenerSaveTimer=null;this.suppressScrollSave=!1;this.selectionGuardKey=0;this.pendingRenderPolicy=null;this.stickToListBottom=!1;this.keyboardTransitionUntil=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||_o(t.target))return;let e=ut().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 p=l?r.scrollHeight:c;r.scrollTop=p,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,ut().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=ut().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 U.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 U.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new hs(this.app),this.log=e.newLog(),this.integrity=new fs(this.tree,this.log),this.order=new ze(this.app),this.sortStore=new gs(this.app),this.fmSync=new us(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):Xo(this,i,n)}),this.debouncedRender=(0,U.debounce)(()=>this.render(),80),this.authorship=new ms(this),this.dnd=new Bs(this),this.bodyRenderer=new Qs(this,this,this.plugin.renderCacheStore)}getViewType(){return ct}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==T){let i=this.tree.get(this.focusId);if(i){let s=this.titleForNode(i).trim(),n=s.length>40?s.slice(0,40)+"\u2026":s;if(n)return`${e} \u2014 ${n} \xB7 ${this.focusId}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let i=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;i&&i.textContent!==t&&i.setText(t)}getIcon(){return"list-tree"}async onOpen(){let t=this.contentEl;t.empty(),t.addClass("stashpad-scroll-host"),this.viewRoot=t.createDiv({cls:"stashpad-view"}),this.viewRoot.setAttribute("tabindex","0"),this.viewRoot.addEventListener("focusin",()=>as(this)),this.viewRoot.addEventListener("click",()=>as(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())}),as(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new U.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);let l=r.path.lastIndexOf("/"),c=(l>=0?r.path.slice(0,l):"").replace(/\/+$/,"");r.path.endsWith(".md")&&c===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=qo(()=>{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(!ut().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(){Go(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,p]of l)this.lastCursorByFocus.set(c,p);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 U.Notice(`"${i}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((i||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=i,this.focusId=T,this.lastCursorByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig();try{await this.bootstrapFolder()}catch(s){let n=s?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",s)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let s=this.app.workspace;typeof s.saveLayout=="function"?await s.saveLayout():this.app.workspace.requestSaveLayout()}catch{this.app.workspace.requestSaveLayout()}this.refreshHeaderTitle(),this.render()}}cmdOpenFolderPicker(){this.openFolderPicker()}openFolderPicker(){this.plugin.openFolderPicker()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof U.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 U.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 U.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 p of n)for(let g of this.extractAttachments(this.stripFrontmatter(p))){let d=this.app.metadataCache.getFirstLinkpathDest(g,"");d&&!r.has(d.path)&&(r.add(d.path),l.push(d))}let c=await Promise.all(l.map(p=>this.app.vault.readBinary(p)));for(let p=0;p<l.length;p++)a.push({path:l[p].path,data:c[p]})}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,U.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 U.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof U.TFolder){s.push(o);continue}if(!(o instanceof U.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=Be(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 U.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 U.TFolder){let p=c.name;if(l===i&&o.has(p)||l===i&&p==="_attachments"&&!s)continue;r.push(c);continue}c instanceof U.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(p=>p.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&&U.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(g=>g.id)]),p=new Set;a=[];for(let g of c)for(let d of this.plugin.lockedSubtreesFor(this.noteFolder,g))p.has(d.blob)||(p.add(d.blob),a.push(d))}let r=a.map(c=>({lk:c,ts:n(c)})).sort((c,p)=>c.ts-p.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((I,f)=>[I.id,f])),p=new Map;for(let{lk:I}of r)I.rootId&&p.set(I.rootId,I);let g=this.currentChildren.map(I=>I.id),d=r.map(({lk:I})=>I).filter(I=>I.rootId).sort((I,f)=>n(f)-n(I)),u=!0;for(;d.length&&u;){u=!1;for(let I=0;I<d.length;I++){let f=d[I],C=f.prevSibling??null,m;if(C==null)m=0;else{let y=g.indexOf(C);if(y<0)continue;m=y+1}g.splice(m,0,f.rootId),d.splice(I,1),I--,u=!0}}for(let I of d)g.push(I.rootId);for(let I of g){let f=c.get(I);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let C=p.get(I);C&&this.renderLockedPlaceholder(t,C)}}for(let I of s.slice().sort((f,C)=>f.stat.ctime-C.stat.ctime))this.renderFileRow(t,I)}else if(s.length===0){let c=0;for(let p=0;p<this.currentChildren.length;p++){let g=Number.isFinite(Date.parse(this.currentChildren[p].created))?Date.parse(this.currentChildren[p].created):0;for(;c<r.length&&r[c].ts<=g;)this.renderLockedPlaceholder(t,r[c].lk),c++;this.renderNote(t,this.currentChildren[p],p)}for(;c<r.length;)this.renderLockedPlaceholder(t,r[c].lk),c++}else{let c=[...this.currentChildren.map((p,g)=>({kind:"note",ts:Number.isFinite(Date.parse(p.created))?Date.parse(p.created):0,idx:g})),...s.map(p=>({kind:"file",ts:p.stat.ctime,file:p})),...r.map(p=>({kind:"lock",ts:p.ts,lk:p.lk}))];c.sort((p,g)=>p.ts-g.ts);for(let p of c)p.kind==="note"?this.renderNote(t,this.currentChildren[p.idx],p.idx):p.kind==="file"?this.renderFileRow(t,p.file):this.renderLockedPlaceholder(t,p.lk)}e.file&&U.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,U.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,U.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async l=>{l.preventDefault(),l.stopPropagation();let c=(this.plugin.settings.lockedSubtrees??[]).find(I=>I.blob===e.blob),p=e.rootId??c?.rootId??null,g=e.parentId??c?.parentId??T,d=e.prevSibling??c?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,p){let I=this.order.getOrder(this.noteFolder,g),f=this.sortStore.getMode(this.noteFolder,g)==="manual";if(I.length===0&&f&&(I=this.tree.getChildren(g).map(C=>C.id)),I.length>0){let C=I.filter(y=>y!==p),m=d&&C.includes(d)?C.indexOf(d)+1:0;C.splice(Math.max(0,m),0,p),this.order.setOrder(this.noteFolder,g,C),this.order.flush(this.noteFolder)}this.pendingCursorId=p}this.render()}};o.onclick=a;let r=l=>{l.preventDefault(),l.stopPropagation();let c=new U.Menu;if(c.addItem(p=>p.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(l))),!U.Platform.isMobile){let p=U.Platform.isMacOS?"Finder":U.Platform.isWin?"File Explorer":"file manager";c.addItem(g=>g.setTitle(`Show in ${p}`).setIcon("folder-search").onClick(()=>{try{let d=window.require?.("electron")?.shell,u=this.app.vault.adapter?.getFullPath?.(e.blob);u&&d?.showItemInFolder&&d.showItemInFolder(u)}catch(d){console.warn("[Stashpad] showItemInFolder failed",d)}}))}c.addItem(p=>p.setTitle("Copy encrypted file path").setIcon("copy").onClick(()=>{let g=e.blob;if(!U.Platform.isMobile)try{g=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(g),new U.Notice("Path copied.")})),c.showAtMouseEvent(l)};if(i.oncontextmenu=r,U.Platform.isMobile){let l=i.createEl("button",{cls:"stashpad-locked-menu"});(0,U.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=ae(this.app.metadataCache.getFileCache(l.file)?.frontmatter?.author);if(!c||c.id!==r)return!1}if(e&&l.created){let c=Date.parse(l.created);if(!Number.isNaN(c)&&c<e)return!1}return!(i&&(!l.file||!this.nodeHasTag(l,i))||s&&(this.colorForNode(l)?.toLowerCase()??null)!==s||n&&this.isCompleted(l)&&!this.hasIncompleteDescendant(l)||o&&!this.hasAttachmentInSubtree(l))})}nodeHasTag(t,e){if(!t.file)return!1;let i=this.app.metadataCache.getFileCache(t.file);if(!i)return!1;if(i.tags){for(let n of i.tags)if((n.tag||"").replace(/^#/,"").toLowerCase()===e)return!0}let s=i.frontmatter?.tags;if(s){let n=Array.isArray(s)?s:[s];for(let o of n)if(typeof o=="string"&&o.replace(/^#/,"").toLowerCase()===e)return!0}return!1}collectFolderTags(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){if(!s.file)continue;let n=this.app.metadataCache.getFileCache(s.file);if(n?.tags)for(let a of n.tags){let r=(a.tag||"").replace(/^#/,"");r&&t.set(r,(t.get(r)??0)+1)}let o=n?.frontmatter?.tags;if(o){let a=Array.isArray(o)?o:[o];for(let r of a){if(typeof r!="string")continue;let l=r.replace(/^#/,"");l&&t.set(l,(t.get(l)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){Nt.enabled&&(this._renderT0=performance.now()),this.pendingRenderPolicy=t??{kind:"preserve"},this.loadConfig();let e=this.viewRoot,i=this.listEl?.scrollTop??0,n=(t??{kind:"preserve"}).kind==="preserve"?this.captureScrollAnchor():null;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let a=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);e.empty(),e.toggleClass("is-mobile",U.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&&!U.Platform.isMobile&&!this.tinyMode&&!this.compactMode&&this.renderFocusedHeader(e,c),this.currentChildren=this.filterChildren(this.collectViewItems(c.id));let p=!1;if(this.autoSelectNewest&&this.currentChildren.length>0){let u=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(u.id),this.lastSelected=u.id,this.autoSelectNewest=!1,p=!0}else if(this.pendingFocusIds){let u=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let I=-1;for(let f of u){let C=this.currentChildren.findIndex(m=>m.id===f);C>=0&&(this.selection.add(f),I<0&&(I=C))}this.cursorIdx=I,I>=0&&(this.lastSelected=u.find(f=>this.currentChildren.some(C=>C.id===f))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let g=e.createDiv({cls:"stashpad-list"});if(this.listEl=g,this.dnd.attachListDnD(g),this.populateListBody(g,c),this.renderComposer(e),U.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(Nt.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),p&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let u=this.pendingComposerCaret;this.pendingComposerCaret=null;let I=this.composerInputEl;if(I&&I.isConnected){if(I.focus({preventScroll:!0}),u!=null){let f=Math.min(u,I.value.length);try{I.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),u!=null)){let C=Math.min(u,f.value.length);try{f.setSelectionRange(C,C)}catch{}}})}let d=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,d&&this.listEl){let u=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,d.kind){case"preserve":u?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let I=d.scrollTop,f=this.listEl,C=()=>{this.suppressScrollSave=!0;let m=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(I,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 I=d.id,f=d.align,C=this.listEl,m=()=>{this.suppressScrollSave=!0;let y=C.querySelector(`[data-id="${I}"]`);y&&y.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 u=this.listEl,I=u.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){u.scrollTop=u.scrollHeight,I=u.scrollTop;return}let m=Math.max(0,u.scrollHeight-u.clientHeight);u.scrollTop<I&&I<=m?u.scrollTop=I:I=u.scrollTop});f.observe(u),this.listResizeObserver=f,u.addEventListener("wheel",m=>{m.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let C=0;u.addEventListener("touchstart",m=>{C=m.touches[0]?.clientY??0},{passive:!0}),u.addEventListener("touchmove",m=>{let y=m.touches[0]?.clientY??C;y>C&&(this.stickToListBottom=!1),C=y},{passive:!0}),u.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),u.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,U.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:[l.path],actions:d.actionsForFile(l.path)}),console.error(t)}}function Vr(d){let l=new Set,t=e=>{if(l.add(e),!!d.tree.get(e))for(let s of d.tree.getChildren(e))t(s.id)};return t(T),l}var Wr=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),ks={nested:"Nested",flat:"Flat",everything:"Everything"},Ss=[{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"}],Ds=class extends U.ItemView{constructor(t,e){super(t);this.focusId=T;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.importedOnly=!1;this.authorFilter=null;this.noteFolder="Stashpad";this.folderOverride=null;this.tinyMode=!1;this.tinyAlwaysOnTop=!1;this.tinyOpacity=1;this.compactMode=!1;this.detachTreeHook=null;this.detachSettings=null;this.slugDebouncers=new Map;this.attachmentDebouncers=new Map;this.bootstrappedFolders=new Set;this.selection=new Set;this.lastSelected=null;this.cursorIdx=-1;this.pendingCursorId=null;this.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.nextDestinationFolder=null;this.nextDestinationLabel=null;this.inListPicker=null;this.pickerEscapeAt=0;this.composerExitAt=0;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.scrollListenerSaveTimer=null;this.suppressScrollSave=!1;this.selectionGuardKey=0;this.pendingRenderPolicy=null;this.stickToListBottom=!1;this.keyboardTransitionUntil=0;this.stickyRowObserver=null;this.listResizeObserver=null;this.composerNarrowObserver=null;this.lastCursorByFocus=new Map;this.lastSelectionByFocus=new Map;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.suppressComposerFocusUntil=0;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navBackStack=[];this.navForwardSnapshots=[];this.treeReconcileTimer=null;this.stampLastCursorTimer=null;this.stampSelectionTimer=null;this._renderT0=null;this.tinyOpacityPopover=null;this.lastListWidth=0;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||ra(t.target))return;let e=ut().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 A=r.value.length;r.setSelectionRange(A,A);return}}let n=!!i&&(i.tagName==="INPUT"||i.tagName==="TEXTAREA"||i.tagName==="BUTTON"||i.tagName==="SELECT");if(t.key==="Escape"&&i instanceof HTMLElement&&(i.tagName==="BUTTON"||i.tagName==="SELECT")&&this.viewRoot.contains(i)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null,this.pickerEscapeAt=Date.now();let r=this.listEl,A=!!r&&r.scrollTop+r.clientHeight>=r.scrollHeight-2,c=r?.scrollTop??0;if(this.render(),r){let g=A?r.scrollHeight:c;r.scrollTop=g,requestAnimationFrame(()=>{r.scrollTop=A?r.scrollHeight:c}),setTimeout(()=>{r.scrollTop=A?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,ut().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 A=r.value.length;r.setSelectionRange(A,A)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let 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 A=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,A>=0&&(this.cursorIdx=A)}this.repaintSelectionClasses(),this.revealCursorRow();return}let o=ut().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 U.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 U.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new fs(this.app),this.log=e.newLog(),this.integrity=new ys(this.tree,this.log),this.order=new ze(this.app),this.sortStore=new ms(this.app),this.fmSync=new Bs(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):oa(this,i,n)}),this.debouncedRender=(0,U.debounce)(()=>this.render(),80),this.authorship=new ws(this),this.dnd=new vs(this),this.bodyRenderer=new Fs(this,this,this.plugin.renderCacheStore)}getViewType(){return ct}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==T){let i=this.tree.get(this.focusId);if(i){let s=this.titleForNode(i).trim(),n=s.length>40?s.slice(0,40)+"\u2026":s;if(n)return`${e} \u2014 ${n} \xB7 ${this.focusId}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let i=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;i&&i.textContent!==t&&i.setText(t)}getIcon(){return"list-tree"}async onOpen(){let t=this.contentEl;t.empty(),t.addClass("stashpad-scroll-host"),this.viewRoot=t.createDiv({cls:"stashpad-view"}),this.viewRoot.setAttribute("tabindex","0"),this.viewRoot.addEventListener("focusin",()=>ds(this)),this.viewRoot.addEventListener("click",()=>ds(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())}),ds(this),this.registerInterval(window.setInterval(()=>this.authorship.pruneContribMaps(),6e4));let e=null,i=()=>{e||(e=new U.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 A=this.currentChildren.findIndex(c=>c.id===r);this.selection.add(r),this.lastSelected=r,A>=0&&(this.cursorIdx=A)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},s=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",i),this.viewRoot.addEventListener("focusout",r=>{let A=r.relatedTarget;A&&this.viewRoot&&this.viewRoot.contains(A)||s()}),this.register(()=>s()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.registerEvent(this.app.metadataCache.on("resolved",()=>this.scheduleTreeReconcile())),this.registerEvent(this.app.metadataCache.on("changed",r=>{if(r.extension!=="md")return;let A=this.app.metadataCache.getFileCache(r)?.frontmatter;this.completedState.set(r.path,!!A?.completed),this.taskTaggedState.set(r.path,this.taggedFromFm(A))})),this.registerEvent(this.app.vault.on("rename",(r,A)=>{for(let c of[this.completedState,this.taskTaggedState])c.has(A)&&(c.set(r.path,c.get(A)),c.delete(A))})),this.registerEvent(this.app.vault.on("delete",r=>{this.completedState.delete(r.path),this.taskTaggedState.delete(r.path);let A=r.path.lastIndexOf("/"),c=(A>=0?r.path.slice(0,A):"").replace(/\/+$/,"");r.path.endsWith(".md")&&c===this.noteFolder.replace(/\/+$/,"")&&(this.tree.rebuild(this.noteFolder),this.debouncedRender())})),this.detachSettings=Zo(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",A=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&A===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&A!==""&&(this.composerDraft=A),!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0),this.debouncedRender()}),this.app.vault.on("modify",this.onFileModify),this.app.vault.on("create",this.onFileCreate),window.addEventListener("keydown",this.onDocKeyDown,!0),this.loadConfig();try{await this.bootstrapFolder()}catch(r){let A=r?.message??"";/already exists/i.test(A)||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[A,c]of r)this.lastCursorByFocus.set(A,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(!ut().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(){$o(this),this.detachTreeHook?.(),this.detachSettings?.(),this.app.vault.off("modify",this.onFileModify),this.app.vault.off("create",this.onFileCreate),window.removeEventListener("keydown",this.onDocKeyDown,!0),this.listResizeObserver?.disconnect(),this.listResizeObserver=null,this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null,this.bodyRenderer.dispose(),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=null,this.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=null,this.treeReconcileTimer!=null&&(window.clearTimeout(this.treeReconcileTimer),this.treeReconcileTimer=null),this.composerAutocomplete?.detach(),this.composerAutocomplete=null;for(let t of this.slugDebouncers.values())t.cancel();for(let t of this.attachmentDebouncers.values())t.cancel();this.authorship.dispose();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}try{await this.fmSync.flush()}catch{}this.stampSelectedCursor(!0),this.fmSyncUnsubscribe?.(),this.fmSyncUnsubscribe=null}setEphemeralState(t){let e=t;e?.focusId&&(this.focusId=e.focusId),e?.timeFilter&&(this.timeFilter=e.timeFilter)}getEphemeralState(){return{focusId:this.focusId,timeFilter:this.timeFilter}}getState(){return{...super.getState()??{},folderOverride:this.folderOverride,timeFilter:this.timeFilter,focusId:this.focusId,tagFilter:this.tagFilter,colorFilter:this.colorFilter,timeFilterCalendar:this.timeFilterCalendar,tinyMode:this.tinyMode,tinyAlwaysOnTop:this.tinyAlwaysOnTop,tinyOpacity:this.tinyOpacity,compactMode:this.compactMode,navBackStack:this.navBackStack,navForwardSnapshots:this.navForwardSnapshots}}async setState(t,e){let i=t??null;if(i){"folderOverride"in i&&(this.folderOverride=i.folderOverride??null),i.timeFilter&&(this.timeFilter=i.timeFilter),i.focusId&&(this.focusId=i.focusId),"tagFilter"in i&&(this.tagFilter=i.tagFilter??null),"colorFilter"in i&&(this.colorFilter=i.colorFilter??null),"timeFilterCalendar"in i&&(this.timeFilterCalendar=!!i.timeFilterCalendar),"tinyMode"in i&&(this.tinyMode=!!i.tinyMode),"tinyAlwaysOnTop"in i&&(this.tinyAlwaysOnTop=!!i.tinyAlwaysOnTop),typeof i.tinyOpacity=="number"&&Number.isFinite(i.tinyOpacity)&&(this.tinyOpacity=Math.min(1,Math.max(.3,i.tinyOpacity))),"compactMode"in i&&(this.compactMode=!!i.compactMode);let o=a=>a&&typeof a.folder=="string"&&typeof a.focusId=="string";Array.isArray(i.navBackStack)&&(this.navBackStack=i.navBackStack.filter(o)),Array.isArray(i.navForwardSnapshots)&&(this.navForwardSnapshots=i.navForwardSnapshots.filter(o))}let s=(this.plugin?.settings?.folder??"Stashpad").trim().replace(/^\/+|\/+$/g,""),n=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;if(this.noteFolder=n||s||"Stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot){this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.lastCursorByFocus.clear(),this.lastSelectionByFocus.clear();try{let A=this.plugin.loadLastCursor(this.noteFolder);for(let[c,g]of A)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 U.Notice(`"${i}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((i||null)!==(this.folderOverride||null)){e.skipHistory||this.recordNavState(),this.folderOverride=i,this.focusId=T,this.lastCursorByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig();try{await this.bootstrapFolder()}catch(s){let n=s?.message??"";/already exists/i.test(n)||console.warn("[Stashpad] bootstrapFolder failed:",s)}this.tree.rebuild(this.noteFolder),this.backfillFrontmatterSync(),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),await this.loadDraftsForFolder();try{let s=this.app.workspace;typeof s.saveLayout=="function"?await s.saveLayout():this.app.workspace.requestSaveLayout()}catch{this.app.workspace.requestSaveLayout()}this.refreshHeaderTitle(),this.render()}}cmdOpenFolderPicker(){this.openFolderPicker()}openFolderPicker(){this.plugin.openFolderPicker()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof U.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 U.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 U.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,A)=>({path:r.path,content:n[A]})),a=[];if(e){let r=new Set,A=[];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),A.push(h))}let c=await Promise.all(A.map(g=>this.app.vault.readBinary(g)));for(let g=0;g<A.length;g++)a.push({path:A[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,U.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 U.TFolder))return t;let s=[i];for(;s.length;){let n=s.pop();for(let o of n.children){if(o instanceof U.TFolder){s.push(o);continue}if(!(o instanceof U.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 A=ye(r),c=this.app.metadataCache.getFirstLinkpathDest(A,o.path);c?t.add(c.path):t.add(A)}}}return t}collectFileItems(t){let e=this.noteFolder,i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof U.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 A=r.pop();for(let c of A.children){if(c instanceof U.TFolder){let g=c.name;if(A===i&&o.has(g)||A===i&&g==="_attachments"&&!s)continue;r.push(c);continue}c instanceof U.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&&U.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),A=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(A&&r.length>0){let c=new Map(this.currentChildren.map((I,f)=>[I.id,f])),g=new Map;for(let{lk:I}of r)I.rootId&&g.set(I.rootId,I);let p=this.currentChildren.map(I=>I.id),h=r.map(({lk:I})=>I).filter(I=>I.rootId).sort((I,f)=>n(f)-n(I)),u=!0;for(;h.length&&u;){u=!1;for(let I=0;I<h.length;I++){let f=h[I],m=f.prevSibling??null,C;if(m==null)C=0;else{let y=p.indexOf(m);if(y<0)continue;C=y+1}p.splice(C,0,f.rootId),h.splice(I,1),I--,u=!0}}for(let I of h)p.push(I.rootId);for(let I of p){let f=c.get(I);if(f!==void 0)this.renderNote(t,this.currentChildren[f],f);else{let m=g.get(I);m&&this.renderLockedPlaceholder(t,m)}}for(let I of s.slice().sort((f,m)=>f.stat.ctime-m.stat.ctime))this.renderFileRow(t,I)}else if(s.length===0){let 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&&U.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,U.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,U.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"unlock");let a=async A=>{A.preventDefault(),A.stopPropagation();let c=(this.plugin.settings.lockedSubtrees??[]).find(I=>I.blob===e.blob),g=e.rootId??c?.rootId??null,p=e.parentId??c?.parentId??T,h=e.prevSibling??c?.prevSibling??null;if(await this.plugin.unlockBundleAt(e.blob)){if(this.selection.clear(),this.lastSelected=null,g){let I=this.order.getOrder(this.noteFolder,p),f=this.sortStore.getMode(this.noteFolder,p)==="manual";if(I.length===0&&f&&(I=this.tree.getChildren(p).map(m=>m.id)),I.length>0){let m=I.filter(y=>y!==g),C=h&&m.includes(h)?m.indexOf(h)+1:0;m.splice(Math.max(0,C),0,g),this.order.setOrder(this.noteFolder,p,m),this.order.flush(this.noteFolder)}this.pendingCursorId=g}this.render()}};o.onclick=a;let r=A=>{A.preventDefault(),A.stopPropagation();let c=new U.Menu;if(c.addItem(g=>g.setTitle("Decrypt (unlock)").setIcon("unlock").onClick(()=>void a(A))),!U.Platform.isMobile){let g=U.Platform.isMacOS?"Finder":U.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,u=this.app.vault.adapter?.getFullPath?.(e.blob);u&&h?.showItemInFolder&&h.showItemInFolder(u)}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(!U.Platform.isMobile)try{p=this.app.vault.adapter?.getFullPath?.(e.blob)||e.blob}catch{}navigator.clipboard.writeText(p),new U.Notice("Path copied.")})),c.showAtMouseEvent(A)};if(i.oncontextmenu=r,U.Platform.isMobile){let A=i.createEl("button",{cls:"stashpad-locked-menu"});(0,U.setIcon)(A,"more-vertical"),A.setAttr("aria-label","Locked note menu"),A.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 A of this.tree.getChildren(r.id))a(A)};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(A=>{if(a&&(!A.file||this.app.metadataCache.getFileCache(A.file)?.frontmatter?.imported!==!0))return!1;if(r){if(!A.file)return!1;let c=le(this.app.metadataCache.getFileCache(A.file)?.frontmatter?.author);if(!c||c.id!==r)return!1}if(e&&A.created){let c=Date.parse(A.created);if(!Number.isNaN(c)&&c<e)return!1}return!(i&&(!A.file||!this.nodeHasTag(A,i))||s&&(this.colorForNode(A)?.toLowerCase()??null)!==s||n&&this.isCompleted(A)&&!this.hasIncompleteDescendant(A)||o&&!this.hasAttachmentInSubtree(A))})}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 A=r.replace(/^#/,"");A&&t.set(A,(t.get(A)??0)+1)}}}let i=[...t.entries()].map(([s,n])=>({raw:s,count:n,label:this.formatTagLabel(s)}));return i.sort((s,n)=>n.count-s.count||s.label.localeCompare(n.label)),i}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(n=>n.charAt(0).toUpperCase()+n.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let s of e){let n=this.colorForNode(s);if(!n)continue;let o=n.toLowerCase();t.set(o,(t.get(o)??0)+1)}let i=[...t.entries()].map(([s,n])=>({hex:s,count:n}));return i.sort((s,n)=>n.count-s.count||s.hex.localeCompare(n.hex)),i}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.collectViewItems(t.id));this.cursorIdx=e.length-1,this.selection.clear(),e.length>0&&(this.selection.add(e[e.length-1].id),this.lastSelected=e[e.length-1].id)}stampSelectedCursor(t=!1){this.stampSelection(t);let i=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;if(!i)return;this.lastCursorByFocus.set(this.focusId,i);let s=()=>{let n=this.lastCursorByFocus.get(this.focusId);n&&this.plugin.saveLastCursor(this.noteFolder,this.focusId,n)};if(t){this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=null,s();return}this.stampLastCursorTimer!=null&&window.clearTimeout(this.stampLastCursorTimer),this.stampLastCursorTimer=window.setTimeout(()=>{this.stampLastCursorTimer=null,s()},400)}captureScrollAnchor(){let t=this.listEl;if(!t)return null;let e=t.getBoundingClientRect().top,i=Array.from(t.querySelectorAll(".stashpad-note"));if(i.length===0)return null;let s=null;for(let n of i){let o=n.dataset.id;if(!o)continue;let a=n.getBoundingClientRect().top-e;if(a>=0){s={id:o,offsetFromListTop:a};break}s={id:o,offsetFromListTop:a}}return s}restoreScrollAnchor(t,e){let i=this.listEl;if(i){if(t){let s=i.querySelector(`[data-id="${t.id}"]`);if(s){let n=i.getBoundingClientRect().top,o=s.getBoundingClientRect().top-n;i.scrollTop+=o-t.offsetFromListTop;return}}e>0&&(i.scrollTop=e)}}render(t){xt.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",U.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 A=this.containerEl.closest(".workspace-tabs");A&&A.classList.toggle("stashpad-has-tiny",this.tinyMode),this.tinyMode?this.renderTinyHeader(e):(this.compactMode||this.renderTimeFilterBar(e),this.renderBreadcrumb(e));let c=this.tree.get(this.focusId)??this.tree.getRoot();c.file&&!U.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 u=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(u.id),this.lastSelected=u.id,this.autoSelectNewest=!1,g=!0}else if(this.pendingFocusIds){let u=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let I=-1;for(let f of u){let m=this.currentChildren.findIndex(C=>C.id===f);m>=0&&(this.selection.add(f),I<0&&(I=m))}this.cursorIdx=I,I>=0&&(this.lastSelected=u.find(f=>this.currentChildren.some(m=>m.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),U.Platform.isMobile&&this.renderMobileNav(e),this._renderT0!=null&&(xt.record("render.total",performance.now()-this._renderT0),this._renderT0=null),this.plugin.notifyStashpadContentChanged(),g&&this.plugin.notifyStashpadSelectionChanged(),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let u=this.pendingComposerCaret;this.pendingComposerCaret=null;let I=this.composerInputEl;if(I&&I.isConnected){if(I.focus({preventScroll:!0}),u!=null){let f=Math.min(u,I.value.length);try{I.setSelectionRange(f,f)}catch{}}}else requestAnimationFrame(()=>{let f=this.composerInputEl;if(f&&(f.focus({preventScroll:!0}),u!=null)){let m=Math.min(u,f.value.length);try{f.setSelectionRange(m,m)}catch{}}})}let h=this.pendingRenderPolicy;if(this.pendingRenderPolicy=null,h&&this.listEl){let u=this.scrollToBottomOnNextRender;switch(this.scrollToBottomOnNextRender=!1,h.kind){case"preserve":u?this.scrollListToBottom():a?this.scrollListToBottom():this.restoreScrollAnchor(n,i);break;case"pin-bottom":this.scrollListToBottom();break;case"restore":{let I=h.scrollTop,f=this.listEl,m=()=>{this.suppressScrollSave=!0;let C=Math.max(0,f.scrollHeight-f.clientHeight);f.scrollTop=Math.min(I,C),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};m(),requestAnimationFrame(m),setTimeout(m,60),setTimeout(m,200),setTimeout(m,600);break}case"follow-cursor":i>0&&(this.listEl.scrollTop=i),this.revealCursorRow();break;case"scroll-to-id":{let I=h.id,f=h.align,m=this.listEl,C=()=>{this.suppressScrollSave=!0;let y=m.querySelector(`[data-id="${I}"]`);y&&y.scrollIntoView({block:f,behavior:"auto"}),Promise.resolve().then(()=>{this.suppressScrollSave=!1})};C(),requestAnimationFrame(C),setTimeout(C,60),setTimeout(C,200),setTimeout(C,600),setTimeout(()=>{this.suppressScrollSave=!1},700);break}}}else this.scrollToBottomOnNextRender?(this.scrollToBottomOnNextRender=!1,this.scrollListToBottom()):this.listEl&&a?this.scrollListToBottom():this.listEl&&i>0&&(this.listEl.scrollTop=i);if(this.stampSelectedCursor(),this.listEl){this.listResizeObserver?.disconnect();let u=this.listEl,I=u.scrollTop,f=new ResizeObserver(()=>{if(Date.now()<this.keyboardTransitionUntil)return;if(this.stickToListBottom){u.scrollTop=u.scrollHeight,I=u.scrollTop;return}let C=Math.max(0,u.scrollHeight-u.clientHeight);u.scrollTop<I&&I<=C?u.scrollTop=I:I=u.scrollTop});f.observe(u),this.listResizeObserver=f,u.addEventListener("wheel",C=>{C.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let m=0;u.addEventListener("touchstart",C=>{m=C.touches[0]?.clientY??0},{passive:!0}),u.addEventListener("touchmove",C=>{let y=C.touches[0]?.clientY??m;y>m&&(this.stickToListBottom=!1),m=y},{passive:!0}),u.addEventListener("mousedown",()=>{this.stickToListBottom=!1}),u.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,U.setIcon)(i.createSpan({cls:"stashpad-btn-icon"}),"folder"),i.createSpan({text:n,cls:"stashpad-btn-text"}),i.title=s?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=d=>{d.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});ue(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=d=>{d.preventDefault(),this.openSearchModal()},U.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,U.setIcon)(r,this.timeFilterCalendar?"calendar":"history"),r.title=this.timeFilterCalendar?"Calendar mode: filters use start-of-day/week/month/year. Click for rolling windows.":"Rolling mode: filters look back N days from now. Click for calendar boundaries.",this.timeFilterCalendar&&r.addClass("is-active"),r.onclick=d=>{d.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let d of Es){let u=this.timeFilterCalendar?d.calShort:d.rollShort,I=this.timeFilterCalendar?d.calLong:d.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:u});f.title=I,this.timeFilter===d.key&&f.addClass("is-active"),f.onclick=C=>{C.preventDefault(),this.setTimeFilter(d.key)}}let l=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let d of Es){let u=this.timeFilterCalendar?d.calLong:d.rollLong,I=l.createEl("option",{text:u});I.value=d.key,this.timeFilter===d.key&&(I.selected=!0)}l.onchange=()=>this.setTimeFilter(l.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!U.Platform.isMobile){let d=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,U.setIcon)(d,"minimize-2"),d.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",d.onclick=u=>{u.preventDefault(),this.plugin.openTinyWindow()}}let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,U.setIcon)(p,this.compactMode?"panel-top":"rows-2"),p.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&&p.addClass("is-active"),p.onclick=d=>{d.preventDefault(),this.toggleCompactMode()},U.Platform.isMobile)return;let g=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,U.setIcon)(g,"external-link"),g.title=ut().popoutDuplicates?"Duplicate this Stashpad tab into a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)":"Move this Stashpad tab to a new Obsidian window. (Toggle in Settings \u2192 Open in new window \u2014 duplicate tab.)",g.onclick=d=>{d.preventDefault();let u=ut().popoutDuplicates;try{let I=this.app.workspace;if(u){let f=this.leaf.getViewState(),C=I.openPopoutLeaf?.();C?C.setViewState({...f,active:!0}):new U.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else I.moveLeafToPopout?.(this.leaf)}catch(I){new U.Notice(`Stashpad: open-in-new-window failed (${I.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),i=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ue(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==T;i.title=this.navBackStack.length>0?"Back":this.focusId!==T?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ue(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;ue(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 p=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),p){let g=this.currentChildren.findIndex(d=>d.id===p);this.selection.add(p),this.lastSelected=p,g>=0&&(this.cursorIdx=g)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let p=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),p&&(this.selection.add(p.id),this.lastSelected=p.id,this.firstSelectedId=p.id),this.render(),new U.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let l=e.createEl("button",{cls:"stashpad-mobile-action-btn"});ue(l,"zap","\u26A1"),l.title="Actions (move, delete, undo, \u2026)",l.onclick=c=>{c.preventDefault(),this.openMobileActionsMenu(l)}}openMobileActionsMenu(t){let e=new U.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 U.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,U.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 (${ys[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(wi[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: ${wi[s]}. Drag-reorder will revert this parent to Manual.`);let c=p=>{o||(p.preventDefault(),this.openSortMenu(a))};a.onclick=c,a.onkeydown=p=>{o||(p.key==="Enter"||p.key===" ")&&c(p)}}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 U.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,U.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(g=>g.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(p)}catch{}},a=g=>{!i.contains(g.target)&&g.target!==t&&!t.contains(g.target)&&o()},r=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:g=>this.populateTagMenuBody(g,o)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:g=>this.populateColorMenuBody(g,this.collectFolderColors(),o)},{key:"time",title:"Time filter",summary:()=>{let g=Es.find(d=>d.key===this.timeFilter);return g?this.timeFilterCalendar?g.calShort:g.rollShort:"All"},populate:g=>this.populateTimeMenuBody(g,o)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":wi[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:g=>{if(this.currentViewMode()!=="nested"){g.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(g,o)}},{key:"view",title:"View",summary:()=>ys[this.currentViewMode()],populate:g=>this.populateViewMenuBody(g,o)}],l="",c=()=>{i.empty();for(let g of r){let d=i.createDiv({cls:"stashpad-mobile-filters-section"}),u=d.createDiv({cls:"stashpad-mobile-filters-header"}),I=u.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,U.setIcon)(I,l===g.key?"chevron-down":"chevron-right"),u.createSpan({cls:"stashpad-mobile-filters-title",text:g.title}),u.createSpan({cls:"stashpad-mobile-filters-summary",text:g.summary()}),u.onclick=f=>{f.preventDefault(),f.stopPropagation(),l=l===g.key?"":g.key,c()},l===g.key){let f=d.createDiv({cls:"stashpad-mobile-filters-body"});g.populate(f)}}};c();let p=new U.Scope(this.app.scope);p.register([],"Escape",g=>(g.preventDefault(),o(),!1)),this.app.keymap?.pushScope(p),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,U.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(ys[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"});U.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 U.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=(E,v)=>{let S=t.createDiv({cls:"stashpad-view-popover-row"});E===i&&S.addClass("is-active"),S.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:ys[E]}),S.createDiv({cls:"stashpad-view-popover-desc",text:v}),S.onclick=async F=>{F.preventDefault(),F.stopPropagation(),e(),E!==i&&(await this.setViewMode(E),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 E=this.currentEncryptionFilter(),v=(S,M,F)=>{let N=t.createDiv({cls:"stashpad-view-popover-row"});S===E&&N.addClass("is-active"),N.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:M}),N.createDiv({cls:"stashpad-view-popover-desc",text:F}),N.onclick=async Q=>{Q.preventDefault(),Q.stopPropagation(),S!==E&&(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 E=>{E.target!==o&&(E.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 E=>{E.target!==r&&(E.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 E=>{E.target!==c&&(E.preventDefault(),c.checked=!c.checked),await this.setAttachmentsOnly(c.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let p=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});i!=="everything"&&p.addClass("is-disabled");let g=p.createEl("input",{type:"checkbox"});g.checked=this.currentIncludeAttachments(),g.disabled=i!=="everything",p.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),p.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."}),p.onclick=async E=>{i==="everything"&&(E.target!==g&&(E.preventDefault(),g.checked=!g.checked),await this.setIncludeAttachments(g.checked),this.refreshList())},t.createDiv({cls:"stashpad-view-popover-divider"});let d=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),u=d.createEl("input",{type:"checkbox"});u.checked=this.importedOnly,d.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Imported notes only"}),d.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that came in via import."}),d.onclick=E=>{E.target!==u&&(E.preventDefault(),u.checked=!u.checked),this.importedOnly=u.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let I=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let E of this.app.vault.getMarkdownFiles()){if((E.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let v=ae(this.app.metadataCache.getFileCache(E)?.frontmatter?.author);v&&I.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 y=m.createEl("select",{cls:"stashpad-view-author-select"}),w=y.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[E,v]of[...I.entries()].sort((S,M)=>S[1].localeCompare(M[1]))){let S=y.createEl("option",{text:v,value:E});this.authorFilter===E&&(S.selected=!0)}y.onclick=E=>E.stopPropagation(),y.onchange=()=>{this.authorFilter=y.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},C.createDiv({cls:"stashpad-view-popover-desc",text:I.size?"Show only notes by the chosen author.":"No authored notes in this folder yet."})}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let i=this.noteFolder,s=this.focusId,n=this.sortStore.getMode(i,s);for(let o of Sn){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:wi[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 Es){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=p=>{p.preventDefault(),p.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"});ue(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==T||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==T?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});ue(n,"arrow-right","\u203A"),n.title=this.navForwardSnapshots.length>0?"Forward":"No forward history",this.navForwardSnapshots.length===0&&n.addClass("is-disabled"),n.onclick=()=>this.navigateForward();let o=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),r=this.focusId===T?a:`${a} / ${this.titleForNode(o).trim()}`,l=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=l.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,U.setIcon)(c,"folder"),l.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:r}),l.title=`${this.noteFolder}${this.focusId!==T?` / ${this.titleForNode(o).trim()}`:""} -Click to switch / create folder.`,l.onclick=I=>{I.preventDefault(),this.plugin.openFolderPicker()};let p=e.createDiv({cls:"stashpad-tiny-sticky"}),g=p.createEl("input",{type:"checkbox"});if(g.checked=this.tinyAlwaysOnTop,p.createSpan({text:"Sticky"}),g.onchange=()=>{this.tinyAlwaysOnTop=g.checked,this.applyTinyAlwaysOnTop()},!U.Platform.isMobile){let I=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,U.setIcon)(I,"contrast"),I.title="Window transparency",this.tinyOpacity<1&&I.addClass("is-active"),I.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(I)}}let d=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,U.setIcon)(d,this.compactMode?"panel-top":"rows-2"),d.title=this.compactMode?"Compact mode is ON \u2014 click to turn off.":"Compact mode \u2014 click to turn on (strips row metadata).",this.compactMode&&d.addClass("is-active"),d.onclick=()=>{this.toggleCompactMode()};let u=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,U.setIcon)(u,"maximize-2"),u.title="Exit tiny mode",u.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),U.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(U.Platform.isMobile?((0,U.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(T),this.focusId===T){let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let p=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,U.setIcon)(p,"panel-top"),p.title="Exit compact mode",p.onclick=g=>{g.preventDefault(),this.toggleCompactMode()}}return}let s=28,n=100,o=this.tree.pathTo(this.focusId),a=o.map(c=>{let p=this.titleForNode(c),g=p.length>s?p.slice(0,s-1)+"\u2026":p;return{id:c.id,label:g}}),r=c=>c.reduce((p,g)=>p+g.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(p=>this.titleForNode(p)).join(" / ");else{let p=c.id,g=e.createSpan({cls:"stashpad-crumb",text:c.label});g.title=c.label,g.onclick=()=>this.navigateTo(p),g.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,p)},U.Platform.isMobile&&this.attachLongPress(g,()=>this.openCrumbMenu(null,p))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,T)}),U.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,T))}let l=this.tree.getChildren(this.focusId).length;if(l>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${l}`}).title=`${l} direct child${l===1?"":"ren"}`),this.compactMode){let c=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,U.setIcon)(c,"panel-top"),c.title="Exit compact mode",c.onclick=p=>{p.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 U.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,U.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",p=>this.handleRenderedClick(p,e));let r=s.createDiv({cls:"stashpad-focused-actions"}),l=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,U.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,U.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:U.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 Ki(this.app,t,U.Platform.isMobile)}bulkActionMessage(t){let e=t.nodes.map(a=>`"${this.titleForNode(a).trim()||"(untitled)"}"`),i=t.suffix?` ${t.suffix}`:"",s=t.destination?` ${t.destination}`:"";if(e.length===0)return`${t.verb}${i}${s}`;if(e.length===1)return`${t.verb} ${e[0]}${i}${s}`;let n=t.bulletMax??10,o=e.length<=n?e.map(a=>`\u2022 ${a}`).join(` +Click to override for this tab.`,s&&i.addClass("is-override"),i.onclick=h=>{h.preventDefault(),this.openFolderPicker()};let o=e.createEl("button",{cls:"stashpad-search-btn"});me(o,"search","\u{1F50D}"),o.title="Search notes (Mod+F)",o.onclick=h=>{h.preventDefault(),this.openSearchModal()},U.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,U.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 Ss){let u=this.timeFilterCalendar?h.calShort:h.rollShort,I=this.timeFilterCalendar?h.calLong:h.rollLong,f=a.createEl("button",{cls:"stashpad-time-filter-btn",text:u});f.title=I,this.timeFilter===h.key&&f.addClass("is-active"),f.onclick=m=>{m.preventDefault(),this.setTimeFilter(h.key)}}let A=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let h of Ss){let u=this.timeFilterCalendar?h.calLong:h.rollLong,I=A.createEl("option",{text:u});I.value=h.key,this.timeFilter===h.key&&(I.selected=!0)}A.onchange=()=>this.setTimeFilter(A.value);let c=e.createDiv({cls:"stashpad-view-mode-btns"});if(!U.Platform.isMobile){let h=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,U.setIcon)(h,"minimize-2"),h.title="Tiny mode \u2014 open this tab in a small always-on-top-capable popout window.",h.onclick=u=>{u.preventDefault(),this.plugin.openTinyWindow()}}let g=c.createEl("button",{cls:"stashpad-view-mode-btn"});if((0,U.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()},U.Platform.isMobile)return;let p=c.createEl("button",{cls:"stashpad-view-mode-btn"});(0,U.setIcon)(p,"external-link"),p.title=ut().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 u=ut().popoutDuplicates;try{let I=this.app.workspace;if(u){let f=this.leaf.getViewState(),m=I.openPopoutLeaf?.();m?m.setViewState({...f,active:!0}):new U.Notice("Stashpad: this Obsidian build doesn't expose openPopoutLeaf.")}else I.moveLeafToPopout?.(this.leaf)}catch(I){new U.Notice(`Stashpad: open-in-new-window failed (${I.message})`)}}}toggleCompactMode(){this.compactMode=!this.compactMode,this.render();try{this.app.workspace.requestSaveLayout?.()}catch{}}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),i=e.createEl("button",{cls:"stashpad-mobile-action-btn"});me(i,"arrow-left","\u2039");let s=this.navBackStack.length>0||this.focusId!==T;i.title=this.navBackStack.length>0?"Back":this.focusId!==T?"Back (up to parent)":"No back history",s||i.addClass("is-disabled"),i.onclick=c=>{c.preventDefault(),this.navigateBack()};let n=e.createEl("button",{cls:"stashpad-mobile-action-btn"});me(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;me(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 U.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let A=e.createEl("button",{cls:"stashpad-mobile-action-btn"});me(A,"zap","\u26A1"),A.title="Actions (move, delete, undo, \u2026)",A.onclick=c=>{c.preventDefault(),this.openMobileActionsMenu(A)}}openMobileActionsMenu(t){let e=new U.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 Es(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 A=this.plugin.getColorAlias(this.noteFolder,r);a.setText(A??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(A=>A.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 U.Scope(this.app.scope),a=()=>{s.remove(),i.removeEventListener("mousedown",r,!0);try{this.app.keymap?.popScope(o)}catch{}},r=A=>{!s.contains(A.target)&&A.target!==t&&!t.contains(A.target)&&a()};o.register([],"Escape",A=>(A.preventDefault(),a(),!1)),this.app.keymap?.pushScope(o),this.populateColorMenuBody(s,e,a),setTimeout(()=>{i.addEventListener("mousedown",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,U.setIcon)(r,"arrow-up-down");let A=a.createSpan({cls:"stashpad-sort-label"});o?(A.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${ks[n]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(A.setText(ki[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: ${ki[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 U.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,U.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 A=c=>{c.preventDefault(),this.openMobileFiltersMenu(e)};e.onclick=A,e.onkeydown=c=>{(c.key==="Enter"||c.key===" ")&&A(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=Ss.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)":ki[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:()=>ks[this.currentViewMode()],populate:p=>this.populateViewMenuBody(p,o)}],A="",c=()=>{i.empty();for(let p of r){let h=i.createDiv({cls:"stashpad-mobile-filters-section"}),u=h.createDiv({cls:"stashpad-mobile-filters-header"}),I=u.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,U.setIcon)(I,A===p.key?"chevron-down":"chevron-right"),u.createSpan({cls:"stashpad-mobile-filters-title",text:p.title}),u.createSpan({cls:"stashpad-mobile-filters-summary",text:p.summary()}),u.onclick=f=>{f.preventDefault(),f.stopPropagation(),A=A===p.key?"":p.key,c()},A===p.key){let f=h.createDiv({cls:"stashpad-mobile-filters-body"});p.populate(f)}}};c();let g=new U.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,U.setIcon)(s,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),i.createSpan({cls:"stashpad-view-label"}).setText(ks[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"});U.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 U.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=(E,v)=>{let D=t.createDiv({cls:"stashpad-view-popover-row"});E===i&&D.addClass("is-active"),D.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:ks[E]}),D.createDiv({cls:"stashpad-view-popover-desc",text:v}),D.onclick=async F=>{F.preventDefault(),F.stopPropagation(),e(),E!==i&&(await this.setViewMode(E),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 E=this.currentEncryptionFilter(),v=(D,x,F)=>{let N=t.createDiv({cls:"stashpad-view-popover-row"});D===E&&N.addClass("is-active"),N.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:x}),N.createDiv({cls:"stashpad-view-popover-desc",text:F}),N.onclick=async Q=>{Q.preventDefault(),Q.stopPropagation(),D!==E&&(await this.setEncryptionFilter(D),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 E=>{E.target!==o&&(E.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 E=>{E.target!==r&&(E.preventDefault(),r.checked=!r.checked),await this.setHideCompleted(r.checked),this.refreshList()};let A=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),c=A.createEl("input",{type:"checkbox"});c.checked=this.currentAttachmentsOnly(),A.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide notes without attachments"}),A.createDiv({cls:"stashpad-view-popover-desc",text:"Show only notes that have an attachment. A parent stays visible while any descendant has one."}),A.onclick=async E=>{E.target!==c&&(E.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 E=>{i==="everything"&&(E.target!==p&&(E.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"}),u=h.createEl("input",{type:"checkbox"});u.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=E=>{E.target!==u&&(E.preventDefault(),u.checked=!u.checked),this.importedOnly=u.checked,this.reconcileSelectionAfterFilter(),this.refreshList()};let I=new Map,f=this.noteFolder.replace(/\/+$/,"");for(let E of this.app.vault.getMarkdownFiles()){if((E.parent?.path?.replace(/\/+$/,"")??"")!==f)continue;let v=le(this.app.metadataCache.getFileCache(E)?.frontmatter?.author);v&&I.set(v.id,v.name)}let m=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),C=m.createDiv({cls:"stashpad-view-popover-main"});C.createSpan({cls:"stashpad-view-popover-label",text:"By author"});let y=C.createEl("select",{cls:"stashpad-view-author-select"}),w=y.createEl("option",{text:"All authors",value:""});this.authorFilter||(w.selected=!0);for(let[E,v]of[...I.entries()].sort((D,x)=>D[1].localeCompare(x[1]))){let D=y.createEl("option",{text:v,value:E});this.authorFilter===E&&(D.selected=!0)}y.onclick=E=>E.stopPropagation(),y.onchange=()=>{this.authorFilter=y.value||null,this.reconcileSelectionAfterFilter(),this.refreshList()},m.createDiv({cls:"stashpad-view-popover-desc",text:I.size?"Show only notes by the chosen author.":"No authored notes in this folder yet."})}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.reconcileSelectionAfterFilter(),this.persistFocus(),this.render())}populateSortMenuBody(t,e){let i=this.noteFolder,s=this.focusId,n=this.sortStore.getMode(i,s);for(let o of Tn){let a=t.createDiv({cls:"stashpad-sort-popover-row"});o===n&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:ki[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 Ss){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"}),A=r.createSpan({cls:"stashpad-color-filter-swatch"});o?A.style.background=o:A.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"});me(i,"arrow-left","\u2039"),i.title="Back (up to parent)",this.navBackStack.length>0||this.focusId!==T||i.addClass("is-disabled"),i.title=this.navBackStack.length>0?"Back":this.focusId!==T?"Back (up to parent)":"No back history",i.onclick=()=>this.navigateBack();let n=e.createEl("button",{cls:"stashpad-tiny-nav-btn"});me(n,"arrow-right","\u203A"),n.title=this.navForwardSnapshots.length>0?"Forward":"No forward history",this.navForwardSnapshots.length===0&&n.addClass("is-disabled"),n.onclick=()=>this.navigateForward();let o=this.tree.get(this.focusId)??this.tree.getRoot(),a=(this.noteFolder.split("/").pop()||this.noteFolder).trim(),r=this.focusId===T?a:`${a} / ${this.titleForNode(o).trim()}`,A=e.createEl("button",{cls:"stashpad-tiny-title stashpad-folder-btn"}),c=A.createSpan({cls:"stashpad-tiny-title-icon stashpad-btn-icon"});(0,U.setIcon)(c,"folder"),A.createSpan({cls:"stashpad-tiny-title-text stashpad-btn-text",text:r}),A.title=`${this.noteFolder}${this.focusId!==T?` / ${this.titleForNode(o).trim()}`:""} +Click to switch / create folder.`,A.onclick=I=>{I.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()},!U.Platform.isMobile){let I=e.createEl("button",{cls:"stashpad-tiny-nav-btn stashpad-tiny-opacity-btn"});(0,U.setIcon)(I,"contrast"),I.title="Window transparency",this.tinyOpacity<1&&I.addClass("is-active"),I.onclick=f=>{f.stopPropagation(),this.toggleTinyOpacityPopover(I)}}let h=e.createEl("button",{cls:"stashpad-tiny-expand stashpad-tiny-exit-compact"});(0,U.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 u=e.createEl("button",{cls:"stashpad-tiny-expand"});(0,U.setIcon)(u,"maximize-2"),u.title="Exit tiny mode",u.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)||A()},r=c=>{c.key==="Escape"&&A()},A=()=>{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),U.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(U.Platform.isMobile?((0,U.setIcon)(i,"home"),i.title="Home"):i.setText("Home"),i.onclick=()=>this.navigateTo(T),this.focusId===T){let c=this.tree.getChildren(this.focusId).length;if(c>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${c}`}).title=`${c} direct child${c===1?"":"ren"}`),this.compactMode){let g=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,U.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)},U.Platform.isMobile&&this.attachLongPress(p,()=>this.openCrumbMenu(null,g))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,T)}),U.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,T))}let A=this.tree.getChildren(this.focusId).length;if(A>0&&(e.createSpan({cls:"stashpad-crumb-count",text:`\xB7 ${A}`}).title=`${A} direct child${A===1?"":"ren"}`),this.compactMode){let c=e.createEl("button",{cls:"stashpad-compact-exit-btn"});(0,U.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 U.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,U.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"}),A=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,U.setIcon)(A,"pencil"),A.title="Edit in new tab",A.onclick=()=>void this.openFileAtEnd(i);let c=r.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,U.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:U.Platform.isMobile,toggleHost:r,toggleAnchor:A})}renderRowBreadcrumb(t,e){let i=this.tree.pathTo(e.id),s=i.findIndex(a=>a.id===this.focusId),n=i.slice(s+1,i.length-1);if(n.length===0)return;let o=t.createDiv({cls:"stashpad-row-breadcrumb"});n.forEach((a,r)=>{let A=o.createSpan({cls:"stashpad-row-breadcrumb-seg",text:this.titleForNode(a)});A.title=`Focus into "${this.titleForNode(a)}"`,A.onclick=c=>{c.stopPropagation(),this.navigateTo(a.id)},r<n.length-1&&o.createSpan({cls:"stashpad-row-breadcrumb-sep",text:" / "})})}actionsForFile(t){return Xi(this.app,t,U.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",E=>this.handleRowClick(E,i,e)),l.addEventListener("dblclick",E=>{!this.plugin.settings.doubleClickToFocus||E.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let p=this.isTask(e)||this.compactMode;p&&(l.addClass("is-task"),U.Platform.isMobile||this.addTaskCheckbox(l,e));let g=l.createDiv({cls:"stashpad-note-meta"}),d=g.createDiv({cls:"stashpad-note-meta-top"});d.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let u=this.colorForNode(e),I=d.createDiv({cls:"stashpad-note-grip"});u&&I.addClass("has-color"),(0,U.setIcon)(I,"grip-vertical"),I.title=u?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",I.draggable=c,c||(I.title=u?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),u&&I.style.setProperty("--stashpad-note-color",u);let f=p&&U.Platform.isMobile;if(n>0||f){let E=g.createDiv({cls:"stashpad-note-meta-bottom"});if(f&&this.addTaskCheckbox(E,e),n>0){let v=E.createSpan({cls:"stashpad-note-enter"});u&&(v.style.color=u),(0,U.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=S=>{S.stopPropagation(),this.navigateTo(e.id)}}}if(u)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",u);else{let E=this.inheritedColorForNode(e);E&&E.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",E.hex),l.style.setProperty("--stashpad-inherited-depth",String(E.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"}),y=l.createDiv({cls:"stashpad-note-actions"}),w;if(U.Platform.isMobile){let E=y.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,U.setIcon)(E,"ellipsis-vertical"),E.title="Actions",E.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},w=E}else{let E=y.createEl("button",{cls:"stashpad-pencil"});(0,U.setIcon)(E,"pencil"),E.title="Edit in new tab",E.onclick=S=>{S.stopPropagation(),this.openFileAtEnd(s)};let v=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,U.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=S=>{S.stopPropagation(),this.navigateTo(e.id)},w=E}this.renderNoteBody(m,e,{clamp:!0,toggleHost:y,toggleAnchor:w}),l.oncontextmenu=E=>{E.preventDefault(),this.openNoteMenu(E,e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,U.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"}),p=this.expandedNotes.has(e.id);if(i.clamp&&!p&&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 g=this.lastListWidth;if(o.ovW===g&&o.ovV!==void 0&&!p){o.ovV?this.attachExpandToggle(i,t,e,p):c.removeClass("is-clamped");return}requestAnimationFrame(()=>{if(t.closest?.(".stashpad-note.is-cursor-expanded"))return;let d=c.scrollHeight>c.clientHeight+4;if(o.ovW=g,o.ovV=d,!d&&!p){c.removeClass("is-clamped");return}this.attachExpandToggle(i,t,e,p)})})}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||U.Platform.isMobile?((0,U.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&&Mr.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=ut(),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,U.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 U.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(),U.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(),U.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new Ye(this.app,a),this.composerAutocomplete.attach();let p=async D=>{let K="";for(let x of D){let Y=await this.importAttachment(x);if(!Y)continue;let q=a.value+K,j=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,A=t.createDiv({cls:"stashpad-note"});o&&A.addClass("is-selected"),a&&A.addClass("is-cursor"),a&&this.plugin.settings.autoExpandCursorRow&&A.addClass("is-cursor-expanded"),r&&A.addClass("is-pick-target"),this.isCompleted(e)&&A.addClass("is-completed"),this.isCutPending(e.id)?A.addClass("is-cut-pending"):this.isCopyPending(e.id)&&A.addClass("is-copy-pending"),A.dataset.idx=String(i),A.dataset.id=e.id;let c=this.currentViewMode()==="nested";A.draggable=c,c&&this.dnd.attachRowDnD(A,e,i),A.addEventListener("click",E=>this.handleRowClick(E,i,e)),A.addEventListener("dblclick",E=>{!this.plugin.settings.doubleClickToFocus||E.target?.closest?.(".internal-link, .tag, a, .stashpad-note-task-checkbox")||(E.preventDefault(),window.getSelection()?.removeAllRanges(),this.navigateTo(e.id))});let g=this.isTask(e)||this.compactMode;g&&(A.addClass("is-task"),U.Platform.isMobile||this.addTaskCheckbox(A,e));let p=A.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 u=this.colorForNode(e),I=h.createDiv({cls:"stashpad-note-grip"});u&&I.addClass("has-color"),(0,U.setIcon)(I,"grip-vertical"),I.title=u?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",I.draggable=c,c||(I.title=u?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),u&&I.style.setProperty("--stashpad-note-color",u);let f=g&&U.Platform.isMobile;if(n>0||f){let E=p.createDiv({cls:"stashpad-note-meta-bottom"});if(f&&this.addTaskCheckbox(E,e),n>0){let v=E.createSpan({cls:"stashpad-note-enter"});u&&(v.style.color=u),(0,U.setIcon)(v.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),v.createSpan({text:` ${n}`}),v.onclick=D=>{D.stopPropagation(),this.navigateTo(e.id)}}}if(u)A.addClass("has-color"),A.style.setProperty("--stashpad-note-color",u);else{let E=this.inheritedColorForNode(e);E&&E.depth>0&&(A.addClass("has-inherited-color"),A.style.setProperty("--stashpad-inherited-color",E.hex),A.style.setProperty("--stashpad-inherited-depth",String(E.depth)))}let m=A.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(m,e);let C=m.createDiv({cls:"stashpad-note-body-content"}),y=A.createDiv({cls:"stashpad-note-actions"}),w;if(U.Platform.isMobile){let E=y.createEl("button",{cls:"stashpad-pencil stashpad-note-more"});(0,U.setIcon)(E,"ellipsis-vertical"),E.title="Actions",E.onclick=v=>{v.stopPropagation(),this.openNoteMenu(v,e)},w=E}else{let E=y.createEl("button",{cls:"stashpad-pencil"});(0,U.setIcon)(E,"pencil"),E.title="Edit in new tab",E.onclick=D=>{D.stopPropagation(),this.openFileAtEnd(s)};let v=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,U.setIcon)(v,"arrow-right"),v.title="Open in Stashpad view",v.onclick=D=>{D.stopPropagation(),this.navigateTo(e.id)},w=E}this.renderNoteBody(C,e,{clamp:!0,toggleHost:y,toggleAnchor:w}),A.oncontextmenu=E=>{E.preventDefault(),this.openNoteMenu(E,e)}}addTaskCheckbox(t,e){let i=t.createSpan({cls:"stashpad-note-task-checkbox"}),s=this.isCompleted(e);(0,U.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:A}=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=A,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||U.Platform.isMobile?((0,U.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&&Wr.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=ut(),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,U.debounce)(S=>{this.saveDraft(S)},250)),a.addEventListener("input",()=>{this.composerDraft=a.value,this.debouncedSaveDraft(a.value)}),a.addEventListener("blur",()=>{this.saveDraft(a.value)});let r=null,A=()=>{r||(r=new U.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",A),a.addEventListener("blur",c),document.activeElement===a&&A(),U.Platform.isMobile){let S=()=>{this.keyboardTransitionUntil=Date.now()+600};a.addEventListener("focus",()=>{document.body.classList.add("stashpad-keyboard-open"),S()}),a.addEventListener("blur",()=>{document.body.classList.remove("stashpad-keyboard-open"),S(),U.Platform.isMobile&&this.cursorIdx>=0&&setTimeout(()=>this.revealCursorRow(),350)})}this.composerInputEl=a,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new Ye(this.app,a),this.composerAutocomplete.attach();let g=async S=>{let O="";for(let M of S){let Y=await this.importAttachment(M);if(!Y)continue;let q=a.value+O,j=q&&!q.endsWith(` `)?` -`:"";K+=`${j}${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(),p(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 U.Notice("Can't paste a cut note into the note you're cutting.");return}D.preventDefault(),this.completeCutIntoComposer();return}let x=[],Y=D.clipboardData;if(Y){for(let q of Array.from(Y.files??[]))x.push(q);if(x.length===0){for(let q of Array.from(Y.items??[]))if(q.kind==="file"){let j=q.getAsFile();j&&x.push(j)}}x.length!==0&&(D.preventDefault(),D.stopPropagation(),p(x))}});let g=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});g.style.display="none";let d=n.createDiv({cls:"stashpad-composer-btn-rail"}),u=d.createDiv({cls:"stashpad-composer-btn-group"}),I=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.setIcon)(I,"list-end"),I.title=s?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",s&&I.addClass("is-active"),I.onmousedown=D=>D.preventDefault(),I.onclick=D=>{D.preventDefault(),this.toggleSplit()};let f=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.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=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.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(` +`:"";O+=`${j}${Y} +`}O&&(a.value=a.value+O,this.composerDraft=a.value,this.saveDraft(a.value),a.focus(),a.setSelectionRange(a.value.length,a.value.length))};a.addEventListener("dragover",S=>{if(!(!S.dataTransfer||!Array.from(S.dataTransfer.types).includes("Files"))){S.preventDefault(),S.stopPropagation();try{S.dataTransfer.dropEffect="copy"}catch{}}}),a.addEventListener("drop",S=>{let O=Array.from(S.dataTransfer?.files??[]);O.length!==0&&(S.preventDefault(),S.stopPropagation(),g(O))}),a.addEventListener("paste",S=>{let O=this.plugin.noteClipboard;if(O?.mode==="cut"&&O.text&&S.clipboardData?.getData("text/plain")===O.text){if(this.focusedInsideCut(O.ids)){S.preventDefault(),new U.Notice("Can't paste a cut note into the note you're cutting.");return}S.preventDefault(),this.completeCutIntoComposer();return}let M=[],Y=S.clipboardData;if(Y){for(let q of Array.from(Y.files??[]))M.push(q);if(M.length===0){for(let q of Array.from(Y.items??[]))if(q.kind==="file"){let j=q.getAsFile();j&&M.push(j)}}M.length!==0&&(S.preventDefault(),S.stopPropagation(),g(M))}});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"}),u=h.createDiv({cls:"stashpad-composer-btn-group"}),I=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.setIcon)(I,"list-end"),I.title=s?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",s&&I.addClass("is-active"),I.onmousedown=S=>S.preventDefault(),I.onclick=S=>{S.preventDefault(),this.toggleSplit()};let f=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.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=S=>S.preventDefault(),f.onclick=S=>{S.preventDefault();let O=document.activeElement===a;this.openDestinationPicker(O)};let m=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.setIcon)(m,i?"corner-down-left":"arrow-big-down-dash"),m.title=i?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",m.onmousedown=S=>S.preventDefault(),m.onclick=S=>{S.preventDefault(),this.modeEnterSubmits=!i,this.render(),this.composerInputEl?.focus()};let C=S=>{let O=a.value&&!a.value.endsWith(` `)?` -`:"";a.value+=`${K}${D} -`,this.composerDraft=a.value},y=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.setIcon)(y,"paperclip"),y.title="Attach files",y.onmousedown=D=>D.preventDefault(),y.onclick=D=>{D.preventDefault();let K=document.activeElement===a;if(g.click(),K){let x=()=>{a.focus()};setTimeout(x,100),setTimeout(x,500)}},g.addEventListener("change",async()=>{let D=Array.from(g.files??[]);g.value="";for(let K of D){let x=await this.importAttachment(K);x&&m(x)}a.focus()});let w=d.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,U.setIcon)(w,"chevron-left"),w.title="Show more composer options",d.insertBefore(w,u);let E=D=>{d.toggleClass("is-expanded",D),w.title=D?"Hide options":"Show more composer options",(0,U.setIcon)(w,D?"chevron-right":"chevron-left")};w.onmousedown=D=>D.preventDefault(),w.onclick=D=>{D.preventDefault(),E(!d.hasClass("is-expanded"))},E(!1);let v=()=>n.clientWidth<700,S=()=>{let D=v();n.toggleClass("is-narrow",D),E(!D)};S(),requestAnimationFrame(S);let M=new ResizeObserver(S);M.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=M;let F=d.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});F.title="Send (Enter)",(0,U.setIcon)(F,"arrow-up");let N=async()=>{let D=a.value.trim();if(!D)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(D)}catch{}let K=this.modeSplit??ut().splitOnLines,x=this.nextDestination,Y=this.nextDestinationFolder,q=!!Y&&Y!==this.noteFolder;this.nextDestination=null,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.autoSelectNewest=!q,this.scrollToBottomOnNextRender=!q;let j=q?{targetFolder:Y}:void 0;if(K)for(let L of D.split(/\r?\n/)){let P=L.trim();P&&await this.createNoteUnder(P,x,j)}else await this.createNoteUnder(D,x,j);ut().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,q&&this.composerInputEl?.focus())};F.onclick=()=>void N(),a.addEventListener("keydown",D=>{let K=this.modeEnterSubmits;if(D.key==="Escape"){D.preventDefault(),D.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(D.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(D.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let x=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,Y=x?this.currentChildren.findIndex(q=>q.id===x):-1;this.cursorIdx=Y>=0?Y:this.currentChildren.length-1,this.selectCursor(!1)}return}D.key==="Enter"&&!D.isComposing&&(K?!D.shiftKey:D.shiftKey)&&(D.preventDefault(),D.stopPropagation(),D.stopImmediatePropagation(),N())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return U.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=ut().bindings,o=p=>{let g=n[p];return g.primary&&g.secondary?g.preferRight?g.secondary:g.primary:g.primary||g.secondary},a=vi(o("toggleSplit")),r=vi(o("pickDestination")),l=vi(o("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${i} sends \xB7 ${s} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${r} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===T)return"Home";let t=this.tree.get(this.nextDestination);return t?this.titleForNode(t).trim():"?"}renderMobileNav(t){let e=t.createDiv({cls:"stashpad-mobile-nav"});e.createEl("button",{text:"Home"}).onclick=()=>this.navigateTo(T),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let a=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(a){let r=this.app.internalPlugins?.plugins?.["global-search"],l=r?.instance?.openGlobalSearch?.bind(r.instance);l&&l(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=t.target,n=s?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let l=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(l){let c=this.app.internalPlugins?.plugins?.["global-search"],p=c?.instance?.openGlobalSearch?.bind(c.instance);p&&p(`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 p=l;p<=c;p++)this.selection.add(this.currentChildren[p].id)}else this.selection.add(i.id)}else if(t.metaKey||t.ctrlKey)if(this.selection.has(i.id))if(this.selection.delete(i.id),this.firstSelectedId===i.id&&(this.firstSelectedId=null),this.lastSelected===i.id&&(this.lastSelected=this.selection.size>0?[...this.selection][this.selection.size-1]:null),this.selection.size===0)this.cursorIdx=-1;else{let 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(U.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 U.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 U.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??T),r=a.indexOf(o.id),l=r>0?a[r-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,l,{silent:!0})&&n++}n>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Locked ${n} stash${n===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}async cmdMoveToArchive(){if(!this.plugin.encryption?.isConfigured?.()){new U.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 U.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 Hn(this.app,t,n).open()}async archiveSources(t,e){let i=this.noteFolder,s=new Set(t.map(l=>l.id)),n=t.filter(l=>{let c=l.parent;for(;c;){if(s.has(c))return!1;c=this.tree.get(c)?.parent??null}return!0});if(n.length===0)return;let o=n.map(l=>l.id),a=[];for(let l of n){let c=this.order.getOrder(i,l.parent??T),p=c.indexOf(l.id),g=p>0?c[p-1]:null,d=await this.plugin.lockNoteSubtree(i,l.id,g,{silent:!0,blobFolder:e});d&&a.push(d.blobPath)}if(a.length===0)return;this.selection.clear(),this.lastSelected=null,this.tree.rebuild(i),this.render();let r=e.split("/").pop()||e;this.plugin.notifications.show({message:`Archived ${a.length} note${a.length===1?"":"s"} \u2192 \u201C${r}\u201D. Undo to bring ${a.length===1?"it":"them"} back.`,kind:"success",category:"system",folder:i}),this.plugin.getUndoStack(i).push({label:`Archive (${a.length})`,undo:async()=>{for(let l of a)try{await this.plugin.unlockBundleAt(l,{silent:!0,destFolder:i})}catch(c){console.warn("[Stashpad] archive undo failed",l,c)}a=[],this.tree.rebuild(i),this.render()},redo:async()=>{a=[];for(let l of o){let c=await this.plugin.lockNoteSubtree(i,l,null,{silent:!0,blobFolder:e});c&&a.push(c.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new U.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 U.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 U.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 U.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??ut().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new ie(this.app,this.tree,i=>this.titleForNode(i),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async i=>{if(e=!0,i.crossFolder){let s=i.crossId??i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===T?"Home":(i.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${n} \u25B8 ${o}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=i.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async i=>{e=!0;let s=await this.createNoteUnder(i,this.focusId);s&&(this.nextDestination=s,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,onClose:()=>{t&&!e&&this.composerInputEl?.focus()}}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===T&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:T,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=s=>{if(s===t)return!0;let n=new Set,o=this.tree.get(s);for(;o&&o.id!==T&&!n.has(o.id);){if(n.add(o.id),o.parent===t||o.id===t)return!0;if(!o.parent)return!1;o=this.tree.get(o.parent)}return t===T},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new ie(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 ie(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 ie(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 p=c.view;if(p&&typeof p.createNoteUnder=="function"){let g=await p.createNoteUnder(s,o);g&&typeof p.navigateTo=="function"&&p.navigateTo(g)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.crossId??i.id.replace(/^cross:/,"");s?this.openNoteInNewTab(i.crossFolder,n):this.switchToFolderAndFocus(i.crossFolder,n);return}i.node&&(s?this.openNoteInNewTab(this.noteFolder,i.node.id):this.navigateTo(i.node.id))},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(i=>i!==this.noteFolder),showFilterChips:!0,localFolder:this.noteFolder});this.openSearchInstance=t;let e=t.onClose.bind(t);t.onClose=()=>{e(),this.openSearchInstance===t&&(this.openSearchInstance=null)},t.open()}excludedSearchFolders(){let t=new Set(this.plugin.searchableFolders(this.noteFolder));return this.plugin.discoverStashpadFolders().filter(e=>e!==this.noteFolder&&!t.has(e))}collectExcludedFolderNotes(){let t=this.excludedSearchFolders();if(!t.length)return[];let e=this.collectCrossFolderNotes(t),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!t.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===T&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:T,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let r=n.get(a);r||(r=[],n.set(a,r)),r.push(o)}for(let o of i){let a=n.get(o)??[],r=new Map;for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter;typeof c?.id=="string"&&r.set(c.id,l)}for(let l of a){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,p=typeof c?.id=="string"?c.id:"";if(!p||p===T)continue;let g=l.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),d,u=c?.parent??null;if(u&&u!==T){let I=r.get(u);I&&(d=I.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:l,folder:o,id:p,title:g,body:"",parentBlurb:d,parentId:u??null})}}return e}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===T){i.push(s.id);continue}let o=n.parent??T;await this.changeParent(s,o),e.push(s)}if(e.length===0){new U.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 we(this.app,i,s,async(n,o)=>{let a=[];for(let p of t)if(p.file){a.push({id:p.id,path:p.file.path,was:this.colorForNode(p)??null});try{await this.app.fileManager.processFrontMatter(p.file,g=>{n?g.color=n:delete g.color})}catch(g){new U.Notice(`Couldn't set color for ${p.id}: ${g.message}`)}}if(o.addToPalette&&typeof n=="string"){let p=[...this.plugin.settings.customPalette??[]],g=n.toLowerCase();p.some(d=>d.toLowerCase()===g)||(p.push(n),this.plugin.settings.customPalette=p,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:T,payload:{color:n}}))}this.render();let r=this.noteFolder,l=n,c=async p=>{for(let g of p){let d=this.app.vault.getAbstractFileByPath(g.path);if(d)try{await this.app.fileManager.processFrontMatter(d,u=>{g.col?u.color=g.col:delete u.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(p=>({path:p.path,col:p.was}))),redo:()=>c(a.map(p=>({path:p.path,col:l})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:T,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new ie(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 U.Notice("Target folder is empty");return}let n=[],o=new Set;for(let g of this.app.vault.getMarkdownFiles())(g.parent?.path?.replace(/\/+$/,"")??"")===s&&o.add(g.path);let a=(g,d)=>{if(!g.file)return;let u=g.file,I=`${s}/${u.name}`;if(o.has(I)){let f=u.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),C=f?f[1]:u.basename,m=f?f[2]:"";for(let y=1;y<1e3;y++){let w=`${C}-${y}${m}.md`,E=`${s}/${w}`;if(!o.has(E)){I=E;break}}}o.add(I),n.push({id:g.id,file:u,oldPath:u.path,newPath:I,oldParent:g.parent,isRoot:d});for(let f of this.tree.getChildren(g.id))a(f,!1)};for(let g of t)a(g,!0);if(!n.length)return;await this.ensureFolder(s);for(let g of n)try{await this.app.fileManager.renameFile(g.file,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(g.file,d=>{d.parent=i}),await this.log.append({type:"parent_change",id:g.id,payload:{from:g.oldParent,to:g.isRoot?i:g.oldParent,crossFolder:{from:this.noteFolder,to:s}}})}catch(d){new U.Notice(`Move failed for ${g.id}: ${d.message}`)}if(ut().writeRecoveryLinks){let g=this.noteFolder;window.setTimeout(()=>{We(this.app,g),We(this.app,s)},350)}let r=this.titleList(t);this.tree.rebuild(this.noteFolder);let l=i===T?"Open home":"Open parent",c=Math.max(0,n.length-t.length),p=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:p,kind:"success",category:"move",duration:0,affectedIds:t.map(g=>g.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 g of n){let d=this.app.vault.getAbstractFileByPath(g.newPath);if(d)try{await this.app.fileManager.renameFile(d,g.oldPath),g.isRoot&&await this.app.fileManager.processFrontMatter(d,u=>{u.parent=g.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let g of n){let d=this.app.vault.getAbstractFileByPath(g.oldPath);if(d)try{await this.app.fileManager.renameFile(d,g.newPath),g.isRoot&&await this.app.fileManager.processFrontMatter(d,u=>{u.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=ut().bindings.move,i=vi(e.primary||e.secondary||"M");new U.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 U.Notice("Select 2+ notes to merge.");return}t.sort((I,f)=>(I.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],a=[];for(let I of t){if(!I.file)continue;let f=await this.app.vault.cachedRead(I.file);a.push(this.stripFrontmatter(f).trim())}let r=a.map(I=>I.trim()).filter(Boolean).join(` -`),l=await this.app.vault.read(e.file),c=l.startsWith("---")?l.indexOf(` ----`,3)+4:0,g=`${l.slice(0,c)} +`:"";a.value+=`${O}${S} +`,this.composerDraft=a.value},y=u.createEl("button",{cls:"stashpad-composer-btn"});(0,U.setIcon)(y,"paperclip"),y.title="Attach files",y.onmousedown=S=>S.preventDefault(),y.onclick=S=>{S.preventDefault();let O=document.activeElement===a;if(p.click(),O){let M=()=>{a.focus()};setTimeout(M,100),setTimeout(M,500)}},p.addEventListener("change",async()=>{let S=Array.from(p.files??[]);p.value="";for(let O of S){let M=await this.importAttachment(O);M&&C(M)}a.focus()});let w=h.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,U.setIcon)(w,"chevron-left"),w.title="Show more composer options",h.insertBefore(w,u);let E=S=>{h.toggleClass("is-expanded",S),w.title=S?"Hide options":"Show more composer options",(0,U.setIcon)(w,S?"chevron-right":"chevron-left")};w.onmousedown=S=>S.preventDefault(),w.onclick=S=>{S.preventDefault(),E(!h.hasClass("is-expanded"))},E(!1);let v=()=>n.clientWidth<700,D=()=>{let S=v();n.toggleClass("is-narrow",S),E(!S)};D(),requestAnimationFrame(D);let x=new ResizeObserver(D);x.observe(n),this.composerNarrowObserver?.disconnect(),this.composerNarrowObserver=x;let F=h.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});F.title="Send (Enter)",(0,U.setIcon)(F,"arrow-up");let N=async()=>{let S=a.value.trim();if(!S)return;a.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(S)}catch{}let O=this.modeSplit??ut().splitOnLines,M=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 j=q?{targetFolder:Y}:void 0;if(O)for(let L of S.split(/\r?\n/)){let P=L.trim();P&&await this.createNoteUnder(P,M,j)}else await this.createNoteUnder(S,M,j);ut().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0,q&&this.composerInputEl?.focus())};F.onclick=()=>void N(),a.addEventListener("keydown",S=>{let O=this.modeEnterSubmits;if(S.key==="Escape"){S.preventDefault(),S.stopPropagation(),a.blur(),this.viewRoot.focus({preventScroll:!0});return}if(S.key==="ArrowUp"&&a.selectionStart===0&&a.selectionEnd===0){if(S.preventDefault(),a.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0){let M=this.lastCursorByFocus.get(this.focusId)??this.lastSelected,Y=M?this.currentChildren.findIndex(q=>q.id===M):-1;this.cursorIdx=Y>=0?Y:this.currentChildren.length-1,this.selectCursor(!1)}return}S.key==="Enter"&&!S.isComposing&&(O?!S.shiftKey:S.shiftKey)&&(S.preventDefault(),S.stopPropagation(),S.stopImmediatePropagation(),N())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(i,s))}composerPlaceholder(t,e){return U.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=ut().bindings,o=g=>{let p=n[g];return p.primary&&p.secondary?p.preferRight?p.secondary:p.primary:p.primary||p.secondary},a=Si(o("toggleSplit")),r=Si(o("pickDestination")),A=Si(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 ${A} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestinationFolder)return this.nextDestinationLabel??this.nextDestinationFolder;if(this.nextDestination===T)return"Home";let t=this.tree.get(this.nextDestination);return t?this.titleForNode(t).trim():"?"}renderMobileNav(t){let e=t.createDiv({cls:"stashpad-mobile-nav"});e.createEl("button",{text:"Home"}).onclick=()=>this.navigateTo(T),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let i=t.target,s=i?.closest?.(".tag");if(s){t.preventDefault(),t.stopPropagation();let a=(s.getAttribute("href")||s.textContent||"").replace(/^#/,"").trim();if(a){let r=this.app.internalPlugins?.plugins?.["global-search"],A=r?.instance?.openGlobalSearch?.bind(r.instance);A&&A(`tag:#${a}`)}return}let n=i?.closest?.(".internal-link");if(n){t.preventDefault(),t.stopPropagation();let o=n.getAttribute("data-href")||n.getAttribute("href");if(o){let a=e.file?.path||"";this.app.workspace.openLinkText(o,a,!0)}}}handleRowClick(t,e,i){let s=t.target,n=s?.closest?.(".tag");if(n){t.preventDefault(),t.stopPropagation();let A=(n.getAttribute("href")||n.textContent||"").replace(/^#/,"").trim();if(A){let c=this.app.internalPlugins?.plugins?.["global-search"],g=c?.instance?.openGlobalSearch?.bind(c.instance);g&&g(`tag:#${A}`)}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 A=i.file?.path||"";this.app.workspace.openLinkText(r,A,!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(A=>A.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),r!==-1){let[A,c]=r<e?[r,e]:[e,r];for(let g=A;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],A=r?this.currentChildren.findIndex(c=>c.id===r):-1;A>=0&&(this.cursorIdx=A)}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(U.Platform.isMobile&&document.body.classList.contains("stashpad-keyboard-open")){let A=this.viewRoot?.querySelector(".stashpad-composer");A&&(r=Math.min(r,A.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 U.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 U.Notice("Nothing to lock (already locked).");return}let n=0;for(let o of s){let a=this.order.getOrder(this.noteFolder,o.parent??T),r=a.indexOf(o.id),A=r>0?a[r-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,o.id,A,{silent:!0})&&n++}n>0&&(this.selection.clear(),this.lastSelected=null,this.render(),this.plugin.notifications.show({message:`Locked ${n} stash${n===1?"":"es"}.`,kind:"success",category:"system",folder:this.noteFolder}))}async cmdMoveToArchive(){if(!this.plugin.encryption?.isConfigured?.()){new U.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 U.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 Jn(this.app,t,n).open()}async archiveSources(t,e){let i=this.noteFolder,s=new Set(t.map(A=>A.id)),n=t.filter(A=>{let c=A.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(A=>A.id),a=[];for(let A of n){let c=this.order.getOrder(i,A.parent??T),g=c.indexOf(A.id),p=g>0?c[g-1]:null,h=await this.plugin.lockNoteSubtree(i,A.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 A of a)try{await this.plugin.unlockBundleAt(A,{silent:!0,destFolder:i})}catch(c){console.warn("[Stashpad] archive undo failed",A,c)}a=[],this.tree.rebuild(i),this.render()},redo:async()=>{a=[];for(let A of o){let c=await this.plugin.lockNoteSubtree(i,A,null,{silent:!0,blobFolder:e});c&&a.push(c.blobPath)}this.tree.rebuild(i),this.render()}})}async cmdEncryptDelete(){if(!this.plugin.encryption?.isConfigured?.()){new U.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 kt(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 U.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 U.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 U.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??ut().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(t=!1){let e=!1;new ne(this.app,this.tree,i=>this.titleForNode(i),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:async i=>{if(e=!0,i.crossFolder){let s=i.crossId??i.id.replace(/^cross:/,"");this.nextDestination=s,this.nextDestinationFolder=i.crossFolder;let n=i.crossFolder.split("/").pop()||i.crossFolder,o=s===T?"Home":(i.crossFile?.basename??"note").replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ");this.nextDestinationLabel=`${n} \u25B8 ${o}`,this.render(),this.composerInputEl?.focus();return}this.nextDestination=i.id,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus()},onCreate:async i=>{e=!0;let s=await this.createNoteUnder(i,this.focusId);s&&(this.nextDestination=s,this.nextDestinationFolder=null,this.nextDestinationLabel=null,this.render(),this.composerInputEl?.focus())},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,onClose:()=>{t&&!e&&this.composerInputEl?.focus()}}).open()}collectCrossFolderDestinations(){let t=this.collectCrossFolderNotes(),e=this.plugin.searchableFolders(this.noteFolder).filter(n=>n!==this.noteFolder),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!e.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===T&&i.set(o,n)}return[...e.map(n=>({file:i.get(n),folder:n,id:T,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...t]}openSearchInParentModal(){let t=this.focusId,e=s=>{if(s===t)return!0;let n=new Set,o=this.tree.get(s);for(;o&&o.id!==T&&!n.has(o.id);){if(n.add(o.id),o.parent===t||o.id===t)return!0;if(!o.parent)return!1;o=this.tree.get(o.parent)}return t===T},i=new Proxy(this.tree,{get:(s,n)=>n==="getRoot"?()=>s.get(t)??s.getRoot():n==="getChildren"?o=>s.getChildren(o):s[n]});new ne(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 ne(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 ne(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",A=this.app.workspace,c=A.getLeaf("tab");await c.setViewState({type:ct,active:!0,state:{focusId:o,folderOverride:a===r?null:a}}),A.revealLeaf(c);let g=c.view;if(g&&typeof g.createNoteUnder=="function"){let p=await g.createNoteUnder(s,o);p&&typeof g.navigateTo=="function"&&g.navigateTo(p)}}}).open()},onPick:i=>{if(i.kind==="folder-open"&&i.folder){this.openFolderInNewTab(i.folder);return}let s=this.plugin.settings.searchOpensInNewTab!==!1;if(i.crossFolder&&i.crossFile){let n=i.crossId??i.id.replace(/^cross:/,"");s?this.openNoteInNewTab(i.crossFolder,n):this.switchToFolderAndFocus(i.crossFolder,n);return}i.node&&(s?this.openNoteInNewTab(this.noteFolder,i.node.id):this.navigateTo(i.node.id))},crossFolderNotes:()=>this.collectCrossFolderDestinations(),excludedFolderNotes:this.excludedSearchFolders().length>0?()=>this.collectExcludedFolderNotes():void 0,folderResults:()=>this.plugin.discoverStashpadFolders().filter(i=>i!==this.noteFolder),showFilterChips:!0,localFolder:this.noteFolder});this.openSearchInstance=t;let e=t.onClose.bind(t);t.onClose=()=>{e(),this.openSearchInstance===t&&(this.openSearchInstance=null)},t.open()}excludedSearchFolders(){let t=new Set(this.plugin.searchableFolders(this.noteFolder));return this.plugin.discoverStashpadFolders().filter(e=>e!==this.noteFolder&&!t.has(e))}collectExcludedFolderNotes(){let t=this.excludedSearchFolders();if(!t.length)return[];let e=this.collectCrossFolderNotes(t),i=new Map;for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(!t.includes(o))continue;this.app.metadataCache.getFileCache(n)?.frontmatter?.id===T&&i.set(o,n)}return[...t.map(n=>({file:i.get(n),folder:n,id:T,title:`Home \u2014 ${n.split("/").pop()||n}`,body:""})),...e]}collectCrossFolderNotes(t){let e=[],i=(t??this.plugin.searchableFolders(this.noteFolder)).filter(o=>o!==this.noteFolder);if(!i.length)return e;let s=new Set(i),n=new Map;for(let o of this.app.vault.getMarkdownFiles()){let a=o.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(a))continue;let r=n.get(a);r||(r=[],n.set(a,r)),r.push(o)}for(let o of i){let a=n.get(o)??[],r=new Map;for(let A of a){let c=this.app.metadataCache.getFileCache(A)?.frontmatter;typeof c?.id=="string"&&r.set(c.id,A)}for(let A of a){let c=this.app.metadataCache.getFileCache(A)?.frontmatter,g=typeof c?.id=="string"?c.id:"";if(!g||g===T)continue;let p=A.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),h,u=c?.parent??null;if(u&&u!==T){let I=r.get(u);I&&(h=I.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}e.push({file:A,folder:o,id:g,title:p,body:"",parentBlurb:h,parentId:u??null})}}return e}async switchToFolderAndFocus(t,e){await this.setFolderOverride(t),this.tree.get(e)&&this.navigateTo(e)}async cmdOutdent(){let t=this.getActionTargets();if(!t.length)return;let e=[],i=[];for(let s of t){let n=s.parent?this.tree.get(s.parent):null;if(!n||n.id===T){i.push(s.id);continue}let o=n.parent??T;await this.changeParent(s,o),e.push(s)}if(e.length===0){new U.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 Fe(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 U.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:T,payload:{color:n}}))}this.render();let r=this.noteFolder,A=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,u=>{p.col?u.color=p.col:delete u.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:A})))})},async n=>{let o=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==n.toLowerCase());return this.plugin.settings.customPalette=o,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:T,payload:{color:n}}),o}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new ne(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 U.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 u=p.file,I=`${s}/${u.name}`;if(o.has(I)){let f=u.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),m=f?f[1]:u.basename,C=f?f[2]:"";for(let y=1;y<1e3;y++){let w=`${m}-${y}${C}.md`,E=`${s}/${w}`;if(!o.has(E)){I=E;break}}}o.add(I),n.push({id:p.id,file:u,oldPath:u.path,newPath:I,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 U.Notice(`Move failed for ${p.id}: ${h.message}`)}if(ut().writeRecoveryLinks){let p=this.noteFolder;window.setTimeout(()=>{$e(this.app,p),$e(this.app,s)},350)}let r=this.titleList(t);this.tree.rebuild(this.noteFolder);let A=i===T?"Open home":"Open parent",c=Math.max(0,n.length-t.length),g=t.length===1?`Moved ${r}${c>0?` and its ${c} nested note${c===1?"":"s"}`:""} \u2192 \`${s}\``:`Moved ${r}${c>0?` (${c} nested)`:""} \u2192 \`${s}\``;this.plugin.notifications.show({message:g,kind:"success",category:"move",duration:0,affectedIds:t.map(p=>p.id),folder:this.noteFolder,actions:[{label:A,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,u=>{u.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,u=>{u.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=ut().bindings.move,i=Si(e.primary||e.secondary||"M");new U.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 U.Notice("Select 2+ notes to merge.");return}t.sort((I,f)=>(I.created||"").localeCompare(f.created||""));let e=t[0];if(!e.file)return;let i=e.file.path,s=await this.app.vault.read(e.file),n=await this.snapshotNotes(t.slice(1),!1),o=[],a=[];for(let I of t){if(!I.file)continue;let f=await this.app.vault.cachedRead(I.file);a.push(this.stripFrontmatter(f).trim())}let r=a.map(I=>I.trim()).filter(Boolean).join(` +`),A=await this.app.vault.read(e.file),c=A.startsWith("---")?A.indexOf(` +---`,3)+4:0,p=`${A.slice(0,c)} ${r} -`;await this.app.vault.modify(e.file,g);for(let I=1;I<t.length;I++){let f=t[I];if(f.file){for(let C of this.tree.getChildren(f.id))C.file&&o.push({childId:C.id,childPath:C.file.path,oldParent:C.parent}),await this.changeParent(C,e.id,{record:!1});await this.app.fileManager.trashFile(f.file),await this.log.append({type:"delete",id:f.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let d=this.titleForNode(e);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Merged",nodes:t,destination:`\u2192 kept "${d}"`}),kind:"success",category:"merge",affectedIds:t.map(I=>I.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let I=e.id,f=this.selectionGuardKey,C=()=>{if(this.selectionGuardKey!==f||this.selection.has(I))return;let m=this.currentChildren.findIndex(y=>y.id===I);m<0||(this.selection.add(I),this.cursorIdx=m,this.render({kind:"follow-cursor"}))};setTimeout(C,120),setTimeout(C,400)}let u=this.noteFolder;this.plugin.getUndoStack(u).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(f=>f.id));let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,s);for(let f of o){let 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(u),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,g);for(let f of o){let C=this.app.vault.getAbstractFileByPath(f.childPath);C&&await this.app.fileManager.processFrontMatter(C,m=>{m.parent=e.id})}this.tree.rebuild(u),this.render()}})}cmdCopy(){return Mn(this)}cmdCopyCodeBlock(){return ea(this)}cmdCopyTree(){return ia(this)}cmdCopyOutline(){return sa(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 U.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=pt(),c=Mt(a,this.activeStopwords()),p=Tt(c,l),g=`${this.noteFolder}/${p}`,d=new Date().toISOString(),u=this.extractAttachments(a),I=["---",`id: ${l}`,`parent: ${e}`,`created: ${d}`];if(u.length>0){I.push("attachments:");for(let C of u)I.push(` - "${C.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(g,I.join(` -`)),i.push(g);let f=this.app.vault.getAbstractFileByPath(g);if(f){try{await this.app.fileManager.processFrontMatter(f,C=>{for(let[m,y]of Object.entries(r))oe.includes(m)||(C[m]=y)})}catch(C){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",C)}try{this.tree.insertSynthetic({id:l,parent:e,children:[],file:f,created:d})}catch{}this.fmSync.scheduleParentChange(l,null,e)}for(let C of s)await this.cloneSubtree(C,l,i);return l}async cmdClone(){let t=this.getActionTargets();if(!t.length){new U.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:Fe(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 U.Notice("Nothing to copy.");return}await Mn(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 I=1;I<t.length;I++){let f=t[I];if(f.file){for(let m of this.tree.getChildren(f.id))m.file&&o.push({childId:m.id,childPath:m.file.path,oldParent:m.parent}),await this.changeParent(m,e.id,{record:!1});await this.app.fileManager.trashFile(f.file),await this.log.append({type:"delete",id:f.id,payload:{mergedInto:e.id}})}}this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=[e.id];let 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(I=>I.id),folder:this.noteFolder}),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});{let I=e.id,f=this.selectionGuardKey,m=()=>{if(this.selectionGuardKey!==f||this.selection.has(I))return;let C=this.currentChildren.findIndex(y=>y.id===I);C<0||(this.selection.add(I),this.cursorIdx=C,this.render({kind:"follow-cursor"}))};setTimeout(m,120),setTimeout(m,400)}let u=this.noteFolder;this.plugin.getUndoStack(u).push({label:`Merge ${t.length} notes`,undo:async()=>{await this.restoreSnapshots(n,t.map(f=>f.id));let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,s);for(let f of o){let m=this.app.vault.getAbstractFileByPath(f.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=f.oldParent})}this.pendingFocusIds=t.map(f=>f.id),this.tree.rebuild(u),this.render({kind:"follow-cursor"})},redo:async()=>{await this.trashNotesAndAttachments(n);let I=this.app.vault.getAbstractFileByPath(i);I&&await this.app.vault.modify(I,p);for(let f of o){let m=this.app.vault.getAbstractFileByPath(f.childPath);m&&await this.app.fileManager.processFrontMatter(m,C=>{C.parent=e.id})}this.tree.rebuild(u),this.render()}})}cmdCopy(){return Gn(this)}cmdCopyCodeBlock(){return ca(this)}cmdCopyTree(){return da(this)}cmdCopyOutline(){return ha(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 U.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??{},A=gt(),c=Mt(a,this.activeStopwords()),g=Tt(c,A),p=`${this.noteFolder}/${g}`,h=new Date().toISOString(),u=this.extractAttachments(a),I=["---",`id: ${A}`,`parent: ${e}`,`created: ${h}`];if(u.length>0){I.push("attachments:");for(let m of u)I.push(` - "${m.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",a),await this.ensureFolder(this.noteFolder),await this.app.vault.create(p,I.join(` +`)),i.push(p);let f=this.app.vault.getAbstractFileByPath(p);if(f){try{await this.app.fileManager.processFrontMatter(f,m=>{for(let[C,y]of Object.entries(r))re.includes(C)||(m[C]=y)})}catch(m){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",m)}try{this.tree.insertSynthetic({id:A,parent:e,children:[],file:f,created:h})}catch{}this.fmSync.scheduleParentChange(A,null,e)}for(let m of s)await this.cloneSubtree(m,A,i);return A}async cmdClone(){let t=this.getActionTargets();if(!t.length){new U.Notice("Nothing to clone.");return}let e=this.noteFolder,i=[],s=[];for(let r of t){if(!r.file)continue;let A=r.parent??this.focusId,c=await this.cloneSubtree(r,A,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:Se(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 A=this.app.vault.getAbstractFileByPath(r);if(A)try{await this.app.fileManager.trashFile(A)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(o,s)}});let a=s.map(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 U.Notice("Nothing to copy.");return}await Gn(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!==T&&s++<1e3;){if(e.has(i))return!0;i=this.tree.get(i)?.parent??null}return!1}async cmdCutNotes(){let t=this.getActionTargets();if(!t.length){new U.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 U.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){let g=(this.currentChildren[this.cursorIdx]??null)?.parent??this.focusId??T,d=t.mode,u=t.folder,I=await this.plugin.crossFolderPaste(u,t.ids,this.noteFolder,g,d);if(!I||!I.rootIds.length)return;d==="cut"&&this.plugin.clearNoteClipboard();let f=this.noteFolder;this.tree.rebuild(f),this.pendingFocusIds=I.rootIds.slice(),this.render(),d==="cut"&&this.plugin.refreshOpenViewsForFolder(u);let C=u.split("/").pop(),m=I.rootIds.length,y=()=>{this.tree.rebuild(f),this.render(),this.plugin.refreshOpenViewsForFolder(u)};this.plugin.getUndoStack(f).push({label:`${d==="cut"?"Move":"Paste"} ${m} note${m===1?"":"s"} from ${C}`,undo:async()=>{await I.undo(),y()},redo:async()=>{await I.redo(),y()}});let w=d==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${w} ${m} note${m===1?"":"s"} (${I.noteCount} total) from "${C}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:d==="cut"?"move":"clone",affectedIds:I.rootIds,folder:f,duration:0});return}let e=t.ids.map(p=>this.tree.get(p)).filter(p=>!!p&&!!p.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new U.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??T;if(t.mode==="cut"){let p=new Set(t.ids);for(let d=s;d&&d!==T;d=this.tree.get(d)?.parent??null)if(p.has(d)){new U.Notice("Can't paste cut notes under themselves.");return}let g=i&&!p.has(i.id)?i.id:"";this.plugin.clearNoteClipboard(),await this.moveAcrossThenReorder(e.map(d=>d.id),s,g,"after");return}let n=this.noteFolder,o=[],a=[];for(let p of e){let g=await this.cloneSubtree(p,s,o);g&&a.push(g)}if(!a.length)return;this.tree.rebuild(n),this.pendingFocusIds=a.slice(),this.render();let r=o.map(p=>this.app.vault.getAbstractFileByPath(p)).filter(p=>!!p&&p.extension==="md").map(p=>({id:Fe(p.basename)??p.basename,parent:null,children:[],file:p,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 p of[...o].reverse()){let g=this.app.vault.getAbstractFileByPath(p);if(g)try{await this.app.fileManager.trashFile(g)}catch{}}this.tree.rebuild(n),this.render()},redo:async()=>{await this.restoreSnapshots(l,a)}});let c=a.map(p=>this.tree.get(p)).filter(p=>!!p);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:c,suffix:`(${o.length} file${o.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:a,folder:n,duration:0})}async completeCutIntoComposer(){let t=this.plugin.noteClipboard;if(!t||t.mode!=="cut")return;if(t.folder!==this.noteFolder){let g=t.folder,d=t.ids.slice();this.plugin.clearNoteClipboard();let u=await this.plugin.orderedSubtreeNodes(g,d),I=ut().prefixTimestampsOnCopy,f=[];for(let{file:E,created:v,depth:S}of u)try{let M=this.stripFrontmatter(await this.app.vault.cachedRead(E)).trim().split(/\r?\n/).join(" "),F=I?`${this.formatTimeInline(v)} `:"";f.push(`${" ".repeat(S)}- ${F}${M}`)}catch{}this.insertIntoComposer(f.length?f.join(` -`):t.text??"");let C=await this.plugin.subtreeFilePaths(g,d),m=await this.plugin.snapshotPaths(C),y=await this.plugin.trashSubtrees(g,d);this.plugin.refreshOpenViewsForFolder(g);let w=y.filter(E=>E.extension==="md").length;this.plugin.getUndoStack(g).push({label:`Cut ${d.length} note${d.length===1?"":"s"} into composer (from ${g.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(m),this.plugin.refreshOpenViewsForFolder(g)},redo:async()=>{await this.plugin.trashSubtrees(g,d),this.plugin.refreshOpenViewsForFolder(g)}}),this.plugin.notifications.show({message:`Pasted the text of ${d.length} cut note${d.length===1?"":"s"} from "${g.split("/").pop()}" into the composer and removed the original${w===1?"":"s"} (${w} note${w===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:d,folder:g,duration:0});return}this.plugin.clearNoteClipboard();let e=t.ids.map(g=>this.tree.get(g)).filter(g=>!!g&&!!g.file);if(!e.length)return;let i=[],s=new Set,n=(g,d)=>{if(!s.has(g.id)){s.add(g.id),i.push({node:g,depth:d});for(let u of this.tree.getChildren(g.id))n(u,d+1)}};for(let g of e)n(g,0);let o=this.noteFolder,a=ut().prefixTimestampsOnCopy,r=[];for(let{node:g,depth:d}of i)if(g.file)try{let u=this.stripFrontmatter(await this.app.vault.cachedRead(g.file)).trim().split(/\r?\n/).join(" "),I=a?`${this.formatTimeInline(g.created)} `:"";r.push(`${" ".repeat(d)}- ${I}${u}`)}catch{}this.insertIntoComposer(r.join(` -`));let l=i.map(g=>g.node),c=await this.snapshotNotes(l,!1);for(let g of[...l].reverse())if(g.file)try{await this.app.fileManager.trashFile(g.file)}catch(d){console.warn("[Stashpad] cut-paste delete failed",g.file.path,d)}this.selection.clear(),this.tree.rebuild(o),this.render();let p=e.map(g=>g.id);this.plugin.getUndoStack(o).push({label:`Cut ${e.length} note${e.length===1?"":"s"} into composer`,undo:async()=>{await this.restoreSnapshots(c,p)},redo:async()=>{for(let g of[...c.notes]){let d=this.app.vault.getAbstractFileByPath(g.path);if(d)try{await this.app.fileManager.trashFile(d)}catch{}}this.tree.rebuild(o),this.render()}}),this.plugin.notifications.show({message:`Pasted the text of ${this.titleList(e)} into the composer and deleted the original${e.length===1?"":"s"} (${l.length} note${l.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:p,folder:o,duration:0})}cmdInsertTemplate(){new ie(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 U.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:Fe(r.basename)??r.basename,parent:null,children:[],file:r,created:new Date().toISOString()})),a=await this.snapshotNotes(o,!1);this.plugin.getUndoStack(i).push({label:"Insert template",undo:async()=>{for(let r of[...s].reverse()){let l=this.app.vault.getAbstractFileByPath(r);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(a=>a.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(a=>a.hex===n)||(this.colorFilter=null)}let i=this.lastCursorByFocus.get(t),s;i&&this.tree.get(i)?(this.pendingFocusIds=[i],s={kind:"scroll-to-id",id:i,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==T&&this.navigateUp();return}this.navForwardSnapshots.push(this.captureNavSnapshot()),this.applyNavSnapshot(t)}navigateForward(){let t=this.navForwardSnapshots.pop();t&&(this.navBackStack.push(this.captureNavSnapshot()),this.applyNavSnapshot(t))}async applyNavSnapshot(t){if(this.tagFilter=null,this.colorFilter=null,t.folder!==this.noteFolder){await this.setFolderOverride(t.folder,{skipHistory:!0}),t.focusId!==this.focusId&&this.tree.get(t.focusId)&&(this.focusId=t.focusId,this.render({kind:"preserve"}));return}if(!this.tree.get(t.focusId))return;this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t.focusId,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus();let e=this.lastCursorByFocus.get(t.focusId),i;e&&this.tree.get(e)?(this.pendingFocusIds=[e],i={kind:"scroll-to-id",id:e,align:"start"}):i={kind:"preserve"},this.render(i),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateUp(){this.selectionGuardKey++,this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null){if(this.navBackStack.length>0){this.navigateBack();return}return this.navigateTo(T)}let e=this.focusId;if(this.recordNavState(),this.listEl){let o=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;o&&this.plugin.saveLastCursor(this.noteFolder,e,o)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let i=this.filterChildren(this.tree.getChildren(this.focusId)),s=i.findIndex(n=>n.id===e);this.selection.clear(),s>=0?(this.cursorIdx=s,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=i.length-1,i.length>0&&(this.selection.add(i[i.length-1].id),this.lastSelected=i[i.length-1].id)),s>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),s<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),i=new U.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(o))),s++)}s||i.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),i.showAtMouseEvent(new MouseEvent("click",{clientX:200,clientY:400}))}async bootstrapFolder(){if(this.bootstrappedFolders.has(this.noteFolder))return;await this.ensureFolder(this.noteFolder),await this.ensureHomeNote(),await this.migrateNullParents();let t=(this.plugin.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),e=(this.plugin.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");t&&await this.ensureFolder(`${this.noteFolder}/${t}`),e&&await this.ensureFolder(`${this.noteFolder}/${e}`),await this.order.load(this.noteFolder),await this.sortStore.load(this.noteFolder),this.bootstrappedFolders.add(this.noteFolder)}backfillFrontmatterSync(){let t=[T],e=this.tree.getRoot(),i=s=>{for(let n of this.tree.getChildren(s))t.push(n.id),i(n.id)};for(let s of e.children)i(s);for(let s of t)this.fmSync.wouldWrite(s)&&this.fmSync.schedule(s)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata +`);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 U.Notice("The note clipboard is empty \u2014 copy or cut notes first.");return}if(t.folder!==this.noteFolder){let p=(this.currentChildren[this.cursorIdx]??null)?.parent??this.focusId??T,h=t.mode,u=t.folder,I=await this.plugin.crossFolderPaste(u,t.ids,this.noteFolder,p,h);if(!I||!I.rootIds.length)return;h==="cut"&&this.plugin.clearNoteClipboard();let f=this.noteFolder;this.tree.rebuild(f),this.pendingFocusIds=I.rootIds.slice(),this.render(),h==="cut"&&this.plugin.refreshOpenViewsForFolder(u);let m=u.split("/").pop(),C=I.rootIds.length,y=()=>{this.tree.rebuild(f),this.render(),this.plugin.refreshOpenViewsForFolder(u)};this.plugin.getUndoStack(f).push({label:`${h==="cut"?"Move":"Paste"} ${C} note${C===1?"":"s"} from ${m}`,undo:async()=>{await I.undo(),y()},redo:async()=>{await I.redo(),y()}});let w=h==="cut"?"Moved":"Pasted (copied)";this.plugin.notifications.show({message:`${w} ${C} note${C===1?"":"s"} (${I.noteCount} total) from "${m}" into this folder. Undo (in the list) reverses it.`,kind:"success",category:h==="cut"?"move":"clone",affectedIds:I.rootIds,folder:f,duration:0});return}let e=t.ids.map(g=>this.tree.get(g)).filter(g=>!!g&&!!g.file);if(!e.length){this.plugin.clearNoteClipboard(),this.render(),new U.Notice("Those notes no longer exist.");return}let i=this.currentChildren[this.cursorIdx]??null,s=i?.parent??this.focusId??T;if(t.mode==="cut"){let g=new Set(t.ids);for(let h=s;h&&h!==T;h=this.tree.get(h)?.parent??null)if(g.has(h)){new U.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:Se(g.basename)??g.basename,parent:null,children:[],file:g,created:new Date().toISOString()})),A=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(A,a)}});let c=a.map(g=>this.tree.get(g)).filter(g=>!!g);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Pasted (duplicated)",nodes:c,suffix:`(${o.length} file${o.length===1?"":"s"} total)`}),kind:"success",category:"clone",affectedIds:a,folder:n,duration:0})}async completeCutIntoComposer(){let t=this.plugin.noteClipboard;if(!t||t.mode!=="cut")return;if(t.folder!==this.noteFolder){let p=t.folder,h=t.ids.slice();this.plugin.clearNoteClipboard();let u=await this.plugin.orderedSubtreeNodes(p,h),I=ut().prefixTimestampsOnCopy,f=[];for(let{file:E,created:v,depth:D}of u)try{let x=this.stripFrontmatter(await this.app.vault.cachedRead(E)).trim().split(/\r?\n/).join(" "),F=I?`${this.formatTimeInline(v)} `:"";f.push(`${" ".repeat(D)}- ${F}${x}`)}catch{}this.insertIntoComposer(f.length?f.join(` +`):t.text??"");let m=await this.plugin.subtreeFilePaths(p,h),C=await this.plugin.snapshotPaths(m),y=await this.plugin.trashSubtrees(p,h);this.plugin.refreshOpenViewsForFolder(p);let w=y.filter(E=>E.extension==="md").length;this.plugin.getUndoStack(p).push({label:`Cut ${h.length} note${h.length===1?"":"s"} into composer (from ${p.split("/").pop()})`,undo:async()=>{await this.plugin.restoreSnapshot(C),this.plugin.refreshOpenViewsForFolder(p)},redo:async()=>{await this.plugin.trashSubtrees(p,h),this.plugin.refreshOpenViewsForFolder(p)}}),this.plugin.notifications.show({message:`Pasted the text of ${h.length} cut note${h.length===1?"":"s"} from "${p.split("/").pop()}" into the composer and removed the original${w===1?"":"s"} (${w} note${w===1?"":"s"}). Undo restores them.`,kind:"warning",category:"delete",affectedIds:h,folder:p,duration:0});return}this.plugin.clearNoteClipboard();let e=t.ids.map(p=>this.tree.get(p)).filter(p=>!!p&&!!p.file);if(!e.length)return;let i=[],s=new Set,n=(p,h)=>{if(!s.has(p.id)){s.add(p.id),i.push({node:p,depth:h});for(let u of this.tree.getChildren(p.id))n(u,h+1)}};for(let p of e)n(p,0);let o=this.noteFolder,a=ut().prefixTimestampsOnCopy,r=[];for(let{node:p,depth:h}of i)if(p.file)try{let u=this.stripFrontmatter(await this.app.vault.cachedRead(p.file)).trim().split(/\r?\n/).join(" "),I=a?`${this.formatTimeInline(p.created)} `:"";r.push(`${" ".repeat(h)}- ${I}${u}`)}catch{}this.insertIntoComposer(r.join(` +`));let A=i.map(p=>p.node),c=await this.snapshotNotes(A,!1);for(let p of[...A].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"} (${A.length} note${A.length===1?"":"s"}). Undo (in the list) restores them.`,kind:"warning",category:"delete",affectedIds:g,folder:o,duration:0})}cmdInsertTemplate(){new ne(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 U.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:Se(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 A=this.app.vault.getAbstractFileByPath(r);if(A)try{await this.app.fileManager.trashFile(A)}catch{}}this.tree.rebuild(i),this.render()},redo:async()=>{await this.restoreSnapshots(a,[n])}}),this.plugin.notifications.show({message:`Inserted template (${s.length} file${s.length===1?"":"s"})`,kind:"success",category:"clone",folder:this.noteFolder})}}).open()}navigateTo(t,e={}){if(e.keepForwardStack||this.recordNavState(),this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.tagFilter){let n=this.tagFilter.toLowerCase();this.collectFolderTags().some(a=>a.raw.toLowerCase()===n)||(this.tagFilter=null)}if(this.colorFilter){let n=this.colorFilter.toLowerCase();this.collectFolderColors().some(a=>a.hex===n)||(this.colorFilter=null)}let i=this.lastCursorByFocus.get(t),s;i&&this.tree.get(i)?(this.pendingFocusIds=[i],s={kind:"scroll-to-id",id:i,align:"start"}):s={kind:"preserve"},this.render(s),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0}),this.plugin.notifyStashpadSelectionChanged()}navigateBack(){let t=this.navBackStack.pop();if(!t){this.focusId!==T&&this.navigateUp();return}this.navForwardSnapshots.push(this.captureNavSnapshot()),this.applyNavSnapshot(t)}navigateForward(){let t=this.navForwardSnapshots.pop();t&&(this.navBackStack.push(this.captureNavSnapshot()),this.applyNavSnapshot(t))}async applyNavSnapshot(t){if(this.tagFilter=null,this.colorFilter=null,t.folder!==this.noteFolder){await this.setFolderOverride(t.folder,{skipHistory:!0}),t.focusId!==this.focusId&&this.tree.get(t.focusId)&&(this.focusId=t.focusId,this.render({kind:"preserve"}));return}if(!this.tree.get(t.focusId))return;this.selectionGuardKey++,this.listEl&&this.stampSelectedCursor(!0),this.focusId=t.focusId,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus();let e=this.lastCursorByFocus.get(t.focusId),i;e&&this.tree.get(e)?(this.pendingFocusIds=[e],i={kind:"scroll-to-id",id:e,align:"start"}):i={kind:"preserve"},this.render(i),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateUp(){this.selectionGuardKey++,this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null){if(this.navBackStack.length>0){this.navigateBack();return}return this.navigateTo(T)}let e=this.focusId;if(this.recordNavState(),this.listEl){let o=this.currentChildren[this.cursorIdx]?.id??this.lastSelected;o&&this.plugin.saveLastCursor(this.noteFolder,e,o)}this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus();let i=this.filterChildren(this.tree.getChildren(this.focusId)),s=i.findIndex(n=>n.id===e);this.selection.clear(),s>=0?(this.cursorIdx=s,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=i.length-1,i.length>0&&(this.selection.add(i[i.length-1].id),this.lastSelected=i[i.length-1].id)),s>=0?this.render({kind:"scroll-to-id",id:e,align:"start"}):this.render({kind:"follow-cursor"}),this.refreshHeaderTitle(),s<0&&this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),i=new U.Menu,s=0;for(let n of t){if(n.type!=="file"||e&&!e.has(n.path))continue;let o=this.tree.idForPath(n.path);o&&(i.addItem(a=>a.setTitle(n.title||n.path).onClick(()=>this.navigateTo(o))),s++)}s||i.addItem(n=>n.setTitle("(no bookmarks in scope)").setDisabled(!0)),i.showAtMouseEvent(new MouseEvent("click",{clientX:200,clientY:400}))}async bootstrapFolder(){if(this.bootstrappedFolders.has(this.noteFolder))return;await this.ensureFolder(this.noteFolder),await this.ensureHomeNote(),await this.migrateNullParents();let t=(this.plugin.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),e=(this.plugin.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");t&&await this.ensureFolder(`${this.noteFolder}/${t}`),e&&await this.ensureFolder(`${this.noteFolder}/${e}`),await this.order.load(this.noteFolder),await this.sortStore.load(this.noteFolder),this.bootstrappedFolders.add(this.noteFolder)}backfillFrontmatterSync(){let t=[T],e=this.tree.getRoot(),i=s=>{for(let n of this.tree.getChildren(s))t.push(n.id),i(n.id)};for(let s of e.children)i(s);for(let s of t)this.fmSync.wouldWrite(s)&&this.fmSync.schedule(s)}installFmSyncActivityNotice(){this.fmSyncUnsubscribe||(this.fmSyncUnsubscribe=this.fmSync.onError((t,e)=>{this.plugin.notifications.show({message:`Stashpad: couldn't update recovery metadata File: \`${t}\` -Error: ${e.message}`,kind:"error",category:"system",duration:0,affectedPaths:[t],folder:this.noteFolder})}))}async ensureHomeNote(){let t=this.noteFolder,e=`${t}/${this.buildHomeFilename(t)}`,i=this.app.vault.getMarkdownFiles().filter(o=>o.path.startsWith(t+"/"));for(let o of i){if(this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==T)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let l=this.app.vault.getAbstractFileByPath(e);if(l instanceof U.TFile)return l}catch(l){console.warn("[Stashpad] home note rename failed; keeping legacy path",l)}return o}let s=new Date().toISOString(),n=["---",`id: ${T}`,"parent: null",`created: ${s}`,"attachments: []","---","","# Home","","This is your Stashpad home note. Edit me freely \u2014 everything else nests below.",""].join(` -`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===T)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=T}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:T,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:ct,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let r=!1;return e.iterateAllLeaves(l=>{l===s&&(r=!0)}),r})())return;e.offref(n),(()=>{let r=!1;return e.iterateAllLeaves(l=>{l===i&&(r=!0)}),r})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))})}async openNoteInNewTab(t,e){let i=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!i||!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",n=this.app.workspace,o=n.getLeaf("tab");await o.setViewState({type:ct,active:!0,state:{focusId:e,folderOverride:i===s?null:i}}),n.setActiveLeaf(o,{focus:!0}),n.revealLeaf(o)}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let i=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",s=this.app.workspace,n=this.leaf,o=s.getLeaf("tab");await o.setViewState({type:ct,active:!0,state:{focusId:T,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let c=!1;return s.iterateAllLeaves(p=>{p===o&&(c=!0)}),c})())return;s.offref(a),(()=>{let c=!1;return s.iterateAllLeaves(p=>{p===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 U.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(p=>{p===s&&(c=!0)}),c})())return;e.offref(n),(()=>{let c=!1;return e.iterateAllLeaves(p=>{p===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 U.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 U.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new U.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 U.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?Me(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 U.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=Qe(i??{});new li(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,p=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:p}),await this.app.fileManager.processFrontMatter(l.file,d=>{e===null?delete d.due:(d.due=e,d.task=!0),a.length>0?(d.assignedTo=a,o&&(d.assignedBy=o.link),d.task=!0):(delete d.assignedTo,delete d.assignedBy)});let g=e!==null||a.length>0;this.taskTaggedState.set(l.file.path,g||p),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 ${Xt(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,p=>{l.due===void 0?delete p.due:p.due=l.due,l.task===void 0?delete p.task:p.task=l.task,l.assignedTo===void 0?delete p.assignedTo:p.assignedTo=l.assignedTo,l.assignedBy===void 0?delete p.assignedBy:p.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 U.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=Qe(i??{});new Ai(this.app,{knownAuthors:s,currentAssignees:n},o=>{this.applyAssignees(t,o)}).open()}async applyAssignees(t,e){let i=this.authorship.currentAuthorLink();for(let r of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,r.id,r.name);let s=e.map(r=>this.plugin.authorRefFor(this.noteFolder,r.id,r.name)),n=[],o=[];for(let r of t){if(!r.file)continue;let l=this.app.metadataCache.getFileCache(r.file)?.frontmatter,c=this.isTaskTagged(r);n.push({path:r.file.path,assignedTo:l?.assignedTo,assignedBy:l?.assignedBy,task:l?.task,wasTagged:c}),await this.app.fileManager.processFrontMatter(r.file,p=>{s.length>0?(p.assignedTo=s,i&&(p.assignedBy=i.link),p.task=!0):(delete p.assignedTo,delete p.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 U.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,p=>{e?(Js(p,"task"),p.completed===void 0&&(p.completed=!1),c=p.completed===!0,delete p.task):(qs(p,"task"),delete p.completed,delete p.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?(Js(c,"task"),c.completed===void 0&&(c.completed=!1),l=c.completed===!0,delete c.task):(qs(c,"task"),delete c.completed,delete c.task,l=!1)}),this.completedState.set(a.path,l),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==T&&!s.has(e.id);){s.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:i};e=e.parent?this.tree.get(e.parent):void 0,i+=1}return null}isDescendant(t,e){let i=this.tree.get(t),s=new Set;for(;i&&i.parent&&!s.has(i.id);){if(i.parent===e)return!0;s.add(i.id),i=this.tree.get(i.parent)}return!1}async moveAcrossThenReorder(t,e,i,s){let n=[],o=new Set;for(let S of t){let M=this.tree.get(S);M?.file&&(n.push({id:S,path:M.file.path,oldParent:M.parent}),o.add(M.parent??T))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(S=>this.tree.get(S)).filter(S=>!!S)),r=this.noteFolder,l={};for(let S of o)l[S]=this.order.getOrder(r,S).slice();for(let S of n){let M=this.app.vault.getAbstractFileByPath(S.path);M&&(await this.app.fileManager.processFrontMatter(M,F=>{F.parent=e}),this.fmSync.scheduleParentChange(S.id,S.oldParent,e),await this.log.append({type:"parent_change",id:S.id,payload:{from:S.oldParent,to:e,reason:"drag"}}),this.order.removeChild(r,S.id))}this.tree.rebuild(r);let c=this.tree.getChildren(e).map(S=>S.id),p=new Set(t),g=c.filter(S=>!p.has(S)),d=g.indexOf(i);d<0&&(d=g.length),s==="after"&&(d+=1);let u=[...g.slice(0,d),...t.filter(S=>!!this.tree.get(S)),...g.slice(d)];this.order.setOrder(r,e,u),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 I=this.focusId===e,f=I?t[0]:e,C=I?t.slice():[e];I?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,y=()=>{if(this.selectionGuardKey!==m||this.selection.has(f))return;let S=this.currentChildren.findIndex(M=>M.id===f);S<0||(this.selection.add(f),this.cursorIdx=S,this.render({kind:"follow-cursor"}))};setTimeout(y,120),setTimeout(y,400);let w=t.map(S=>this.tree.get(S)).filter(S=>!!S),E=this.tree.get(e),v=E?this.titleForNode(E):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${v}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:r,actions:e===T?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(r).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let S of n){let M=this.app.vault.getAbstractFileByPath(S.path);M&&(await this.app.fileManager.processFrontMatter(M,F=>{S.oldParent===null||S.oldParent===void 0?F.parent=T:F.parent=S.oldParent}),await this.log.append({type:"parent_change",id:S.id,payload:{from:e,to:S.oldParent,reason:"drag-undo"}}))}for(let[S,M]of Object.entries(l))if(M.length===0){let F=this.order.cache.get(r)??{};delete F[S],this.order.cache.set(r,F)}else this.order.setOrder(r,S,M);await this.order.save(r),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(r),this.render()},redo:async()=>{for(let S of n){let M=this.app.vault.getAbstractFileByPath(S.path);M&&(await this.app.fileManager.processFrontMatter(M,F=>{F.parent=e}),this.order.removeChild(r,S.id))}this.order.setOrder(r,e,u),await this.order.save(r),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(r),this.render()}})}async reorderToTarget(t,e,i){let s=this.tree.get(e);if(!s)return;let n=t.map(m=>this.tree.get(m)).filter(m=>!!m&&!!m.file);if(n.length===0)return;if(n.some(m=>m.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(i==="into"){for(let m of n)if(this.isDescendant(e,m.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(m)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let o=i==="into"?e:s.parent??T;if(n.some(m=>(m.parent??T)!==o)){let m=ut(),y=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),E=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} ${E} note${E===1?"":"s"} ${S} "${w}"? Their parent will change.`,v,M=>{M&&y()}).open()}else await y();return}let r=o,l=n.map(m=>m.id),c=this.tree.getChildren(r).map(m=>m.id),p=new Set(l),g=c.filter(m=>!p.has(m)),d=g.indexOf(e);if(d<0)return;i==="after"&&(d+=1);let u=[...g.slice(0,d),...l,...g.slice(d)];if(xn(u,c))return;let I=this.noteFolder,f=this.order.getOrder(I,r).slice();this.order.setOrder(I,r,u),await this.order.save(I),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(I),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:I}),this.plugin.getUndoStack(I).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(f.length===0){let m=this.order.cache.get(I)??{};delete m[r],this.order.cache.set(I,m)}else this.order.setOrder(I,r,f);await this.order.save(I),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(I),this.render()},redo:async()=>{this.order.setOrder(I,r,u),await this.order.save(I),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(I),this.render()}})}cmdMoveUp(){this.reorderSelection("up")}cmdMoveDown(){this.reorderSelection("down")}cmdMoveToTop(){this.reorderSelection("top")}cmdMoveToBottom(){this.reorderSelection("bottom")}async reorderSelection(t){let e=[];if(this.selection.size>0){let p=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(p.length===0)return;if(new Set(p.map(d=>d.parent)).size>1){new U.Notice("Reorder requires a single-parent selection.");return}e=p}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new U.Notice("Nothing to reorder.");return}let i=e[0].parent??T,s=this.tree.getChildren(i).map(p=>p.id);if(s.length===0)return;let n=new Set(e.map(p=>p.id)),o=s.filter(p=>n.has(p));if(o.length===0)return;let a=ta(s,o,t);if(xn(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(p=>this.tree.get(p)).filter(p=>!!p);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 p=this.order.cache.get(r)??{};delete p[i],this.order.cache.set(r,p)}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 u=this.tree.get(this.focusId);u?.file&&(t=[u])}if(t.length===0){new U.Notice("Nothing selected to delete.");return}if((this.plugin.settings.encryptTrash??!1)&&!(this.plugin.settings.encryptTrashFollowObsidian??!1)){if(!this.plugin.encryption?.isConfigured?.()){new U.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=u=>{if(!i.has(u.id)){i.add(u.id);for(let I of this.tree.getChildren(u.id))s(I);e.push(u)}};for(let u of t)s(u);let n=e.filter(u=>!!u.file),o=await Promise.all(n.map(u=>this.app.vault.read(u.file))),a=[];for(let u=0;u<n.length;u++){let I=n[u];a.push(...this.extractAttachments(this.stripFrontmatter(o[u])));let f=this.app.metadataCache.getFileCache(I.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(Be(C))}let r=[...new Set(a)],l=e.length-t.length,c=async u=>{let I=await this.snapshotNotes(e,u),f=0;if(u)for(let D of r){let K=this.app.metadataCache.getFirstLinkpathDest(D,"");if(K)try{await this.app.fileManager.trashFile(K),await this.log.append({type:"attachment_remove",id:T,payload:{path:K.path}}),this.plugin.notifications.show({message:`Deleted attachment "${K.name}"`,kind:"warning",category:"attachment",affectedPaths:[K.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let D of e)D.parent&&C.add(D.parent);let m=this.authorship.collectAuthorIds(e),y=new Set(t.map(D=>D.id)),w=this.currentChildren.map((D,K)=>y.has(D.id)?K:-1).filter(D=>D>=0),E=w.length>0?w[0]:-1,v=null;if(E>=0){for(let D=E+1;D<this.currentChildren.length;D++)if(!y.has(this.currentChildren[D].id)){v=this.currentChildren[D].id;break}if(!v){for(let D=E-1;D>=0;D--)if(!y.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:u?r:[]}})}this.selection.clear(),this.cursorIdx=-1,v&&(this.pendingFocusIds=[v]),this.tree.rebuild(this.noteFolder);for(let D of C)e.some(K=>K.id===D)||this.fmSync.scheduleParentOfDeleted(D);this.render({kind:"follow-cursor"});let S=f>0?` with ${f} attachment${f===1?"":"s"}`:"",M=this.noteFolder,F=t.map(D=>D.id),N=!1,Q=async()=>{N||(N=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(I,F.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:S.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(D=>D.id),affectedAuthorIds:m,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void Q()}]}),this.plugin.getUndoStack(M).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await Q()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,N=!1,await this.trashNotesAndAttachments(I)}}),this.focusView()},p=ut(),g=p.confirmBulkDelete,d=r.length>0&&p.confirmAttachmentDelete;if(!g&&!d){await c(!1);return}new Pe(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,r.length,d,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new U.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 U.Notice("Note is too short to split.");return}let a=s,r=i.path,l=async(c,p,g)=>{if(!c.trim()||!p.trim()){new U.Notice("Split would leave one part empty.");return}try{let d=s.startsWith("---")?s.slice(0,s.indexOf(` ----`,3)+4):"",u=d+(d?` +Error: ${e.message}`,kind:"error",category:"system",duration:0,affectedPaths:[t],folder:this.noteFolder})}))}async ensureHomeNote(){let t=this.noteFolder,e=`${t}/${this.buildHomeFilename(t)}`,i=this.app.vault.getMarkdownFiles().filter(o=>o.path.startsWith(t+"/"));for(let o of i){if(this.app.metadataCache.getFileCache(o)?.frontmatter?.id!==T)continue;if(o.path===e||this.app.vault.getAbstractFileByPath(e))return o;try{await this.app.fileManager.renameFile(o,e);let A=this.app.vault.getAbstractFileByPath(e);if(A instanceof U.TFile)return A}catch(A){console.warn("[Stashpad] home note rename failed; keeping legacy path",A)}return o}let s=new Date().toISOString(),n=["---",`id: ${T}`,"parent: null",`created: ${s}`,"attachments: []","---","","# Home","","This is your Stashpad home note. Edit me freely \u2014 everything else nests below.",""].join(` +`);return this.app.vault.create(e,n)}buildHomeFilename(t){return`Home-${(t.split("/").filter(Boolean).pop()??"Stashpad").replace(/[^A-Za-z0-9_-]+/g,"-").replace(/-+/g,"-").replace(/^-+|-+$/g,"")||"Stashpad"}.md`}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(i=>i.path.startsWith(t+"/"));for(let i of e){let s=this.app.metadataCache.getFileCache(i)?.frontmatter,n=s?.id;if(!n||n===T)continue;let o=s?.parent;(o==null||o===""||o==="null")&&(await this.app.fileManager.processFrontMatter(i,a=>{a.parent=T}),await this.log.append({type:"parent_change",id:n,payload:{from:null,to:T,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace,i=this.leaf,s=e.getLeaf("tab");await s.setViewState({type:ct,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s);let n=e.on("active-leaf-change",()=>{if((()=>{let r=!1;return e.iterateAllLeaves(A=>{A===s&&(r=!0)}),r})())return;e.offref(n),(()=>{let r=!1;return e.iterateAllLeaves(A=>{A===i&&(r=!0)}),r})()&&(e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i))})}async openNoteInNewTab(t,e){let i=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!i||!e)return;let s=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",n=this.app.workspace,o=n.getLeaf("tab");await o.setViewState({type:ct,active:!0,state:{focusId:e,folderOverride:i===s?null:i}}),n.setActiveLeaf(o,{focus:!0}),n.revealLeaf(o)}async openFolderInNewTab(t){let e=(t||"").trim().replace(/^\/+|\/+$/g,"");if(!e)return;let i=(this.plugin.settings.folder||"Stashpad").trim().replace(/^\/+|\/+$/g,"")||"Stashpad",s=this.app.workspace,n=this.leaf,o=s.getLeaf("tab");await o.setViewState({type:ct,active:!0,state:{focusId:T,folderOverride:e===i?null:e}}),s.setActiveLeaf(o,{focus:!0}),s.revealLeaf(o);let a=s.on("active-leaf-change",()=>{if((()=>{let c=!1;return s.iterateAllLeaves(g=>{g===o&&(c=!0)}),c})())return;s.offref(a),(()=>{let c=!1;return s.iterateAllLeaves(g=>{g===n&&(c=!0)}),c})()&&(s.setActiveLeaf(n,{focus:!0}),s.revealLeaf(n))})}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let i of e)i.file&&this.openFileAtEnd(i.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new U.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(),A=a.getLine(r)?.length??0;a.setCursor({line:r,ch:A}),a.scrollIntoView({from:{line:r,ch:A},to:{line:r,ch:A}},!0),a.focus()}catch{}})}cmdSelectAll(){if(this.currentChildren.length!==0){this.selection.clear();for(let t of this.currentChildren)this.selection.add(t.id);this.firstSelectedId=this.currentChildren[0].id,this.lastSelected=this.currentChildren[this.currentChildren.length-1].id,this.cursorIdx=this.currentChildren.length-1,this.render()}}async cmdTogglePin(){let t=this.getActionTargets();if(t.length===0){let n=this.tree.get(this.focusId);n?.file&&(t=[n])}if(t.length===0){new U.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 U.Notice(`Pinned ${i} note${i===1?"":"s"} to sidebar.`):s>0&&new U.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 U.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,A=>{i?A.completed=!0:delete A.completed}),this.completedState.set(a.file.path,i),n.push(a.id))}if(this.render(),n.length>0){await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length}});let a=n.map(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 A=this.app.vault.getAbstractFileByPath(r.path);A&&(await this.app.fileManager.processFrontMatter(A,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,A=>{i?A.completed=!0:delete A.completed})}n.length>0&&await this.log.append({type:i?"complete":"uncomplete",id:n[0],payload:{ids:n,count:n.length,redo:!0}}),this.tree.rebuild(o),this.render()}})}isCompleted(t){if(!t.file)return!1;let e=this.completedState.get(t.file.path);return e!==void 0?e:!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed}taggedFromFm(t){return t?Me(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 U.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=Ee(i??{});new ci(this.app,s,a=>{this.applyDue(t,a.iso,a.assignees)},{knownAuthors:n,currentAssignees:o}).open()}async applyDue(t,e,i=[]){let s=[],n=[],o=this.authorship.currentAuthorLink();for(let A of i)await this.plugin.ensureAuthorStubFor(this.noteFolder,A.id,A.name);let a=i.map(A=>this.plugin.authorRefFor(this.noteFolder,A.id,A.name));for(let A of t){if(!A.file)continue;let c=this.app.metadataCache.getFileCache(A.file)?.frontmatter,g=this.isTaskTagged(A);s.push({id:A.id,path:A.file.path,due:c?.due,task:c?.task,assignedTo:c?.assignedTo,assignedBy:c?.assignedBy,wasTagged:g}),await this.app.fileManager.processFrontMatter(A.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(A.file.path,p||g),n.push(A.id)}if(this.render(),n.length>0){let A=n.map(c=>this.tree.get(c)).filter(c=>!!c);this.plugin.notifications.show({message:this.bulkActionMessage({verb:e===null?"Cleared due date":`Due ${Zt(Date.parse(e),this.plugin.settings)}`,nodes:A}),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 A of s){let c=this.app.vault.getAbstractFileByPath(A.path);c&&(await this.app.fileManager.processFrontMatter(c,g=>{A.due===void 0?delete g.due:g.due=A.due,A.task===void 0?delete g.task:g.task=A.task,A.assignedTo===void 0?delete g.assignedTo:g.assignedTo=A.assignedTo,A.assignedBy===void 0?delete g.assignedBy:g.assignedBy=A.assignedBy}),this.taskTaggedState.set(A.path,A.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 U.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=Ee(i??{});new Ai(this.app,{knownAuthors:s,currentAssignees:n},o=>{this.applyAssignees(t,o)}).open()}async applyAssignees(t,e){let i=this.authorship.currentAuthorLink();for(let r of e)await this.plugin.ensureAuthorStubFor(this.noteFolder,r.id,r.name);let s=e.map(r=>this.plugin.authorRefFor(this.noteFolder,r.id,r.name)),n=[],o=[];for(let r of t){if(!r.file)continue;let A=this.app.metadataCache.getFileCache(r.file)?.frontmatter,c=this.isTaskTagged(r);n.push({path:r.file.path,assignedTo:A?.assignedTo,assignedBy:A?.assignedBy,task:A?.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),A=e.map(c=>c.name).join(", ");this.plugin.notifications.show({message:this.bulkActionMessage({verb:s.length>0?`Assigned to ${A}`:"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 A=this.app.vault.getAbstractFileByPath(r.path);A&&(await this.app.fileManager.processFrontMatter(A,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 U.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),A=this.app.metadataCache.getFileCache(a.file)?.frontmatter;if(i.push({id:a.id,path:a.file.path,tags:A?.tags,completed:A?.completed,task:A?.task,wasTagged:r}),r===e)continue;let c=!1;await this.app.fileManager.processFrontMatter(a.file,g=>{e?(Vs(g,"task"),g.completed===void 0&&(g.completed=!1),c=g.completed===!0,delete g.task):($s(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 A=this.tree.get(s[0]);r=`"${A&&this.titleForNode(A).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,A=>{a.tags===void 0?delete A.tags:A.tags=a.tags,a.completed===void 0?delete A.completed:A.completed=a.completed,a.task===void 0?delete A.task:A.task=a.task}),this.completedState.set(a.path,!!a.completed),this.taskTaggedState.set(a.path,a.wasTagged))}this.tree.rebuild(n),this.render()};this.plugin.getUndoStack(n).push({label:`${e?"Mark task":"Unmark task"} (${t.length})`,undo:o,redo:async()=>{for(let a of i){let r=this.app.vault.getAbstractFileByPath(a.path);if(!r)continue;let A=!1;await this.app.fileManager.processFrontMatter(r,c=>{e?(Vs(c,"task"),c.completed===void 0&&(c.completed=!1),A=c.completed===!0,delete c.task):($s(c,"task"),delete c.completed,delete c.task,A=!1)}),this.completedState.set(a.path,A),this.taskTaggedState.set(a.path,e)}this.tree.rebuild(n),this.render()}})}async toggleCompletedForNode(t){if(!t.file)return;let e=t.file.path,i=this.isCompleted(t);await this.app.fileManager.processFrontMatter(t.file,n=>{n.completed=!i}),this.completedState.set(e,!i),await this.log.append({type:i?"uncomplete":"complete",id:t.id}),this.render();let s=this.noteFolder;this.plugin.getUndoStack(s).push({label:i?"Mark incomplete":"Mark complete",undo:async()=>{let n=this.app.vault.getAbstractFileByPath(e);n&&(await this.app.fileManager.processFrontMatter(n,o=>{o.completed=i}),this.tree.rebuild(s),this.render())}})}isTaskTagged(t){if(!t.file)return!1;let e=this.taskTaggedState.get(t.file.path);if(e!==void 0)return e;let i=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return this.taggedFromFm(i)}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let i=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(i)?i:null}inheritedColorForNode(t){let e=t,i=0,s=new Set;for(;e&&e.id!==T&&!s.has(e.id);){s.add(e.id);let n=this.colorForNode(e);if(n)return{hex:n,depth:i};e=e.parent?this.tree.get(e.parent):void 0,i+=1}return null}isDescendant(t,e){let i=this.tree.get(t),s=new Set;for(;i&&i.parent&&!s.has(i.id);){if(i.parent===e)return!0;s.add(i.id),i=this.tree.get(i.parent)}return!1}async moveAcrossThenReorder(t,e,i,s){let n=[],o=new Set;for(let D of t){let x=this.tree.get(D);x?.file&&(n.push({id:D,path:x.file.path,oldParent:x.parent}),o.add(x.parent??T))}o.add(e);let a=this.authorship.collectAuthorIds(t.map(D=>this.tree.get(D)).filter(D=>!!D)),r=this.noteFolder,A={};for(let D of o)A[D]=this.order.getOrder(r,D).slice();for(let D of n){let x=this.app.vault.getAbstractFileByPath(D.path);x&&(await this.app.fileManager.processFrontMatter(x,F=>{F.parent=e}),this.fmSync.scheduleParentChange(D.id,D.oldParent,e),await this.log.append({type:"parent_change",id:D.id,payload:{from:D.oldParent,to:e,reason:"drag"}}),this.order.removeChild(r,D.id))}this.tree.rebuild(r);let c=this.tree.getChildren(e).map(D=>D.id),g=new Set(t),p=c.filter(D=>!g.has(D)),h=p.indexOf(i);h<0&&(h=p.length),s==="after"&&(h+=1);let u=[...p.slice(0,h),...t.filter(D=>!!this.tree.get(D)),...p.slice(h)];this.order.setOrder(r,e,u),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 I=this.focusId===e,f=I?t[0]:e,m=I?t.slice():[e];I?this.pendingFocusIds=m:(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=m),this.tree.rebuild(r),this.render({kind:"follow-cursor"});let C=this.selectionGuardKey,y=()=>{if(this.selectionGuardKey!==C||this.selection.has(f))return;let D=this.currentChildren.findIndex(x=>x.id===f);D<0||(this.selection.add(f),this.cursorIdx=D,this.render({kind:"follow-cursor"}))};setTimeout(y,120),setTimeout(y,400);let w=t.map(D=>this.tree.get(D)).filter(D=>!!D),E=this.tree.get(e),v=E?this.titleForNode(E):"(root)";this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reparented",nodes:w,destination:`\u2192 "${v}"`}),kind:"success",category:"move",affectedIds:t,affectedAuthorIds:a,folder:r,actions:e===T?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]}),this.plugin.getUndoStack(r).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let D of n){let x=this.app.vault.getAbstractFileByPath(D.path);x&&(await this.app.fileManager.processFrontMatter(x,F=>{D.oldParent===null||D.oldParent===void 0?F.parent=T:F.parent=D.oldParent}),await this.log.append({type:"parent_change",id:D.id,payload:{from:e,to:D.oldParent,reason:"drag-undo"}}))}for(let[D,x]of Object.entries(A))if(x.length===0){let F=this.order.cache.get(r)??{};delete F[D],this.order.cache.set(r,F)}else this.order.setOrder(r,D,x);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 D of n){let x=this.app.vault.getAbstractFileByPath(D.path);x&&(await this.app.fileManager.processFrontMatter(x,F=>{F.parent=e}),this.order.removeChild(r,D.id))}this.order.setOrder(r,e,u),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(C=>this.tree.get(C)).filter(C=>!!C&&!!C.file);if(n.length===0)return;if(n.some(C=>C.id===e)){this.plugin.notifications.show({message:"Can't move a note into itself.",kind:"warning",category:"move",folder:this.noteFolder});return}if(i==="into"){for(let C of n)if(this.isDescendant(e,C.id)){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(C)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",folder:this.noteFolder});return}}let o=i==="into"?e:s.parent??T;if(n.some(C=>(C.parent??T)!==o)){let C=ut(),y=async()=>{i==="into"?await this.moveAcrossThenReorder(n.map(w=>w.id),o,"","after"):await this.moveAcrossThenReorder(n.map(w=>w.id),o,e,i)};if(C.confirmCrossParentDrag){let w=this.titleForNode(s),E=n.length,v=i==="into"?"Nest":"Move",D=i==="into"?"as children of":"under";new kt(this.app,i==="into"?"Nest under target?":"Move under different parent?",`${v} ${E} note${E===1?"":"s"} ${D} "${w}"? Their parent will change.`,v,x=>{x&&y()}).open()}else await y();return}let r=o,A=n.map(C=>C.id),c=this.tree.getChildren(r).map(C=>C.id),g=new Set(A),p=c.filter(C=>!g.has(C)),h=p.indexOf(e);if(h<0)return;i==="after"&&(h+=1);let u=[...p.slice(0,h),...A,...p.slice(h)];if(Rn(u,c))return;let I=this.noteFolder,f=this.order.getOrder(I,r).slice();this.order.setOrder(I,r,u),await this.order.save(I),await this.forceManualMode(r),await this.log.append({type:"reorder",id:r,payload:{dir:"drag",parent:r,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(I),this.render();let m=A.map(C=>this.tree.get(C)).filter(C=>!!C);this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Reordered",nodes:m}),kind:"success",category:"reorder",affectedIds:A,folder:I}),this.plugin.getUndoStack(I).push({label:`Reorder (drag, ${A.length})`,undo:async()=>{if(f.length===0){let C=this.order.cache.get(I)??{};delete C[r],this.order.cache.set(I,C)}else this.order.setOrder(I,r,f);await this.order.save(I),await this.log.append({type:"reorder",id:r,payload:{dir:"undo",parent:r,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(I),this.render()},redo:async()=>{this.order.setOrder(I,r,u),await this.order.save(I),await this.log.append({type:"reorder",id:r,payload:{dir:"redo:drag",parent:r,ids:A,count:A.length}}),this.pendingFocusIds=A.slice(),this.tree.rebuild(I),this.render()}})}cmdMoveUp(){this.reorderSelection("up")}cmdMoveDown(){this.reorderSelection("down")}cmdMoveToTop(){this.reorderSelection("top")}cmdMoveToBottom(){this.reorderSelection("bottom")}async reorderSelection(t){let e=[];if(this.selection.size>0){let 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 U.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 U.Notice("Nothing to reorder.");return}let i=e[0].parent??T,s=this.tree.getChildren(i).map(g=>g.id);if(s.length===0)return;let n=new Set(e.map(g=>g.id)),o=s.filter(g=>n.has(g));if(o.length===0)return;let a=Aa(s,o,t);if(Rn(a,s))return;let r=this.noteFolder,A=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(A.length===0){let g=this.order.cache.get(r)??{};delete g[i],this.order.cache.set(r,g)}else this.order.setOrder(r,i,A);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 u=this.tree.get(this.focusId);u?.file&&(t=[u])}if(t.length===0){new U.Notice("Nothing selected to delete.");return}if((this.plugin.settings.encryptTrash??!1)&&!(this.plugin.settings.encryptTrashFollowObsidian??!1)){if(!this.plugin.encryption?.isConfigured?.()){new U.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=u=>{if(!i.has(u.id)){i.add(u.id);for(let I of this.tree.getChildren(u.id))s(I);e.push(u)}};for(let u of t)s(u);let n=e.filter(u=>!!u.file),o=await Promise.all(n.map(u=>this.app.vault.read(u.file))),a=[];for(let u=0;u<n.length;u++){let I=n[u];a.push(...this.extractAttachments(this.stripFrontmatter(o[u])));let f=this.app.metadataCache.getFileCache(I.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let m of f.attachments)typeof m=="string"&&m.trim()&&a.push(ye(m))}let r=[...new Set(a)],A=e.length-t.length,c=async u=>{let I=await this.snapshotNotes(e,u),f=0;if(u)for(let S of r){let O=this.app.metadataCache.getFirstLinkpathDest(S,"");if(O)try{await this.app.fileManager.trashFile(O),await this.log.append({type:"attachment_remove",id:T,payload:{path:O.path}}),this.plugin.notifications.show({message:`Deleted attachment "${O.name}"`,kind:"warning",category:"attachment",affectedPaths:[O.path],folder:this.noteFolder}),f+=1}catch{}}let m=new Set;for(let S of e)S.parent&&m.add(S.parent);let C=this.authorship.collectAuthorIds(e),y=new Set(t.map(S=>S.id)),w=this.currentChildren.map((S,O)=>y.has(S.id)?O:-1).filter(S=>S>=0),E=w.length>0?w[0]:-1,v=null;if(E>=0){for(let S=E+1;S<this.currentChildren.length;S++)if(!y.has(this.currentChildren[S].id)){v=this.currentChildren[S].id;break}if(!v){for(let S=E-1;S>=0;S--)if(!y.has(this.currentChildren[S].id)){v=this.currentChildren[S].id;break}}}for(let S of e)if(S.file){try{await this.app.fileManager.trashFile(S.file)}catch{}await this.log.append({type:"delete",id:S.id,payload:{path:S.file.path,attachmentsRemoved:u?r:[]}})}this.selection.clear(),this.cursorIdx=-1,v&&(this.pendingFocusIds=[v]),this.tree.rebuild(this.noteFolder);for(let S of m)e.some(O=>O.id===S)||this.fmSync.scheduleParentOfDeleted(S);this.render({kind:"follow-cursor"});let D=f>0?` with ${f} attachment${f===1?"":"s"}`:"",x=this.noteFolder,F=t.map(S=>S.id),N=!1,Q=async()=>{N||(N=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(I,F.slice()))};this.plugin.notifications.show({message:this.bulkActionMessage({verb:"Deleted",nodes:t,suffix:D.trim()||void 0}),kind:"warning",category:"delete",duration:0,affectedIds:t.map(S=>S.id),affectedAuthorIds:C,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void Q()}]}),this.plugin.getUndoStack(x).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{await Q()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,N=!1,await this.trashNotesAndAttachments(I)}}),this.focusView()},g=ut(),p=g.confirmBulkDelete,h=r.length>0&&g.confirmAttachmentDelete;if(!p&&!h){await c(!1);return}new Pe(this.app,`${t.length} selected note${t.length===1?"":"s"}`,A,r.length,h,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new U.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 U.Notice("Note is too short to split.");return}let a=s,r=i.path,A=async(c,g,p)=>{if(!c.trim()||!g.trim()){new U.Notice("Split would leave one part empty.");return}try{let h=s.startsWith("---")?s.slice(0,s.indexOf(` +---`,3)+4):"",u=h+(h?` `:"")+c+` -`;await this.app.vault.modify(i,u);let I=e.parent??T,f=Date.parse(e.created||""),C=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),m=await this.createNoteUnder(p,I,{record:!1,createdOverride:C});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:m,...g}}),this.tree.rebuild(this.noteFolder),this.render(),this.suppressComposerFocusUntil=Date.now()+500,this.viewRoot?.focus({preventScroll:!0}),this.plugin.notifications.show({message:`Split "${this.titleForNode(e)}" into two`,kind:"success",category:"split",affectedIds:[e.id],folder:this.noteFolder});let y=m?this.tree.get(m):void 0,w=y?.file?.path,E=w?await this.app.vault.read(y.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(w){let M=this.app.vault.getAbstractFileByPath(w);if(M)try{await this.app.fileManager.trashFile(M)}catch{}}let S=this.app.vault.getAbstractFileByPath(r);S&&await this.app.vault.modify(S,a),this.tree.rebuild(v),this.render()},redo:async()=>{let S=this.app.vault.getAbstractFileByPath(r);S&&await this.app.vault.modify(S,u),w&&E&&!await this.app.vault.adapter.exists(w)&&await this.app.vault.create(w,E),this.tree.rebuild(v),this.render()}})}catch(d){new U.Notice(`Stashpad: split failed (${d.message})`),console.error(d)}};new ni(this.app,n,async c=>{let p=o.slice(0,c).join(` -`).replace(/\s+$/,""),g=o.slice(c).join(` -`).replace(/^\s+|\s+$/g,"");await l(p,g,{mode:"line",splitAtLine:c})},async c=>{let p=n.slice(0,c).replace(/\s+$/,""),g=n.slice(c).replace(/^\s+|\s+$/g,"");await l(p,g,{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 na(this,t)}cmdImportStash(){return oa(this)}processStashFile(t){return Tn(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=pt(),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),y=this.stripFrontmatter(m);a=this.app.metadataCache.getFileCache(C)?.frontmatter??{},y.includes("{{body}}")?t=y.replace(/\{\{body\}\}/g,t):t.trim()?y.trim()&&(t=`${t} +`;await this.app.vault.modify(i,u);let I=e.parent??T,f=Date.parse(e.created||""),m=Number.isFinite(f)?new Date(f+1).toISOString():new Date().toISOString(),C=await this.createNoteUnder(g,I,{record:!1,createdOverride:m});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:C,...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 y=C?this.tree.get(C):void 0,w=y?.file?.path,E=w?await this.app.vault.read(y.file):null,v=this.noteFolder;this.plugin.getUndoStack(v).push({label:"Split note",undo:async()=>{if(w){let x=this.app.vault.getAbstractFileByPath(w);if(x)try{await this.app.fileManager.trashFile(x)}catch{}}let D=this.app.vault.getAbstractFileByPath(r);D&&await this.app.vault.modify(D,a),this.tree.rebuild(v),this.render()},redo:async()=>{let D=this.app.vault.getAbstractFileByPath(r);D&&await this.app.vault.modify(D,u),w&&E&&!await this.app.vault.adapter.exists(w)&&await this.app.vault.create(w,E),this.tree.rebuild(v),this.render()}})}catch(h){new U.Notice(`Stashpad: split failed (${h.message})`),console.error(h)}};new oi(this.app,n,async c=>{let g=o.slice(0,c).join(` +`).replace(/\s+$/,""),p=o.slice(c).join(` +`).replace(/^\s+|\s+$/g,"");await A(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 A(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 pa(this,t)}cmdExportOkf(t){return ga(this,t)}cmdImportStash(){return fa(this)}processStashFile(t){return Ln(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=gt(),a=null;{let f=(this.plugin.settings.noteTemplates??{})[s];if(f){let m=this.app.vault.getAbstractFileByPath(f);if(m&&m.extension==="md")try{let C=await this.app.vault.cachedRead(m),y=this.stripFrontmatter(C);a=this.app.metadataCache.getFileCache(m)?.frontmatter??{},y.includes("{{body}}")?t=y.replace(/\{\{body\}\}/g,t):t.trim()?y.trim()&&(t=`${t} -${y}`):t=y}catch(m){console.warn("[Stashpad] template read failed",m)}}}let r=Mt(t,this.activeStopwords()),l=Tt(r,o),c=`${s}/${l}`,p=e??this.focusId,g=i.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),u=this.authorship.currentAuthorLink();u&&this.authorship.ensureAuthorFile(u);let I=["---",`id: ${o}`,`parent: ${p}`,`created: ${g}`,`modified: ${g}`];if(u&&I.push(`author: "${u.link.replace(/"/g,'\\"')}"`),d.length>0){I.push("attachments:");for(let f of d)I.push(` - "${f.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",t);try{let f=I.join(` -`);this.plugin.importService.suppress(c,6e4),await Nt.timeAsync("write.createNote.file",()=>this.app.vault.create(c,f));try{let C=this.app.vault.getAbstractFileByPath(c);if(C&&C.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:p,children:[],file:C,created:g}),this.render(),this.fmSync.scheduleParentChange(o,null,p);else{this.render();let m=s.split("/").pop()||s,y=(t.split(` -`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${y}" 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[y,w]of Object.entries(a))oe.includes(y)||m[y]===void 0&&(m[y]=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:p}}),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 y=C.length;this.composerInputEl.setSelectionRange(y,y),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 U.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 U.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${n}-${s}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:T,payload:{path:o,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[o],folder:this.noteFolder}),`![[${o}]]`}catch(e){return new U.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(u=>typeof u=="string"&&u.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 p=t.createDiv({cls:"stashpad-note-authorship"}),g=(u,I)=>{let f=I.replace(/^\[\[/,"").replace(/\]\]$/,""),C=f.indexOf("|"),m=C>=0?f.slice(0,C):f,y=C>=0?f.slice(C+1):f.split("/").pop()??f,w=u.createEl("a",{cls:"internal-link",text:y});w.setAttribute("data-href",m),w.setAttribute("href",m)},d=[];r&&d.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"by "}),g(u,n)}),l&&d.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((I,f)=>{f>0&&u.createSpan({text:", "}),g(u,I)})}),c&&d.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"edited "}),u.createSpan({text:this.formatTimeInline(a)})}),d.forEach((u,I)=>{I>0&&p.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=p.createSpan({cls:"stashpad-authorship-piece"});u(f)}),p.addEventListener("click",u=>this.handleRenderedClick(u,e))}activeStopwords(){return this.plugin.settings.slugStopWords??zt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,U.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=Fe(t.basename);if(!e||e===T)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Mt(s,this.activeStopwords()),o=Tt(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,U.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=>Be(c));if(a.length===s.length&&a.every((c,p)=>c===s[p]))return;let l=s.map(c=>Yt(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,U.moment)(t);if(!e.isValid())return"";if(ut().useTemplatesFormat){let s=ls(this.app);if(s)return`${e.format(s.dateFormat)} +${y}`):t=y}catch(C){console.warn("[Stashpad] template read failed",C)}}}let r=Mt(t,this.activeStopwords()),A=Tt(r,o),c=`${s}/${A}`,g=e??this.focusId,p=i.createdOverride??new Date().toISOString(),h=this.extractAttachments(t),u=this.authorship.currentAuthorLink();u&&this.authorship.ensureAuthorFile(u);let I=["---",`id: ${o}`,`parent: ${g}`,`created: ${p}`,`modified: ${p}`];if(u&&I.push(`author: "${u.link.replace(/"/g,'\\"')}"`),h.length>0){I.push("attachments:");for(let f of h)I.push(` - "${f.replace(/"/g,'\\"')}"`)}else I.push("attachments: []");I.push("---",t);try{let f=I.join(` +`);this.plugin.importService.suppress(c,6e4),await xt.timeAsync("write.createNote.file",()=>this.app.vault.create(c,f));try{let m=this.app.vault.getAbstractFileByPath(c);if(m&&m.extension==="md"){if(!n)this.tree.insertSynthetic({id:o,parent:g,children:[],file:m,created:p}),this.render(),this.fmSync.scheduleParentChange(o,null,g);else{this.render();let C=s.split("/").pop()||s,y=(t.split(` +`).find(w=>w.trim())??"note").trim().slice(0,60);this.plugin.notifications.show({message:`"${y}" landed in \`${C}\``,kind:"success",category:"create",duration:0,folder:s,affectedIds:[o],actions:[{label:"Jump to note",onClick:()=>{this.switchToFolderAndFocus(s,o)}}]})}if(a)try{await this.app.fileManager.processFrontMatter(m,C=>{for(let[y,w]of Object.entries(a))re.includes(y)||C[y]===void 0&&(C[y]=w)})}catch(C){console.warn("[Stashpad] template fm overlay failed",C)}}}catch{}if(await this.log.append({type:"create",id:o,payload:{path:c,parent:g}}),i.record!==!1){let m=t;this.plugin.getUndoStack(s).push({label:n?"Send note":"Create note",undo:async()=>{let C=this.app.vault.getAbstractFileByPath(c);if(C)try{await this.app.fileManager.trashFile(C)}catch{}if(this.composerDraft=m,this.saveDraft(m),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=m;let y=m.length;this.composerInputEl.setSelectionRange(y,y),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(m),this.composerInputEl&&(this.composerInputEl.value=""),n||this.tree.rebuild(this.noteFolder),this.render()}})}return o}catch(f){return new U.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 U.TFolder))throw new Error(`${t} exists and is not a folder`);return}try{await this.app.vault.createFolder(t)}catch(e){let i=e?.message??"";if(!/already exists/i.test(i))throw e}}async importAttachment(t){try{let e=await t.arrayBuffer(),i=`${this.noteFolder}/_attachments`;await this.ensureFolder(i);let s=t.name.replace(/[^\w.\-]+/g,"_"),n=Date.now().toString(36),o=`${i}/${n}-${s}`;return await this.app.vault.createBinary(o,e),await this.log.append({type:"attachment_add",id:T,payload:{path:o,name:t.name,size:t.size}}),this.plugin.notifications.show({message:`Attached ${t.name}`,kind:"success",category:"attachment",affectedPaths:[o],folder:this.noteFolder}),`![[${o}]]`}catch(e){return new U.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(u=>typeof u=="string"&&u.trim()!==""):[],a=typeof s.modified=="string"?s.modified:typeof s.created=="string"?s.created:"",r=i.showAuthor&&!!n,A=i.showContributors&&o.length>0,c=i.showLastEdit&&!!a;if(!r&&!A&&!c)return;let g=t.createDiv({cls:"stashpad-note-authorship"}),p=(u,I)=>{let f=I.replace(/^\[\[/,"").replace(/\]\]$/,""),m=f.indexOf("|"),C=m>=0?f.slice(0,m):f,y=m>=0?f.slice(m+1):f.split("/").pop()??f,w=u.createEl("a",{cls:"internal-link",text:y});w.setAttribute("data-href",C),w.setAttribute("href",C)},h=[];r&&h.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"by "}),p(u,n)}),A&&h.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"with "}),o.forEach((I,f)=>{f>0&&u.createSpan({text:", "}),p(u,I)})}),c&&h.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"edited "}),u.createSpan({text:this.formatTimeInline(a)})}),h.forEach((u,I)=>{I>0&&g.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let f=g.createSpan({cls:"stashpad-authorship-piece"});u(f)}),g.addEventListener("click",u=>this.handleRenderedClick(u,e))}activeStopwords(){return this.plugin.settings.slugStopWords??Vt}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,U.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=Se(t.basename);if(!e||e===T)return;let i=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(i),n=Mt(s,this.activeStopwords()),o=Tt(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,U.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=>ye(c));if(a.length===s.length&&a.every((c,g)=>c===s[g]))return;let A=s.map(c=>zt(c));await this.app.fileManager.processFrontMatter(t,c=>{c.attachments=A})}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,U.moment)(t);if(!e.isValid())return"";if(ut().useTemplatesFormat){let s=gs(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,U.moment)(t);if(!e.isValid())return"";if(ut().useTemplatesFormat){let s=ls(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,U.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 U.Menu;s.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),s.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(i)})),s.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),s.addSeparator(),s.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),s.addItem(r=>r.setTitle("Clone (duplicate / copy)").setIcon("files").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdClone()})),s.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),s.addItem(r=>r.setTitle("Export to .stash").setIcon("package").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportStash()})),this.plugin.encryption?.isConfigured?.()&&s.addItem(r=>r.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let l=this.order.getOrder(this.noteFolder,e.parent??T),c=l.indexOf(e.id),p=c>0?l[c-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,p)&&this.render()})),s.addSeparator(),s.addItem(r=>r.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(r=>r.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,T),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==T&&this.navigateTo(T)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(r=>r.setTitle(o?"Unpin from sidebar":"Pin to sidebar").setIcon(o?"pin-off":"pin").onClick(async()=>{o?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),s.addItem(r=>r.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let a=this.isCompleted(e);s.addItem(r=>r.setTitle(a?"Mark incomplete":"Mark complete").setIcon(a?"circle":"check-circle").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleComplete()})),s.addSeparator(),s.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),await this.cmdDelete()})),s.addSeparator(),s.addItem(r=>r.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=u=>{for(let I of this.tree.getChildren(u.id))i(I),e.push(I)};i(t);let s=[...e,t],n=s.filter(u=>!!u.file),o=await Promise.all(n.map(u=>this.app.vault.cachedRead(u.file))),a=[];for(let u=0;u<n.length;u++){let I=n[u];a.push(...this.extractAttachments(this.stripFrontmatter(o[u])));let f=this.app.metadataCache.getFileCache(I.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let C of f.attachments)typeof C=="string"&&C.trim()&&a.push(Be(C))}let r=[...new Set(a)],l=this.authorship.collectAuthorIds(s),c=async u=>{let I=await this.snapshotNotes(s,u),f=0;if(u)for(let N of r){let Q=this.app.metadataCache.getFirstLinkpathDest(N,"");if(Q)try{await this.app.fileManager.trashFile(Q),await this.log.append({type:"attachment_remove",id:T,payload:{path:Q.path}}),this.plugin.notifications.show({message:`Deleted attachment "${Q.name}"`,kind:"warning",category:"attachment",affectedPaths:[Q.path],folder:this.noteFolder}),f+=1}catch{}}let C=new Set;for(let N of s)N.parent&&C.add(N.parent);let m=this.currentChildren.findIndex(N=>N.id===t.id),y=null;if(m>=0){for(let N=m+1;N<this.currentChildren.length;N++)if(this.currentChildren[N].id!==t.id){y=this.currentChildren[N].id;break}if(!y){for(let N=m-1;N>=0;N--)if(this.currentChildren[N].id!==t.id){y=this.currentChildren[N].id;break}}}for(let N of s)if(N.file){try{await this.app.fileManager.trashFile(N.file)}catch{}await this.log.append({type:"delete",id:N.id,payload:{path:N.file.path,attachmentsRemoved:u?r:[]}})}this.selection.clear(),this.cursorIdx=-1,y&&(this.pendingFocusIds=[y]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let N of C)s.some(Q=>Q.id===N)||this.fmSync.scheduleParentOfDeleted(N);let w=this.noteFolder,E=`Delete "${this.titleForNode(t)}"`,v=t.id,S=f>0?` with ${f} attachment${f===1?"":"s"}`:"",M=!1,F=async()=>{M||(M=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(I,[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:E,undo:async()=>{await F()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,M=!1,await this.trashNotesAndAttachments(I)}})},p=ut(),g=e.length>0&&p.confirmBulkDelete,d=r.length>0&&p.confirmAttachmentDelete;if(!g&&!d){await c(!1),this.focusView();return}new Pe(this.app,this.titleForNode(t),e.length,r.length,d,async u=>{await c(u),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new U.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===T){new U.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new U.Notice("Couldn't find the parent note.");return}let i=e.parent??T,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(r=>r.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new Ft(this.app,"Swap notes?",a.join(` -`),"Swap",async r=>{r&&await this.swapParentChild(e,t,i)}).open()}offerSwapForDescendantMove(t,e){let i=this.tree.get(e);if(!i?.file){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under one of its own descendants \u2014 that would create a cycle.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder});return}if(i.parent!==t.id){this.plugin.notifications.show({message:`Can't nest "${this.titleForNode(t)}" under "${this.titleForNode(i)}" \u2014 it's a deeper descendant. Only direct parent \u2194 child swaps are supported (try moving "${this.titleForNode(i)}" up first, then swap).`,kind:"warning",category:"move",affectedIds:[t.id,i.id],folder:this.noteFolder});return}let s=this.titleForNode(t),n=this.titleForNode(i),o=this.tree.getChildren(t.id).filter(r=>r.id!==i.id).length,a=[`"${s}" becomes a child of "${n}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new Ft(this.app,"Confirm Note Swap",a.join(` -`),"Swap",async r=>{if(!r)return;let l=t.parent??T;await this.swapParentChild(t,i,l)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new U.Notice("Swap aborted: parent/child relationship changed.");return}let s=this.noteFolder,n=t.parent,o=this.tree.getChildren(t.id).filter(d=>d.id!==e.id).filter(d=>!!d.file),a=o.map(d=>({id:d.id,path:d.file.path,was:d.parent})),r=this.order.getOrder(s,i).slice(),l=this.order.getOrder(s,e.id).slice(),c=this.order.getOrder(s,t.id).slice();await this.app.fileManager.processFrontMatter(e.file,d=>{d.parent=i}),this.fmSync.scheduleParentChange(e.id,t.id,i),await this.app.fileManager.processFrontMatter(t.file,d=>{d.parent=e.id}),this.fmSync.scheduleParentChange(t.id,n,e.id);for(let d of o)await this.app.fileManager.processFrontMatter(d.file,u=>{u.parent=e.id}),this.fmSync.scheduleParentChange(d.id,t.id,e.id);if(r.length>0){let d=r.includes(t.id)?r.map(u=>u===t.id?e.id:u):[...r.filter(u=>u!==e.id),e.id];this.order.setOrder(s,i,d)}let p=o.map(d=>d.id),g=[t.id,...l.filter(d=>d!==t.id&&!p.includes(d)),...p];this.order.setOrder(s,e.id,g),this.order.setOrder(s,t.id,[]),await this.order.save(s),await this.log.append({type:"parent_change",id:e.id,payload:{from:t.id,to:i,reason:"swap"}}),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e.id,reason:"swap"}});for(let d of a)await this.log.append({type:"parent_change",id:d.id,payload:{from:d.was,to:e.id,reason:"swap"}});this.tree.rebuild(s),this.pendingFocusIds=[e.id],this.render({kind:"follow-cursor"}),this.plugin.notifications.show({message:`Swapped "${this.titleForNode(e)}" \u2194 "${this.titleForNode(t)}".`,kind:"success",category:"move",affectedIds:[e.id,t.id,...p],folder:s}),this.plugin.getUndoStack(s).push({label:`Swap "${this.titleForNode(e)}" \u2194 parent`,undo:async()=>{let d=this.tree.get(t.id),u=this.tree.get(e.id);d?.file&&await this.app.fileManager.processFrontMatter(d.file,I=>{n==null||n===T?(delete I.parent,I.parent=T):I.parent=n}),u?.file&&await this.app.fileManager.processFrontMatter(u.file,I=>{I.parent=t.id});for(let I of a){let f=this.app.vault.getAbstractFileByPath(I.path);f&&await this.app.fileManager.processFrontMatter(f,C=>{I.was==null?C.parent=T:C.parent=I.was})}this.order.setOrder(s,i,r),this.order.setOrder(s,e.id,l),this.order.setOrder(s,t.id,c),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=r=>r??T;if(o(n)===o(e)){if(!i.quiet){let r=this.titleForNode(t),l=e===T?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${r}" is already under ${l}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==T&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let a=this.authorship.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(s,r=>{r.parent=e}),this.fmSync.scheduleParentChange(t.id,n,e),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),!i.quiet&&!i.silentSuccess){let r=this.tree.get(e),l=r?this.titleForNode(r):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${l}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===T?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let r=this.noteFolder,l=s.path,c=t.id;this.plugin.getUndoStack(r).push({label:"Move note",undo:async()=>{let p=this.app.vault.getAbstractFileByPath(l);if(p){await this.app.fileManager.processFrontMatter(p,g=>{g.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 g=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==g||this.selection.has(c))return;let u=this.currentChildren.findIndex(I=>I.id===c);u<0||(this.selection.add(c),this.cursorIdx=u,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}},redo:async()=>{let p=this.app.vault.getAbstractFileByPath(l);if(p){await this.app.fileManager.processFrontMatter(p,g=>{g.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 g=this.selectionGuardKey,d=()=>{if(this.selectionGuardKey!==g||this.selection.has(c))return;let u=this.currentChildren.findIndex(I=>I.id===c);u<0||(this.selection.add(c),this.cursorIdx=u,this.render({kind:"follow-cursor"}))};setTimeout(d,120),setTimeout(d,400)}}}})}return!0}notifyBatchMove(t,e,i){if(!t.length)return;let s=this.tree.get(e),n=e===T?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=r=>i.get(r.id)??0,a;if(t.length===1){let r=this.titleForNode(t[0]),l=o(t[0]);a=l>0?`Moved "${r}" and its ${l} ${l===1?"child":"children"} \u2192 ${n}`:`Moved "${r}" \u2192 ${n}`}else{let r=t.reduce((l,c)=>l+o(c),0);a=r>0?`Moved ${t.length} notes (${r} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===T?void 0:0,affectedIds:t.map(r=>r.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===T?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}},Hn=class extends U.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)}},vs=class extends U.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 se=require("obsidian");Et();var Tr=se.moment,Fs=class extends se.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0}getViewType(){return xe}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,se.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,se.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",p=e.createDiv({cls:"stashpad-trash-group"}),g=p.createDiv({cls:"stashpad-trash-group-head"});(0,se.setIcon)(g.createSpan({cls:"stashpad-trash-group-icon"}),c?"lock":"folder"),g.createSpan({text:c?"Hidden (title obscured)":l.split("/").pop()||l}),g.createSpan({cls:"stashpad-trash-group-count",text:String(a.get(l).length)});for(let d of a.get(l)){let u=p.createDiv({cls:"stashpad-trash-row"}),I=u.createDiv({cls:"stashpad-trash-row-main"});I.createSpan({cls:"stashpad-trash-title",text:c?"Locked note":d.meta?.title||"Locked note"});let f=d.meta?.deletedAt?`deleted ${Tr(d.meta.deletedAt).fromNow()}`:"deleted",C=d.meta&&d.meta.count>1?` \xB7 ${d.meta.count} ${d.meta.kind==="rawtrash"?"files":"notes"}`:"";I.createSpan({cls:"stashpad-trash-sub",text:f+C});let m=u.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,se.setIcon)(m.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),m.onclick=async()=>{m.disabled=!0,await this.plugin.restoreDeletedAt(d.blob)?await this.render():m.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function aa(h){let{workspace:A}=h.app,t=A.getLeavesOfType(xe);if(t.length>0){A.revealLeaf(t[0]);return}let e=A.getLeaf("tab");await e.setViewState({type:xe,active:!0}),A.revealLeaf(e)}Et();var dt=require("obsidian");Et();Ht();var ks=class h extends dt.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderTimer=null;this.pinExpanded=new Set;this.homeColorByFolder=new Map}getViewType(){return Ce}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=p=>{p.button===0&&(p.preventDefault(),p.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,p)=>p!==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,p=`${e}|${i}`,g=this.pinExpanded.has(p),d=t.createDiv({cls:"stashpad-pinned-row"});a&&(d.addClass("has-color"),d.style.setProperty("--stashpad-note-color",a)),r&&d.addClass("is-completed"),d.draggable=!0,d.dataset.pinIdx=String(n),d.addEventListener("dragstart",C=>{C.dataTransfer?.setData("text/plain",String(n)),C.dataTransfer&&(C.dataTransfer.effectAllowed="move"),d.addClass("is-dragging")}),d.addEventListener("dragend",()=>d.removeClass("is-dragging")),d.addEventListener("dragover",C=>{C.preventDefault(),C.dataTransfer&&(C.dataTransfer.dropEffect="move");let m=d.getBoundingClientRect(),y=C.clientY-m.top<m.height/2;d.toggleClass("drop-before",y),d.toggleClass("drop-after",!y)}),d.addEventListener("dragleave",()=>{d.removeClass("drop-before"),d.removeClass("drop-after")}),d.addEventListener("drop",C=>{C.preventDefault(),d.removeClass("drop-before"),d.removeClass("drop-after");let m=parseInt(C.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(m)||m===n)return;let y=d.getBoundingClientRect(),w=C.clientY-y.top<y.height/2;this.reorderPin(m,w?n:n+1)});let u=d.createSpan({cls:"stashpad-pinned-toggle"});c&&(ve(u,l.length,g),u.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let I=d.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(I,c?"folder-tree":"file-text"),a&&(I.style.color=a);let f=d.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(s)});if(f.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(s)},d.createSpan({cls:"stashpad-pinned-folder",text:e.split("/").pop()||e}),d.oncontextmenu=C=>{C.preventDefault();let m=new dt.Menu;m.addItem(y=>y.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),m.showAtMouseEvent(C)},c&&g){let C=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(C,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let r=typeof o.color=="string"?o.color:null,l=o.completed===!0,c=this.childrenOf(e,a),p=c.length>0,g=`${e}|${a}`,d=this.pinExpanded.has(g),u=t.createDiv({cls:"stashpad-pinned-subrow"});l&&u.addClass("is-completed"),u.style.paddingLeft=`${s*16}px`;let I=u.createSpan({cls:"stashpad-pinned-toggle"});p&&(ve(I,c.length,d),I.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(f,"file-text"),r&&(f.style.color=r);let C=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});C.onclick=()=>{this.onNavigateAway(),this.plugin.revealNoteInStashpad(n)},p&&d&&this.renderPinSubtree(t,e,a,s+1)}}childrenOf(t,e){let i=[];for(let s of this.app.vault.getMarkdownFiles()){if((s.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter;if(!o||typeof o.id!="string")continue;let a=o.parent;if(a===e||e===T&&(a==null||a===T)){if(o.id===T)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",a=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(a))}),i}onNavigateAway(){dt.Platform.isMobile&&(this.plugin.suppressComposerAutofocusUntil=Date.now()+1500,this.app.workspace.leftSplit?.collapse?.())}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}openFolders(){let t=new Set,e=(this.plugin.settings.folder||"Stashpad").replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(ct)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=h.clean(t),i=this.plugin.settings;return(i.folderPanelPinned??[]).includes(e)?"pinned":(i.folderPanelDownranked??[]).includes(e)?"downranked":(i.folderPanelHidden??[]).includes(e)?"hidden":"normal"}async setFolderState(t,e){let i=h.clean(t),s=this.plugin.settings;s.folderPanelPinned=(s.folderPanelPinned??[]).filter(n=>n!==i),s.folderPanelDownranked=(s.folderPanelDownranked??[]).filter(n=>n!==i),s.folderPanelHidden=(s.folderPanelHidden??[]).filter(n=>n!==i),e==="pinned"?s.folderPanelPinned.push(i):e==="downranked"?s.folderPanelDownranked.push(i):e==="hidden"&&s.folderPanelHidden.push(i),await this.plugin.saveSettings(),this.render()}folderHomeColor(t){return this.homeColorByFolder.get(h.clean(t))??null}rebuildHomeColors(){this.homeColorByFolder.clear();for(let t of this.app.vault.getMarkdownFiles()){let e=this.app.metadataCache.getFileCache(t)?.frontmatter;if(!e||e.id!==T||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let l of e)switch(this.folderState(l)){case"pinned":s.push(l);break;case"downranked":o.push(l);break;case"hidden":a.push(l);break;default:n.push(l)}let r=[...s,...n,...o];if(r.length===0&&a.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}for(let l of r)this.renderFolderRow(t,l,i);a.length>0&&this.renderHiddenSection(t,a)}renderFolderRow(t,e,i){let s=this.folderState(e),n=i.has(h.clean(e)),o=t.createDiv({cls:"stashpad-folderpanel-row stashpad-folderpanel-folder-row"});n&&o.addClass("is-open"),s==="downranked"&&o.addClass("is-downranked"),s==="pinned"&&o.addClass("is-pinned");let a=o.createSpan({cls:"stashpad-folderpanel-dot"});if(a.setAttr("aria-label",n?"Open in a tab":"Not open"),n&&a.setAttr("title","Open in a tab"),s==="pinned"){let u=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,dt.setIcon)(u,"pin"),u.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 p=e.split("/").pop()||e;o.createSpan({cls:"stashpad-folderpanel-row-label",text:p});let d=o.createDiv({cls:"stashpad-folderpanel-actions"}).createEl("button",{cls:"stashpad-folderpanel-iconbtn"});(0,dt.setIcon)(d,"plus-square"),d.setAttr("aria-label","Open in new tab"),d.onmousedown=u=>{u.button===0&&(u.preventDefault(),u.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",u=>{u.button===0&&(u.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=u=>{u.preventDefault(),this.openFolderMenu(u,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=p=>{p.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 Pn(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()}},Pn=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 Ss(h){let A=h.workspace.getLeavesOfType(Ce);if(A.length>0){h.workspace.revealLeaf(A[0]);return}let t=h.workspace.getLeftLeaf(!1);if(!t){new dt.Notice("Stashpad: couldn't open the folder panel.");return}await t.setViewState({type:Ce,active:!0}),h.workspace.revealLeaf(t)}Ht();Ue();var Ds=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 bs=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 Ns=class{constructor(A,t){this.app=A;this.data={version:1,authors:{}};this.loaded=!1;this.dirOk=!1;this.writeChain=Promise.resolve();this.path=`${t.replace(/\/+$/,"")}/authors.json`}getPath(){return this.path}async load(){if(!this.loaded){this.loaded=!0;try{let A=this.app.vault.adapter;if(await A.exists(this.path)){let t=JSON.parse(await A.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(A){console.warn("[Stashpad] author registry load failed; starting empty",A),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((A,t)=>(t.lastSeen??"").localeCompare(A.lastSeen??""))}get(A){return this.data.authors[A]??null}record(A){let t=(A.id??"").trim();if(!t)return!1;let e=A.at??new Date().toISOString(),i=(A.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:A.role?.trim()||void 0,department:A.department?.trim()||void 0,firstSeen:e,lastSeen:e,renames:[]},n=!0;else{if(i&&i!==s.name&&(s.renames.push({from:s.name,to:i,at:e}),s.name=i,n=!0),A.role!==void 0){let o=A.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(A.department!==void 0){let o=A.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(A,t){let e=t??new Date().toISOString(),i={};for(let s of A){let n=(s.id??"").trim();if(!n)continue;let o=this.data.authors[n],a=(s.name??"").trim()||o?.name||"",r=o?.renames?[...o.renames]:[];o&&a&&a!==o.name&&r.push({from:o.name,to:a,at:e}),i[n]={id:n,name:a,role:s.role?.trim()||o?.role||void 0,department:s.department?.trim()||o?.department||void 0,firstSeen:o?.firstSeen??e,lastSeen:e,renames:r}}this.data={version:1,authors:i},this.save()}async ensureDir(){if(this.dirOk)return;let A=this.app.vault.adapter,e=this.path.slice(0,this.path.lastIndexOf("/")).split("/").filter(Boolean),i="";for(let s of e)i=i?`${i}/${s}`:s,await A.exists(i)||await A.mkdir(i);this.dirOk=!0}save(){return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.write(this.path,JSON.stringify(this.data,null,2))}catch(A){console.warn("[Stashpad] author registry save failed",A)}}),this.writeChain}};var It=require("obsidian");Et();Gt();Ue();Ti();Ht();var xs=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),ra="_archive",Aa=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)&&(xs.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)||Aa.has(A.extension))return!1;let t=A.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return xs.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(A){if(!this.isEligiblePath(A))return!1;if(A.extension==="md")try{let{fm:t}=Dt(await this.app.vault.read(A));if(t&&typeof t.id=="string"&&t.id)return!1}catch{}return!0}async drain(){if(this.drainTimer=null,!this.draining){this.draining=!0;try{let A=[...this.pending.keys()];this.pending.clear();let t=A.map(p=>this.app.vault.getAbstractFileByPath(p)).filter(p=>p instanceof It.TFile),e=[];for(let p of t)await this.isStillImportable(p)&&e.push(p);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(p=>this.app.vault.getAbstractFileByPath(p)).filter(p=>p instanceof It.TFolder).map(p=>({folder:p,files:this.filesUnder(p.path)})).filter(p=>p.files.length>0),n=s.reduce((p,g)=>p+g.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,r=[],l=e.filter(p=>this.plugin.importLog.findDuplicate(p.name,p.stat?.size??null));if(l.length>0){let p=l.slice(0,5).map(u=>`\u2022 ${u.name}`).join(` -`),g=l.length>5?` -\u2026and ${l.length-5} more`:"",d=await this.dupChoice(`${l.length} of these look like files you've imported before: -${p}${g} +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,U.moment)(t);if(!e.isValid())return"";if(ut().useTemplatesFormat){let s=gs(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,U.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 U.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.settings.okfEnabled&&s.addItem(r=>r.setTitle("Export as OKF\u2026").setIcon("book-marked").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdExportOkf()})),this.plugin.encryption?.isConfigured?.()&&s.addItem(r=>r.setTitle("Encrypt (lock) note + children").setIcon("lock").onClick(async()=>{let A=this.order.getOrder(this.noteFolder,e.parent??T),c=A.indexOf(e.id),g=c>0?A[c-1]:null;await this.plugin.lockNoteSubtree(this.noteFolder,e.id,g)&&this.render()})),s.addSeparator(),s.addItem(r=>r.setTitle("Move to\u2026").setIcon("move").onClick(()=>this.cmdMovePicker())),s.addItem(r=>r.setTitle("Move to Home").setIcon("home").onClick(async()=>{await this.changeParent(e,T),this.plugin.settings.autoNavOnMoveOut&&this.focusId!==T&&this.navigateTo(T)}));let n={folder:this.noteFolder,id:e.id},o=this.plugin.isPinned(n);s.addItem(r=>r.setTitle(o?"Unpin from sidebar":"Pin to sidebar").setIcon(o?"pin-off":"pin").onClick(async()=>{o?await this.plugin.unpinNote(n):await this.plugin.pinNote(n)})),s.addItem(r=>r.setTitle("Set color\u2026").setIcon("palette").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdSetColor()}));let a=this.isCompleted(e);s.addItem(r=>r.setTitle(a?"Mark incomplete":"Mark complete").setIcon(a?"circle":"check-circle").onClick(()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),this.cmdToggleComplete()})),s.addSeparator(),s.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{this.selection.has(e.id)||(this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id),await this.cmdDelete()})),s.addSeparator(),s.addItem(r=>r.setTitle("More commands\u2026").setIcon("terminal").onClick(()=>this.openCommandPalette())),s.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],i=u=>{for(let I of this.tree.getChildren(u.id))i(I),e.push(I)};i(t);let s=[...e,t],n=s.filter(u=>!!u.file),o=await Promise.all(n.map(u=>this.app.vault.cachedRead(u.file))),a=[];for(let u=0;u<n.length;u++){let I=n[u];a.push(...this.extractAttachments(this.stripFrontmatter(o[u])));let f=this.app.metadataCache.getFileCache(I.file)?.frontmatter;if(Array.isArray(f?.attachments))for(let m of f.attachments)typeof m=="string"&&m.trim()&&a.push(ye(m))}let r=[...new Set(a)],A=this.authorship.collectAuthorIds(s),c=async u=>{let I=await this.snapshotNotes(s,u),f=0;if(u)for(let N of r){let Q=this.app.metadataCache.getFirstLinkpathDest(N,"");if(Q)try{await this.app.fileManager.trashFile(Q),await this.log.append({type:"attachment_remove",id:T,payload:{path:Q.path}}),this.plugin.notifications.show({message:`Deleted attachment "${Q.name}"`,kind:"warning",category:"attachment",affectedPaths:[Q.path],folder:this.noteFolder}),f+=1}catch{}}let m=new Set;for(let N of s)N.parent&&m.add(N.parent);let C=this.currentChildren.findIndex(N=>N.id===t.id),y=null;if(C>=0){for(let N=C+1;N<this.currentChildren.length;N++)if(this.currentChildren[N].id!==t.id){y=this.currentChildren[N].id;break}if(!y){for(let N=C-1;N>=0;N--)if(this.currentChildren[N].id!==t.id){y=this.currentChildren[N].id;break}}}for(let N of s)if(N.file){try{await this.app.fileManager.trashFile(N.file)}catch{}await this.log.append({type:"delete",id:N.id,payload:{path:N.file.path,attachmentsRemoved:u?r:[]}})}this.selection.clear(),this.cursorIdx=-1,y&&(this.pendingFocusIds=[y]),this.tree.rebuild(this.noteFolder),this.render({kind:"follow-cursor"});for(let N of m)s.some(Q=>Q.id===N)||this.fmSync.scheduleParentOfDeleted(N);let w=this.noteFolder,E=`Delete "${this.titleForNode(t)}"`,v=t.id,D=f>0?` with ${f} attachment${f===1?"":"s"}`:"",x=!1,F=async()=>{x||(x=!0,this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(I,[v]))};this.plugin.notifications.show({message:`Deleted "${this.titleForNode(t)}"${D}`,kind:"warning",category:"delete",duration:0,affectedIds:[t.id],affectedAuthorIds:A,folder:this.noteFolder,actions:[{label:"Undo delete",onClick:()=>void F()}]}),this.plugin.getUndoStack(w).push({label:E,undo:async()=>{await F()},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,x=!1,await this.trashNotesAndAttachments(I)}})},g=ut(),p=e.length>0&&g.confirmBulkDelete,h=r.length>0&&g.confirmAttachmentDelete;if(!p&&!h){await c(!1),this.focusView();return}new Pe(this.app,this.titleForNode(t),e.length,r.length,h,async u=>{await c(u),this.focusView()}).open()}async cmdSwapWithParent(){let t=this.cursorIdx>=0?this.currentChildren[this.cursorIdx]:null;if(!t?.file){new U.Notice("Pick a note first (move the cursor onto it).");return}if(!t.parent||t.parent===T){new U.Notice("Already at Home \u2014 no parent to swap with.");return}let e=this.tree.get(t.parent);if(!e?.file){new U.Notice("Couldn't find the parent note.");return}let i=e.parent??T,s=this.titleForNode(t),n=this.titleForNode(e),o=this.tree.getChildren(e.id).filter(r=>r.id!==t.id).length,a=[`"${n}" becomes a child of "${s}".`];o>0&&a.push(`${o} sibling${o===1?"":"s"} move with it.`),new kt(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 kt(this.app,"Confirm Note Swap",a.join(` +`),"Swap",async r=>{if(!r)return;let A=t.parent??T;await this.swapParentChild(t,i,A)}).open()}async swapParentChild(t,e,i){if(!t.file||!e.file)return;if(e.parent!==t.id){new U.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(),A=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,u=>{u.parent=e.id}),this.fmSync.scheduleParentChange(h.id,t.id,e.id);if(r.length>0){let h=r.includes(t.id)?r.map(u=>u===t.id?e.id:u):[...r.filter(u=>u!==e.id),e.id];this.order.setOrder(s,i,h)}let g=o.map(h=>h.id),p=[t.id,...A.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),u=this.tree.get(e.id);h?.file&&await this.app.fileManager.processFrontMatter(h.file,I=>{n==null||n===T?(delete I.parent,I.parent=T):I.parent=n}),u?.file&&await this.app.fileManager.processFrontMatter(u.file,I=>{I.parent=t.id});for(let I of a){let f=this.app.vault.getAbstractFileByPath(I.path);f&&await this.app.fileManager.processFrontMatter(f,m=>{I.was==null?m.parent=T:m.parent=I.was})}this.order.setOrder(s,i,r),this.order.setOrder(s,e.id,A),this.order.setOrder(s,t.id,c),await this.order.save(s),this.tree.rebuild(s),this.pendingFocusIds=[t.id],this.render({kind:"follow-cursor"})},redo:async()=>{await this.swapParentChild(t,e,i)}})}async changeParent(t,e,i={record:!0}){if(!t.file)return!1;let s=t.file,n=t.parent,o=r=>r??T;if(o(n)===o(e)){if(!i.quiet){let r=this.titleForNode(t),A=e===T?"Home":`"${this.titleForNode(this.tree.get(e)??t)}"`;this.plugin.notifications.show({message:`"${r}" is already under ${A}.`,kind:"info",category:"move",affectedIds:[t.id],folder:this.noteFolder})}return!1}if(e===t.id)return i.quiet||this.plugin.notifications.show({message:`Can't move "${this.titleForNode(t)}" into itself.`,kind:"warning",category:"move",affectedIds:[t.id],folder:this.noteFolder}),!1;if(e!==T&&this.isDescendant(e,t.id))return i.quiet||this.offerSwapForDescendantMove(t,e),!1;let a=this.authorship.collectAuthorIds([t]);if(await this.app.fileManager.processFrontMatter(s,r=>{r.parent=e}),this.fmSync.scheduleParentChange(t.id,n,e),await this.log.append({type:"parent_change",id:t.id,payload:{from:n,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==n?(this.selection.clear(),this.cursorIdx=-1):this.focusId===n&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),!i.quiet&&!i.silentSuccess){let r=this.tree.get(e),A=r?this.titleForNode(r):"(root)";this.plugin.notifications.show({message:`Reparented "${this.titleForNode(t)}" \u2192 "${A}"`,kind:"success",category:"move",affectedIds:[t.id],affectedAuthorIds:a,folder:this.noteFolder,actions:e===T?[]:[{label:"Jump to parent",onClick:()=>this.navigateTo(e)}]})}if(i.record!==!1){let r=this.noteFolder,A=s.path,c=t.id;this.plugin.getUndoStack(r).push({label:"Move note",undo:async()=>{let g=this.app.vault.getAbstractFileByPath(A);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 u=this.currentChildren.findIndex(I=>I.id===c);u<0||(this.selection.add(c),this.cursorIdx=u,this.render({kind:"follow-cursor"}))};setTimeout(h,120),setTimeout(h,400)}}},redo:async()=>{let g=this.app.vault.getAbstractFileByPath(A);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 u=this.currentChildren.findIndex(I=>I.id===c);u<0||(this.selection.add(c),this.cursorIdx=u,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===T?"Home":`"${s?this.titleForNode(s):"the destination"}"`,o=r=>i.get(r.id)??0,a;if(t.length===1){let r=this.titleForNode(t[0]),A=o(t[0]);a=A>0?`Moved "${r}" and its ${A} ${A===1?"child":"children"} \u2192 ${n}`:`Moved "${r}" \u2192 ${n}`}else{let r=t.reduce((A,c)=>A+o(c),0);a=r>0?`Moved ${t.length} notes (${r} nested) \u2192 ${n}`:`Moved ${t.length} notes \u2192 ${n}`}this.plugin.notifications.show({message:a,kind:"success",category:"move",duration:e===T?void 0:0,affectedIds:t.map(r=>r.id),affectedAuthorIds:this.authorship.collectAuthorIds(t),folder:this.noteFolder,actions:e===T?[]:[{label:"Jump to destination",onClick:()=>this.navigateTo(e)}]})}},Jn=class extends U.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)}},bs=class extends U.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 oe=require("obsidian");Qt();var Xr=oe.moment,xs=class extends oe.ItemView{constructor(t,e){super(t);this.plugin=e;this.renderPending=!1;this.renderGen=0}getViewType(){return Ne}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,oe.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,oe.setIcon)(o.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),o.onclick=async()=>{o.disabled=!0,await this.plugin.restoreAllTrash(),await this.render()};let a=new Map;for(let A of n){let c=A.meta?.title?A.meta.originalFolder||"(unknown folder)":" hidden";(a.get(c)??a.set(c,[]).get(c)).push(A)}let r=[...a.keys()].sort((A,c)=>A===" hidden"?1:c===" hidden"?-1:A.localeCompare(c));for(let A of r){let c=A===" hidden",g=e.createDiv({cls:"stashpad-trash-group"}),p=g.createDiv({cls:"stashpad-trash-group-head"});(0,oe.setIcon)(p.createSpan({cls:"stashpad-trash-group-icon"}),c?"lock":"folder"),p.createSpan({text:c?"Hidden (title obscured)":A.split("/").pop()||A}),p.createSpan({cls:"stashpad-trash-group-count",text:String(a.get(A).length)});for(let h of a.get(A)){let u=g.createDiv({cls:"stashpad-trash-row"}),I=u.createDiv({cls:"stashpad-trash-row-main"});I.createSpan({cls:"stashpad-trash-title",text:c?"Locked note":h.meta?.title||"Locked note"});let f=h.meta?.deletedAt?`deleted ${Xr(h.meta.deletedAt).fromNow()}`:"deleted",m=h.meta&&h.meta.count>1?` \xB7 ${h.meta.count} ${h.meta.kind==="rawtrash"?"files":"notes"}`:"";I.createSpan({cls:"stashpad-trash-sub",text:f+m});let C=u.createEl("button",{cls:"stashpad-trash-restore",text:"Restore"});(0,oe.setIcon)(C.createSpan({cls:"stashpad-btn-icon"}),"rotate-ccw"),C.onclick=async()=>{C.disabled=!0,await this.plugin.restoreDeletedAt(h.blob)?await this.render():C.disabled=!1}}}}async onClose(){this.contentEl.empty()}};async function ma(d){let{workspace:l}=d.app,t=l.getLeavesOfType(Ne);if(t.length>0){l.revealLeaf(t[0]);return}let e=l.getLeaf("tab");await e.setViewState({type:Ne,active:!0}),l.revealLeaf(e)}Qt();var dt=require("obsidian");Qt();Ht();var Ns=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 Be}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"}),A=r.createSpan({cls:"stashpad-folderpanel-heading-title stashpad-folderpanel-heading-switch",text:"Folders"});if(A.setAttr("aria-label","Open folder switcher"),A.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 A=this.clampFrac((a.clientY-r.top)/r.height);s=A,e.style.flex=`0 0 ${(A*100).toFixed(2)}%`},o=a=>{document.removeEventListener("pointermove",n),document.removeEventListener("pointerup",o),document.body.removeClass("stashpad-folderpanel-resizing");try{i.releasePointerCapture(a.pointerId)}catch{}s!=null&&(this.plugin.settings.folderPanelPinnedFraction=s,this.plugin.saveSettings())};i.addEventListener("pointerdown",a=>{a.preventDefault(),document.body.addClass("stashpad-folderpanel-resizing");try{i.setPointerCapture(a.pointerId)}catch{}document.addEventListener("pointermove",n),document.addEventListener("pointerup",o)})}openPinnedOptionsMenu(t){let e=this.plugin.settings.folderPanelPinnedGrouping??"pin-order",i=new 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.discoverStashpadFolders().filter(n=>this.folderState(n)==="pinned"),i=this.plugin.listPinnedNotes();if(e.length===0&&i.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"Nothing pinned yet \u2014 pin a note or folder from its right-click menu."});return}if(e.length>0){let n=this.openFolders();for(let o of e)this.renderFolderRow(t,o,n)}if(i.length===0)return;if((this.plugin.settings.folderPanelPinnedGrouping??"pin-order")==="folder"){let n=new Map;i.forEach((r,A)=>{let c=n.get(r.folder);c||(c=[],n.set(r.folder,c)),c.push({...r,idx:A})});let o=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder,a=Array.from(n.keys());o&&n.has(o)&&(a.splice(a.indexOf(o),1),a.unshift(o));for(let r of a){let A=t.createDiv({cls:"stashpad-pinned-group-header"});r===o&&A.addClass("is-active-folder"),A.createSpan({cls:"stashpad-pinned-group-name",text:r.split("/").pop()||r});for(let c of n.get(r)??[])this.renderPinNote(t,c.folder,c.id,c.file,c.idx)}}else i.forEach((n,o)=>this.renderPinNote(t,n.folder,n.id,n.file,o))}async reorderPin(t,e){let i=this.plugin.listPinnedNotes();if(t<0||t>=i.length)return;let s=i[t],n=i.filter((c,g)=>g!==t),o=Math.max(0,Math.min(e>t?e-1:e,n.length)),a=n[o-1],r=n[o],A;!a&&!r?A=Date.now():a?r?A=(a.pinnedAt+r.pinnedAt)/2:A=a.pinnedAt+1e3:A=r.pinnedAt-1e3;try{await this.app.fileManager.processFrontMatter(s.file,c=>{c.pinnedAt=A})}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,A=this.childrenOf(e,i),c=A.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",m=>{m.dataTransfer?.setData("text/plain",String(n)),m.dataTransfer&&(m.dataTransfer.effectAllowed="move"),h.addClass("is-dragging")}),h.addEventListener("dragend",()=>h.removeClass("is-dragging")),h.addEventListener("dragover",m=>{m.preventDefault(),m.dataTransfer&&(m.dataTransfer.dropEffect="move");let C=h.getBoundingClientRect(),y=m.clientY-C.top<C.height/2;h.toggleClass("drop-before",y),h.toggleClass("drop-after",!y)}),h.addEventListener("dragleave",()=>{h.removeClass("drop-before"),h.removeClass("drop-after")}),h.addEventListener("drop",m=>{m.preventDefault(),h.removeClass("drop-before"),h.removeClass("drop-after");let C=parseInt(m.dataTransfer?.getData("text/plain")??"",10);if(!Number.isFinite(C)||C===n)return;let y=h.getBoundingClientRect(),w=m.clientY-y.top<y.height/2;this.reorderPin(C,w?n:n+1)});let u=h.createSpan({cls:"stashpad-pinned-toggle"});c&&(ke(u,A.length,p),u.onclick=m=>{m.stopPropagation(),this.pinExpanded.has(g)?this.pinExpanded.delete(g):this.pinExpanded.add(g),this.render()});let I=h.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(I,c?"folder-tree":"file-text"),a&&(I.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=m=>{m.preventDefault();let C=new dt.Menu;C.addItem(y=>y.setTitle("Unpin from sidebar").setIcon("pin-off").onClick(()=>void this.plugin.unpinNote({folder:e,id:i}))),C.showAtMouseEvent(m)},c&&p){let m=t.createDiv({cls:"stashpad-pinned-children"});this.renderPinSubtree(m,e,i,1)}}renderPinSubtree(t,e,i,s){for(let n of this.childrenOf(e,i)){let o=this.app.metadataCache.getFileCache(n)?.frontmatter??{},a=typeof o.id=="string"?o.id:null;if(!a)continue;let r=typeof o.color=="string"?o.color:null,A=o.completed===!0,c=this.childrenOf(e,a),g=c.length>0,p=`${e}|${a}`,h=this.pinExpanded.has(p),u=t.createDiv({cls:"stashpad-pinned-subrow"});A&&u.addClass("is-completed"),u.style.paddingLeft=`${s*16}px`;let I=u.createSpan({cls:"stashpad-pinned-toggle"});g&&(ke(I,c.length,h),I.onclick=C=>{C.stopPropagation(),this.pinExpanded.has(p)?this.pinExpanded.delete(p):this.pinExpanded.add(p),this.render()});let f=u.createSpan({cls:"stashpad-pinned-icon"});(0,dt.setIcon)(f,"file-text"),r&&(f.style.color=r);let m=u.createSpan({cls:"stashpad-pinned-label",text:this.titleFromFile(n)});m.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===T&&(a==null||a===T)){if(o.id===T)continue;i.push(s)}}return i.sort((s,n)=>{let o=this.app.metadataCache.getFileCache(s)?.frontmatter?.created??"",a=this.app.metadataCache.getFileCache(n)?.frontmatter?.created??"";return String(o).localeCompare(String(a))}),i}onNavigateAway(){dt.Platform.isMobile&&(this.plugin.suppressComposerAutofocusUntil=Date.now()+1500,this.app.workspace.leftSplit?.collapse?.())}titleFromFile(t){return t.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||t.basename}openFolders(){let t=new Set,e=(this.plugin.settings.folder||"Stashpad").replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(ct)){let s=(i.view?.noteFolder??"").replace(/\/+$/,"");s||(s=(((i.getViewState?.()?.state??{}).folderOverride??"")||e).replace(/\/+$/,"")),s&&t.add(s)}return t}static clean(t){return t.replace(/\/+$/,"")}folderState(t){let e=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!==T||typeof e.color!="string"||!e.color.trim())continue;let i=(t.parent?.path??"").replace(/\/+$/,"");i&&this.homeColorByFolder.set(i,e.color)}}renderFolders(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){t.createDiv({cls:"stashpad-folderpanel-empty",text:"No Stashpad folders yet."});return}this.rebuildHomeColors();let i=this.openFolders(),s=[],n=[],o=[],a=[];for(let A of e)switch(this.folderState(A)){case"pinned":s.push(A);break;case"downranked":o.push(A);break;case"hidden":a.push(A);break;default:n.push(A)}let 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 A of r)this.renderFolderRow(t,A,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 u=o.createSpan({cls:"stashpad-folderpanel-pinmark"});(0,dt.setIcon)(u,"pin"),u.setAttr("aria-label","Pinned")}let r=this.plugin.isArchiveFolder(e),A=o.createSpan({cls:"stashpad-folderpanel-folder-icon"});(0,dt.setIcon)(A,r?"archive":"folder"),r&&A.setAttr("aria-label","Archive folder \u2014 notes moved in are auto-encrypted");let c=this.folderHomeColor(e);c&&(A.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=u=>{u.button===0&&(u.preventDefault(),u.stopPropagation(),this.onNavigateAway(),this.plugin.activateViewForFolder(e))},o.addEventListener("mousedown",u=>{u.button===0&&(u.target?.closest?.(".stashpad-folderpanel-actions")||(this.onNavigateAway(),this.jumpToFolder(e)))}),o.oncontextmenu=u=>{u.preventDefault(),this.openFolderMenu(u,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"}),A=a.split("/").pop()||a;r.createSpan({cls:"stashpad-folderpanel-row-label",text:A});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 kt(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 qn(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(A){console.warn("[Stashpad] folder rename failed",A),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 kt(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()}},qn=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 l=d.workspace.getLeavesOfType(Be);if(l.length>0){d.workspace.revealLeaf(l[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:Be,active:!0}),d.workspace.revealLeaf(t)}Ht();Ue();Qt();var On="OKF Template.md",Zr=`--- +okfType: concept +--- +{{body}} +`,Kn=["> Generated by Stashpad \u2014 this folder is an Open Knowledge Format (OKF) bundle.","> Field legend: `okfType`\u2192`type`, `okfTitle`\u2192`title`, `okfDescription`\u2192`description`, `okfTags`\u2192`tags`, `okfTimestamp`\u2192`timestamp`; `okfParent`/`okfChildren` are relative-markdown cross-links. Stashpad's own `id`/`parent` are extensions \u2014 ignore them for OKF."].join(` +`);function bi(d){return d.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ").trim()||d.basename}function Ca(d){return`[${bi(d)}](${encodeURI(d.name)})`}async function Ba(d,l=On){try{await d.vault.adapter.exists(l)||await d.vault.create(l,Zr)}catch{}return l}function Qa(d,l){if(!l)return[];let t=l.replace(/^\/+/,"");return Object.entries(d??{}).filter(([,e])=>(e??"").replace(/^\/+/,"")===t).map(([e])=>e.replace(/\/+$/,""))}async function Ts(d,l){let t=l.replace(/\/+$/,""),e=new Map,i=new Map;for(let o of d.vault.getMarkdownFiles()){if((o.parent?.path?.replace(/\/+$/,"")??"")!==t)continue;let a;try{a=wt(await d.vault.read(o)).fm}catch{continue}let r=typeof a.id=="string"?a.id:null;if(!r)continue;let A=typeof a.parent=="string"?a.parent:T;e.set(r,{file:o,id:r,parent:A,modified:typeof a.modified=="string"?a.modified:"",created:typeof a.created=="string"?a.created:""});let c=i.get(A)??[];c.push(r),i.set(A,c)}let s=0,n=0;for(let o of e.values()){if(o.id===T)continue;s+=1;let a=o.parent&&o.parent!==T&&e.get(o.parent)?Ca(e.get(o.parent).file):null,r=(i.get(o.id)??[]).map(A=>e.get(A)).filter(A=>!!A).map(A=>Ca(A.file));try{let A=!1;await d.fileManager.processFrontMatter(o.file,c=>{a?c.okfParent!==a&&(c.okfParent=a,A=!0):c.okfParent!==void 0&&(delete c.okfParent,A=!0);let g=Array.isArray(c.okfChildren)?c.okfChildren:[],p=g.length===r.length&&g.every((h,u)=>h===r[u]);if(r.length?p||(c.okfChildren=r,A=!0):c.okfChildren!==void 0&&(delete c.okfChildren,A=!0),c.okfType===void 0&&(c.okfType="concept",A=!0),c.okfTitle===void 0&&(c.okfTitle=bi(o.file),A=!0),c.okfTimestamp===void 0){let h=o.modified||o.created;h&&(c.okfTimestamp=h,A=!0)}}),A&&(n+=1,await new Promise(c=>setTimeout(c,50)))}catch(A){console.warn("[Stashpad] OKF rebuild failed",o.file.path,A)}}try{await d.vault.adapter.write(`${t}/index.md`,await Yn(d,t))}catch(o){console.warn("[Stashpad] OKF index.md write failed",t,o)}return{checked:s,written:n}}async function Yn(d,l,t){let e=l.replace(/\/+$/,""),i=new Map,s=new Map;for(let c of d.vault.getMarkdownFiles()){if((c.parent?.path?.replace(/\/+$/,"")??"")!==e||c.name==="index.md")continue;let g;try{g=wt(await d.vault.read(c)).fm}catch{continue}let p=typeof g.id=="string"?g.id:null;!p||p===T||t&&!t.has(p)||i.set(p,{id:p,file:c,parent:typeof g.parent=="string"?g.parent:T,title:typeof g.okfTitle=="string"&&g.okfTitle?g.okfTitle:bi(c),type:typeof g.okfType=="string"&&g.okfType?g.okfType:"concept",position:typeof g.position=="number"?g.position:Number.MAX_SAFE_INTEGER,created:typeof g.created=="string"?g.created:""})}for(let c of i.values()){let g=s.get(c.parent)??[];g.push(c),s.set(c.parent,g)}for(let c of s.values())c.sort((g,p)=>g.position-p.position||g.created.localeCompare(p.created));let n=[],o=(c,g,p)=>{if(!p.has(c.id)){p.add(c.id),n.push(`${" ".repeat(g)}- [${c.title}](${encodeURI(c.file.name)}) \u2014 ${c.type}`);for(let h of s.get(c.id)??[])o(h,g+1,p)}},a=new Set,r=[...i.values()].filter(c=>c.parent===T||!i.has(c.parent)).sort((c,g)=>c.position-g.position||c.created.localeCompare(g.created));for(let c of r)o(c,0,a);let A=e.split("/").pop()||e;return["---","type: index",`title: ${A} (OKF index)`,"---","",`# ${A}`,"",Kn,"","## Concepts",n.length?n.join(` +`):"_No concepts yet._",""].join(` +`)}var _r=new TextEncoder,Hs=d=>_r.encode(d);function xi(d){if(typeof d=="number"||typeof d=="boolean")return String(d);let l=String(d??"");return/[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(l)?JSON.stringify(l):l}function jr(d,l){let{fm:t}=wt(d),e=[];e.push(`type: ${xi(typeof t.okfType=="string"&&t.okfType?t.okfType:"concept")}`),e.push(`title: ${xi(typeof t.okfTitle=="string"&&t.okfTitle?t.okfTitle:bi(l))}`),typeof t.okfDescription=="string"&&t.okfDescription&&e.push(`description: ${xi(t.okfDescription)}`);let i=t.okfTags;if(Array.isArray(i)&&i.length){e.push("tags:");for(let a of i)e.push(` - ${xi(a)}`)}let s=typeof t.okfTimestamp=="string"&&t.okfTimestamp||typeof t.modified=="string"&&t.modified||typeof t.created=="string"&&t.created||"";s&&e.push(`timestamp: ${xi(s)}`);let n=e.join(` +`),o=d.match(/^---\r?\n/);return o?d.slice(0,o[0].length)+n+` +`+d.slice(o[0].length):`--- +${n} +--- +${d}`}async function ya(d,l,t,e){let i=[],s=new Map;for(let n of l){let o=await d.vault.read(n);i.push({name:n.name,data:Hs(jr(o,n))});for(let a of o.match(/!\[\[([^\]]+?)\]\]/g)??[]){let r=a.slice(3,-2).split("|")[0].split("#")[0].trim(),A=d.metadataCache.getFirstLinkpathDest(r,n.path);A&&!s.has(A.name)&&s.set(A.name,A)}}for(let[n,o]of s)i.push({name:`_attachments/${n}`,data:new Uint8Array(await d.vault.readBinary(o))});return i.push({name:"index.md",data:Hs(await Yn(d,t,e))}),i.push({name:"_okf.md",data:Hs(`# About this bundle -Replace the existing notes, skip the duplicates, or import them anyway as new notes?`);if(d==="skip"){let u=new Set(l.map(I=>I.path));if(a=e.filter(I=>!u.has(I.path)),a.length===0&&s.length===0){new It.Notice(`Skipped ${l.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(d==="replace")for(let u of l){let I=this.plugin.importLog.findDuplicate(u.name,u.stat?.size??null);for(let f of I?.notePaths??[]){let C=this.app.vault.getAbstractFileByPath(f);if(C instanceof It.TFile)try{r.push({path:f,content:await this.app.vault.read(C)}),await this.app.fileManager.trashFile(C)}catch(m){console.warn("[Stashpad] replace: couldn't remove prior note",f,m)}}}}if(o=a.length+n,o>=Ze.BATCH_CONFIRM_AT){let p=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${p}. Proceed? -Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new It.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let c=[];for(let p of a)try{let g=p.stat?.size??null,d=p.extension==="md"?await this.importMarkdown(p):await this.importOtherFile(p);d&&(c.push(d),this.plugin.importLog.append({ts:new Date().toISOString(),folder:d.folder,kind:d.kind,originalName:p.name,size:g,sourcePath:p.path,notePaths:d.kind==="folder"?d.notePaths:[d.notePath]}))}catch(g){console.warn("[Stashpad] import failed",p.path,g)}for(let{folder:p}of s)try{let g=await this.importFolder(p);g&&g.kind==="folder"&&(c.push(g),this.plugin.importLog.append({ts:new Date().toISOString(),folder:g.folder,kind:"folder",originalName:g.originalName,size:null,sourcePath:p.path,notePaths:g.notePaths}))}catch(g){console.warn("[Stashpad] folder import failed",p.path,g)}(c.length>0||r.length>0)&&this.announce(c,r)}finally{this.draining=!1}}}async importMarkdown(A){let t=A.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(A),{fm:i,body:s}=Dt(e),n=`${t}/${ra}`;await this.ensureFolder(n);let o=await this.uniquePath(n,A.name);if(await this.app.fileManager.renameFile(A,o),!(this.app.vault.getAbstractFileByPath(o)instanceof It.TFile))throw new Error(`archive move failed for ${A.path} \u2014 import aborted to avoid data loss`);let a={};for(let[p,g]of Object.entries(i))oe.includes(p)||(a[p]=g);a.id=pt(),a.parent=T;let r=this.preservedTimes(i,A);a.created=r.created,r.modified&&(a.modified=r.modified),a.attachments=Array.isArray(i.attachments)?i.attachments:[],i.author!==void 0&&(a.author=i.author),i.contributors!==void 0&&(a.contributors=i.contributors),a.imported=!0;let l=Mt(s)||A.basename,c=await this.uniquePath(t,Tt(l,a.id));return await this.createNote(c,le(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=pt(),o={id:n,parent:T,created:new Date().toISOString(),attachments:[Yt(i)],imported:!0},a=`${s} +${Kn.replace(/^> /gm,"")} +`)}),i}async function Ea(d){let{default:l}=await Promise.resolve().then(()=>Pi(vi())),t=new l;for(let e of d)t.file(e.name,e.data);return t.generateAsync({type:"uint8array",compression:"DEFLATE"})}function Ze(d,l){return d.toString(8).padStart(l-1,"0")+"\0"}function tl(d,l){let t=new Uint8Array(512),e=(s,n,o)=>{let a=Hs(s);t.set(a.subarray(0,o),n)};e(d.slice(0,100),0,100),e(Ze(420,8),100,8),e(Ze(0,8),108,8),e(Ze(0,8),116,8),e(Ze(l,12),124,12),e(Ze(0,12),136,12),e(" ",148,8),t[156]=48,e("ustar\0",257,6),e("00",263,2);let i=0;for(let s=0;s<512;s++)i+=t[s];return e(Ze(i,8),148,8),t}function el(d){let l=[],t=0;for(let s of d){let n=tl(s.name,s.data.length);l.push(n,s.data),t+=512+s.data.length;let o=(512-s.data.length%512)%512;o&&(l.push(new Uint8Array(o)),t+=o)}l.push(new Uint8Array(1024)),t+=1024;let e=new Uint8Array(t),i=0;for(let s of l)e.set(s,i),i+=s.length;return e}async function il(d){let l=new CompressionStream("gzip"),t=new Response(d).body.pipeThrough(l);return new Uint8Array(await new Response(t).arrayBuffer())}async function wa(d){return il(el(d))}var Ps=class{constructor(l,t,e){this.app=l;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 l=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let i of t)e=e?`${e}/${i}`:i,await l.exists(e)||await l.mkdir(e);this.dirOk=!0}append(l){let t=l.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...l};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 l=this.app.vault.adapter;if(!await l.exists(this.statePath))return{};try{return JSON.parse(await l.read(this.statePath))}catch{return{}}}async writeState(l){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(l,null,2))}};Qt();var Us=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(l){for(this.undoStack.push(l),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let l=this.undoStack.pop();if(!l)return null;try{await l.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(l),l}async redo(){let l=this.redoStack.pop();if(!l)return null;if(l.redo)try{await l.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(l),l}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 Rs=class{constructor(l,t){this.app=l;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 l=this.app.vault.adapter;if(await l.exists(this.path)){let t=JSON.parse(await l.read(this.path));t&&typeof t=="object"&&t.authors&&(this.data={version:typeof t.version=="number"?t.version:1,authors:t.authors})}}catch(l){console.warn("[Stashpad] author registry load failed; starting empty",l),this.data={version:1,authors:{}}}}}all(){return Object.values(this.data.authors).sort((l,t)=>(t.lastSeen??"").localeCompare(l.lastSeen??""))}get(l){return this.data.authors[l]??null}record(l){let t=(l.id??"").trim();if(!t)return!1;let e=l.at??new Date().toISOString(),i=(l.name??"").trim(),s=this.data.authors[t],n=!1;if(!s)this.data.authors[t]={id:t,name:i,role:l.role?.trim()||void 0,department:l.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),l.role!==void 0){let o=l.role.trim()||void 0;o!==s.role&&(s.role=o,n=!0)}if(l.department!==void 0){let o=l.department.trim()||void 0;o!==s.department&&(s.department=o,n=!0)}s.lastSeen=e}return n&&this.save(),n}replaceAll(l,t){let e=t??new Date().toISOString(),i={};for(let s of l){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 l=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 l.exists(i)||await l.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(l){console.warn("[Stashpad] author registry save failed",l)}}),this.writeChain}};var It=require("obsidian");Qt();Lt();Ue();Li();Ht();var Gs=new Set(["_attachments","_authors","_exports","_imports","_processed","_archive",".archive"]),va="_archive",Fa=new Set([ie,"edtz","stashenc","stashmeta"]),_e=class _e{constructor(l){this.plugin=l;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(l){this.armed=l}isArmed(){return this.armed}get app(){return this.plugin.app}enqueue(l){this.armed&&this.plugin.settings.autoImport&&this.isEligiblePath(l)&&(this.pending.set(l.path,Date.now()),this.arm())}enqueueFolder(l){if(!this.armed||!this.plugin.settings.autoImport||this.suppressed.has(l.path))return;let t=l.parent?.path?.replace(/\/+$/,"")??"";this.plugin.discoverStashpadFolders().includes(t)&&(Gs.has(l.name)||(this.pendingFolders.set(l.path,Date.now()),this.arm()))}arm(){this.drainTimer!=null&&window.clearTimeout(this.drainTimer),this.drainTimer=window.setTimeout(()=>void this.drain(),_e.DEBOUNCE_MS)}suppress(l,t=4e3){this.suppressed.add(l),window.setTimeout(()=>this.suppressed.delete(l),t)}async createNote(l,t){this.suppress(l,6e4),await this.app.vault.create(l,t)}isEligiblePath(l){if(this.suppressed.has(l.path)||Fa.has(l.extension))return!1;let t=l.parent?.path?.replace(/\/+$/,"")??"",e=t.split("/").pop()??"";return Gs.has(e)?!1:this.plugin.discoverStashpadFolders().includes(t)}async isStillImportable(l){if(!this.isEligiblePath(l))return!1;if(l.extension==="md")try{let{fm:t}=wt(await this.app.vault.read(l));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 l=[...this.pending.keys()];this.pending.clear();let t=l.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFile),e=[];for(let g of t)await this.isStillImportable(g)&&e.push(g);let i=[...this.pendingFolders.keys()];this.pendingFolders.clear();let s=i.map(g=>this.app.vault.getAbstractFileByPath(g)).filter(g=>g instanceof It.TFolder).map(g=>({folder:g,files:this.filesUnder(g.path)})).filter(g=>g.files.length>0),n=s.reduce((g,p)=>g+p.files.length,0),o=e.length+n;if(o===0)return;await this.plugin.importLog.load();let a=e,r=[],A=e.filter(g=>this.plugin.importLog.findDuplicate(g.name,g.stat?.size??null));if(A.length>0){let g=A.slice(0,5).map(u=>`\u2022 ${u.name}`).join(` +`),p=A.length>5?` +\u2026and ${A.length-5} more`:"",h=await this.dupChoice(`${A.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 u=new Set(A.map(I=>I.path));if(a=e.filter(I=>!u.has(I.path)),a.length===0&&s.length===0){new It.Notice(`Skipped ${A.length} duplicate file(s) \u2014 nothing new to import.`);return}}else if(h==="replace")for(let u of A){let I=this.plugin.importLog.findDuplicate(u.name,u.stat?.size??null);for(let f of I?.notePaths??[]){let m=this.app.vault.getAbstractFileByPath(f);if(m instanceof It.TFile)try{r.push({path:f,content:await this.app.vault.read(m)}),await this.app.fileManager.trashFile(m)}catch(C){console.warn("[Stashpad] replace: couldn't remove prior note",f,C)}}}}if(o=a.length+n,o>=_e.BATCH_CONFIRM_AT){let g=s.length?` (incl. ${s.length} folder${s.length===1?"":"s"})`:"";if(!await this.confirm("Import many files?",`You're about to auto-import ${o} files into Stashpad${g}. Proceed? +Markdown becomes notes (originals archived); other files move to _attachments with a linking note. Dropped folders move to _archive.`,"Import all")){new It.Notice(`Import cancelled \u2014 ${o} file(s) left as-is.`);return}}let c=[];for(let g of a)try{let p=g.stat?.size??null,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(l){let t=l.parent.path.replace(/\/+$/,""),e=await this.app.vault.read(l),{fm:i,body:s}=wt(e),n=`${t}/${va}`;await this.ensureFolder(n);let o=await this.uniquePath(n,l.name);if(await this.app.fileManager.renameFile(l,o),!(this.app.vault.getAbstractFileByPath(o)instanceof It.TFile))throw new Error(`archive move failed for ${l.path} \u2014 import aborted to avoid data loss`);let a={};for(let[g,p]of Object.entries(i))re.includes(g)||(a[g]=p);a.id=gt(),a.parent=T;let r=this.preservedTimes(i,l);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 A=Mt(s)||l.basename,c=await this.uniquePath(t,Tt(A,a.id));return await this.createNote(c,de(a,s)),{kind:"md",folder:t,archivePath:o,notePath:c,originalName:l.name}}async importOtherFile(l){let t=l.parent.path.replace(/\/+$/,""),e=`${t}/_attachments`;await this.ensureFolder(e);let i=await this.uniquePath(e,l.name);await this.app.fileManager.renameFile(l,i);let s=l.basename,n=gt(),o={id:n,parent:T,created:new Date().toISOString(),attachments:[zt(i)],imported:!0},a=`${s} ![[${i}]] -`,r=Mt(s)||s,l=await this.uniquePath(t,Tt(r,n));return await this.createNote(l,le(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}/${ra}`;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 p=this.app.metadataCache.getFileCache(c)?.frontmatter?.id;typeof p=="string"&&p&&o.add(p)}let a=[],r=[],l=await this.createFolderNote(t,e,T,r,o);return n instanceof It.TFolder&&await this.buildNotesFromArchive(n,t,l,r,o,a),a.length&&new It.Notice(`Stashpad: ${a.length} attachment name collision(s) renamed on import \u2014 check ![[links]] in the imported notes.`),{kind:"folder",folder:t,archivePath:s,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(A,t,e,i,s){let n=pt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Mt(t)||t,r=await this.uniquePath(A,Tt(a,n));return await this.createNote(r,le(o,`${t} -`)),i.push(r),n}async mergeReservedFolder(A,t,e){await this.ensureFolder(t);for(let i of[...A.children])if(i instanceof It.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof It.TFile){let s=`${t}/${i.name}`;await this.app.vault.adapter.exists(s)&&(s=await this.uniquePath(t,i.name),e.push(`${i.name} \u2192 ${s.split("/").pop()}`)),await this.app.fileManager.renameFile(i,s)}}async buildNotesFromArchive(A,t,e,i,s,n){for(let o of[...A.children])if(o instanceof It.TFolder)if(xs.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let a=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,a,i,s,n)}else if(o instanceof It.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:r,body:l}=Dt(a),c={};for(let[f,C]of Object.entries(r))oe.includes(f)||(c[f]=C);let p=typeof r.id=="string"&&r.id?r.id:null,g=p&&!s.has(p)?p:pt();s.add(g),c.id=g,c.parent=e;let d=this.preservedTimes(r,o);c.created=d.created,d.modified&&(c.modified=d.modified),c.attachments=Array.isArray(r.attachments)?r.attachments:[];let u=Mt(l)||o.basename,I=await this.uniquePath(t,Tt(u,c.id));await this.createNote(I,le(c,l)),i.push(I)}else{if(Aa.has(o.extension))continue;{let a=pt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[Yt(o.path)]},l=`${o.basename} +`,r=Mt(s)||s,A=await this.uniquePath(t,Tt(r,n));return await this.createNote(A,de(o,a)),{kind:"file",folder:t,attachmentPath:i,notePath:A,originalName:l.name}}preservedTimes(l,t){let e=n=>typeof n=="string"&&n.trim().length>0&&!Number.isNaN(Date.parse(n)),i=e(l.created)?l.created:t.stat?.ctime?new Date(t.stat.ctime).toISOString():new Date().toISOString(),s=e(l.modified)?l.modified:t.stat?.mtime?new Date(t.stat.mtime).toISOString():null;return{created:i,modified:s}}filesUnder(l){let t=l.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(e=>e.path.startsWith(t))}async importFolder(l){let t=l.parent.path.replace(/\/+$/,""),e=l.name,i=`${t}/${va}`;await this.ensureFolder(i);let s=await this.uniquePath(i,e);await this.app.fileManager.renameFile(l,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=[],A=await this.createFolderNote(t,e,T,r,o);return n instanceof It.TFolder&&await this.buildNotesFromArchive(n,t,A,r,o,a),a.length&&new It.Notice(`Stashpad: ${a.length} attachment name collision(s) renamed on import \u2014 check ![[links]] in the imported notes.`),{kind:"folder",folder:t,archivePath:s,notePaths:r,attachmentPaths:[],originalName:e}}async createFolderNote(l,t,e,i,s){let n=gt();s.add(n);let o={id:n,parent:e,created:new Date().toISOString(),attachments:[]},a=Mt(t)||t,r=await this.uniquePath(l,Tt(a,n));return await this.createNote(r,de(o,`${t} +`)),i.push(r),n}async mergeReservedFolder(l,t,e){await this.ensureFolder(t);for(let i of[...l.children])if(i instanceof It.TFolder)await this.mergeReservedFolder(i,`${t}/${i.name}`,e);else if(i instanceof It.TFile){let s=`${t}/${i.name}`;await this.app.vault.adapter.exists(s)&&(s=await this.uniquePath(t,i.name),e.push(`${i.name} \u2192 ${s.split("/").pop()}`)),await this.app.fileManager.renameFile(i,s)}}async buildNotesFromArchive(l,t,e,i,s,n){for(let o of[...l.children])if(o instanceof It.TFolder)if(Gs.has(o.name))await this.mergeReservedFolder(o,`${t}/${o.name}`,n);else{let a=await this.createFolderNote(t,o.name,e,i,s);await this.buildNotesFromArchive(o,t,a,i,s,n)}else if(o instanceof It.TFile)if(o.extension==="md"){let a=await this.app.vault.read(o),{fm:r,body:A}=wt(a),c={};for(let[f,m]of Object.entries(r))re.includes(f)||(c[f]=m);let g=typeof r.id=="string"&&r.id?r.id:null,p=g&&!s.has(g)?g:gt();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 u=Mt(A)||o.basename,I=await this.uniquePath(t,Tt(u,c.id));await this.createNote(I,de(c,A)),i.push(I)}else{if(Fa.has(o.extension))continue;{let a=gt(),r={id:a,parent:e,created:new Date().toISOString(),attachments:[zt(o.path)]},A=`${o.basename} ![[${o.path}]] -`,c=Mt(o.basename)||o.basename,p=await this.uniquePath(t,Tt(c,a));await this.createNote(p,le(r,l)),i.push(p)}}}recordNotePaths(A){return A.kind==="folder"?A.notePaths:[A.notePath]}announce(A,t=[]){let e=A[0]?.folder??"",i=A.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(A,t))};this.plugin.notifications.show({message:`Imported ${i} file${i===1?"":"s"}${s} into \`${e.split("/").pop()}\`.`,kind:"success",category:"import",duration:0,folder:e,affectedPaths:A.flatMap(a=>this.recordNotePaths(a)),actions:[{label:"Undo import",onClick:()=>void o()}]}),e&&this.plugin.getUndoStack(e).push({label:`Import ${i} file${i===1?"":"s"}`,undo:async()=>{await o()},redo:async()=>{}})}async undo(A,t=[]){for(let e of A)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else if(e.kind==="file"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else{for(let s of e.notePaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof It.TFolder){let s=await this.uniquePath(e.folder,e.originalName);this.suppress(s),await this.app.fileManager.renameFile(i,s)}}}catch(i){console.warn("[Stashpad] import undo failed",e,i)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(i){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,i)}new It.Notice(`Undid import of ${A.length} file(s).`)}pickFilesInto(A){let t=document.createElement("input");t.type="file",t.multiple=!0,t.style.display="none",t.onchange=async()=>{let e=Array.from(t.files??[]);if(t.remove(),e.length===0)return;let i=[];for(let n of e)try{let o=await n.arrayBuffer(),a=await this.uniquePath(A,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let r=this.app.vault.getAbstractFileByPath(a);r instanceof It.TFile&&i.push(r)}catch(o){console.warn("[Stashpad] file-picker write failed",n.name,o)}if(i.length===0)return;await this.plugin.importLog.load();let s=[];for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getFiles().filter(n=>(n.parent?.path?.replace(/\/+$/,"")??"")===t),i=[];for(let n of e)await this.isStillImportable(n)&&i.push(n);if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] loose-file import failed",n.path,o)}return s}async importLooseFoldersIn(A){let t=A.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof It.TFolder))return 0;let i=e.children.filter(n=>n instanceof It.TFolder&&!xs.has(n.name));if(i.length===0)return 0;await this.plugin.importLog.load();let s=0;for(let n of i){let o=n.path;try{let a=await this.importFolder(n);a&&a.kind==="folder"&&(s++,this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:null,sourcePath:o,notePaths:a.notePaths}))}catch(a){console.warn("[Stashpad] loose-folder import failed",o,a)}}return s}pendingEncryptedPaths(){for(let A of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(A)instanceof It.TFile||this.pendingEncryptedStashes.delete(A);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(A){this.pendingEncryptedStashes.delete(A)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(A){this.encryptedNotifySnoozeUntil=A===1/0?Number.MAX_SAFE_INTEGER:Date.now()+A}parkEncrypted(A){return this.pendingEncryptedStashes.has(A)?!1:(this.pendingEncryptedStashes.add(A),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let A=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof It.TFile))continue;let s=i.parent?.path?.replace(/\/+$/,"")??"";if(await this.importOneStash(i,s,this.liveRootIds(s),!1,{allowLater:!0,onLater:()=>{t=!0,this.snoozeEncryptedNotify(60*60*1e3)}})&&A++,t)break}return{imported:A,rescheduled:t}}liveRootIds(A){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==A)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(A,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(A));if(i&&qt(n))return this.pendingEncryptedStashes.add(A.path),!1;let o=await qe(this.app,n,{...s,secretId:ii(A.basename)});if(!o)return!1;let a=await Vt(this.app,o,t,e);if(a.colorAliases)for(let[r,l]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,r,l)}catch{}try{await this.app.fileManager.trashFile(A)}catch{}this.pendingEncryptedStashes.delete(A.path);try{await this.plugin.newLog().append({type:"stash_import",id:T,payload:{from:A.path,into:t,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,loose:!0}})}catch{}return!0}catch(n){return console.warn("[Stashpad] loose .stash import failed",A.path,n),!1}}async importLooseStashesIn(A,t={}){let e=A.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===Ae);if(i.length===0)return 0;let s=this.liveRootIds(e),n=0;for(let o of i)await this.importOneStash(o,e,s,!!t.auto)&&n++;return n}async importLooseInto(A,t={}){let e=await this.importLooseFilesIn(A),i=await this.importLooseFoldersIn(A),s=await this.importLooseStashesIn(A,t);return{files:e,folders:i,stashes:s}}defaultDestination(){let t=this.plugin.lastActiveStashpadLeaf?.view?.noteFolder;return t&&this.plugin.discoverStashpadFolders().includes(t)?t:this.plugin.discoverStashpadFolders()[0]??null}confirm(A,t,e){return new Promise(i=>{new Ft(this.app,A,t,e,i).open()})}dupChoice(A){return new Promise(t=>{new di(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 Ms=Ze;var Ts=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 Ps=class Ps{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()},Ps.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}};Ps.SAVE_DEBOUNCE_MS=8e3;var Hs=Ps;var Un="stashpad:unghost-after-reload",Us=class extends $.Plugin{constructor(){super(...arguments);this.settings={...he};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 Oi(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new Ns(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new Ms(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new Ts(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 Hs(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 Ds(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 p=await t.read(r);await t.write(c,p),console.debug("[Stashpad] migrated",r,"\u2192",c)}catch(p){console.warn(`Stashpad: failed to migrate ${r}`,p)}}}catch(a){console.warn("Stashpad: .stashpad migration scan failed",a)}}async loadData(){let t=this.app.vault.adapter,e=this.pluginPrivatePath("data.json");if(!await t.exists(e))return null;try{return JSON.parse(await t.read(e))}catch(i){return console.warn("Stashpad: data.json parse failed",i),null}}async saveData(t){let e=this.app.vault.adapter,i=this.pluginPrivatePath();if(!await e.exists(i)){let s=i.split("/").filter(Boolean),n="";for(let o of s)n=n?`${n}/${o}`:o,await e.exists(n)||await e.mkdir(n)}await e.write(this.pluginPrivatePath("data.json"),JSON.stringify(t,null,2))}async createNewStashpad(t){let e=t.trim().replace(/^\/+|\/+$/g,"");if(!e)throw new Error("Folder name is empty");let i=this.app.vault.adapter,s=e.split("/").filter(Boolean),n="";for(let l of s)n=n?`${n}/${l}`:l,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let l=this.app.vault.getAbstractFileByPath(o);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=T),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),r=["---",`id: ${T}`,"parent: null",`created: ${a}`,"---","Home"].join(` -`);await this.app.vault.create(o,r);try{await this.seedLocalAuthorStub(e)}catch{}try{await this.seedKnownAuthorsInFolder(e)}catch{}}collectColorsInFolder(t){let e=new Map,i=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==i&&!o.startsWith(i+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=typeof a?.color=="string"?a.color.trim():"";if(!r||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(r))continue;let l=r.toLowerCase();e.set(l,(e.get(l)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let r of this.app.vault.getMarkdownFiles()){let l=r.parent?.path?.replace(/\/+$/,"")??"";if(l!==s&&!l.startsWith(s+"/"))continue;let c=this.app.metadataCache.getFileCache(r)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===n)try{await this.app.fileManager.processFrontMatter(r,g=>{i?g.color=i:delete g.color}),o++}catch(g){console.warn(`Stashpad: recolor failed for ${r.path}`,g)}}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,p=typeof c?.id=="string"?c.id.trim():"";if(!p)continue;let g=c&&"parent"in c?c.parent??null:null;s[p]={parent:g,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 p=o[l];p?p.parent!==c.parent?await i.append({type:"parent_change",id:l,payload:{from:p.parent,to:c.parent}}):p.path!==c.path&&await i.append({type:"rename",id:l,payload:{from:p.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 bs,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),Nt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new ji(this.app,()=>({...yi(),...this.settings.encryption??{}}),async d=>{this.settings.encryption=d,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.settingTab=new As(this.app,this),this.addSettingTab(this.settingTab),await this.renderCacheStore.load(),this.registerEvent(this.app.vault.on("delete",d=>this.renderCacheStore.evict(d.path))),this.registerEvent(this.app.vault.on("rename",(d,u)=>this.renderCacheStore.evict(u))),await this.authorRegistry.load();{let d=(this.settings.authorId??"").trim();d&&this.authorRegistry.record({id:d,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment})}this.app.workspace.onLayoutReady(()=>{this.reconcileLockedRegistry(),window.setTimeout(()=>void this.checkDueReminders(),6e3),this.registerInterval(window.setInterval(()=>void this.checkDueReminders(),5*60*1e3)),window.setTimeout(()=>{this.seedLocalAuthorStubsEverywhere()},4e3),window.setTimeout(()=>this.syncObsidianExcludedArchives(),4500),window.setTimeout(()=>this.importService.setArmed(!0),2500),window.setTimeout(()=>void this.runAutoImportSweep(),5e3),this.registerInterval(window.setInterval(()=>void this.runAutoImportSweep(),5*60*1e3)),window.setTimeout(()=>void this.migratePinnedNotesToFrontmatter(),3e3),window.setTimeout(()=>void this.unghostStashpadTabsIfFlagged(),1200)}),this.registerView(ct,d=>new ws(d,this)),this.registerView(me,d=>new cs(d,this)),this.registerView(ne,d=>new Ui(d,this)),this.registerView(xe,d=>new Fs(d,this)),this.registerView(Ce,d=>new ks(d,this)),this.registerEvent(this.app.workspace.on("active-leaf-change",d=>{d&&d.view.getViewType()===ct&&(this.lastActiveStashpadLeaf=d,this.settings.autoOpenDetailPanel&&this.app.workspace.getLeavesOfType(me).length===0&&setTimeout(()=>{ds(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let d=ee(),u=!!d&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===d,I=!!u&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",I),document.body.classList.toggle("stashpad-active",!!u)};this.register(Lo(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=d=>{try{let u=Array.from(document.querySelectorAll("style")).filter(I=>(I.textContent??"").includes(".stashpad-"));for(let I of u){let f=I.id||"",C=f?`style[data-stashpad-source="${f}"]`:null;if(C&&d.head.querySelector(C))continue;let m=d.createElement("style");f?m.setAttribute("data-stashpad-source",f):m.setAttribute("data-stashpad-source","anon"),m.textContent=I.textContent??"",d.head.appendChild(m)}}catch(u){console.warn("[Stashpad] inject popout styles failed",u)}};this.registerEvent(this.app.workspace.on("window-open",d=>{let u=d?.doc??d?.win?.document??null;u&&e(u)})),this.registerEvent(this.app.workspace.on("file-menu",(d,u)=>{if(!(u instanceof $.TFolder))return;let I=u.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(I)&&d.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(I))})})),setTimeout(()=>{try{let d=this.app.workspace;typeof d.iterateAllLeaves=="function"&&d.iterateAllLeaves(u=>{let I=u?.view?.containerEl?.ownerDocument;I&&I!==document&&e(I)})}catch{}},200),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let i=window.visualViewport,s=()=>{let d=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),u=d&&d.isConnected?d.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${u}px`);let I=0;i&&(I=Math.max(0,window.innerHeight-i.height-i.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${I}px`),document.body.classList.toggle("stashpad-keyboard-open",I>100)};s(),i&&(i.addEventListener("resize",s),i.addEventListener("scroll",s),this.register(()=>{i.removeEventListener("resize",s),i.removeEventListener("scroll",s)})),window.addEventListener("resize",s),this.register(()=>window.removeEventListener("resize",s)),requestAnimationFrame(s),setTimeout(s,250),setTimeout(s,1e3),this.addRibbonIcon("list-tree","Open Stashpad",()=>{if(this.discoverStashpadFolders().length===0){this.activateView({reveal:!0});return}this.openFolderPicker()}).addEventListener("contextmenu",d=>{d.preventDefault(),this.openFolderPicker()}),this.addRibbonIcon("panel-left","Open Stashpad panels (sidebar)",()=>{Ri(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Ss(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{ds(this.app)}),this.addCommand({id:"stashpad-open",name:"Open Stashpad in new tab",callback:()=>{if(this.discoverStashpadFolders().length>=2){this.openFolderPicker();return}this.activateView({reveal:!1})}}),this.addCommand({id:"stashpad-reveal",name:"Reveal or open Stashpad",callback:()=>void this.activateView({reveal:!0})}),this.addCommand({id:"stashpad-focus-last-tab",name:"Focus last Stashpad tab",callback:()=>void this.focusLastStashpadTab()}),this.addCommand({id:"stashpad-focus-folder-panel",name:"Focus folder panel",callback:()=>void this.focusFolderPanel()}),this.addCommand({id:"stashpad-lock-encryption",name:"Lock encryption (forget password)",callback:()=>{if(!this.encryption.isConfigured()){new $.Notice("Encryption isn't set up.");return}this.encryption.lock(),new $.Notice("Encryption locked.")}});let o=d=>{let u=ee();u&&typeof u[d]=="function"&&u[d]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>o("toggleSplit")}),this.addCommand({id:"stashpad-command-palette",name:"Command palette (Stashpad only)",callback:()=>o("openStashpadCommandPalette")}),this.addCommand({id:"stashpad-lock-selection",name:"Encrypt (lock) selection (notes + children)",callback:()=>o("cmdLockSelection")}),this.addCommand({id:"stashpad-unlock-all",name:"Decrypt (unlock) locked notes in view",callback:()=>o("cmdUnlockAll")}),this.addCommand({id:"stashpad-unlock-all-vault",name:"Decrypt (unlock) ALL locked notes in the vault",callback:()=>void this.unlockAllInVault()}),this.addCommand({id:"stashpad-copy-notes",name:"Copy notes (note clipboard \u2014 paste to duplicate)",callback:()=>o("cmdCopyNotes")}),this.addCommand({id:"stashpad-cut-notes",name:"Cut notes (paste in list to move, in composer to extract text)",callback:()=>o("cmdCutNotes")}),this.addCommand({id:"stashpad-paste-notes",name:"Paste notes (from the note clipboard)",callback:()=>o("cmdPasteNotes")}),this.addCommand({id:"stashpad-move-to-archive",name:"Move selection to archive (encrypt)",callback:()=>o("cmdMoveToArchive")}),this.addCommand({id:"stashpad-encrypt-delete",name:"Encrypt & delete selection (to encrypted trash)",callback:()=>o("cmdEncryptDelete")}),this.addCommand({id:"stashpad-restore-trash",name:"Open encrypted trash (restore deleted)\u2026",callback:()=>this.openEncryptedTrash()}),this.addCommand({id:"stashpad-encrypt-existing-trash",name:"Encrypt existing Obsidian trash (backfill .trash into encrypted trash)",callback:()=>void this.encryptExistingTrash()}),this.addCommand({id:"stashpad-close-duplicate-tabs",name:"Close duplicate & orphaned Stashpad tabs (tidy up)",callback:()=>void this.closeDuplicateStashpadTabs()}),this.addCommand({id:"stashpad-claim-selected-author",name:"Claim authorship of selected notes",callback:()=>o("claimSelectedAsAuthor")}),this.addCommand({id:"stashpad-claim-folder-author",name:"Claim authorship of all unauthored notes in this folder",callback:()=>o("claimFolderAsAuthor")}),this.addCommand({id:"stashpad-claim-selected-contributor",name:"Claim selected notes (author if unowned, else add me as contributor)",callback:()=>o("claimSelectedWithContributor")}),this.addCommand({id:"stashpad-claim-folder-contributor",name:"Claim all notes in this folder (author if unowned, else add me as contributor)",callback:()=>o("claimFolderWithContributor")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>o("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>o("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>o("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>o("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>o("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>o("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>o("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>o("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>o("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>o("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>o("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>o("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>o("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>o("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>o("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>o("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>o("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>o("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>o("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>o("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>o("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>o("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>o("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>o("cmdToggleComplete")}),this.addCommand({id:"stashpad-toggle-task",name:"Toggle task (todo)",callback:()=>o("cmdToggleTask")}),this.addCommand({id:"stashpad-set-due",name:"Set due date\u2026",callback:()=>o("cmdSetDue")}),this.addCommand({id:"stashpad-dump-perf",name:"Dump performance profile (copy to clipboard)",callback:async()=>{if(!this.settings.enablePerfProfiling){new $.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let d=Nt.report();console.log(d);try{await navigator.clipboard.writeText(d)}catch{}new $.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{Nt.reset(),new $.Notice("Performance profile reset.")}}),this.addCommand({id:"stashpad-jump-to-top",name:"Jump to top of list",callback:()=>o("jumpToTop")}),this.addCommand({id:"stashpad-jump-to-bottom",name:"Jump to bottom of list",callback:()=>o("jumpToBottom")}),this.addCommand({id:"stashpad-assign",name:"Assign task to\u2026",callback:()=>o("cmdAssign")}),this.addCommand({id:"stashpad-open-import-log",name:"Open import log",callback:async()=>{await this.importLog.load();let{ImportLogModal:d}=await Promise.resolve().then(()=>(Ht(),hi));new d(this.app,this.importLog.recent()).open()}}),this.addCommand({id:"stashpad-import-files",name:"Import file(s) into Stashpad\u2026",callback:()=>this.openImportPicker()}),this.addCommand({id:"stashpad-import-loose-files",name:"Import loose files & folders in this folder (scan for moved-in / unprocessed items)",checkCallback:d=>{let u=this.importService.defaultDestination();return d?!!u:(u&&this.runImportLooseFiles(u),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:d=>{let u=this.importService.defaultDestination();return d?!!u:(u&&this.runFolderSlugPass(u),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:d=>{let u=this.importService.defaultDestination();return d?!!u:(u&&this.runFolderFrontmatterBackfill(u),!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 Ri(this.app)}),this.addCommand({id:"stashpad-open-folder-panel",name:"Open folder panel (sidebar)",callback:()=>void Ss(this.app)}),this.addCommand({id:"stashpad-open-detail",name:"Open Stashpad detail panel (right sidebar)",callback:()=>void ds(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:d=>{let u=this.app.workspace.getActiveFile(),I=!!u&&u.extension==="md"&&this.isStashpadNoteFile(u);return d||I&&u&&this.revealNoteInStashpad(u),I}});let a=Object.keys(gi);for(let d of a){let u=gi[d];this.addCommand({id:`stashpad-open-panels-${d}`,name:`Open Stashpad panel: ${u.label}`,callback:async()=>{await Ri(this.app),this.app.workspace.getLeavesOfType(ne)[0]?.view?.setActivePanel?.(d)}})}this.addCommand({id:"stashpad-swap-with-parent",name:"Swap with parent (ouroboros)",callback:()=>o("cmdSwapWithParent")}),this.addCommand({id:"stashpad-toggle-pin",name:"Pin / unpin selected note (sidebar)",callback:()=>o("cmdTogglePin")}),this.addCommand({id:"stashpad-open-tiny",name:"Open Stashpad in tiny window",callback:()=>void this.openTinyWindow()}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>o("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>o("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>o("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>o("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>o("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Stashpad: open / switch / create folder\u2026",callback:()=>this.openFolderPicker()}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:d=>{let u=ee(),I=u&&u.noteFolder;return I?(d||(new $.Notice(`Running integrity check on "${I}"\u2026`),this.runIntegrityCheckOnFolder(I).then(()=>{new $.Notice("Integrity check complete \u2014 see Stashpad log.")})),!0):!1}}),this.addCommand({id:"stashpad-fix-orphans",name:"Set missing parents to Home (orphan fix)",callback:()=>void this.fixOrphanParents()}),this.addCommand({id:"stashpad-rebuild-author-registry",name:"Rebuild author registry (scan authors + note frontmatter)",callback:async()=>{new $.Notice("Stashpad: rebuilding author registry\u2026");try{let d=await this.rebuildAuthorRegistry();this.notifications.show({message:`Author registry rebuilt: ${d.total} author(s) \u2014 ${d.fromStubs} from stubs, ${d.fromNotes} from note links.`,kind:"success",category:"system"})}catch(d){new $.Notice(`Author registry rebuild failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new $.Notice("Stashpad: restoring author stubs\u2026");try{let d=await this.restoreMissingAuthorStubs();this.notifications.show({message:d.created>0?`Restored ${d.created} author stub(s) across ${d.folders} folder(s).`:`No missing author stubs \u2014 all present across ${d.folders} folder(s).`,kind:"success",category:"system"})}catch(d){new $.Notice(`Restore author stubs failed: ${d.message}`)}}}),this.addCommand({id:"stashpad-sync-authors",name:"Sync authors across all folders (multiplayer)",callback:()=>void this.syncAuthorsAcrossFolders()}),this.addCommand({id:"stashpad-rebootstrap-all",name:"Rebootstrap all Stashpad folders (backfill metadata + rename stale titles)",callback:async()=>{new $.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:d,fmChecked:u,fmWritten:I,slugsRenamed:f,authors:C,imported:m,attachmentsLinked:y}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${d.length} folder${d.length===1?"":"s"}`),m>0&&w.push(`imported ${m} loose file${m===1?"":"s"}`),y>0&&w.push(`linked attachments on ${y} note${y===1?"":"s"}`),I>0&&w.push(`updated ${I} note${I===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 ${u} total)`),new $.Notice(`Stashpad: ${w.join(" \xB7 ")}`)}catch(d){new $.Notice(`Stashpad: rebootstrap failed (${d.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:d=>{let u=this.app.workspace.getActiveFile();return!u||u.extension!=="md"?!1:(d||this.adoptNote(u),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ht(),hi)).then(({NotificationHistoryModal:d,LogModal:u})=>{new d(this.app,this.notifications,async()=>{let I=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await I.exists(f)){new $.Notice("No log yet \u2014 make some changes first.");return}let C=await I.read(f);new u(this.app,C,f).open()},this.settings.authorId||null,I=>this.lookupNoteAuthorIds(I)).open()})}});let r=[{key:"prefixTimestampsOnCopy",label:"Prefix timestamps when copying"},{key:"useTemplatesFormat",label:"Use Templates plugin date/time formats"},{key:"autoNavOnMoveIn",label:"Auto-navigate into parent on move IN"},{key:"autoNavOnMoveOut",label:"Auto-navigate to destination on move OUT"},{key:"confirmCrossParentDrag",label:"Confirm cross-parent drag-and-drop"},{key:"confirmBulkDelete",label:"Confirm bulk deletes"},{key:"confirmAttachmentDelete",label:"Offer to delete attachments with note"},{key:"autofocusComposerAfterSend",label:"Autofocus composer after sending"},{key:"popoutDuplicates",label:"Open in new window \u2014 duplicate tab"},{key:"autoExpandCursorRow",label:"Expand the cursor row's body automatically"},{key:"autoOpenDetailPanel",label:"Auto-open the detail panel"},{key:"doubleClickToFocus",label:"Double-click a note to open it"}];for(let d of r){let u=`stashpad-toggle-${String(d.key).replace(/[A-Z]/g,I=>`-${I.toLowerCase()}`)}`;this.addCommand({id:u,name:`Toggle: ${d.label}`,callback:async()=>{let I=!this.settings[d.key];this.settings[d.key]=I,await this.saveSettings(),new $.Notice(`${d.label}: ${I?"ON":"OFF"}`)}})}this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id))}}),this.addCommand({id:"stashpad-search-settings",name:"Search Stashpad settings\u2026",callback:()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{d?.modalEl?.querySelector?.("input[type='search']")?.focus()},0))}});for(let d of rs)this.addCommand({id:`stashpad-open-settings-${d.id}`,name:`Open Stashpad settings: ${d.label}`,callback:()=>{let u=this.app.setting;!u?.open||!u?.openTabById||(u.open(),u.openTabById(this.manifest.id))}});let l=()=>{let d=this.app.setting;!d?.open||!d?.openTabById||(d.open(),d.openTabById(this.manifest.id),setTimeout(()=>{document.getElementById("stashpad-jd-index-section")?.scrollIntoView({behavior:"smooth",block:"start"})},100))};this.addCommand({id:"stashpad-preview-jd-index",name:"Preview JD index (overwrites home note body)",callback:async()=>{try{let{buildJdIndexPreview:d}=await Promise.resolve().then(()=>(ui(),Ji)),u=await d(this.app,this,this.settings);if(u.error==="no-dest"){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(u.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:I}=await Promise.resolve().then(()=>(ui(),Ji));I(this.app,u)}catch(d){console.error("[stashpad] preview failed",d),new $.Notice(`Preview failed: ${d?.message??d}`,8e3)}}}),this.addCommand({id:"stashpad-build-jd-index",name:"Build JD index notes (creates Stashpad-note hierarchy)",callback:async()=>{try{let{buildJdIndexNotes:d,scanForJdNotes:u,JdBuildConfirmModal:I}=await Promise.resolve().then(()=>(ui(),Ji));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}let C=u(this.app,this,this.settings);new I(this.app,this,this.settings,C.indexed.length,async()=>{try{let y=await d(this.app,this,this.settings);if(y.error==="no-dest"){new $.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),l();return}if(y.error==="dest-not-stashpad"){new $.Notice(`"${y.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: ${y.created} created, ${y.updated} updated, ${y.skipped} skipped \u2192 ${y.destFolder}`,6e3)}catch(y){console.error("[stashpad] build failed",y),new $.Notice(`Build failed: ${y?.message??y}`,8e3)}}).open()}catch(d){console.error("[stashpad] build failed",d),new $.Notice(`Build failed: ${d?.message??d}`,8e3)}}});let c=d=>{if(d.extension!==Ae)return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),I=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=d.parent?.path||"",C=f.split("/").pop()??"";if(u&&C===u){if(I&&f.endsWith(`/${I}`))return;let m=f.slice(0,f.length-u.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(d,m);return}this.settings.autoImport&&this.importService.isArmed()&&(Te(d.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(d,f))};this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile&&c(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile&&c(d)}));let p=d=>{if(d.extension!=="md")return;let u=d.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(u)&&setTimeout(()=>{this.fixOrphanParentForFile(d)},800)},g=d=>{if(d.extension!=="md")return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!u)return;let I=d.parent?.path?.replace(/\/+$/,"")??"";if((I.split("/").pop()??"")!==u)return;let C=I.slice(0,I.length-u.length).replace(/\/+$/,"");!C||!this.discoverStashpadFolders().includes(C)||setTimeout(()=>{this.adoptMarkdownDrop(d,C)},200)};this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile&&(p(d),g(d))})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile&&(p(d),g(d))})),this.registerEvent(this.app.vault.on("delete",d=>{if(!(d instanceof $.TFolder))return;let u=d.path.replace(/\/+$/,"");this.knownStashpadFolders.has(u)&&this.handleStashpadFolderDeleted(u)})),this.registerEvent(this.app.vault.on("rename",(d,u)=>{d instanceof $.TFile&&this.maybeReHomeOnCrossFolderMove(d,u)})),this.registerEvent(this.app.vault.on("rename",(d,u)=>{d instanceof $.TFile&&this.maybeArchiveOnMoveIn(d,u)})),this.registerEvent(this.app.vault.on("create",d=>{d instanceof $.TFile?this.importService.enqueue(d):d instanceof $.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",d=>{d instanceof $.TFile?this.importService.enqueue(d):d instanceof $.TFolder&&this.importService.enqueueFolder(d)})),this.registerEvent(this.app.vault.on("rename",(d,u)=>{d instanceof $.TFile&&this.maybeAdoptAuthorRename(d,u)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(Un,"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(Un)==="1"}catch{}if(t){try{window.localStorage?.removeItem(Un)}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(()=>(Gt(),Hi)),p,g=!1,d=!1;if(await this.app.fileManager.processFrontMatter(t,f=>{if(a&&(typeof f.id=="string"&&f.id.trim()||(p=c(),f.id=p)),r){let C=f.parent;(typeof C=="string"?C.trim()!=="":C!=null)||(f.parent=T,g=!0)}l&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),d=!0))}),!p&&!g&&!d)return;let u=this.newLog(),I=p||i;I&&await u.append({type:"parent_change",id:I,payload:{from:null,to:T,reason:"orphan_auto_fix",path:t.path,addedId:!!p,addedParent:g,addedCreated:d}}),new $.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}maybeReHomeOnCrossFolderMove(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");i!==n&&this.discoverStashpadFolders().includes(i)&&(this.reHomePending.has(t.path)||(this.reHomePending.add(t.path),setTimeout(()=>{this.reHomePending.delete(t.path),this.reHomeDanglingParent(t,i)},900)))}async reHomeDanglingParent(t,e){try{let i=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof i?.id=="string"?i.id.trim():"",n=typeof i?.parent=="string"?i.parent.trim():"";if(!s||!n||n===T||this.app.vault.getMarkdownFiles().some(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(a)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,a=>{let r=typeof a.parent=="string"?a.parent.trim():"";r&&r!==T&&(a.parent=T)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:T,reason:"rehome_cross_folder_move",path:t.path}}),new $.Notice(`Re-homed ${t.basename} \u2192 Home (its parent isn't in this folder)`)}catch(i){console.warn("[Stashpad] re-home on cross-folder move failed",i)}}async autoImportStash(t,e){try{let i=new Uint8Array(await this.app.vault.readBinary(t));if(qt(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await qe(this.app,i);if(!s)return;let n=ee(),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 Vt(this.app,s,e,o);try{await this.newLog().append({type:"stash_import",id:T,payload:{from:t.path,into:e,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let r=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&r.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&r.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:r.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed +`,c=Mt(o.basename)||o.basename,g=await this.uniquePath(t,Tt(c,a));await this.createNote(g,de(r,A)),i.push(g)}}}recordNotePaths(l){return l.kind==="folder"?l.notePaths:[l.notePath]}announce(l,t=[]){let e=l[0]?.folder??"",i=l.length,s=t.length?`, replaced ${t.length}`:"",n=!1,o=async()=>{n||(n=!0,await this.undo(l,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:l.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(l,t=[]){for(let e of l)try{if(e.kind==="md"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.archivePath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else if(e.kind==="file"){let i=this.app.vault.getAbstractFileByPath(e.notePath);i instanceof It.TFile&&await this.app.fileManager.trashFile(i);let s=this.app.vault.getAbstractFileByPath(e.attachmentPath);if(s instanceof It.TFile){let n=await this.uniquePath(e.folder,e.originalName);this.suppress(n),await this.app.fileManager.renameFile(s,n)}}else{for(let s of e.notePaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}for(let s of e.attachmentPaths){let n=this.app.vault.getAbstractFileByPath(s);n instanceof It.TFile&&await this.app.fileManager.trashFile(n)}let i=this.app.vault.getAbstractFileByPath(e.archivePath);if(i instanceof It.TFolder){let s=await this.uniquePath(e.folder,e.originalName);this.suppress(s),await this.app.fileManager.renameFile(i,s)}}}catch(i){console.warn("[Stashpad] import undo failed",e,i)}for(let e of t)try{await this.app.vault.adapter.exists(e.path)||await this.app.vault.create(e.path,e.content)}catch(i){console.warn("[Stashpad] import undo: couldn't restore replaced note",e.path,i)}new It.Notice(`Undid import of ${l.length} file(s).`)}pickFilesInto(l){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(l,n.name);this.suppress(a,6e4),await this.app.vault.createBinary(a,o);let r=this.app.vault.getAbstractFileByPath(a);r instanceof It.TFile&&i.push(r)}catch(o){console.warn("[Stashpad] file-picker write failed",n.name,o)}if(i.length===0)return;await this.plugin.importLog.load();let s=[];for(let n of i)try{let o=n.stat?.size??null,a=n.extension==="md"?await this.importMarkdown(n):await this.importOtherFile(n);a&&(s.push(a),this.plugin.importLog.append({ts:new Date().toISOString(),folder:a.folder,kind:a.kind,originalName:n.name,size:o,sourcePath:n.path,notePaths:a.kind==="folder"?a.notePaths:[a.notePath]}))}catch(o){console.warn("[Stashpad] file-picker import failed",n.path,o)}s.length>0&&this.announce(s,[])},document.body.appendChild(t),t.click()}async importLooseFilesIn(l){let t=l.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(l){let t=l.replace(/\/+$/,""),e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof It.TFolder))return 0;let i=e.children.filter(n=>n instanceof It.TFolder&&!Gs.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 l of[...this.pendingEncryptedStashes])this.app.vault.getAbstractFileByPath(l)instanceof It.TFile||this.pendingEncryptedStashes.delete(l);return[...this.pendingEncryptedStashes]}clearPendingEncrypted(l){this.pendingEncryptedStashes.delete(l)}shouldNotifyEncrypted(){return Date.now()>=this.encryptedNotifySnoozeUntil}snoozeEncryptedNotify(l){this.encryptedNotifySnoozeUntil=l===1/0?Number.MAX_SAFE_INTEGER:Date.now()+l}parkEncrypted(l){return this.pendingEncryptedStashes.has(l)?!1:(this.pendingEncryptedStashes.add(l),this.encryptedNotifySnoozeUntil=0,!0)}async importPendingEncrypted(){let l=0,t=!1;for(let e of this.pendingEncryptedPaths()){let i=this.app.vault.getAbstractFileByPath(e);if(!(i instanceof It.TFile))continue;let s=i.parent?.path?.replace(/\/+$/,"")??"";if(await this.importOneStash(i,s,this.liveRootIds(s),!1,{allowLater:!0,onLater:()=>{t=!0,this.snoozeEncryptedNotify(60*60*1e3)}})&&l++,t)break}return{imported:l,rescheduled:t}}liveRootIds(l){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){if((e.parent?.path?.replace(/\/+$/,"")??"")!==l)continue;let i=this.app.metadataCache.getFileCache(e)?.frontmatter?.id;typeof i=="string"&&i&&t.add(i)}return t}async importOneStash(l,t,e,i,s={}){try{let n=new Uint8Array(await this.app.vault.readBinary(l));if(i&&Ot(n))return this.pendingEncryptedStashes.add(l.path),!1;let o=await qe(this.app,n,{...s,secretId:si(l.basename)});if(!o)return!1;let a=await $t(this.app,o,t,e);if(a.colorAliases)for(let[r,A]of Object.entries(a.colorAliases))try{await this.plugin.setColorAlias(t,r,A)}catch{}try{await this.app.fileManager.trashFile(l)}catch{}this.pendingEncryptedStashes.delete(l.path);try{await this.plugin.newLog().append({type:"stash_import",id:T,payload:{from:l.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",l.path,n),!1}}async importLooseStashesIn(l,t={}){let e=l.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>(o.parent?.path?.replace(/\/+$/,"")??"")===e&&o.extension===ie);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(l,t={}){let e=await this.importLooseFilesIn(l),i=await this.importLooseFoldersIn(l),s=await this.importLooseStashesIn(l,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(l,t,e){return new Promise(i=>{new kt(this.app,l,t,e,i).open()})}dupChoice(l){return new Promise(t=>{new hi(this.app,l,t).open()})}async ensureFolder(l){let t=this.app.vault.adapter,e=l.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(l,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=`${l}/${t}`,a=0;for(;await e.exists(o);)a+=1,o=`${l}/${s}-${a}${n}`;return o}};_e.DEBOUNCE_MS=900,_e.BATCH_CONFIRM_AT=8;var Ls=_e;var Js=class{constructor(l,t){this.app=l;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 l=this.app.vault.adapter;if(await l.exists(this.path)){let t=await l.read(this.path);for(let e of t.split(/\r?\n/))if(e.trim())try{this.entries.push(JSON.parse(e))}catch{}}}catch(l){console.warn("[Stashpad] import log load failed",l)}}}recent(){return[...this.entries].reverse()}findDuplicate(l,t){for(let e=this.entries.length-1;e>=0;e--){let i=this.entries[e];if(i.originalName===l&&(t==null||i.size==null||i.size===t))return i}return null}append(l){this.entries.push(l),this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir(),await this.app.vault.adapter.append(this.path,JSON.stringify(l)+` +`)}catch(t){console.warn("[Stashpad] import log append failed",t)}})}async ensureDir(){if(this.dirOk)return;let l=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 l.exists(i)||await l.mkdir(i);this.dirOk=!0}};var Os=class Os{constructor(l,t){this.app=l;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 l=this.app.vault.adapter;if(await l.exists(this.path)){let t=JSON.parse(await l.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(l){console.warn("[Stashpad] render cache load failed; starting empty",l),this.map.clear()}}}evict(l){this.map.delete(l)&&(this.dirty=!0,this.save())}get(l){return this.map.get(l)}has(l){return this.map.has(l)}set(l,t){this.map.set(l,t),this.dirty=!0,this.scheduleSave()}scheduleSave(){this.saveTimer==null&&(this.saveTimer=window.setTimeout(()=>{this.saveTimer=null,this.save()},Os.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 l={schema:1,entries:Object.fromEntries(this.map)};await this.app.vault.adapter.write(this.path,JSON.stringify(l))}catch(l){console.warn("[Stashpad] render cache save failed",l)}}),this.writeChain):this.writeChain}async ensureDir(){if(this.dirOk)return;let l=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 l.exists(i)||await l.mkdir(i);this.dirOk=!0}};Os.SAVE_DEBOUNCE_MS=8e3;var qs=Os;var zn="stashpad:unghost-after-reload",Ks=class extends X.Plugin{constructor(){super(...arguments);this.settings={...ue};this.undoStacks=new Map;this.lastActiveStashpadLeaf=null;this.rebootstrapInProgress=!1;this.suppressComposerAutofocusUntil=0;this.settingTab=null;this.stashpadSelectionListeners=new Set;this.stashpadContentListeners=new Set;this._notifications=null;this._authorRegistry=null;this._importService=null;this._importLog=null;this.noteClipboard=null;this.noteClipboardNotice=null;this._renderCacheStore=null;this.knownStashpadFolders=new Set;this.suppressedFolderDeletes=new Set;this.sweptFolders=new Set;this.notifiedBuildVersion=null;this.authorRenameInFlight=new Set;this.reHomePending=new Set;this.okfRebuildTimers=new Map;this.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 Wi(this.app)),this._notifications}get authorRegistry(){return this._authorRegistry||(this._authorRegistry=new Rs(this.app,this.pluginPrivatePath())),this._authorRegistry}get importService(){return this._importService||(this._importService=new Ls(this)),this._importService}get importLog(){return this._importLog||(this._importLog=new Js(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 qs(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 Ps(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 A of a)r=r?`${r}/${A}`:A,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 A=r.replace(/^.*\//,""),c=this.pluginPrivatePath(A);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 A of s)n=n?`${n}/${A}`:A,await i.exists(n)||await i.mkdir(n);let o=`${e}/Home.md`;if(await i.exists(o)){let A=this.app.vault.getAbstractFileByPath(o);A&&await this.app.fileManager.processFrontMatter(A,c=>{(typeof c.id!="string"||!c.id)&&(c.id=T),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),r=["---",`id: ${T}`,"parent: null",`created: ${a}`,"---","Home"].join(` +`);await this.app.vault.create(o,r);try{await this.seedLocalAuthorStub(e)}catch{}try{await this.seedKnownAuthorsInFolder(e)}catch{}}collectColorsInFolder(t){let e=new Map,i=t.replace(/\/+$/,"");for(let n of this.app.vault.getMarkdownFiles()){let o=n.parent?.path?.replace(/\/+$/,"")??"";if(o!==i&&!o.startsWith(i+"/"))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter,r=typeof a?.color=="string"?a.color.trim():"";if(!r||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(r))continue;let A=r.toLowerCase();e.set(A,(e.get(A)??0)+1)}let s=[...e.entries()].map(([n,o])=>({hex:n,count:o}));return s.sort((n,o)=>o.count-n.count||n.hex.localeCompare(o.hex)),s}async recolorAllInFolder(t,e,i){let s=t.replace(/\/+$/,""),n=e.toLowerCase(),o=0;for(let r of this.app.vault.getMarkdownFiles()){let A=r.parent?.path?.replace(/\/+$/,"")??"";if(A!==s&&!A.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(A){console.warn("[Stashpad] couldn't ensure .trash",A)}let o=`${n}/${i}`;for(let A=1;await s.exists(o);A++)o=`${n}/${i} (${A})`;this.suppressedFolderDeletes.add(e),window.setTimeout(()=>this.suppressedFolderDeletes.delete(e),5e3);let a=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);try{await s.rename(e,o)}catch(A){console.warn("[Stashpad] folder delete failed",A),this.suppressedFolderDeletes.delete(e),new X.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 X.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 X.Notice(`Restored \u201C${i}\u201D.`),this.activateViewForFolder(e)}catch(A){console.warn("[Stashpad] folder undo failed",A),new X.Notice("Undo failed (see console).")}}}]})}async handleStashpadFolderDeleted(t){let e=t.replace(/\/+$/,"");if(!e||this.suppressedFolderDeletes.has(e))return;let i=this.closeStashpadTabsFor(e);await this.prunePlacementFor(e),this.knownStashpadFolders.delete(e);let s=e.split("/").pop()||e;this.notifications.show({message:i>0?`Stashpad \u201C${s}\u201D was deleted \u2014 closed ${i} open tab${i===1?"":"s"}.`:`Stashpad \u201C${s}\u201D was deleted.`,kind:"warning",category:"delete",folder:e})}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),i=new Set(this.settings.searchExcludedFolders),s=new Set((this.settings.archiveFolders??[]).map(A=>(A??"").replace(/\/+$/,""))),o=this.discoverStashpadFolders().filter(A=>s.has(A)?!1:e.size>0?e.has(A):!i.has(A)),a=(t||"").trim().replace(/\/+$/,""),r=o.filter(A=>A!==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(A=>A.path===t||A.path.startsWith(t+"/"));for(let A of n){let c=this.app.metadataCache.getFileCache(A)?.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:A.path}}let o=await i.readState(),a=A=>A===t||A.startsWith(t+"/");if(!e.silent){for(let[A,c]of Object.entries(s)){let g=o[A];g?g.parent!==c.parent?await i.append({type:"parent_change",id:A,payload:{from:g.parent,to:c.parent}}):g.path!==c.path&&await i.append({type:"rename",id:A,payload:{from:g.path,to:c.path}}):await i.append({type:"create",id:A,payload:{path:c.path,parent:c.parent}})}for(let[A,c]of Object.entries(o))!s[A]&&a(c.path)&&await i.append({type:"missing",id:A,payload:{lastPath:c.path}})}let r={};for(let[A,c]of Object.entries(o))a(c.path)||(r[A]=c);for(let[A,c]of Object.entries(s))r[A]=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 Us,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),xt.enabled=!!this.settings.enablePerfProfiling,this.encryption=new os(this.app,()=>({...wi(),...this.settings.encryption??{}}),async h=>{this.settings.encryption=h,await this.saveSettings()},()=>this.settings.encryptionIdleLockMinutes??0),this.encryption.init().then(()=>this.encryption.tryAutoUnlock()),this.settingTab=new ps(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,u)=>this.renderCacheStore.evict(u))),this.registerEvent(this.app.vault.on("create",h=>this.onOkfFileEvent(h.path))),this.registerEvent(this.app.vault.on("delete",h=>this.onOkfFileEvent(h.path))),this.registerEvent(this.app.vault.on("rename",(h,u)=>{this.onOkfFileEvent(h.path),this.onOkfFileEvent(u)})),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 Ds(h,this)),this.registerView(Qe,h=>new us(h,this)),this.registerView(ae,h=>new Oi(h,this)),this.registerView(Ne,h=>new xs(h,this)),this.registerView(Be,h=>new Ns(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(Qe).length===0&&setTimeout(()=>{Is(this.app)},0),this.notifyStashpadSelectionChanged())}));let t=()=>{let h=se(),u=!!h&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===h,I=!!u&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",I),document.body.classList.toggle("stashpad-active",!!u)};this.register(Wo(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t));let e=h=>{try{let u=Array.from(document.querySelectorAll("style")).filter(I=>(I.textContent??"").includes(".stashpad-"));for(let I of u){let f=I.id||"",m=f?`style[data-stashpad-source="${f}"]`:null;if(m&&h.head.querySelector(m))continue;let C=h.createElement("style");f?C.setAttribute("data-stashpad-source",f):C.setAttribute("data-stashpad-source","anon"),C.textContent=I.textContent??"",h.head.appendChild(C)}}catch(u){console.warn("[Stashpad] inject popout styles failed",u)}};this.registerEvent(this.app.workspace.on("window-open",h=>{let u=h?.doc??h?.win?.document??null;u&&e(u)})),this.registerEvent(this.app.workspace.on("file-menu",(h,u)=>{if(!(u instanceof X.TFolder))return;let I=u.path.replace(/\/+$/,"");this.discoverStashpadFolders().includes(I)&&h.addItem(f=>{f.setTitle("Open folder in Stashpad").setIcon("layout-list").onClick(()=>void this.openFolderInStashpad(I))})})),setTimeout(()=>{try{let h=this.app.workspace;typeof h.iterateAllLeaves=="function"&&h.iterateAllLeaves(u=>{let I=u?.view?.containerEl?.ownerDocument;I&&I!==document&&e(I)})}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"),u=h&&h.isConnected?h.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${u}px`);let I=0;i&&(I=Math.max(0,window.innerHeight-i.height-i.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${I}px`),document.body.classList.toggle("stashpad-keyboard-open",I>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)",()=>{Ki(this.app)}),this.addRibbonIcon("folders","Open Stashpad folder panel (sidebar)",()=>{Ms(this.app)}),this.addRibbonIcon("panel-right","Open Stashpad detail panel (right sidebar)",()=>{Is(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 X.Notice("Encryption isn't set up.");return}this.encryption.lock(),new X.Notice("Encryption locked.")}});let o=h=>{let u=se();u&&typeof u[h]=="function"&&u[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 X.Notice("Enable \u201CPerformance profiling\u201D in Stashpad settings first, then use the app and run this again.");return}let h=xt.report();console.log(h);try{await navigator.clipboard.writeText(h)}catch{}new X.Notice("Performance profile copied to clipboard (also in the console).")}}),this.addCommand({id:"stashpad-reset-perf",name:"Reset performance profile",callback:()=>{xt.reset(),new X.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(),gi));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 u=this.importService.defaultDestination();return h?!!u:(u&&this.runImportLooseFiles(u),!0)}}),this.addCommand({id:"stashpad-rerun-slug-pass",name:"Re-run filename (slug) pass on this folder",checkCallback:h=>{let u=this.importService.defaultDestination();return h?!!u:(u&&this.runFolderSlugPass(u),!0)}}),this.addCommand({id:"stashpad-rerun-frontmatter-backfill",name:"Re-run frontmatter backfill (recovery links) on this folder",checkCallback:h=>{let u=this.importService.defaultDestination();return h?!!u:(u&&this.runFolderFrontmatterBackfill(u),!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 Ki(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 Is(this.app)}),this.addCommand({id:"stashpad-reveal-active-note",name:"Open this note in Stashpad",checkCallback:h=>{let u=this.app.workspace.getActiveFile(),I=!!u&&u.extension==="md"&&this.isStashpadNoteFile(u);return h||I&&u&&this.revealNoteInStashpad(u),I}});let a=Object.keys(ui);for(let h of a){let u=ui[h];this.addCommand({id:`stashpad-open-panels-${h}`,name:`Open Stashpad panel: ${u.label}`,callback:async()=>{await Ki(this.app),this.app.workspace.getLeavesOfType(ae)[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-export-okf",name:"Export selection as OKF bundle (.zip / .tar.gz / .stash)",callback:()=>o("cmdExportOkf")}),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 u=se(),I=u&&u.noteFolder;return I?(h||(new X.Notice(`Running integrity check on "${I}"\u2026`),this.runIntegrityCheckOnFolder(I).then(()=>{new X.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 X.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 X.Notice(`Author registry rebuild failed: ${h.message}`)}}}),this.addCommand({id:"stashpad-restore-author-stubs",name:"Restore missing author stubs (from registry)",callback:async()=>{new X.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 X.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 X.Notice("Stashpad: rebootstrapping\u2026");try{let{touched:h,fmChecked:u,fmWritten:I,slugsRenamed:f,authors:m,imported:C,attachmentsLinked:y}=await this.rebootstrapAllFolders(),w=[];w.push(`rebootstrapped ${h.length} folder${h.length===1?"":"s"}`),C>0&&w.push(`imported ${C} loose file${C===1?"":"s"}`),y>0&&w.push(`linked attachments on ${y} note${y===1?"":"s"}`),I>0&&w.push(`updated ${I} note${I===1?"":"s"}' metadata`),f>0&&w.push(`renamed ${f} note${f===1?"":"s"}`),m>0&&w.push(`${m} author${m===1?"":"s"} in registry`),w.push(`(checked ${u} total)`),new X.Notice(`Stashpad: ${w.join(" \xB7 ")}`)}catch(h){new X.Notice(`Stashpad: rebootstrap failed (${h.message})`)}}}),this.addCommand({id:"stashpad-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:h=>{let u=this.app.workspace.getActiveFile();return!u||u.extension!=="md"?!1:(h||this.adoptNote(u),!0)}}),this.addCommand({id:"stashpad-open-notification-history",name:"Open notification history",callback:()=>{Promise.resolve().then(()=>(Ht(),gi)).then(({NotificationHistoryModal:h,LogModal:u})=>{new h(this.app,this.notifications,async()=>{let I=this.app.vault.adapter,f=this.pluginPrivatePath("log.jsonl");if(!await I.exists(f)){new X.Notice("No log yet \u2014 make some changes first.");return}let m=await I.read(f);new u(this.app,m,f).open()},this.settings.authorId||null,I=>this.lookupNoteAuthorIds(I)).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 u=`stashpad-toggle-${String(h.key).replace(/[A-Z]/g,I=>`-${I.toLowerCase()}`)}`;this.addCommand({id:u,name:`Toggle: ${h.label}`,callback:async()=>{let I=!this.settings[h.key];this.settings[h.key]=I,await this.saveSettings(),new X.Notice(`${h.label}: ${I?"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 hs)this.addCommand({id:`stashpad-open-settings-${h.id}`,name:`Open Stashpad settings: ${h.label}`,callback:()=>{let u=this.app.setting;!u?.open||!u?.openTabById||(u.open(),u.openTabById(this.manifest.id))}});let A=()=>{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(()=>(fi(),Vi)),u=await h(this.app,this,this.settings);if(u.error==="no-dest"){new X.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}if(u.error==="no-home"){new X.Notice(`"${this.settings.jdIndexStashpadFolder}" has no Stashpad home note. Open the folder in Stashpad first to create one.`,7e3);return}let{buildJdPreviewNotice:I}=await Promise.resolve().then(()=>(fi(),Vi));I(this.app,u)}catch(h){console.error("[stashpad] preview failed",h),new X.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:u,JdBuildConfirmModal:I}=await Promise.resolve().then(()=>(fi(),Vi));if(!(this.settings.jdIndexStashpadFolder??"").trim().replace(/^\/+|\/+$/g,"")){new X.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}let m=u(this.app,this,this.settings);new I(this.app,this,this.settings,m.indexed.length,async()=>{try{let y=await h(this.app,this,this.settings);if(y.error==="no-dest"){new X.Notice("Set a Designated Stashpad folder for Index in settings first.",6e3),A();return}if(y.error==="dest-not-stashpad"){new X.Notice(`"${y.destFolder}" isn't a known Stashpad folder. Pick a real Stashpad folder in settings.`,7e3),A();return}this.settings.jdIndexHasBuilt=!0,await this.saveSettings(),new X.Notice(`Index built: ${y.created} created, ${y.updated} updated, ${y.skipped} skipped \u2192 ${y.destFolder}`,6e3)}catch(y){console.error("[stashpad] build failed",y),new X.Notice(`Build failed: ${y?.message??y}`,8e3)}}).open()}catch(h){console.error("[stashpad] build failed",h),new X.Notice(`Build failed: ${h?.message??h}`,8e3)}}});let c=h=>{if(h.extension!==ie)return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),I=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),f=h.parent?.path||"",m=f.split("/").pop()??"";if(u&&m===u){if(I&&f.endsWith(`/${I}`))return;let C=f.slice(0,f.length-u.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(h,C);return}this.settings.autoImport&&this.importService.isArmed()&&(Te(h.path)||this.discoverStashpadFolders().includes(f)&&this.autoImportStash(h,f))};this.registerEvent(this.app.vault.on("create",h=>{h instanceof X.TFile&&c(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof X.TFile&&c(h)}));let g=h=>{if(h.extension!=="md")return;let u=h.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(u)&&setTimeout(()=>{this.fixOrphanParentForFile(h)},800)},p=h=>{if(h.extension!=="md")return;let u=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!u)return;let I=h.parent?.path?.replace(/\/+$/,"")??"";if((I.split("/").pop()??"")!==u)return;let m=I.slice(0,I.length-u.length).replace(/\/+$/,"");!m||!this.discoverStashpadFolders().includes(m)||setTimeout(()=>{this.adoptMarkdownDrop(h,m)},200)};this.registerEvent(this.app.vault.on("create",h=>{h instanceof X.TFile&&(g(h),p(h))})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof X.TFile&&(g(h),p(h))})),this.registerEvent(this.app.vault.on("delete",h=>{if(!(h instanceof X.TFolder))return;let u=h.path.replace(/\/+$/,"");this.knownStashpadFolders.has(u)&&this.handleStashpadFolderDeleted(u)})),this.registerEvent(this.app.vault.on("rename",(h,u)=>{h instanceof X.TFile&&this.maybeReHomeOnCrossFolderMove(h,u)})),this.registerEvent(this.app.vault.on("rename",(h,u)=>{h instanceof X.TFile&&this.maybeArchiveOnMoveIn(h,u)})),this.registerEvent(this.app.vault.on("create",h=>{h instanceof X.TFile?this.importService.enqueue(h):h instanceof X.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",h=>{h instanceof X.TFile?this.importService.enqueue(h):h instanceof X.TFolder&&this.importService.enqueueFolder(h)})),this.registerEvent(this.app.vault.on("rename",(h,u)=>{h instanceof X.TFile&&this.maybeAdoptAuthorRename(h,u)})),this.registerDomEvent(window,"focus",()=>void this.checkForSyncedBuild()),setTimeout(()=>void this.checkForSyncedBuild(),5e3),this.registerInterval(window.setInterval(()=>void this.checkForSyncedBuild(),45e3))}async checkForSyncedBuild(){try{let t=this.manifest.dir;if(!t)return;let e=`${t.replace(/\/+$/,"")}/manifest.json`,i=this.app.vault.adapter;if(!await i.exists(e))return;let s=JSON.parse(await i.read(e))?.version,n=this.manifest.version;if(typeof s!="string"||!s||s===n||!this.isSemverGreater(s,n)||this.notifiedBuildVersion===s)return;this.notifiedBuildVersion=s,this.notifications.show({message:`A newer Stashpad build synced in (\`${n}\` \u2192 \`${s}\`). Reload the app to apply it.`,kind:"info",category:"system",duration:0,actions:[{label:"Reload app",onClick:()=>this.reloadAppForUpdate()}]})}catch(t){console.debug("[Stashpad] synced-build check failed",t)}}reloadAppForUpdate(){try{window.localStorage?.setItem(zn,"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 X.Notice("Reload Obsidian (close + reopen) to apply the Stashpad update.")}}async unghostStashpadTabsIfFlagged(){let t=!1;try{t=window.localStorage?.getItem(zn)==="1"}catch{}if(t){try{window.localStorage?.removeItem(zn)}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`,A=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&&(A=c)}catch(c){console.warn("[Stashpad] author file rename failed",c);continue}try{await this.refreshAuthorStub(A)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),i=(this.settings.authorRole??"").trim(),s=(this.settings.authorDepartment??"").trim();if(e)try{let n=await this.app.vault.read(t),o=n.replace(/^# .*$/m,`# ${e}`);o!==n&&await this.app.vault.modify(t,o),await this.app.fileManager.processFrontMatter(t,a=>{a.aliases=[e],delete a.name,i?a.role=i:delete a.role,s?a.department=s:delete a.department})}catch(n){console.warn("[Stashpad] refreshAuthorStub failed",n)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let i=this.parseAuthorFilePath(t.path);if(!i)return;let s=(this.settings.authorId??"").trim();if(!s||i.id!==s)return;let n=i.name.trim();!n||n===(this.settings.authorName??"").trim()||(this.settings.authorName=n,await this.saveSettings(),await this.syncAuthorFilesToName())}async adoptMarkdownDrop(t,e){try{let i=this.app.vault.adapter,s=t.name,n=s.lastIndexOf("."),o=n>0?s.slice(0,n):s,a=n>0?s.slice(n):"",r=0;for(;await i.exists(`${e}/${s}`);)r+=1,s=`${o}-${r}${a}`;let A=`${e}/${s}`;await this.app.fileManager.renameFile(t,A);let c=this.app.vault.getAbstractFileByPath(A);c instanceof X.TFile&&setTimeout(()=>{this.fixOrphanParentForFile(c)},500),this.notifications.show({message:`Imported \`${t.name}\` \u2192 \`${e}\``,kind:"success",category:"import",folder:e,affectedPaths:[A]})}catch(i){console.warn("Stashpad: markdown drop adoption failed",i),this.notifications.show({message:`Couldn't import \`${t.name}\`: ${i.message}`,kind:"error",category:"import"})}}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,i=typeof e?.id=="string"?e.id.trim():"",s=e?.parent,n=typeof s=="string"?s.trim()!=="":s!=null,o=typeof e?.created=="string"&&e.created.trim()!=="",a=!i,r=!n,A=!o;if(!a&&!r&&!A)return;let{newId:c}=await Promise.resolve().then(()=>(Lt(),Ji)),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 m=f.parent;(typeof m=="string"?m.trim()!=="":m!=null)||(f.parent=T,p=!0)}A&&(typeof f.created=="string"&&f.created.trim()||(f.created=new Date(t.stat.ctime).toISOString(),h=!0))}),!g&&!p&&!h)return;let u=this.newLog(),I=g||i;I&&await u.append({type:"parent_change",id:I,payload:{from:null,to:T,reason:"orphan_auto_fix",path:t.path,addedId:!!g,addedParent:p,addedCreated:h}}),new X.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}maybeReHomeOnCrossFolderMove(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");i!==n&&this.discoverStashpadFolders().includes(i)&&(this.reHomePending.has(t.path)||(this.reHomePending.add(t.path),setTimeout(()=>{this.reHomePending.delete(t.path),this.reHomeDanglingParent(t,i)},900)))}async reHomeDanglingParent(t,e){try{let i=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof i?.id=="string"?i.id.trim():"",n=typeof i?.parent=="string"?i.parent.trim():"";if(!s||!n||n===T||this.app.vault.getMarkdownFiles().some(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===e&&this.app.metadataCache.getFileCache(a)?.frontmatter?.id===n))return;await this.app.fileManager.processFrontMatter(t,a=>{let r=typeof a.parent=="string"?a.parent.trim():"";r&&r!==T&&(a.parent=T)}),await this.newLog().append({type:"parent_change",id:s,payload:{from:n,to:T,reason:"rehome_cross_folder_move",path:t.path}}),new X.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(Ot(i)){this.importService.parkEncrypted(t.path),this.notifyPendingEncrypted();return}let s=await qe(this.app,i);if(!s)return;let n=se(),o=new Set;if(n&&typeof n.collectExistingIds=="function"&&n.noteFolder===e)for(let A of n.collectExistingIds())o.add(A);else for(let A of this.app.vault.getMarkdownFiles()){if(!A.path.startsWith(e+"/"))continue;let c=this.app.metadataCache.getFileCache(A)?.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:T,payload:{from:t.path,into:e,noteCount:a.notesWritten,attachmentsWritten:a.attachmentsWritten,collisionsRenamed:a.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let r=[`Auto-imported ${a.notesWritten} note${a.notesWritten===1?"":"s"} from ${t.name}`];a.attachmentsWritten&&r.push(`+ ${a.attachmentsWritten} attachment${a.attachmentsWritten===1?"":"s"}`),a.collisionsRenamed&&r.push(`(${a.collisionsRenamed} renamed)`),this.notifications.show({message:r.join(" "),kind:"success",category:"import",folder:e}),n&&typeof n.debouncedRender=="function"&&n.debouncedRender()}catch(i){this.notifications.show({message:`Stashpad: auto-import failed File: \`${t.name}\` Error: ${i.message} -Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:Ki(this.app,t.path,$.Platform.isMobile)}),console.error(i)}}lookupNoteAuthorIds(t){let e=new Set,i=s=>{if(typeof s!="string")return null;let n=s.match(/-([a-z0-9]{4,12})(?:\.md)?(?:\||\]\])/i);return n?n[1]:null};for(let s of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(s)?.frontmatter;if(n?.id!==t)continue;let o=i(n?.author);o&&e.add(o);let a=n?.contributors;if(Array.isArray(a))for(let r of a){let l=i(r);l&&e.add(l)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let d of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(d)?.frontmatter?.id!==t)continue;let I=d.parent?.path;I&&e.add(I)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async d=>{if(d&&!await this.app.vault.adapter.exists(d))try{await this.app.vault.createFolder(d)}catch(u){let I=u?.message??"";if(!/already exists/i.test(I))throw u}},a=0,r=0,l=0,c=0;for(let d of e)try{if(i&&await o(`${d}/${i}`),s&&await o(`${d}/${s}`),this.settings.autoImport)try{let I=await this.importService.importLooseInto(d);c+=I.files+I.folders+I.stashes}catch(I){console.warn("Stashpad: loose sweep failed",d,I)}let u=await We(this.app,d);a+=u.checked,r+=u.written,l+=await this.rebootstrapFolderSlugs(d),n.push(d)}catch(u){console.warn(`Stashpad: rebootstrap skipped ${d}`,u)}let p=0;try{p=(await this.rebuildAuthorRegistry()).total}catch(d){console.warn("Stashpad: rebootstrap author-registry rebuild failed",d)}let g=0;try{g=await this.convertAttachmentsToLinks()}catch(d){console.warn("Stashpad: attachment-link conversion failed",d)}return{touched:n,fmChecked:a,fmWritten:r,slugsRenamed:l,authors:p,imported:c,attachmentsLinked:g}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??zt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let r=Fe(a.basename);if(!(!r||r===e||this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==r))try{let c=await this.app.vault.cachedRead(a),p=c.startsWith("---")?c.slice(c.indexOf(` ----`,3)+4).replace(/^\r?\n/,""):c,g=Mt(p,s),d=Tt(g,r);if(a.name===d)continue;let u=a.parent?`${a.parent.path}/${d}`:d;if(this.app.vault.getAbstractFileByPath(u))continue;await this.app.fileManager.renameFile(a,u),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(ne);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=u=>{let f=u.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=ee(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let u of this.app.vault.getAllLoadedFiles())if(u.children){let I=u.path;I&&I!=="/"&&!I.startsWith(".")&&o.add(I)}let a=u=>{let I=u.split("/").filter(Boolean).pop()??"";return I?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(I):!1},r=new Set,l=[],c=[],p=new Set;for(let u of e){let I=t(u);if(p.has(I))continue;p.add(I),r.add(I);let f=I.split("/").pop()||I;l.push({kind:"reveal",folder:I,label:`Reveal "${f}" tab`,leaf:u,icon:this.isArchiveFolder(I)?"archive":"layout-grid"}),c.push({kind:"open-anyway",folder:I,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let u of i.filter(I=>!r.has(I))){let I=u.split("/").pop()||u;l.push({kind:"open",folder:u,label:`Open "${I}" in new tab`,icon:this.isArchiveFolder(u)?"archive":"layout-template"})}let g=this,d=new class extends $.SuggestModal{getSuggestions(u){let I=u.trim().toLowerCase(),f=I?I.split(/\s+/).filter(Boolean):[],C=E=>{if(!f.length)return!0;let v=E.toLowerCase();for(let S of f)if(!v.includes(S))return!1;return!0},m=I?l.filter(E=>{let v="folder"in E?E.folder:"";return C(E.label)||C(v)}):l.slice();if(I&&s&&n)for(let E of i){if(E.toLowerCase()===n.toLowerCase())continue;let v=E.split("/").pop()??E,S=`${E} ${v}`;C(S)&&m.push({kind:"switch-current",folder:E,label:`Switch this tab to "${v}"`,icon:"folder-input"})}let y=u.trim().replace(/^\/+|\/+$/g,"");if(y&&!a(y)){let E=Array.from(o).find(S=>S.toLowerCase()===y.toLowerCase()),v=i.some(S=>S.toLowerCase()===y.toLowerCase());if(E&&!v)m.push({kind:"convert",folder:E,label:`Convert \u201C${Fi(E)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!E){let S=Fi(y);m.push({kind:"create",folder:y,label:`+ Create new Stashpad \u201C${S}\u201D`,icon:"folder-plus"})}}let w=c.filter(E=>C(E.label)||C("folder"in E?E.folder:""));return m.push(...w),g.encryption?.isConfigured?.()&&C("trash deleted encrypted")&&m.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),m}renderSuggestion(u,I){I.addClass("stashpad-suggest-item"),I.addClass("stashpad-ribbon-suggest-item"),u.kind==="create"&&I.addClass("stashpad-suggest-create");let f=I.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,$.setIcon)(f,u.icon);let C=I.createDiv({cls:"stashpad-ribbon-suggest-body"});C.createDiv({cls:"stashpad-suggest-title",text:u.label}),"folder"in u&&u.folder&&u.label!==u.folder&&C.createDiv({cls:"stashpad-suggest-preview",text:u.folder})}async onChooseSuggestion(u){if(u.kind==="trash"){g.openEncryptedTrash();return}if(u.kind==="reveal"){g.app.workspace.revealLeaf(u.leaf);return}if(u.kind==="open"||u.kind==="open-anyway"){await g.activateViewForFolder(u.folder);return}if(u.kind==="switch-current"){let I=s;I&&typeof I.setFolderOverride=="function"&&(await I.setFolderOverride(u.folder),g.app.workspace.revealLeaf(I.leaf));return}if(u.kind==="create"){try{let I=Fi(u.folder);await g.app.vault.adapter.exists(I)||await g.app.vault.createFolder(I),await g.activateViewForFolder(I)}catch(I){new $.Notice(`Stashpad: couldn't create folder (${I.message})`)}return}if(u.kind==="convert"){let{ConfirmModal:I}=await Promise.resolve().then(()=>(Ht(),hi)),f=u.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 I(g.app,"Convert into a Stashpad?",C.join(` -`),"Convert",async m=>{if(m)try{await g.activateViewForFolder(f)}catch(y){new $.Notice(`Stashpad: couldn't convert folder (${y.message})`)}}).open();return}}}(this.app);d.setPlaceholder(s?"Open, switch this tab, or create a Stashpad folder \u2014 type to filter\u2026":"Open or create a Stashpad folder \u2014 type to filter\u2026"),d.open()}async openTinyWindow(){let t=ee(),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 Ss(this.app);let t=this.app.workspace.getLeavesOfType(Ce)[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 bo(this.app,n.path);a&&(e.push({folder:o,blob:n.path,parentId:a.parentId,title:a.title,count:a.count,created:a.created,rootId:a.rootId,prevSibling:a.prevSibling}),i=!0)}i&&(this.settings.lockedSubtrees=e,await this.saveSettings(),this.refreshAllStashpadViews?.())}lockedSubtreesFor(t,e){let i=t.replace(/\/+$/,""),s=[],n=new Set;for(let o of this.settings.lockedSubtrees??[])(o.folder??"").replace(/\/+$/,"")===i&&(o.parentId??T)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??T,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let a=o.parent?.path?.replace(/\/+$/,"")??"";a!==i||a==="_deleted"||a.startsWith("_deleted/")||e===T&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:T,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new xt(this.app,{mode:"unlock",offerKeychain:!0,onSubmit:async({current:e,remember:i})=>await this.encryption.unlock(e,i)?(t(!0),null):"Wrong password. Try again.",onCancel:()=>t(!1)}).open()}):(new $.Notice("Set up encryption first (Settings \u2192 Encryption)."),!1)}async lockNoteSubtree(t,e,i=null,s={}){if(!await this.ensureEncryptionUnlocked())return null;let n=this.encryption.getSessionKey();if(!n)return null;try{let o=this.settings.hideLockedTitles??!1,a=await xo(this.app,t,e,n,i,o,s.blobFolder),r=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(l=>l.blob!==a.blobPath),{folder:r,blob:a.blobPath,parentId:a.parentId,title:a.title,count:a.noteCount,created:a.created,rootId:a.rootId,prevSibling:i}],await this.saveSettings(),a.unpurged.length>0?new $.Notice(`\u26A0\uFE0F Locked, but ${a.unpurged.length} file${a.unpurged.length===1?" is":"s are"} still in plaintext (couldn't be removed or changed during the lock): +Inspect with the buttons below \u2014 rename to .zip to crack it open in an archive tool.`,kind:"error",category:"import",affectedPaths:[t.path],actions:Xi(this.app,t.path,X.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 A=i(r);A&&e.add(A)}break}return Array.from(e)}lookupNoteAuthorId(t){return this.lookupNoteAuthorIds(t)[0]??null}async rebootstrapAllFolders(){this.rebootstrapInProgress=!0;try{return await this.rebootstrapAllFoldersInner()}finally{window.setTimeout(()=>{this.rebootstrapInProgress=!1},2500)}}async rebootstrapAllFoldersInner(){let t="__root__",e=new Set;for(let u of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(u)?.frontmatter?.id!==t)continue;let f=u.parent?.path;f&&e.add(f)}let i=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),s=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),n=[],o=async u=>{if(u&&!await this.app.vault.adapter.exists(u))try{await this.app.vault.createFolder(u)}catch(I){let f=I?.message??"";if(!/already exists/i.test(f))throw I}},a=0,r=0,A=0,c=0,g=new Set(this.okfActiveFolders());for(let u of e)try{if(i&&await o(`${u}/${i}`),s&&await o(`${u}/${s}`),this.settings.autoImport)try{let f=await this.importService.importLooseInto(u);c+=f.files+f.folders+f.stashes}catch(f){console.warn("Stashpad: loose sweep failed",u,f)}let I=await $e(this.app,u);if(a+=I.checked,r+=I.written,A+=await this.rebootstrapFolderSlugs(u),g.has(u.replace(/\/+$/,"")))try{await Ts(this.app,u)}catch(f){console.warn("Stashpad: OKF rebuild during rebootstrap failed",u,f)}n.push(u)}catch(I){console.warn(`Stashpad: rebootstrap skipped ${u}`,I)}let p=0;try{p=(await this.rebuildAuthorRegistry()).total}catch(u){console.warn("Stashpad: rebootstrap author-registry rebuild failed",u)}let h=0;try{h=await this.convertAttachmentsToLinks()}catch(u){console.warn("Stashpad: attachment-link conversion failed",u)}return{touched:n,fmChecked:a,fmWritten:r,slugsRenamed:A,authors:p,imported:c,attachmentsLinked:h}}async rebootstrapFolderSlugs(t){let e="__root__",i=t.replace(/\/+$/,""),s=this.settings.slugStopWords??Vt,n=0,o=this.app.vault.getMarkdownFiles().filter(a=>(a.parent?.path?.replace(/\/+$/,"")??"")===i);for(let a of o){let r=Se(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=Mt(g,s),h=Tt(p,r);if(a.name===h)continue;let u=a.parent?`${a.parent.path}/${h}`:h;if(this.app.vault.getAbstractFileByPath(u))continue;await this.app.fileManager.renameFile(a,u),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(ae);for(let e of t){let i=e.view;i&&typeof i.render=="function"&&i.render()}}refreshAllStashpadViews(){for(let t of this.app.workspace.getLeavesOfType(ct)){let e=t.view;e&&typeof e.render=="function"&&e.render()}}openFolderPicker(){let t=u=>{let f=u.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=se(),n=s?(s.noteFolder??"").trim().replace(/^\/+|\/+$/g,""):"",o=new Set;for(let u of this.app.vault.getAllLoadedFiles())if(u.children){let I=u.path;I&&I!=="/"&&!I.startsWith(".")&&o.add(I)}let a=u=>{let I=u.split("/").filter(Boolean).pop()??"";return I?new Set([this.settings.importDropFolder,this.settings.exportFolder,"_attachments","_processed","_authors","_exports","_imports","_archive",".archive","_deleted"].map(m=>(m??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(I):!1},r=new Set,A=[],c=[],g=new Set;for(let u of e){let I=t(u);if(g.has(I))continue;g.add(I),r.add(I);let f=I.split("/").pop()||I;A.push({kind:"reveal",folder:I,label:`Reveal "${f}" tab`,leaf:u,icon:this.isArchiveFolder(I)?"archive":"layout-grid"}),c.push({kind:"open-anyway",folder:I,label:`Open "${f}" in another new tab`,icon:"layout-template"})}for(let u of i.filter(I=>!r.has(I))){let I=u.split("/").pop()||u;A.push({kind:"open",folder:u,label:`Open "${I}" in new tab`,icon:this.isArchiveFolder(u)?"archive":"layout-template"})}let p=this,h=new class extends X.SuggestModal{getSuggestions(u){let I=u.trim().toLowerCase(),f=I?I.split(/\s+/).filter(Boolean):[],m=E=>{if(!f.length)return!0;let v=E.toLowerCase();for(let D of f)if(!v.includes(D))return!1;return!0},C=I?A.filter(E=>{let v="folder"in E?E.folder:"";return m(E.label)||m(v)}):A.slice();if(I&&s&&n)for(let E of i){if(E.toLowerCase()===n.toLowerCase())continue;let v=E.split("/").pop()??E,D=`${E} ${v}`;m(D)&&C.push({kind:"switch-current",folder:E,label:`Switch this tab to "${v}"`,icon:"folder-input"})}let y=u.trim().replace(/^\/+|\/+$/g,"");if(y&&!a(y)){let E=Array.from(o).find(D=>D.toLowerCase()===y.toLowerCase()),v=i.some(D=>D.toLowerCase()===y.toLowerCase());if(E&&!v)C.push({kind:"convert",folder:E,label:`Convert \u201C${Di(E)}\u201D into a Stashpad\u2026`,icon:"folder-cog"});else if(!E){let D=Di(y);C.push({kind:"create",folder:y,label:`+ Create new Stashpad \u201C${D}\u201D`,icon:"folder-plus"})}}let w=c.filter(E=>m(E.label)||m("folder"in E?E.folder:""));return C.push(...w),p.encryption?.isConfigured?.()&&m("trash deleted encrypted")&&C.push({kind:"trash",label:"Open encrypted trash",icon:"trash-2"}),C}renderSuggestion(u,I){I.addClass("stashpad-suggest-item"),I.addClass("stashpad-ribbon-suggest-item"),u.kind==="create"&&I.addClass("stashpad-suggest-create");let f=I.createSpan({cls:"stashpad-ribbon-suggest-icon"});(0,X.setIcon)(f,u.icon);let m=I.createDiv({cls:"stashpad-ribbon-suggest-body"});m.createDiv({cls:"stashpad-suggest-title",text:u.label}),"folder"in u&&u.folder&&u.label!==u.folder&&m.createDiv({cls:"stashpad-suggest-preview",text:u.folder})}async onChooseSuggestion(u){if(u.kind==="trash"){p.openEncryptedTrash();return}if(u.kind==="reveal"){p.app.workspace.revealLeaf(u.leaf);return}if(u.kind==="open"||u.kind==="open-anyway"){await p.activateViewForFolder(u.folder);return}if(u.kind==="switch-current"){let I=s;I&&typeof I.setFolderOverride=="function"&&(await I.setFolderOverride(u.folder),p.app.workspace.revealLeaf(I.leaf));return}if(u.kind==="create"){try{let I=Di(u.folder);await p.app.vault.adapter.exists(I)||await p.app.vault.createFolder(I),await p.activateViewForFolder(I)}catch(I){new X.Notice(`Stashpad: couldn't create folder (${I.message})`)}return}if(u.kind==="convert"){let{ConfirmModal:I}=await Promise.resolve().then(()=>(Ht(),gi)),f=u.folder,m=[`\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 I(p.app,"Convert into a Stashpad?",m.join(` +`),"Convert",async C=>{if(C)try{await p.activateViewForFolder(f)}catch(y){new X.Notice(`Stashpad: couldn't convert folder (${y.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=se(),e=t?.folderOverride??null,i=t?.focusId??"__root__",s=!!t?.compactMode,n=this.app.workspace.openPopoutLeaf?.();if(!n){new X.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(Be)[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 Go(this.app,n.path);a&&(e.push({folder:o,blob:n.path,parentId:a.parentId,title:a.title,count:a.count,created:a.created,rootId:a.rootId,prevSibling:a.prevSibling}),i=!0)}i&&(this.settings.lockedSubtrees=e,await this.saveSettings(),this.refreshAllStashpadViews?.())}lockedSubtreesFor(t,e){let i=t.replace(/\/+$/,""),s=[],n=new Set;for(let o of this.settings.lockedSubtrees??[])(o.folder??"").replace(/\/+$/,"")===i&&(o.parentId??T)===e&&(s.push({blob:o.blob,title:o.title??"",count:o.count??0,created:o.created??"",rootId:o.rootId,parentId:o.parentId??T,prevSibling:o.prevSibling??null}),n.add(o.blob));for(let o of this.app.vault.getFiles()){if(o.extension!=="stashenc"||n.has(o.path))continue;let a=o.parent?.path?.replace(/\/+$/,"")??"";a!==i||a==="_deleted"||a.startsWith("_deleted/")||e===T&&s.push({blob:o.path,title:o.basename,count:0,created:"",rootId:void 0,parentId:T,prevSibling:null})}return s}async ensureEncryptionUnlocked(){return this.encryption.isConfigured()?this.encryption.isUnlocked()||await this.encryption.tryAutoUnlock()?!0:new Promise(t=>{new Nt(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 X.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 Jo(this.app,t,e,n,i,o,s.blobFolder),r=(s.blobFolder??t).replace(/\/+$/,"");return this.settings.lockedSubtrees=[...(this.settings.lockedSubtrees??[]).filter(A=>A.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 X.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 unlockBundleCore(t,e,i){let s=(i??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,""),n=new Set;for(let o of this.app.vault.getMarkdownFiles())if((o.parent?.path?.replace(/\/+$/,"")??"")===s)try{let a=Dt(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}return Mo(this.app,t,e,n,i)}async unlockBundleAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,"");try{let n=await this.unlockBundleCore(t,i,e.destFolder);return this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(o=>o.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${n.notesWritten} note${n.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:s}),!0}catch(n){return console.warn("[Stashpad] unlock failed",n),new $.Notice(`Couldn't unlock: ${n.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 p;try{p=Dt(await this.app.vault.read(c)).fm}catch{continue}let g=p.id;typeof g!="string"||g===T||(typeof p.parent=="string"?p.parent:T)!==T||i.push(g)}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 ze(this.app).load(e))[T]??[],r=n.length>3?new $.Notice("",0):null,l=0;for(let c=0;c<n.length;c++){let p=n[c];r?.setMessage(`\u{1F512} Encrypting ${c+1}/${n.length}\u2026`);let g=a.indexOf(p),d=g>0?a[g-1]:null;await this.lockNoteSubtree(e,p,d,{silent:!0})&&l++}return r?.hide(),l>0&&this.notifications.show({message:`Locked ${l} note${l===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),l}async unlockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>o.extension==="stashenc"&&(o.parent?.path?.replace(/\/+$/,"")??"")===e).map(o=>o.path);if(i.length===0)return new $.Notice("No locked notes in this folder."),0;let s=i.length>3?new $.Notice("",0):null,n=0;for(let o=0;o<i.length;o++){s?.setMessage(`\u{1F513} Decrypting ${o+1}/${i.length}\u2026`);try{await this.unlockBundleAt(i[o],{silent:!0})&&n++}catch(a){console.warn("[Stashpad] folder unlock skipped",i[o],a)}}return s?.hide(),n>0&&this.notifications.show({message:`Unlocked ${n} note${n===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),n}async unlockAllInVault(){if(!await this.ensureEncryptionUnlocked())return 0;let t=this.app.vault.getFiles().filter(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(a=>a.path);if(t.length===0)return new $.Notice("No locked notes anywhere in the vault."),0;let e=this.encryption.getSessionKey();if(!e)return 0;let i=t.length>3?new $.Notice("",0):null,s=0,n=[];for(let a=0;a<t.length;a++){i?.setMessage(`\u{1F513} Decrypting ${a+1}/${t.length}\u2026`);try{let r=await this.unlockBundleCore(t[a],e);s+=r.notesWritten,n.push(t[a])}catch(r){console.warn("[Stashpad] vault unlock skipped",t[a],r)}}if(n.length>0){let a=new Set(n);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(r=>!a.has(r.blob)),await this.saveSettings()}i?.hide();let o=t[0].replace(/\/[^/]*$/,"");return s>0&&this.notifications.show({message:`Unlocked ${s} note${s===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:o}),s}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),n=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),o=await To(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 X.Notice(`Couldn't lock: ${o.message}`),null}}async unlockBundleCore(t,e,i){let s=(i??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,""),n=new Set;for(let o of this.app.vault.getMarkdownFiles())if((o.parent?.path?.replace(/\/+$/,"")??"")===s)try{let a=wt(await this.app.vault.read(o)).fm.id;typeof a=="string"&&n.add(a)}catch{}return qo(this.app,t,e,n,i)}async unlockBundleAt(t,e={}){if(!await this.ensureEncryptionUnlocked())return!1;let i=this.encryption.getSessionKey();if(!i)return!1;let s=(e.destFolder??t.replace(/\/[^/]*$/,"")).replace(/\/+$/,"");try{let n=await this.unlockBundleCore(t,i,e.destFolder);return this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(o=>o.blob!==t),await this.saveSettings(),e.silent||this.notifications.show({message:`Unlocked ${n.notesWritten} note${n.notesWritten===1?"":"s"}.`,kind:"success",category:"system",folder:s}),!0}catch(n){return console.warn("[Stashpad] unlock failed",n),new X.Notice(`Couldn't unlock: ${n.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=wt(await this.app.vault.read(c)).fm}catch{continue}let p=g.id;typeof p!="string"||p===T||(typeof g.parent=="string"?g.parent:T)!==T||i.push(p)}let s=new Set((this.settings.lockedSubtrees??[]).map(c=>c.rootId).filter(c=>!!c)),n=i.filter(c=>!s.has(c));if(n.length===0)return new X.Notice("Nothing to lock in this folder."),0;let a=(await new ze(this.app).load(e))[T]??[],r=n.length>3?new X.Notice("",0):null,A=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})&&A++}return r?.hide(),A>0&&this.notifications.show({message:`Locked ${A} note${A===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),A}async unlockFolder(t){if(!await this.ensureEncryptionUnlocked())return 0;let e=t.replace(/\/+$/,""),i=this.app.vault.getFiles().filter(o=>o.extension==="stashenc"&&(o.parent?.path?.replace(/\/+$/,"")??"")===e).map(o=>o.path);if(i.length===0)return new X.Notice("No locked notes in this folder."),0;let s=i.length>3?new X.Notice("",0):null,n=0;for(let o=0;o<i.length;o++){s?.setMessage(`\u{1F513} Decrypting ${o+1}/${i.length}\u2026`);try{await this.unlockBundleAt(i[o],{silent:!0})&&n++}catch(a){console.warn("[Stashpad] folder unlock skipped",i[o],a)}}return s?.hide(),n>0&&this.notifications.show({message:`Unlocked ${n} note${n===1?"":"s"} in \u201C${e.split("/").pop()}\u201D.`,kind:"success",category:"system",folder:e}),n}async unlockAllInVault(){if(!await this.ensureEncryptionUnlocked())return 0;let t=this.app.vault.getFiles().filter(a=>a.extension==="stashenc"&&(a.parent?.path?.replace(/\/+$/,"")??"")!=="_deleted").map(a=>a.path);if(t.length===0)return new X.Notice("No locked notes anywhere in the vault."),0;let e=this.encryption.getSessionKey();if(!e)return 0;let i=t.length>3?new X.Notice("",0):null,s=0,n=[];for(let a=0;a<t.length;a++){i?.setMessage(`\u{1F513} Decrypting ${a+1}/${t.length}\u2026`);try{let r=await this.unlockBundleCore(t[a],e);s+=r.notesWritten,n.push(t[a])}catch(r){console.warn("[Stashpad] vault unlock skipped",t[a],r)}}if(n.length>0){let a=new Set(n);this.settings.lockedSubtrees=(this.settings.lockedSubtrees??[]).filter(r=>!a.has(r.blob)),await this.saveSettings()}i?.hide();let o=t[0].replace(/\/[^/]*$/,"");return s>0&&this.notifications.show({message:`Unlocked ${s} note${s===1?"":"s"} across the vault.`,kind:"success",category:"system",folder:o}),s}async encryptDeleteSubtree(t,e){if(!await this.ensureEncryptionUnlocked())return null;let i=this.encryption.getSessionKey();if(!i)return null;try{let s=new Date().toISOString(),n=(this.settings.hideLockedTitles??!1)||(this.settings.encryptTrashFilenames??!1),o=await Oo(this.app,t,e,i,s,n);return o.unpurged.length>0&&new X.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 ns(this.app,t);if(s?.kind==="rawtrash")try{let n=await Uo(this.app,t,i);return e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Ot}/).`,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 Qn(this.app,t,s,i),o=new Set;for(let r of this.app.vault.getMarkdownFiles())if((r.parent?.path?.replace(/\/+$/,"")??"")===n.replace(/\/+$/,""))try{let l=Dt(await this.app.vault.read(r)).fm.id;typeof l=="string"&&o.add(l)}catch{}let a=await Ho(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 Ro(this.app),e=[];for(let i of t)e.push({blob:i,meta:await ns(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 Po(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 X.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 As(this.app,t);if(s?.kind==="rawtrash")try{let n=await zo(this.app,t,i);return e.silent||this.notifications.show({message:`Restored ${n.filesWritten} file${n.filesWritten===1?"":"s"} to Obsidian's trash (${Kt}/).`,kind:"success",category:"system",folder:""}),!0}catch(n){return console.warn("[Stashpad] trash-backfill restore failed",n),new X.Notice(`Couldn't restore: ${n.message}`,0),!1}try{let n=await kn(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 A=wt(await this.app.vault.read(r)).fm.id;typeof A=="string"&&o.add(A)}catch{}let a=await Ko(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 X.Notice(`Couldn't restore: ${n.message}`,0),!1}}async listDeletedTrash(){let t=await Vo(this.app),e=[];for(let i of t)e.push({blob:i,meta:await As(this.app,i)});return e}async restoreAllTrash(){if(!await this.ensureEncryptionUnlocked())return 0;let t=await this.listDeletedTrash();if(t.length===0)return new X.Notice("Nothing to restore."),0;let e=t.length>3?new X.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 Yo(this.app,t,new Date().toISOString(),e);return i?(i.unpurged.length>0?new X.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 ${Ot}/.`,kind:"success",category:"system",folder:""}),!0):(new $.Notice(`Obsidian's vault trash (${Ot}/) 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}aa(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 vs(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)}async idsInFolder(t){let e=t.replace(/\/+$/,""),i=new Set;for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===e)try{let n=Dt(await this.app.vault.read(s)).fm.id;typeof n=="string"&&i.add(n)}catch{}return i}async crossFolderPaste(t,e,i,s,n){let o=i.replace(/\/+$/,"");if(this.isArchiveFolder(o))return new $.Notice(`"${o.split("/").pop()}" auto-encrypts notes moved in, so cross-folder paste is disabled there. Use the "Move to archive" command \u2014 it checks the encryption key first.`),null;let a=[],r=[],l=[],c=[];for(let M of e){let F=await be(this.app,t,M);if(F){l.push(F.rootNote.id),a.push({id:F.rootNote.id,file:F.rootNote.file}),c.push(F.rootNote.file);for(let N of F.descendants)r.push({id:N.id,file:N.file}),c.push(N.file)}}if(!a.length)return null;let p=a.length+r.length,g=[],d=[];n==="cut"&&(g=await this.exclusiveAttachmentsOf(c),d=await this.snapshotPaths([...c.map(M=>M.path),...g.map(M=>M.path)]));let u=await De(this.app,{rootNotes:a,allDescendants:r,sourceFolder:t}),I=await this.idsInFolder(o),f=new Set(this.filesUnder(o)),C=await Vt(this.app,u,o,I,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),m=this.filesUnder(o).filter(M=>!f.has(M)),y=await this.snapshotPaths(m),w=l.map(M=>C.idRemap[M]).filter(M=>!!M);if(n==="cut"){for(let M of c)try{await this.app.fileManager.trashFile(M)}catch(F){console.warn("[Stashpad] cross-folder move: couldn't trash source note",M.path,F)}for(let M of g)try{await this.app.fileManager.trashFile(M)}catch(F){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",M.path,F)}}let E=async()=>{for(let M of[...m].reverse()){let F=this.app.vault.getAbstractFileByPath(M);if(F)try{await this.app.fileManager.trashFile(F)}catch{}}};return{rootIds:w,noteCount:p,undo:n==="cut"?async()=>{await E(),await this.restoreSnapshot(d)}:async()=>{await E()},redo:n==="cut"?async()=>{await this.restoreSnapshot(y);for(let M of d){let F=this.app.vault.getAbstractFileByPath(M.path);if(F)try{await this.app.fileManager.trashFile(F)}catch{}}}:async()=>{await this.restoreSnapshot(y)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let a=await be(this.app,t,o);a&&i.push(a.rootNote.file,...a.descendants.map(r=>r.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i),n=[];for(let o of[...i,...s])try{await this.app.fileManager.trashFile(o),n.push(o)}catch(a){console.warn("[Stashpad] trashSubtrees: couldn't trash",o.path,a)}return n}async exclusiveAttachmentsOf(t){let e=new Set(t.map(n=>n.path)),i=new Map;for(let n of t)for(let o of await is(this.app,n))i.set(o.path,o);let s=this.app.metadataCache.resolvedLinks??{};for(let n of Object.keys(s))if(!e.has(n))for(let o of Object.keys(s[n]??{}))i.delete(o);return[...i.values()]}async subtreeFilePaths(t,e){let i=[];for(let n of e){let o=await be(this.app,t,n);o&&i.push(o.rootNote.file,...o.descendants.map(a=>a.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i);return[...i.map(n=>n.path),...s.map(n=>n.path)]}async orderedSubtreeNodes(t,e){let i=[],s=new Set,n=o=>{let a=this.app.metadataCache.getFileCache(o)?.frontmatter?.position;return typeof a=="number"?a:Number.MAX_SAFE_INTEGER};for(let o of e){let a=await be(this.app,t,o);if(!a)continue;let r=new Map;for(let c of a.descendants){if(!c.parent)continue;let p=r.get(c.parent)??[];p.push({id:c.id,file:c.file,created:c.created}),r.set(c.parent,p)}for(let c of r.values())c.sort((p,g)=>n(p.file)-n(g.file)||p.created.localeCompare(g.created));let l=(c,p)=>{if(!s.has(c.id)){s.add(c.id),i.push({file:c.file,created:c.created,depth:p});for(let g of r.get(c.id)??[])l(g,p+1)}};l({id:a.rootNote.id,file:a.rootNote.file,created:a.rootNote.created},0)}return i}filesUnder(t){let e=t.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(i=>i.path.startsWith(e)).map(i=>i.path)}async snapshotPaths(t){let e=[];for(let i of t){let s=this.app.vault.getAbstractFileByPath(i);if(!s)continue;let n=!i.toLowerCase().endsWith(".md");try{n?e.push({path:i,binary:n,data:await this.app.vault.readBinary(s)}):e.push({path:i,binary:n,text:await this.app.vault.read(s)})}catch(o){console.warn("[Stashpad] snapshotPaths: couldn't read",i,o)}}return e}async restoreSnapshot(t){for(let e of t){let i=e.path.split("/").slice(0,-1).join("/");await this.ensureVaultFolder(i);let s=this.app.vault.getAbstractFileByPath(e.path);try{e.binary?s?await this.app.vault.adapter.writeBinary(e.path,e.data):await this.app.vault.createBinary(e.path,e.data):s?await this.app.vault.modify(s,e.text??""):await this.app.vault.create(e.path,e.text??"")}catch(n){console.warn("[Stashpad] restoreSnapshot: couldn't write",e.path,n)}}}async ensureVaultFolder(t){if(!t)return;let e="";for(let i of t.split("/"))if(e=e?`${e}/${i}`:i,!await this.app.vault.adapter.exists(e))try{await this.app.vault.createFolder(e)}catch{}}refreshOpenViewsForFolder(t){let e=t.replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(ct)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,""),s=[];for(let l of e){let c=this.app.vault.getAbstractFileByPath(l);if(!(c instanceof $.TFile)||(c.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let p;try{p=Dt(await this.app.vault.read(c)).fm}catch{continue}let g=typeof p.id=="string"?p.id:null;!g||g===T||s.push({id:g,parent:typeof p.parent=="string"?p.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 u of t)try{await u.loadIfDeferred?.()}catch{}let i=u=>u.getViewState()?.state??{},s=u=>{let I=i(u);return(u.isDeferred?I.folderOverride??"":u.view?.noteFolder??I.folderOverride??"").replace(/\/+$/,"")},n=u=>{let I=i(u);return(u.isDeferred?I.focusId:u.view?.focusId??I.focusId)||T},o=u=>{let I=u.view;return!!I&&I.getViewType?.()===ct&&typeof I.navigateTo=="function"&&typeof I.noteFolder=="string"},a=new Map;for(let u of this.app.vault.getMarkdownFiles()){let I=(u.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(u)?.frontmatter?.id;typeof f=="string"&&f&&(a.get(I)??a.set(I,new Set).get(I)).add(f)}let r=0,l=[];for(let u of t){let I=s(u),f=n(u);if(I&&f&&f!==T){let C=!u.isDeferred&&!!u.view?.tree?.get?.(f),m=a.get(I)?.has(f)??!1;if(!C&&!m){u.detach(),r++;continue}}l.push(u)}let c=new Map;for(let u of l){let I=s(u);if(!I)continue;let f=I+" "+n(u);(c.get(f)??c.set(f,[]).get(f)).push(u)}let p=0;for(let u of c.values()){if(u.length<=1)continue;u.sort((f,C)=>{let m=y=>y===e?2:y.isDeferred?0:1;return m(C)-m(f)});let I=null;for(let f of u){try{await f.loadIfDeferred?.()}catch{}if(o(f)){I=f;break}}I||(I=u[0]);for(let f of u)f!==I&&(f.detach(),p++)}let g=this.app.workspace.getLeavesOfType(ct).length,d=document.createDocumentFragment();return d.createEl("div",{text:p+r>0?"Stashpad tabs cleaned up:":"Stashpad tabs - nothing to clean up:"}),d.createEl("div",{text:`\u2022 ${p} duplicate tab${p===1?"":"s"} closed`}),d.createEl("div",{text:`\u2022 ${r} orphaned tab${r===1?"":"s"} pruned (note no longer exists)`}),d.createEl("div",{text:`\u2022 ${g} Stashpad tab${g===1?"":"s"} remaining`}),new $.Notice(d,7e3),p+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(u=>typeof u=="string"):[],l=a.includes(e),c=r.some(u=>u.includes(e));if(!l&&!c)continue;let p=n.parent?.path??"",g=i.find(u=>p===u||p.startsWith(u+"/"));if(!g)continue;s.has(g)||s.set(g,{authored:0,contributed:0});let d=s.get(g);l&&d.authored++,c&&d.contributed++}return[...s.entries()].map(([n,o])=>({folder:n,...o})).sort((n,o)=>o.authored+o.contributed-(n.authored+n.contributed))}parseAuthorRef(t){return ae(t)}authorRefFor(t,e,i){let s=i.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${s}-${e}.md`,o=i.replace(/[\[\]|]/g,"").trim()||s;return`[[${n}|${o}]]`}async ensureAuthorStubFor(t,e,i){if(!e||!i)return!1;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(l=>l.path.startsWith(s+"/")&&this.parseAuthorFilePath(l.path)?.id===e))return!1;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),r=`${s}/${a}-${e}.md`;try{return await this.ensureFolderPath(s),await this.app.vault.adapter.exists(r)?!1:(await this.app.vault.create(r,this.buildAuthorStub({id:e,name:i,role:o?.role,department:o?.department},new Date().toISOString())),!0)}catch(l){return console.warn("[Stashpad] ensureAuthorStubFor failed",r,l),!1}}async seedKnownAuthorsInFolder(t){let e=0;for(let i of this.collectKnownAuthors())await this.ensureAuthorStubFor(t,i.id,i.name)&&e++;return e}async checkDueReminders(){let t=Date.now(),e=new Set(this.settings.notifiedDueKeys??[]),i=(this.settings.authorId??"").trim(),s=[];for(let o of this.app.vault.getMarkdownFiles()){if(o.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!a||a.due==null)continue;let r=typeof a.id=="string"?a.id:"";if(!r)continue;let l=String(a.due),c=typeof a.due=="number"?a.due:Date.parse(l);if(!Number.isFinite(c)||c>t)continue;let p=Qe(a);if(p.length>0&&!(i&&p.some(d=>d.id===i)))continue;let g=`${r}@${l}`;e.has(g)||s.push({id:r,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:c,key:g})}if(s.length===0)return;this.settings.notifiedDueKeys=[...this.settings.notifiedDueKeys??[],...s.map(o=>o.key)].slice(-2e3),await this.saveSettings();let n=async o=>{try{let r=Dt(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(l=>l.trim()).find(l=>l.length>0);if(r)return r.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(s.length<=3)for(let o of s){let a=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${a}\u201D (${Xt(o.dueMs,this.settings)})`,kind:"warning",category:"reminder",duration:0,folder:o.folder,affectedIds:[o.id],actions:[{label:"Open",onClick:()=>void this.revealNoteByRef(o.folder,o.id)}]})}else this.notifications.show({message:`\u23F0 ${s.length} tasks are due \u2014 open the Tasks panel to review.`,kind:"warning",category:"reminder",duration:0,folder:""})}async syncAuthorsAcrossFolders(){await this.rebuildAuthorRegistry();let t=this.collectKnownAuthors(),e=this.discoverStashpadFolders();if(!t.length||!e.length){new $.Notice("No authors or Stashpad folders to sync.");return}let i=e.length*t.length>8?new $.Notice("",0):null,s=0;for(let n of e){i?.setMessage(`Syncing authors \u2192 ${n.split("/").pop()}\u2026`);for(let o of t)await this.ensureAuthorStubFor(n,o.id,o.name)&&s++}i?.hide(),this.notifications.show({message:`Synced authors across ${e.length} folder${e.length===1?"":"s"} \u2014 ${s} new stub${s===1?"":"s"} (${t.length} author${t.length===1?"":"s"} known).`,kind:"success",category:"system",folder:""})}collectKnownAuthors(){let t=new Map,e=(this.settings.authorId??"").trim(),i=(this.settings.authorName??"").trim();e&&i&&t.set(e,i);for(let s of this.authorRegistry.all())t.has(s.id)||t.set(s.id,s.name);for(let s of this.app.vault.getMarkdownFiles()){if(!s.path.includes("/_authors/"))continue;let n=this.parseAuthorFilePath(s.path);if(!n)continue;let o=this.app.metadataCache.getFileCache(s)?.frontmatter,r=((Array.isArray(o?.aliases)?o.aliases.find(l=>typeof l=="string")??"":typeof o?.aliases=="string"?o.aliases:"")||(typeof o?.name=="string"?o.name:"")||n.name).trim();t.has(n.id)||t.set(n.id,r),this.authorRegistry.record({id:n.id,name:r})}return[...t.entries()].map(([s,n])=>({id:s,name:n}))}async rebuildAuthorRegistry(){let t=this.discoverStashpadFolders(),e=new Map,i=0;for(let n of this.app.vault.getMarkdownFiles()){let o=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!o)continue;let a=[];if(typeof o.author=="string"&&a.push(o.author),Array.isArray(o.contributors))for(let r of o.contributors)typeof r=="string"&&a.push(r);for(let r of a){let l=this.parseAuthorRef(r);if(l)if(!e.has(l.id))e.set(l.id,{id:l.id,name:l.name,fromStub:!1}),i++;else{let c=e.get(l.id);!c.name&&l.name&&(c.name=l.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let l=this.app.metadataCache.getFileCache(a)?.frontmatter,p=((Array.isArray(l?.aliases)?l.aliases.find(I=>typeof I=="string")??"":typeof l?.aliases=="string"?l.aliases:"")||(typeof l?.name=="string"?l.name:"")||r.name).trim(),g=typeof l?.role=="string"?l.role:void 0,d=typeof l?.department=="string"?l.department:void 0,u=e.get(r.id);u||s++,e.set(r.id,{id:r.id,name:p||u?.name,role:g??u?.role,department:d??u?.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(p){console.warn("[Stashpad] restore author stub failed",c,p)}}}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+"/")||Te(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(g=>typeof g=="string"&&g.trim()&&!e(g)))))try{await this.app.fileManager.processFrontMatter(n,g=>{Array.isArray(g.attachments)?g.attachments=g.attachments.map(d=>typeof d=="string"&&d.trim()?Yt(d):d):typeof g.attachments=="string"&&g.attachments.trim()&&(g.attachments=[Yt(g.attachments)])}),t++}catch(g){console.warn("[Stashpad] attachment-link conversion failed",n.path,g)}}}return t}syncObsidianExcludedArchives(){try{let t=this.app.vault;if(typeof t.getConfig!="function"||typeof t.setConfig!="function")return;let e=Array.isArray(t.getConfig("userIgnoreFilters"))?t.getConfig("userIgnoreFilters"):[],i=new Set(e),s=!1;for(let n of this.discoverStashpadFolders()){let o=`${n.replace(/\/+$/,"")}/_archive/`;i.has(o)||(i.add(o),s=!0)}s&&t.setConfig("userIgnoreFilters",[...i])}catch(t){console.warn("[Stashpad] couldn't update Obsidian excluded files",t)}}openImportPicker(){let t=this.discoverStashpadFolders();if(t.length===0){new $.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 Rn(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 We(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={...he,...t,shortcuts:{...he.shortcuts,...t?.shortcuts??{}},mod:{...he.mod,...t?.mod??{}},bindings:Hr(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:Pr(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...zt]},Fn(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(),Fn(this.settings),Nt.enabled=!!this.settings.enablePerfProfiling;let t=(this.settings.authorId??"").trim();t&&this.authorRegistry.record({id:t,name:this.settings.authorName,role:this.settings.authorRole,department:this.settings.authorDepartment}),console.debug("[Stashpad] saveSettings",{shortcuts:this.settings.shortcuts,mod:this.settings.mod})}async persistSettingsQuiet(){await this.queueWrite()}async fixOrphanParents(){let t=new Set(this.discoverStashpadFolders());if(t.size===0){new $.Notice("No Stashpad folders found.");return}let e=new Set,i=this.app.vault.getMarkdownFiles();for(let p of i){let g=this.app.metadataCache.getFileCache(p)?.frontmatter,d=typeof g?.id=="string"?g.id.trim():"";d&&e.add(d)}let{newId:s}=await Promise.resolve().then(()=>(Gt(),Hi)),n=()=>{for(let p=0;p<100;p++){let g=s();if(!e.has(g))return e.add(g),g}for(let p=8;p<=16;p+=2){let g=s(p);if(!e.has(g))return e.add(g),g}throw new Error("Could not generate a unique id")},o=[];for(let p of i){let g=p.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(g))continue;let d=this.app.metadataCache.getFileCache(p)?.frontmatter,u=typeof d?.id=="string"?d.id.trim():"",I=d?.parent,f=typeof I=="string"?I.trim()!=="":I!=null,C=typeof d?.created=="string"&&d.created.trim()!=="",m=!u,y=!f,w=!C;!m&&!y&&!w||o.push({file:p,addId:m,addParent:y,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 p of o)try{let g;await this.app.fileManager.processFrontMatter(p.file,I=>{if(p.addId&&(typeof I.id=="string"&&I.id.trim()||(g=n(),I.id=g)),p.addParent){let f=I.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(I.parent=T)}p.addCreated&&(typeof I.created=="string"&&I.created.trim()||(I.created=new Date(p.file.stat.ctime).toISOString()))});let d=this.app.metadataCache.getFileCache(p.file)?.frontmatter,u=g??d?.id??"";u&&await l.append({type:"parent_change",id:u,payload:{from:null,to:T,reason:"orphan_fix",path:p.file.path,addedId:p.addId,addedParent:p.addParent,addedCreated:p.addCreated}}),a++}catch(g){console.warn("Stashpad: orphan fix failed for",p.file.path,g),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(()=>(Gt(),Hi)),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,p=typeof c?.id=="string"?c.id.trim():"";p&&i.add(p)}let s=()=>{for(let l=0;l<50;l++){let c=e();if(!i.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!i.has(c))return c}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||i.has(c)?(l.id=s(),n.push("id")):o.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?o.push("parent"):(l.parent=T,n.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?o.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(l){new $.Notice(`Adopt failed: ${l.message}`);return}let a=!1;try{let l=this.app.metadataCache.getFileCache(t)?.frontmatter,c=typeof l?.id=="string"?l.id.trim():"";if(c&&t.basename&&!t.basename.endsWith(`-${c}`)){let p=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(p)||(await this.app.fileManager.renameFile(t,p),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,p=c?.id??"";p&&await l.append({type:"create",id:p,payload:{path:t.path,parent:c?.parent??T,source:"adopt",added:n}})}catch{}}};function Hr(h,A,t){let e=vn();for(let i of Ke){let s=A&&typeof A[i.id]=="string"?A[i.id]:t&&typeof t[i.id]=="string"?t[i.id]:null;s!=null&&s!==""&&(e[i.id].primary=s)}if(h&&typeof h=="object")for(let i of Ke){let s=h[i.id];!s||typeof s!="object"||(e[i.id]={primary:typeof s.primary=="string"?s.primary:e[i.id].primary,secondary:typeof s.secondary=="string"?s.secondary:"",preferRight:!!s.preferRight,useBoth:!!s.useBoth})}for(let i of Ke){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 Pr(h){let A={};if(!h||typeof h!="object")return A;for(let[t,e]of Object.entries(h))if(typeof e=="string")A[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){A[t]=i;break}}return A}var Rn=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)}}; +`)}`,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 ${Kt}/.`,kind:"success",category:"system",folder:""}),!0):(new X.Notice(`Obsidian's vault trash (${Kt}/) 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 X.Notice(`Couldn't encrypt the existing trash: ${e.message}`,0),!1}}openEncryptedTrash(t){if(!this.encryption.isConfigured()){new X.Notice("Set up encryption first (Settings \u2192 Encryption).");return}ma(this)}async openRestoreTrashPicker(){if(!this.encryption.isConfigured()){new X.Notice("Set up encryption first (Settings \u2192 Encryption).");return}let t=await this.listDeletedTrash();if(t.length===0){new X.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 bs(this.app,e,i=>{this.restoreDeletedAt(i)}).open()}isArchiveFolder(t){let e=t.replace(/\/+$/,"");return(this.settings.archiveFolders??[]).includes(e)}async ensureOkfTemplate(){let t=await Ba(this.app,this.settings.okfTemplatePath||void 0);return this.settings.okfTemplatePath!==t&&(this.settings.okfTemplatePath=t,await this.saveSettings()),t}okfTemplatePathOrDefault(){return this.settings.okfTemplatePath||On}okfActiveFolders(){return this.settings.okfEnabled?Qa(this.settings.noteTemplates,this.okfTemplatePathOrDefault()).filter(t=>!this.isArchiveFolder(t)):[]}onOkfFileEvent(t){if(!this.settings.okfEnabled||!t.toLowerCase().endsWith(".md"))return;let e=t.lastIndexOf("/"),i=(e>=0?t.slice(0,e):"").replace(/\/+$/,"");(e>=0?t.slice(e+1):t)!=="index.md"&&(/(^|\/)(_imports|_exports|_attachments|_deleted|\.stashpad)(\/|$)/.test(t)||this.okfActiveFolders().includes(i)&&this.scheduleOkfRebuild(i))}scheduleOkfRebuild(t){let e=this.okfRebuildTimers.get(t);e!=null&&window.clearTimeout(e),this.okfRebuildTimers.set(t,window.setTimeout(()=>{this.okfRebuildTimers.delete(t),this.okfActiveFolders().includes(t)&&Ts(this.app,t).catch(i=>console.warn("[Stashpad] OKF auto-rebuild failed",t,i))},2500))}async rebuildAllOkf(){let t=this.okfActiveFolders(),e=0,i=0;for(let s of t){let n=await Ts(this.app,s);e+=n.checked,i+=n.written}return{folders:t.length,checked:e,written:i}}async exportOkf(t,e,i,s){let n=t.replace(/\/+$/,""),o=[],a=[],r=[],A=new Set;for(let f of e){let m=await ge(this.app,n,f);if(m){o.push({id:m.rootNote.id,file:m.rootNote.file}),r.push(m.rootNote.file),A.add(m.rootNote.id);for(let C of m.descendants)a.push({id:C.id,file:C.file}),r.push(C.file),A.add(C.id)}}if(!r.length)return[];let c=(i||"okf-export").replace(/[\\/:*?"<>|]+/g," ").replace(/\s+/g," ").trim().slice(0,80)||"okf-export",g=new Date().toISOString().replace(/\D/g,"").slice(0,14),p=(this.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),h=`${n}/${p}`;for(let f of[n,h])try{await this.app.vault.adapter.exists(f)||await this.app.vault.adapter.mkdir(f)}catch{}let u=[],I=async(f,m)=>{let C=`${h}/${f}`;await this.app.vault.createBinary(C,m.buffer.slice(m.byteOffset,m.byteOffset+m.byteLength)),u.push(C)};if(s.zip||s.targz){let f=await ya(this.app,r,n,A);s.zip&&await I(`${c}-${g}.okf.zip`,await Ea(f)),s.targz&&await I(`${c}-${g}.okf.tar.gz`,await wa(f))}if(s.stash){let f=await ce(this.app,{rootNotes:o,allDescendants:a,sourceFolder:n});await I(`${c}-${g}.${ie}`,f)}return u}async idsInFolder(t){let e=t.replace(/\/+$/,""),i=new Set;for(let s of this.app.vault.getMarkdownFiles())if((s.parent?.path?.replace(/\/+$/,"")??"")===e)try{let n=wt(await this.app.vault.read(s)).fm.id;typeof n=="string"&&i.add(n)}catch{}return i}async crossFolderPaste(t,e,i,s,n){let o=i.replace(/\/+$/,"");if(this.isArchiveFolder(o))return new X.Notice(`"${o.split("/").pop()}" auto-encrypts notes moved in, so cross-folder paste is disabled there. Use the "Move to archive" command \u2014 it checks the encryption key first.`),null;let a=[],r=[],A=[],c=[];for(let x of e){let F=await ge(this.app,t,x);if(F){A.push(F.rootNote.id),a.push({id:F.rootNote.id,file:F.rootNote.file}),c.push(F.rootNote.file);for(let N of F.descendants)r.push({id:N.id,file:N.file}),c.push(N.file)}}if(!a.length)return null;let g=a.length+r.length,p=[],h=[];n==="cut"&&(p=await this.exclusiveAttachmentsOf(c),h=await this.snapshotPaths([...c.map(x=>x.path),...p.map(x=>x.path)]));let u=await ce(this.app,{rootNotes:a,allDescendants:r,sourceFolder:t}),I=await this.idsInFolder(o),f=new Set(this.filesUnder(o)),m=await $t(this.app,u,o,I,{dedupeExisting:!1,forceNewIds:n==="copy",reparentRootsTo:s}),C=this.filesUnder(o).filter(x=>!f.has(x)),y=await this.snapshotPaths(C),w=A.map(x=>m.idRemap[x]).filter(x=>!!x);if(n==="cut"){for(let x of c)try{await this.app.fileManager.trashFile(x)}catch(F){console.warn("[Stashpad] cross-folder move: couldn't trash source note",x.path,F)}for(let x of p)try{await this.app.fileManager.trashFile(x)}catch(F){console.warn("[Stashpad] cross-folder move: couldn't trash source attachment",x.path,F)}}let E=async()=>{for(let x of[...C].reverse()){let F=this.app.vault.getAbstractFileByPath(x);if(F)try{await this.app.fileManager.trashFile(F)}catch{}}};return{rootIds:w,noteCount:g,undo:n==="cut"?async()=>{await E(),await this.restoreSnapshot(h)}:async()=>{await E()},redo:n==="cut"?async()=>{await this.restoreSnapshot(y);for(let x of h){let F=this.app.vault.getAbstractFileByPath(x.path);if(F)try{await this.app.fileManager.trashFile(F)}catch{}}}:async()=>{await this.restoreSnapshot(y)}}}async trashSubtrees(t,e){let i=[];for(let o of e){let a=await ge(this.app,t,o);a&&i.push(a.rootNote.file,...a.descendants.map(r=>r.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i),n=[];for(let o of[...i,...s])try{await this.app.fileManager.trashFile(o),n.push(o)}catch(a){console.warn("[Stashpad] trashSubtrees: couldn't trash",o.path,a)}return n}async exclusiveAttachmentsOf(t){let e=new Set(t.map(n=>n.path)),i=new Map;for(let n of t)for(let o of await rs(this.app,n))i.set(o.path,o);let s=this.app.metadataCache.resolvedLinks??{};for(let n of Object.keys(s))if(!e.has(n))for(let o of Object.keys(s[n]??{}))i.delete(o);return[...i.values()]}async subtreeFilePaths(t,e){let i=[];for(let n of e){let o=await ge(this.app,t,n);o&&i.push(o.rootNote.file,...o.descendants.map(a=>a.file))}if(!i.length)return[];let s=await this.exclusiveAttachmentsOf(i);return[...i.map(n=>n.path),...s.map(n=>n.path)]}async orderedSubtreeNodes(t,e){let i=[],s=new Set,n=o=>{let a=this.app.metadataCache.getFileCache(o)?.frontmatter?.position;return typeof a=="number"?a:Number.MAX_SAFE_INTEGER};for(let o of e){let a=await ge(this.app,t,o);if(!a)continue;let r=new Map;for(let c of a.descendants){if(!c.parent)continue;let g=r.get(c.parent)??[];g.push({id:c.id,file:c.file,created:c.created}),r.set(c.parent,g)}for(let c of r.values())c.sort((g,p)=>n(g.file)-n(p.file)||g.created.localeCompare(p.created));let A=(c,g)=>{if(!s.has(c.id)){s.add(c.id),i.push({file:c.file,created:c.created,depth:g});for(let p of r.get(c.id)??[])A(p,g+1)}};A({id:a.rootNote.id,file:a.rootNote.file,created:a.rootNote.created},0)}return i}filesUnder(t){let e=t.replace(/\/+$/,"")+"/";return this.app.vault.getFiles().filter(i=>i.path.startsWith(e)).map(i=>i.path)}async snapshotPaths(t){let e=[];for(let i of t){let s=this.app.vault.getAbstractFileByPath(i);if(!s)continue;let n=!i.toLowerCase().endsWith(".md");try{n?e.push({path:i,binary:n,data:await this.app.vault.readBinary(s)}):e.push({path:i,binary:n,text:await this.app.vault.read(s)})}catch(o){console.warn("[Stashpad] snapshotPaths: couldn't read",i,o)}}return e}async restoreSnapshot(t){for(let e of t){let i=e.path.split("/").slice(0,-1).join("/");await this.ensureVaultFolder(i);let s=this.app.vault.getAbstractFileByPath(e.path);try{e.binary?s?await this.app.vault.adapter.writeBinary(e.path,e.data):await this.app.vault.createBinary(e.path,e.data):s?await this.app.vault.modify(s,e.text??""):await this.app.vault.create(e.path,e.text??"")}catch(n){console.warn("[Stashpad] restoreSnapshot: couldn't write",e.path,n)}}}async ensureVaultFolder(t){if(!t)return;let e="";for(let i of t.split("/"))if(e=e?`${e}/${i}`:i,!await this.app.vault.adapter.exists(e))try{await this.app.vault.createFolder(e)}catch{}}refreshOpenViewsForFolder(t){let e=t.replace(/\/+$/,"");for(let i of this.app.workspace.getLeavesOfType(ct)){let s=i.view;if((s?.noteFolder?.replace(/\/+$/,"")??"")===e)try{s.tree?.rebuild?.(t),s.render?.()}catch(n){console.warn("[Stashpad] refresh view failed",n)}}}maybeArchiveOnMoveIn(t,e){if(t.extension!=="md")return;let i=t.parent?.path?.replace(/\/+$/,"")??"",s=e.lastIndexOf("/"),n=(s>=0?e.slice(0,s):"").replace(/\/+$/,"");if(i===n||!this.isArchiveFolder(i)||!this.encryption.isConfigured())return;let o=this.archivePending.get(i);o||(o={paths:new Set,timer:0},this.archivePending.set(i,o)),o.paths.add(t.path),window.clearTimeout(o.timer),o.timer=window.setTimeout(()=>{this.archivePending.delete(i),this.archiveSweep(i,[...o.paths])},1800)}async archiveSweep(t,e){if(!this.isArchiveFolder(t))return;let i=t.replace(/\/+$/,""),s=[];for(let A of e){let c=this.app.vault.getAbstractFileByPath(A);if(!(c instanceof X.TFile)||(c.parent?.path?.replace(/\/+$/,"")??"")!==i)continue;let g;try{g=wt(await this.app.vault.read(c)).fm}catch{continue}let p=typeof g.id=="string"?g.id:null;!p||p===T||s.push({id:p,parent:typeof g.parent=="string"?g.parent:null})}if(s.length===0)return;let n=new Set(s.map(A=>A.id)),o=new Set((this.settings.lockedSubtrees??[]).map(A=>A.rootId).filter(A=>!!A)),a=s.filter(A=>!o.has(A.id)&&!(A.parent&&n.has(A.parent)));if(a.length===0)return;if(!await this.ensureEncryptionUnlocked()){new X.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 A of a)await this.lockNoteSubtree(i,A.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 X.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 u of t)try{await u.loadIfDeferred?.()}catch{}let i=u=>u.getViewState()?.state??{},s=u=>{let I=i(u);return(u.isDeferred?I.folderOverride??"":u.view?.noteFolder??I.folderOverride??"").replace(/\/+$/,"")},n=u=>{let I=i(u);return(u.isDeferred?I.focusId:u.view?.focusId??I.focusId)||T},o=u=>{let I=u.view;return!!I&&I.getViewType?.()===ct&&typeof I.navigateTo=="function"&&typeof I.noteFolder=="string"},a=new Map;for(let u of this.app.vault.getMarkdownFiles()){let I=(u.parent?.path??"").replace(/\/+$/,""),f=this.app.metadataCache.getFileCache(u)?.frontmatter?.id;typeof f=="string"&&f&&(a.get(I)??a.set(I,new Set).get(I)).add(f)}let r=0,A=[];for(let u of t){let I=s(u),f=n(u);if(I&&f&&f!==T){let m=!u.isDeferred&&!!u.view?.tree?.get?.(f),C=a.get(I)?.has(f)??!1;if(!m&&!C){u.detach(),r++;continue}}A.push(u)}let c=new Map;for(let u of A){let I=s(u);if(!I)continue;let f=I+" "+n(u);(c.get(f)??c.set(f,[]).get(f)).push(u)}let g=0;for(let u of c.values()){if(u.length<=1)continue;u.sort((f,m)=>{let C=y=>y===e?2:y.isDeferred?0:1;return C(m)-C(f)});let I=null;for(let f of u){try{await f.loadIfDeferred?.()}catch{}if(o(f)){I=f;break}}I||(I=u[0]);for(let f of u)f!==I&&(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 X.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(u=>typeof u=="string"):[],A=a.includes(e),c=r.some(u=>u.includes(e));if(!A&&!c)continue;let g=n.parent?.path??"",p=i.find(u=>g===u||g.startsWith(u+"/"));if(!p)continue;s.has(p)||s.set(p,{authored:0,contributed:0});let h=s.get(p);A&&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 le(t)}authorRefFor(t,e,i){let s=i.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",n=`${t.replace(/\/+$/,"")}/_authors/${s}-${e}.md`,o=i.replace(/[\[\]|]/g,"").trim()||s;return`[[${n}|${o}]]`}async ensureAuthorStubFor(t,e,i){if(!e||!i)return!1;this.authorRegistry.record({id:e,name:i});let s=`${t.replace(/\/+$/,"")}/_authors`;if(this.app.vault.getMarkdownFiles().some(A=>A.path.startsWith(s+"/")&&this.parseAuthorFilePath(A.path)?.id===e))return!1;let o=this.authorRegistry.get(e),a=this.authorNameToSafe(i),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(A){return console.warn("[Stashpad] ensureAuthorStubFor failed",r,A),!1}}async seedKnownAuthorsInFolder(t){let e=0;for(let i of this.collectKnownAuthors())await this.ensureAuthorStubFor(t,i.id,i.name)&&e++;return e}async checkDueReminders(){let t=Date.now(),e=new Set(this.settings.notifiedDueKeys??[]),i=(this.settings.authorId??"").trim(),s=[];for(let o of this.app.vault.getMarkdownFiles()){if(o.path.includes("/_authors/"))continue;let a=this.app.metadataCache.getFileCache(o)?.frontmatter;if(!a||a.due==null)continue;let r=typeof a.id=="string"?a.id:"";if(!r)continue;let A=String(a.due),c=typeof a.due=="number"?a.due:Date.parse(A);if(!Number.isFinite(c)||c>t)continue;let g=Ee(a);if(g.length>0&&!(i&&g.some(h=>h.id===i)))continue;let p=`${r}@${A}`;e.has(p)||s.push({id:r,folder:(o.parent?.path??"").replace(/\/+$/,""),file:o,dueMs:c,key:p})}if(s.length===0)return;this.settings.notifiedDueKeys=[...this.settings.notifiedDueKeys??[],...s.map(o=>o.key)].slice(-2e3),await this.saveSettings();let n=async o=>{try{let r=wt(await this.app.vault.cachedRead(o)).body.split(/\r?\n/).map(A=>A.trim()).find(A=>A.length>0);if(r)return r.replace(/^[#>\-*\s]+/,"").slice(0,60)}catch{}return o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")};if(s.length<=3)for(let o of s){let a=await n(o.file);this.notifications.show({message:`\u23F0 Task due: \u201C${a}\u201D (${Zt(o.dueMs,this.settings)})`,kind:"warning",category:"reminder",duration:0,folder:o.folder,affectedIds:[o.id],actions:[{label:"Open",onClick:()=>void this.revealNoteByRef(o.folder,o.id)}]})}else this.notifications.show({message:`\u23F0 ${s.length} tasks are due \u2014 open the Tasks panel to review.`,kind:"warning",category:"reminder",duration:0,folder:""})}async syncAuthorsAcrossFolders(){await this.rebuildAuthorRegistry();let t=this.collectKnownAuthors(),e=this.discoverStashpadFolders();if(!t.length||!e.length){new X.Notice("No authors or Stashpad folders to sync.");return}let i=e.length*t.length>8?new X.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(A=>typeof A=="string")??"":typeof o?.aliases=="string"?o.aliases:"")||(typeof o?.name=="string"?o.name:"")||n.name).trim();t.has(n.id)||t.set(n.id,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 A=this.parseAuthorRef(r);if(A)if(!e.has(A.id))e.set(A.id,{id:A.id,name:A.name,fromStub:!1}),i++;else{let c=e.get(A.id);!c.name&&A.name&&(c.name=A.name)}}}let s=0;for(let n of t){let o=`${n}/_authors`;for(let a of this.app.vault.getMarkdownFiles()){if(!a.path.startsWith(o+"/"))continue;let r=this.parseAuthorFilePath(a.path);if(!r)continue;let A=this.app.metadataCache.getFileCache(a)?.frontmatter,g=((Array.isArray(A?.aliases)?A.aliases.find(I=>typeof I=="string")??"":typeof A?.aliases=="string"?A.aliases:"")||(typeof A?.name=="string"?A.name:"")||r.name).trim(),p=typeof A?.role=="string"?A.role:void 0,h=typeof A?.department=="string"?A.department:void 0,u=e.get(r.id);u||s++,e.set(r.id,{id:r.id,name:g||u?.name,role:p??u?.role,department:h??u?.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 A=this.parseAuthorFilePath(r.path)?.id;A&&a.add(A)}for(let r of t){if(a.has(r.id))continue;let A=this.authorNameToSafe(r.name),c=`${o}/${A}-${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+"/")||Te(n.path))continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!a||typeof a.id!="string"||!a.id)continue;let r=a.attachments,A=Array.isArray(r),c=typeof r=="string"&&r.trim().length>0;if(!(!A&&!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()?zt(h):h):typeof p.attachments=="string"&&p.attachments.trim()&&(p.attachments=[zt(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 X.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 Vn(this.app,e,t,i=>this.importService.pickFilesInto(i)).open()}async runImportLooseFiles(t){let e=t.split("/").pop()||t,i=0,s=0,n=0;try{({files:i,folders:s,stashes:n}=await this.importService.importLooseInto(t))}catch(A){this.notifications.show({message:`Stashpad: import failed in \`${e}\` +Error: ${A.message}`,kind:"error",category:"import",folder:t}),console.error("[Stashpad] runImportLooseFiles failed",t,A);return}let o=i+s+n,a=this.lastActiveStashpadLeaf?.view;o>0&&a?.noteFolder===t&&a?.tree&&(a.tree.rebuild(t),a.render?.());let r;if(o===0)r=`Nothing to import in \`${e}\` \u2014 everything here is already a Stashpad note.`;else{let A=[];i&&A.push(`${i} loose file${i===1?"":"s"}`),s&&A.push(`${s} folder${s===1?"":"s"} (as nested notes)`),n&&A.push(`${n} .stash bundle${n===1?"":"s"}`),r=`Imported ${A.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 $e(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={...ue,...t,shortcuts:{...ue.shortcuts,...t?.shortcuts??{}},mod:{...ue.mod,...t?.mod??{}},bindings:sl(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:nl(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...Vt]},Nn(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(),Nn(this.settings),xt.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 X.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(()=>(Lt(),Ji)),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,u=typeof h?.id=="string"?h.id.trim():"",I=h?.parent,f=typeof I=="string"?I.trim()!=="":I!=null,m=typeof h?.created=="string"&&h.created.trim()!=="",C=!u,y=!f,w=!m;!C&&!y&&!w||o.push({file:g,addId:C,addParent:y,addCreated:w})}if(o.length===0){new X.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,r=0,A=this.newLog();for(let g of o)try{let p;await this.app.fileManager.processFrontMatter(g.file,I=>{if(g.addId&&(typeof I.id=="string"&&I.id.trim()||(p=n(),I.id=p)),g.addParent){let f=I.parent;(typeof f=="string"?f.trim()!=="":f!=null)||(I.parent=T)}g.addCreated&&(typeof I.created=="string"&&I.created.trim()||(I.created=new Date(g.file.stat.ctime).toISOString()))});let h=this.app.metadataCache.getFileCache(g.file)?.frontmatter,u=p??h?.id??"";u&&await A.append({type:"parent_change",id:u,payload:{from:null,to:T,reason:"orphan_fix",path:g.file.path,addedId:g.addId,addedParent:g.addParent,addedCreated:g.addCreated}}),a++}catch(p){console.warn("Stashpad: orphan fix failed for",g.file.path,p),r++}let c=r?` (${r} failed \u2014 see console)`:"";new X.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Lt(),Ji)),i=new Set;for(let A of this.app.vault.getMarkdownFiles()){if(A.path===t.path)continue;let c=this.app.metadataCache.getFileCache(A)?.frontmatter,g=typeof c?.id=="string"?c.id.trim():"";g&&i.add(g)}let s=()=>{for(let A=0;A<50;A++){let c=e();if(!i.has(c))return c}for(let A=8;A<=16;A+=2){let c=e(A);if(!i.has(c))return c}throw new Error("Could not generate a unique id")},n=[],o=[];try{await this.app.fileManager.processFrontMatter(t,A=>{let c=typeof A.id=="string"?A.id.trim():"";!c||/\s/.test(c)||i.has(c)?(A.id=s(),n.push("id")):o.push("id"),A.parent!==void 0&&A.parent!==null&&String(A.parent).trim()!==""?o.push("parent"):(A.parent=T,n.push("parent")),typeof A.created=="string"&&A.created.trim()!==""?o.push("created"):(A.created=new Date(t.stat.ctime).toISOString(),n.push("created"))})}catch(A){new X.Notice(`Adopt failed: ${A.message}`);return}let a=!1;try{let A=this.app.metadataCache.getFileCache(t)?.frontmatter,c=typeof A?.id=="string"?A.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(A){console.warn("Stashpad: adopt rename failed",A)}if(n.length===0&&!a){new X.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 X.Notice(`Adopted into Stashpad \u2014 ${r.join("; ")}.`);try{let A=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,g=c?.id??"";g&&await A.append({type:"create",id:g,payload:{path:t.path,parent:c?.parent??T,source:"adopt",added:n}})}catch{}}};function sl(d,l,t){let e=xn();for(let i of Ke){let s=l&&typeof l[i.id]=="string"?l[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 Ke){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 Ke){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 nl(d){let l={};if(!d||typeof d!="object")return l;for(let[t,e]of Object.entries(d))if(typeof e=="string")l[t]=e;else if(e&&typeof e=="object"){for(let i of Object.values(e))if(typeof i=="string"&&i.length>0){l[t]=i;break}}return l}var Vn=class extends X.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 5cf9e05..7917c75 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.100.0", + "version": "0.102.12", "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 6a126bf..e3475bb 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "stashpad-obsidian", - "version": "0.100.0", + "version": "0.102.12", "private": true, "scripts": { "dev": "node esbuild.config.mjs", diff --git a/release-notes/0.102.12.md b/release-notes/0.102.12.md new file mode 100644 index 0000000..71792f5 --- /dev/null +++ b/release-notes/0.102.12.md @@ -0,0 +1,51 @@ +# 0.102.12 — Open Knowledge Format (OKF) support + +Turn a Stashpad folder into a browsable **Open Knowledge Format** bundle — the open, +vendor-neutral way to share curated knowledge with LLMs and agents — without +hand-authoring any of it. See `docs/okf-guide.md` for a from-scratch walkthrough. + +## OKF (new) + +- **New "Open Knowledge Format (OKF)" settings tab.** Flip it on, and a folder you + opt in becomes a valid OKF bundle while staying a normal Stashpad folder — + nothing of yours is renamed or removed. +- **Opt in per folder via a template.** Enabling OKF creates an `OKF Template.md`; + assign it to the folders you want (all, some, or none) in Settings → Templates. + A one-click "Create template + open Templates" gets you there. +- **Complementary frontmatter.** OKF folders get `okfType` / `okfTitle` / + `okfTimestamp` (yours to edit) plus `okfParent` / `okfChildren` as relative- + Markdown links that mirror your note tree — added alongside Stashpad's own fields. +- **Generated `index.md`** per OKF folder (an OKF table-of-contents) with a legend + explaining the fields. +- **Export as OKF.** Right-click a note (or selection) → "Export as OKF…" and pick + any of **.zip** / **.tar.gz** (portable OKF bundles) or **.stash** (re-importable). + Bundles map the `okf*` fields to OKF's standard keys, keep the originals for + lossless re-import, include a scope-adjusted `index.md`, and bundle attachments. +- **Stays in sync automatically.** Adding, moving, or deleting notes refreshes the + folder's OKF fields + `index.md` a few seconds later (a manual "Rebuild" button + forces it immediately). Archive folders are always excluded. + +## Folder panel + +- **Pinned folders now appear in the top "Pinned" section**, mixed with pinned + notes, so notes and folders share one quick-access area. The folder list below is + unchanged (pinned folders still rank first there). + +## Templates + +- The per-folder template field's autocomplete is now **keyboard-driven**: ↑/↓ to + move through suggestions, Enter to pick, Esc to close, and Tab to complete the + path one segment at a time. + +## Encryption + +- Added a clear, prominent disclaimer in the Encryption settings: the encryption + feature is **AI-built and not human-audited or security-tested** — a best-effort + nice-to-have, not a guarantee. Don't rely on it for anything sensitive, and keep + your own unencrypted backups. (Still beta.) + +## Polish + +- Settings text alignment fixes across several sections, monospaced code references + in the settings copy, and clearer setup guidance. +</content> diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs index 358c0d4..6efafe3 100644 --- a/scripts/deploy.mjs +++ b/scripts/deploy.mjs @@ -23,15 +23,20 @@ import { fileURLToPath } from "node:url"; const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url))); const ARTIFACTS = ["main.js", "manifest.json", "styles.css"]; -function resolveTarget() { +function resolveTargets() { + // Multiple targets supported: STASHPAD_DEPLOY or `.deploy-target` may list ONE + // PATH PER LINE (blank lines + `#` comments ignored). EVERY target is updated on + // each deploy — keep the Plugin Test vault and the Claude Dev Vault in sync so + // live testing never runs a stale build. + const fromText = (raw) => raw.split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith("#")).map((l) => resolve(l)); const envTarget = process.env.STASHPAD_DEPLOY?.trim(); - if (envTarget) return resolve(envTarget); + if (envTarget) return fromText(envTarget); const cfgPath = join(ROOT, ".deploy-target"); if (existsSync(cfgPath)) { - const raw = readFileSync(cfgPath, "utf8").trim(); - if (raw) return resolve(raw); + const targets = fromText(readFileSync(cfgPath, "utf8")); + if (targets.length) return targets; } - return null; + return []; } function fail(msg) { @@ -39,41 +44,39 @@ function fail(msg) { process.exit(1); } -const target = resolveTarget(); -if (!target) { +const targets = resolveTargets(); +if (targets.length === 0) { fail( "No deploy target configured. Set STASHPAD_DEPLOY env var or create a\n" + - ".deploy-target file at the project root with the destination path.\n" + + ".deploy-target file at the project root with one destination path per line.\n" + "Example: /Users/you/MyVault/.obsidian/plugins/stashpad", ); } -// Sanity-check: refuse to write to a path that doesn't look like a -// plugin folder (avoids accidental misconfigurations clobbering things). -const targetParent = dirname(target); -if (!existsSync(target)) { - try { - mkdirSync(target, { recursive: true }); - } catch (e) { - fail(`Couldn't create destination folder: ${target}\n${e.message}`); +let totalCopied = 0; +const allMissing = new Set(); +for (const target of targets) { + const targetParent = dirname(target); + if (!existsSync(target)) { + try { mkdirSync(target, { recursive: true }); } + catch (e) { fail(`Couldn't create destination folder: ${target}\n${e.message}`); } } -} -if (!existsSync(targetParent)) { - fail(`Parent of destination doesn't exist: ${targetParent}`); -} + if (!existsSync(targetParent)) fail(`Parent of destination doesn't exist: ${targetParent}`); -let copied = 0; -let missing = []; -for (const name of ARTIFACTS) { - const src = join(ROOT, name); - if (!existsSync(src)) { missing.push(name); continue; } - const dst = join(target, name); - copyFileSync(src, dst); - const sz = statSync(dst).size; - console.log(`[deploy] ${name.padEnd(14)} → ${dst} (${sz} bytes)`); - copied++; + let copied = 0; + for (const name of ARTIFACTS) { + const src = join(ROOT, name); + if (!existsSync(src)) { allMissing.add(name); continue; } + const dst = join(target, name); + copyFileSync(src, dst); + const sz = statSync(dst).size; + console.log(`[deploy] ${name.padEnd(14)} → ${dst} (${sz} bytes)`); + copied++; + } + console.log(`[deploy] copied ${copied}/${ARTIFACTS.length} → ${target}`); + totalCopied += copied; } -if (missing.length) { - console.warn(`[deploy] WARNING: missing artifacts: ${missing.join(", ")} — did you build?`); +if (allMissing.size) { + console.warn(`[deploy] WARNING: missing artifacts: ${[...allMissing].join(", ")} — did you build?`); } -console.log(`[deploy] copied ${copied}/${ARTIFACTS.length} → ${target}`); +console.log(`[deploy] done — ${targets.length} target${targets.length === 1 ? "" : "s"}, ${totalCopied} file copies`); diff --git a/src/commands/io-cmds.ts b/src/commands/io-cmds.ts index 0d4e911..0306107 100644 --- a/src/commands/io-cmds.ts +++ b/src/commands/io-cmds.ts @@ -3,7 +3,7 @@ import { ROOT_ID, type StashpadId, type TreeNode } from "../types"; import { buildStashZip, importStashZip, STASH_EXT } from "../stash-package"; import { argon2Available, encryptStash, resolveStashBytes, STASH_KDF_INFO } from "../stash-crypto"; import { secretIdForStashName } from "../passphrase"; -import { ExportStashModal } from "../modals"; +import { ExportStashModal, OkfExportModal } from "../modals"; import type { StashpadView } from "../view"; /** .stash import/export command group extracted from StashpadView @@ -33,6 +33,30 @@ export async function cmdExportStash(view: StashpadView, rootNode?: TreeNode): P }, argon2Available).open(); } +/** Export the selection/cursor subtree as an OKF bundle (.zip / .tar.gz) and/or a + * Stashpad .stash, via plugin.exportOkf. */ +export async function cmdExportOkf(view: StashpadView, rootNode?: TreeNode): Promise<void> { + const roots = collectExportRoots(view, rootNode); + if (roots.length === 0) { new Notice("Nothing to export."); return; } + const all = collectExportSubtree(view, roots); + if (all.length === 0) { new Notice("No exportable notes."); return; } + const folderTag = (view.noteFolder.split("/").pop() || view.noteFolder).trim(); + const defaultBase = roots.length === 1 ? view.titleForNode(roots[0]) : `${folderTag}-okf`; + new OkfExportModal(view.app, defaultBase, all.length, (base, formats) => { + void (async () => { + try { + const written = await view.plugin.exportOkf(view.noteFolder, roots.map((r) => r.id), base, formats); + if (!written.length) { new Notice("Nothing exported."); return; } + view.plugin.notifications.show({ + message: `Exported OKF — ${written.length} file${written.length === 1 ? "" : "s"} → \`${view.noteFolder}/${(view.plugin.settings.exportFolder || "_exports")}\``, + kind: "success", category: "export", affectedPaths: written, folder: view.noteFolder, duration: 0, + }); + await view.log.append({ type: "stash_export", id: roots[0].id, payload: { okf: true, paths: written, noteCount: all.length, rootIds: roots.map((r) => r.id) } }); + } catch (e) { new Notice(`OKF export failed: ${(e as Error).message}`); console.error(e); } + })(); + }).open(); +} + /** Build + write the .stash with the chosen base name, optionally encrypted, * then notify. */ async function runExport(view: StashpadView, roots: TreeNode[], all: TreeNode[], baseName: string, password: string | null, remember = false): Promise<void> { diff --git a/src/folder-panel-view.ts b/src/folder-panel-view.ts index 1d9a1d1..97990bb 100644 --- a/src/folder-panel-view.ts +++ b/src/folder-panel-view.ts @@ -137,11 +137,20 @@ export class StashpadFolderPanelView extends ItemView { } private renderPinned(list: HTMLElement): void { + // 0.102.x: pinned FOLDERS mix into the top "Pinned" section (above the pinned + // notes), using the same folder rows as the list below. The bottom Folders + // subsection is unchanged — pinned folders still appear there ranked-first. + const pinnedFolders = this.plugin.discoverStashpadFolders().filter((f) => this.folderState(f) === "pinned"); const pins = this.plugin.listPinnedNotes(); - if (pins.length === 0) { - list.createDiv({ cls: "stashpad-folderpanel-empty", text: "No pinned notes yet — pin a note from its right-click menu." }); + if (pinnedFolders.length === 0 && pins.length === 0) { + list.createDiv({ cls: "stashpad-folderpanel-empty", text: "Nothing pinned yet — pin a note or folder from its right-click menu." }); return; } + if (pinnedFolders.length > 0) { + const open = this.openFolders(); + for (const folder of pinnedFolders) this.renderFolderRow(list, folder, open); + } + if (pins.length === 0) return; const grouping = this.plugin.settings.folderPanelPinnedGrouping ?? "pin-order"; if (grouping === "folder") { // Group by Stashpad, MRU folder floated to the top (mirrors the Pinned panel). diff --git a/src/main.ts b/src/main.ts index 994d87e..d82044b 100644 --- a/src/main.ts +++ b/src/main.ts @@ -16,6 +16,8 @@ import { import { DEFAULT_STOPWORDS, bodyToSlug, buildFilename, parseIdFromFilename } from "./slug-service"; import { getActiveView, onActiveViewChange } from "./active-view"; import { importStashZip, buildStashZip, resolveNoteAttachmentFiles, STASH_EXT, splitFrontmatter } from "./stash-package"; +import { ensureOkfTemplate, okfFolders, rebuildOkfForFolder, OKF_DEFAULT_TEMPLATE_PATH } from "./okf"; +import { buildOkfBundleFiles, zipBundle, tarGzBundle } from "./okf-export"; import { formatDateTime } from "./format"; import { resolveStashBytes, isEncryptedStash } from "./stash-crypto"; import { StashpadLog } from "./log"; @@ -699,6 +701,14 @@ export default class StashpadPlugin extends Plugin { // last readable plaintext copy, sitting in render-cache.json. this.registerEvent(this.app.vault.on("delete", (f) => this.renderCacheStore.evict(f.path))); this.registerEvent(this.app.vault.on("rename", (_f, oldPath) => this.renderCacheStore.evict(oldPath))); + // 0.102.x: OKF auto-rebuild — when a note is added/deleted/moved in an OKF + // folder, refresh that folder's OKF frontmatter + index.md (debounced). Gated + // through okfActiveFolders so it never runs when OKF is off / for non-OKF / + // archive folders. Frontmatter writes are "modify" events (not listened here), + // so this can't loop on its own work; index.md is ignored explicitly. + this.registerEvent(this.app.vault.on("create", (f) => this.onOkfFileEvent(f.path))); + this.registerEvent(this.app.vault.on("delete", (f) => this.onOkfFileEvent(f.path))); + this.registerEvent(this.app.vault.on("rename", (f, oldPath) => { this.onOkfFileEvent(f.path); this.onOkfFileEvent(oldPath); })); // 0.77.1: load the author registry and seed it with the local user. await this.authorRegistry.load(); { @@ -1348,6 +1358,11 @@ export default class StashpadPlugin extends Plugin { name: "Export selection to .stash", callback: () => call("cmdExportStash"), }); + this.addCommand({ + id: "stashpad-export-okf", + name: "Export selection as OKF bundle (.zip / .tar.gz / .stash)", + callback: () => call("cmdExportOkf"), + }); this.addCommand({ id: "stashpad-import-stash", name: "Import .stash file…", @@ -2316,6 +2331,7 @@ export default class StashpadPlugin extends Plugin { let fmWritten = 0; let slugsRenamed = 0; let imported = 0; + const okfSet = new Set(this.okfActiveFolders()); for (const folder of seen) { try { if (importSub) await ensureFolder(`${folder}/${importSub}`); @@ -2347,6 +2363,13 @@ export default class StashpadPlugin extends Plugin { // landed (and any whose body was edited without the per-view // scheduleSlugRename firing). slugsRenamed += await this.rebootstrapFolderSlugs(folder); + // 0.102.x: rebootstrap also fixes OKF frontmatter + regenerates index.md + // for OKF-enabled folders (those using the OKF template). The OKF-section + // "Rebuild" button is just a scoped shortcut to this same pass — not an + // alias for the whole rebootstrap. + if (okfSet.has(folder.replace(/\/+$/, ""))) { + try { await rebuildOkfForFolder(this.app, folder); } catch (e) { console.warn("Stashpad: OKF rebuild during rebootstrap failed", folder, e); } + } touched.push(folder); } catch (e) { console.warn(`Stashpad: rebootstrap skipped ${folder}`, e); @@ -3318,6 +3341,111 @@ export default class StashpadPlugin extends Plugin { return (this.settings.archiveFolders ?? []).includes(cleaned); } + /** Ensure the OKF template note exists and remember its path (called when OKF + * is enabled). */ + async ensureOkfTemplate(): Promise<string> { + const path = await ensureOkfTemplate(this.app, this.settings.okfTemplatePath || undefined); + if (this.settings.okfTemplatePath !== path) { this.settings.okfTemplatePath = path; await this.saveSettings(); } + return path; + } + + /** The OKF template path, defaulting to the standard name when the setting is + * empty (e.g. OKF was enabled in an older build before create-on-enable). */ + okfTemplatePathOrDefault(): string { + return this.settings.okfTemplatePath || OKF_DEFAULT_TEMPLATE_PATH; + } + + /** Folders the OKF process should ACTUALLY touch: only when OKF is on, only + * folders assigned the OKF template, and NEVER archive folders (their whole + * point is private-at-rest — OKF would make them browsable/exportable). This + * is the single guard every OKF run goes through, so OKF-off / no-folders / + * excluded-folders can never accidentally trigger the process. */ + okfActiveFolders(): string[] { + if (!this.settings.okfEnabled) return []; + return okfFolders(this.settings.noteTemplates, this.okfTemplatePathOrDefault()) + .filter((f) => !this.isArchiveFolder(f)); + } + + /** Per-folder debounce timers for OKF auto-rebuild. */ + private okfRebuildTimers = new Map<string, number>(); + + /** A vault file changed (create/delete/rename) — if it's a real note in an + * active OKF folder, schedule a debounced rebuild of that folder. Ignores + * index.md (our own generated artifact, to avoid a write→event→rebuild loop) + * and reserved subfolders. */ + private onOkfFileEvent(path: string): void { + if (!this.settings.okfEnabled) return; + if (!path.toLowerCase().endsWith(".md")) return; + const slash = path.lastIndexOf("/"); + const folder = (slash >= 0 ? path.slice(0, slash) : "").replace(/\/+$/, ""); + const name = slash >= 0 ? path.slice(slash + 1) : path; + if (name === "index.md") return; + if (/(^|\/)(_imports|_exports|_attachments|_deleted|\.stashpad)(\/|$)/.test(path)) return; + if (!this.okfActiveFolders().includes(folder)) return; + this.scheduleOkfRebuild(folder); + } + + /** Debounced per-folder OKF rebuild (coalesces bursts like imports/resets). */ + private scheduleOkfRebuild(folder: string): void { + const prev = this.okfRebuildTimers.get(folder); + if (prev != null) window.clearTimeout(prev); + this.okfRebuildTimers.set(folder, window.setTimeout(() => { + this.okfRebuildTimers.delete(folder); + if (!this.okfActiveFolders().includes(folder)) return; // re-check at fire time + void rebuildOkfForFolder(this.app, folder).catch((e) => console.warn("[Stashpad] OKF auto-rebuild failed", folder, e)); + }, 2500)); + } + + /** Rebuild OKF frontmatter (relative-markdown links + defaults) + index.md for + * every active OKF folder. No-op when OKF is off / no folders use the template. */ + async rebuildAllOkf(): Promise<{ folders: number; checked: number; written: number }> { + const folders = this.okfActiveFolders(); + let checked = 0, written = 0; + for (const f of folders) { const r = await rebuildOkfForFolder(this.app, f); checked += r.checked; written += r.written; } + return { folders: folders.length, checked, written }; + } + + /** Export the subtree(s) rooted at `rootIds` in `folder` as OKF bundle(s) and/or + * a Stashpad .stash, written into the folder's export subfolder. Returns the + * paths written. zip/tar.gz are OKF bundles (spec keys mapped, scoped index.md); + * .stash is the native round-trip format. Reachable for tests + the command. */ + async exportOkf(folder: string, rootIds: StashpadId[], baseName: string, formats: { zip?: boolean; targz?: boolean; stash?: boolean }): Promise<string[]> { + const cleaned = folder.replace(/\/+$/, ""); + const rootNotes: { id: StashpadId; file: TFile }[] = []; + const allDescendants: { id: StashpadId; file: TFile }[] = []; + const files: TFile[] = []; + const scopeIds = new Set<string>(); + for (const rid of rootIds) { + const sub = await collectSubtree(this.app, cleaned, rid); + if (!sub) continue; + rootNotes.push({ id: sub.rootNote.id, file: sub.rootNote.file }); + files.push(sub.rootNote.file); scopeIds.add(sub.rootNote.id); + for (const d of sub.descendants) { allDescendants.push({ id: d.id, file: d.file }); files.push(d.file); scopeIds.add(d.id); } + } + if (!files.length) return []; + const safe = (baseName || "okf-export").replace(/[\\/:*?"<>|]+/g, " ").replace(/\s+/g, " ").trim().slice(0, 80) || "okf-export"; + const stamp = new Date().toISOString().replace(/\D/g, "").slice(0, 14); + const exportSub = (this.settings.exportFolder || "_exports").trim().replace(/^\/+|\/+$/g, ""); + const exportFolder = `${cleaned}/${exportSub}`; + for (const seg of [cleaned, exportFolder]) { try { if (!(await this.app.vault.adapter.exists(seg))) await this.app.vault.adapter.mkdir(seg); } catch { /* */ } } + const written: string[] = []; + const write = async (name: string, data: Uint8Array) => { + const path = `${exportFolder}/${name}`; + await this.app.vault.createBinary(path, data.buffer.slice(data.byteOffset, data.byteOffset + data.byteLength) as ArrayBuffer); + written.push(path); + }; + if (formats.zip || formats.targz) { + const bundle = await buildOkfBundleFiles(this.app, files, cleaned, scopeIds); + if (formats.zip) await write(`${safe}-${stamp}.okf.zip`, await zipBundle(bundle)); + if (formats.targz) await write(`${safe}-${stamp}.okf.tar.gz`, await tarGzBundle(bundle)); + } + if (formats.stash) { + const buf = await buildStashZip(this.app, { rootNotes, allDescendants, sourceFolder: cleaned }); + await write(`${safe}-${stamp}.${STASH_EXT}`, buf); + } + return written; + } + /** Ids of the markdown notes living directly in `folder` (read from DISK — the * metadata cache can lag and an under-read here would miss a real id collision * on import). */ diff --git a/src/modals.ts b/src/modals.ts index c556da4..54217d5 100644 --- a/src/modals.ts +++ b/src/modals.ts @@ -2068,3 +2068,39 @@ export class ImportDupChoiceModal extends Modal { } onClose(): void { if (!this.chose) this.onChoose("skip"); this.contentEl.empty(); } } + +/** OKF export: pick a name + one or more container formats. Delegates the actual + * bundle build to plugin.exportOkf (see okf-export.ts). */ +export class OkfExportModal extends Modal { + private base: string; + constructor(app: App, defaultBase: string, private noteCount: number, private onConfirm: (base: string, formats: { zip: boolean; targz: boolean; stash: boolean }) => void) { + super(app); this.base = defaultBase; + } + onOpen(): void { + this.contentEl.empty(); + this.modalEl.addClass("stashpad-export-modal"); + this.titleEl.setText("Export as OKF"); + this.contentEl.createEl("p", { cls: "stashpad-export-desc", text: `Export ${this.noteCount} note${this.noteCount === 1 ? "" : "s"} as an Open Knowledge Format bundle. Pick one or more formats.` }); + const name = this.contentEl.createEl("input", { type: "text" }) as HTMLInputElement; + name.addClass("stashpad-export-name"); name.value = this.base; name.placeholder = "Export name"; + const mk = (label: string, checked: boolean): HTMLInputElement => { + const row = this.contentEl.createDiv({ cls: "stashpad-okf-fmt" }); + const cb = row.createEl("input", { type: "checkbox" }) as HTMLInputElement; cb.checked = checked; + row.createEl("label", { text: label }); + return cb; + }; + const zip = mk(".zip — OKF bundle (portable)", true); + const targz = mk(".tar.gz — OKF bundle (tarball)", false); + const stash = mk(".stash — Stashpad format (re-importable)", false); + const footer = this.contentEl.createDiv({ cls: "stashpad-export-footer" }); + footer.createEl("button", { text: "Cancel" }).onclick = () => this.close(); + const go = footer.createEl("button", { cls: "mod-cta", text: "Export" }); + go.onclick = () => { + if (!zip.checked && !targz.checked && !stash.checked) { new Notice("Pick at least one format."); return; } + this.close(); + this.onConfirm(name.value.trim() || this.base, { zip: zip.checked, targz: targz.checked, stash: stash.checked }); + }; + requestAnimationFrame(() => name.focus()); + } + onClose(): void { this.contentEl.empty(); } +} diff --git a/src/okf-export.ts b/src/okf-export.ts new file mode 100644 index 0000000..9aadd48 --- /dev/null +++ b/src/okf-export.ts @@ -0,0 +1,121 @@ +import type { App, TFile } from "obsidian"; +import { splitFrontmatter } from "./stash-package"; +import { okfTitleFromFile, buildOkfIndex, OKF_LEGEND } from "./okf"; + +/** OKF export (Phase 4): turn an exported subtree into an OKF BUNDLE — concept + * markdown files whose frontmatter carries the bare OKF spec keys + * (`type`/`title`/`description`/`tags`/`timestamp`) mapped from our `okf*` fields, + * while KEEPING `id`/`okf*` redundantly so the bundle re-imports into Stashpad + * losslessly — plus a scope-adjusted `index.md`, a `_okf.md` legend, and the + * referenced attachments. Packaged as .zip and/or .tar.gz (no new dependency: + * JSZip for zip, a tiny tar writer + the platform `CompressionStream` for + * .tar.gz). The Stashpad-native `.stash` remains a separate option. */ + +export interface BundleFile { name: string; data: Uint8Array; } + +const te = new TextEncoder(); +const enc = (s: string): Uint8Array => te.encode(s); + +/** Minimal YAML scalar: quote when it has YAML-significant chars (the okf link + * values contain []() etc.). */ +function yamlScalar(v: unknown): string { + if (typeof v === "number" || typeof v === "boolean") return String(v); + const s = String(v ?? ""); + return /[:#[\]{}",&*!|>%@`]|^\s|\s$|^$/.test(s) ? JSON.stringify(s) : s; +} + +/** Inject the OKF spec keys at the TOP of a note's frontmatter, mapped from its + * `okf*` fields, keeping the rest of the frontmatter verbatim (so id/parent/okf* + * survive for a lossless Stashpad re-import). */ +function toConceptMarkdown(raw: string, file: TFile): string { + const { fm } = splitFrontmatter(raw); + const lines: string[] = []; + lines.push(`type: ${yamlScalar(typeof fm.okfType === "string" && fm.okfType ? fm.okfType : "concept")}`); + lines.push(`title: ${yamlScalar(typeof fm.okfTitle === "string" && fm.okfTitle ? fm.okfTitle : okfTitleFromFile(file))}`); + if (typeof fm.okfDescription === "string" && fm.okfDescription) lines.push(`description: ${yamlScalar(fm.okfDescription)}`); + const tags = fm.okfTags; + if (Array.isArray(tags) && tags.length) { lines.push("tags:"); for (const t of tags) lines.push(` - ${yamlScalar(t)}`); } + const ts = (typeof fm.okfTimestamp === "string" && fm.okfTimestamp) || (typeof fm.modified === "string" && fm.modified) || (typeof fm.created === "string" && fm.created) || ""; + if (ts) lines.push(`timestamp: ${yamlScalar(ts)}`); + const block = lines.join("\n"); + const m = raw.match(/^---\r?\n/); + if (m) return raw.slice(0, m[0].length) + block + "\n" + raw.slice(m[0].length); + return `---\n${block}\n---\n${raw}`; // note had no frontmatter +} + +/** Build the OKF bundle's files for an exported subtree (within `folder`). */ +export async function buildOkfBundleFiles( + app: App, files: TFile[], folder: string, scopeIds: Set<string>, +): Promise<BundleFile[]> { + const out: BundleFile[] = []; + const attachments = new Map<string, TFile>(); // basename -> file (dedup) + for (const f of files) { + const raw = await app.vault.read(f); + out.push({ name: f.name, data: enc(toConceptMarkdown(raw, f)) }); + // Collect referenced attachments (resolved against this note's path). + for (const ref of raw.match(/!\[\[([^\]]+?)\]\]/g) ?? []) { + const inner = ref.slice(3, -2).split("|")[0].split("#")[0].trim(); + const af = app.metadataCache.getFirstLinkpathDest(inner, f.path); + if (af && !attachments.has(af.name)) attachments.set(af.name, af); + } + } + for (const [name, af] of attachments) { + out.push({ name: `_attachments/${name}`, data: new Uint8Array(await app.vault.readBinary(af)) }); + } + out.push({ name: "index.md", data: enc(await buildOkfIndex(app, folder, scopeIds)) }); + out.push({ name: "_okf.md", data: enc(`# About this bundle\n\n${OKF_LEGEND.replace(/^> /gm, "")}\n`) }); + return out; +} + +/** Zip the bundle (JSZip, already a dependency). */ +export async function zipBundle(files: BundleFile[]): Promise<Uint8Array> { + const { default: JSZip } = await import("jszip"); + const zip = new JSZip(); + for (const f of files) zip.file(f.name, f.data); + return zip.generateAsync({ type: "uint8array", compression: "DEFLATE" }); +} + +// ---- minimal tar (ustar) + gzip, no dependency ---- +function octal(n: number, len: number): string { + return n.toString(8).padStart(len - 1, "0") + "\0"; +} +function tarHeader(name: string, size: number): Uint8Array { + const h = new Uint8Array(512); + const put = (s: string, off: number, len: number) => { const b = enc(s); h.set(b.subarray(0, len), off); }; + put(name.slice(0, 100), 0, 100); + put(octal(0o644, 8), 100, 8); // mode + put(octal(0, 8), 108, 8); // uid + put(octal(0, 8), 116, 8); // gid + put(octal(size, 12), 124, 12); // size + put(octal(0, 12), 136, 12); // mtime (0 — deterministic; Date.* is unavailable here anyway) + put(" ", 148, 8); // checksum placeholder (spaces) + h[156] = 0x30; // typeflag '0' (normal file) + put("ustar\0", 257, 6); put("00", 263, 2); + let sum = 0; for (let i = 0; i < 512; i++) sum += h[i]; + put(octal(sum, 8), 148, 8); + return h; +} +function buildTar(files: BundleFile[]): Uint8Array { + const parts: Uint8Array[] = []; + let total = 0; + for (const f of files) { + const header = tarHeader(f.name, f.data.length); + parts.push(header, f.data); + total += 512 + f.data.length; + const pad = (512 - (f.data.length % 512)) % 512; + if (pad) { parts.push(new Uint8Array(pad)); total += pad; } + } + parts.push(new Uint8Array(1024)); total += 1024; // two zero blocks = EOF + const tar = new Uint8Array(total); + let off = 0; for (const p of parts) { tar.set(p, off); off += p.length; } + return tar; +} +async function gzip(data: Uint8Array): Promise<Uint8Array> { + const cs = new CompressionStream("gzip"); + const stream = new Response(data as unknown as ArrayBuffer).body!.pipeThrough(cs); + return new Uint8Array(await new Response(stream).arrayBuffer()); +} +/** Tar + gzip the bundle (no dependency). */ +export async function tarGzBundle(files: BundleFile[]): Promise<Uint8Array> { + return gzip(buildTar(files)); +} diff --git a/src/okf.ts b/src/okf.ts new file mode 100644 index 0000000..e39566e --- /dev/null +++ b/src/okf.ts @@ -0,0 +1,157 @@ +import type { App, TFile } from "obsidian"; +import { ROOT_ID } from "./types"; +import { splitFrontmatter } from "./stash-package"; + +/** OKF (Open Knowledge Format) — Phase 2: the complementary frontmatter model + + * the template + the per-folder rebuild. See docs/branches/okf.md. + * + * Design: COMPLEMENTARY, never subtractive. Stashpad keeps its id-based + * parent/parentLink/children untouched; OKF adds its own namespaced fields so a + * folder is browsable as OKF AND still a normal Stashpad folder: + * - `okfParent` / `okfChildren` — RELATIVE MARKDOWN links (OKF's cross-link + * style), Stashpad-managed (reserved; rebuilt here). + * - `okfType` / `okfTitle` / `okfTimestamp` — user-editable; filled with + * defaults only when missing. On EXPORT these map to OKF's bare spec keys + * (`type`/`title`/`timestamp`) — that mapping is Phase 4. */ + +export const OKF_DEFAULT_TEMPLATE_PATH = "OKF Template.md"; +/** Seed template: `okfType` is a user-editable default; {{body}} is where the + * composed note body lands. okfParent/okfChildren/okfTitle/okfTimestamp are + * filled by the rebuild, not the template (they're per-note/derived). */ +export const OKF_TEMPLATE_BODY = "---\nokfType: concept\n---\n{{body}}\n"; + +/** Field legend embedded in each generated index.md so an LLM/agent reading the + * LIVE vault knows how Stashpad's namespaced fields map to OKF (we keep `okf*` + * live to avoid colliding with Obsidian's own `tags`/`title`; the bare spec keys + * are emitted on export). */ +export const OKF_LEGEND = [ + "> Generated by Stashpad — this folder is an Open Knowledge Format (OKF) bundle.", + "> Field legend: `okfType`→`type`, `okfTitle`→`title`, `okfDescription`→`description`, `okfTags`→`tags`, `okfTimestamp`→`timestamp`; `okfParent`/`okfChildren` are relative-markdown cross-links. Stashpad's own `id`/`parent` are extensions — ignore them for OKF.", +].join("\n"); + +/** Human/LLM-readable label for an OKF link (drop the -<id> filename suffix). */ +export function okfTitleFromFile(file: TFile): string { + return file.basename.replace(/-[a-z0-9]{4,12}$/, "").replace(/-/g, " ").trim() || file.basename; +} +/** A relative markdown link to a sibling note (Stashpad folders are flat, so the + * target is just the filename). Spaces %-encoded so the link is valid. */ +function okfLink(file: TFile): string { + return `[${okfTitleFromFile(file)}](${encodeURI(file.name)})`; +} + +/** Create the OKF template note if it's missing; returns its vault path. */ +export async function ensureOkfTemplate(app: App, path = OKF_DEFAULT_TEMPLATE_PATH): Promise<string> { + try { + if (!(await app.vault.adapter.exists(path))) await app.vault.create(path, OKF_TEMPLATE_BODY); + } catch { /* raced / already exists — fine */ } + return path; +} + +/** Folders that "use OKF" = folders whose assigned note template IS the OKF + * template (template-driven enablement, per the user's design). */ +export function okfFolders(noteTemplates: Record<string, string> | undefined, templatePath: string): string[] { + if (!templatePath) return []; + const tp = templatePath.replace(/^\/+/, ""); + return Object.entries(noteTemplates ?? {}) + .filter(([, v]) => (v ?? "").replace(/^\/+/, "") === tp) + .map(([k]) => k.replace(/\/+$/, "")); +} + +/** Write/refresh OKF frontmatter for every note directly in `folder`. Managed + * link fields (okfParent/okfChildren) are always reconciled; okfType/okfTitle/ + * okfTimestamp are only filled when absent (user owns them after). Reads from + * DISK (cache lags after edits), skip-if-equal, paced writes. */ +export async function rebuildOkfForFolder(app: App, folder: string): Promise<{ checked: number; written: number }> { + const cleaned = folder.replace(/\/+$/, ""); + type E = { file: TFile; id: string; parent: string; modified: string; created: string }; + const byId = new Map<string, E>(); + const childrenByParent = new Map<string, string[]>(); + for (const f of app.vault.getMarkdownFiles()) { + if ((f.parent?.path?.replace(/\/+$/, "") ?? "") !== cleaned) continue; + let fm: Record<string, unknown>; + try { fm = splitFrontmatter(await app.vault.read(f)).fm; } catch { continue; } + const id = typeof fm.id === "string" ? fm.id : null; + if (!id) continue; + const parent = typeof fm.parent === "string" ? fm.parent : ROOT_ID; + byId.set(id, { file: f, id, parent, modified: typeof fm.modified === "string" ? fm.modified : "", created: typeof fm.created === "string" ? fm.created : "" }); + const arr = childrenByParent.get(parent) ?? []; arr.push(id); childrenByParent.set(parent, arr); + } + + let checked = 0, written = 0; + for (const e of byId.values()) { + if (e.id === ROOT_ID) continue; // the home note is represented by index.md (Phase 3) + checked += 1; + const parentLink = (e.parent && e.parent !== ROOT_ID && byId.get(e.parent)) ? okfLink(byId.get(e.parent)!.file) : null; + const childLinks = (childrenByParent.get(e.id) ?? []).map((cid) => byId.get(cid)).filter((x): x is E => !!x).map((x) => okfLink(x.file)); + try { + let changed = false; + await app.fileManager.processFrontMatter(e.file, (m) => { + // Managed relative-markdown links. + if (parentLink) { if (m.okfParent !== parentLink) { m.okfParent = parentLink; changed = true; } } + else if (m.okfParent !== undefined) { delete m.okfParent; changed = true; } + const cur = Array.isArray(m.okfChildren) ? (m.okfChildren as unknown[]) : []; + const eq = cur.length === childLinks.length && cur.every((v, i) => v === childLinks[i]); + if (childLinks.length) { if (!eq) { m.okfChildren = childLinks; changed = true; } } + else if (m.okfChildren !== undefined) { delete m.okfChildren; changed = true; } + // User-editable defaults — only fill when missing. + if (m.okfType === undefined) { m.okfType = "concept"; changed = true; } + if (m.okfTitle === undefined) { m.okfTitle = okfTitleFromFile(e.file); changed = true; } + if (m.okfTimestamp === undefined) { const ts = e.modified || e.created; if (ts) { m.okfTimestamp = ts; changed = true; } } + }); + if (changed) { written += 1; await new Promise((r) => setTimeout(r, 50)); } + } catch (err) { console.warn("[Stashpad] OKF rebuild failed", e.file.path, err); } + } + // Regenerate the folder's index.md (OKF requires a per-dir index). + try { await app.vault.adapter.write(`${cleaned}/index.md`, await buildOkfIndex(app, cleaned)); } + catch (err) { console.warn("[Stashpad] OKF index.md write failed", cleaned, err); } + return { checked, written }; +} + +/** Build the OKF `index.md` for a folder: a `type: index` concept that lists every + * note (nested by hierarchy) with relative-markdown links, plus the field legend. + * `scopeIds` (optional) limits it to an exported subtree — index reflects the + * EXPORT scope, not the whole folder. NOTE: never reads/writes `.claude/INDEX.md` + * (that's Claude's code map) — this is a lowercase `index.md` in vault content. */ +export async function buildOkfIndex(app: App, folder: string, scopeIds?: Set<string>): Promise<string> { + const cleaned = folder.replace(/\/+$/, ""); + type N = { id: string; file: TFile; parent: string; title: string; type: string; position: number; created: string }; + const byId = new Map<string, N>(); + const kids = new Map<string, N[]>(); + for (const f of app.vault.getMarkdownFiles()) { + if ((f.parent?.path?.replace(/\/+$/, "") ?? "") !== cleaned) continue; + if (f.name === "index.md") continue; // never index the index + let fm: Record<string, unknown>; + try { fm = splitFrontmatter(await app.vault.read(f)).fm; } catch { continue; } + const id = typeof fm.id === "string" ? fm.id : null; + if (!id || id === ROOT_ID) continue; + if (scopeIds && !scopeIds.has(id)) continue; + byId.set(id, { + id, file: f, parent: typeof fm.parent === "string" ? fm.parent : ROOT_ID, + title: typeof fm.okfTitle === "string" && fm.okfTitle ? fm.okfTitle : okfTitleFromFile(f), + type: typeof fm.okfType === "string" && fm.okfType ? fm.okfType : "concept", + position: typeof fm.position === "number" ? fm.position : Number.MAX_SAFE_INTEGER, + created: typeof fm.created === "string" ? fm.created : "", + }); + } + for (const n of byId.values()) { const a = kids.get(n.parent) ?? []; a.push(n); kids.set(n.parent, a); } + for (const a of kids.values()) a.sort((x, y) => (x.position - y.position) || x.created.localeCompare(y.created)); + + const lines: string[] = []; + const walk = (n: N, depth: number, seen: Set<string>): void => { + if (seen.has(n.id)) return; seen.add(n.id); + lines.push(`${" ".repeat(depth)}- [${n.title}](${encodeURI(n.file.name)}) — ${n.type}`); + for (const c of kids.get(n.id) ?? []) walk(c, depth + 1, seen); + }; + // Roots of the (possibly scoped) set: parent is ROOT or outside the set. + const seen = new Set<string>(); + const roots = [...byId.values()].filter((n) => n.parent === ROOT_ID || !byId.has(n.parent)) + .sort((x, y) => (x.position - y.position) || x.created.localeCompare(y.created)); + for (const r of roots) walk(r, 0, seen); + + const folderName = cleaned.split("/").pop() || cleaned; + return [ + "---", "type: index", `title: ${folderName} (OKF index)`, "---", "", + `# ${folderName}`, "", OKF_LEGEND, "", "## Concepts", + lines.length ? lines.join("\n") : "_No concepts yet._", "", + ].join("\n"); +} diff --git a/src/settings.ts b/src/settings.ts index 3d16f6f..6999200 100644 --- a/src/settings.ts +++ b/src/settings.ts @@ -438,6 +438,13 @@ export interface StashpadSettings { * before that — and to step back to the terser confirm once the * user has built once and presumably knows what they're doing. */ jdIndexHasBuilt: boolean; + /** OKF (Open Knowledge Format) support — master toggle. When on, folders using + * the OKF template get OKF frontmatter + a generated index.md (see + * docs/branches/okf.md). */ + okfEnabled: boolean; + /** Vault path of the auto-created OKF template note (assigned per-folder via the + * Templates section). Empty until OKF is first enabled. */ + okfTemplatePath: string; /** Per-folder composer draft text. Stored in the plugin's data.json. */ drafts: Record<string, string>; /** Per-folder: the text most recently sent via Enter, used to suppress @@ -521,6 +528,8 @@ export const DEFAULT_SETTINGS: StashpadSettings = { jdIndexIncludeStashpadFolders: false, jdIndexSort: "natural", jdIndexHasBuilt: false, + okfEnabled: false, + okfTemplatePath: "", drafts: {}, lastSubmitted: {}, bindings: buildDefaultBindings(), @@ -554,7 +563,7 @@ export function getTemplatesFormats(app: App): { dateFormat: string; timeFormat: /** 0.73.1: settings tab redesigned into a tabbed UI. SETTINGS_TABS * is the source of truth for both the bar at the top and the * search-mode group order. Order here = display order. */ -export type SettingsTabId = "general" | "encryption" | "diagnostics" | "authorship" | "templates" | "jdindex" | "hotkeys"; +export type SettingsTabId = "general" | "encryption" | "diagnostics" | "authorship" | "templates" | "jdindex" | "okf" | "hotkeys"; export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = [ { id: "general", label: "General" }, { id: "encryption", label: "Encryption" }, @@ -562,6 +571,7 @@ export const SETTINGS_TABS: Array<{ id: SettingsTabId; label: string }> = [ { id: "authorship", label: "Authorship" }, { id: "templates", label: "Templates" }, { id: "jdindex", label: "JD Index" }, + { id: "okf", label: "Open Knowledge Format (OKF)" }, { id: "hotkeys", label: "Hotkeys" }, ]; @@ -667,6 +677,7 @@ export class StashpadSettingTab extends PluginSettingTab { case "authorship": return this.authorshipItems(); case "templates": return this.templatesItems(); case "jdindex": return this.jdIndexItems(); + case "okf": return this.okfItems(); default: return null; } } @@ -1023,6 +1034,9 @@ export class StashpadSettingTab extends PluginSettingTab { const betaRow = host.createDiv({ cls: "stashpad-beta-row" }); betaRow.createEl("span", { cls: "stashpad-beta-badge", text: "BETA" }); betaRow.createEl("span", { cls: "stashpad-beta-note", text: "Encryption is in beta — keep your own backups of anything important." }); + host.createEl("div", { cls: "stashpad-ai-disclaimer" }).setText( + "⚠️ AI-built, NOT human-audited. This encryption was written by an AI assistant — not designed, reviewed, or security-audited by a human, and not tested by any security professional. It may carry real security, privacy, and DATA-LOSS risks. Treat it as a best-effort nice-to-have that might buy a little time against a casual snoop — nothing is guaranteed. Do NOT rely on it for anything sensitive, and always keep your own unencrypted backups of anything important.", + ); host.createEl("p", { cls: "setting-item-description" }).setText( "⚠️ Encryption protects what you lock in this vault. Each device unlocks with its own password (which never leaves the device); the vault key is shared with collaborators by approving their device — no shared password. If everyone with access loses their password, anything encrypted is gone for good. While encrypting, avoid a sync/cloud service writing the vault mid-operation — it can corrupt files.", ); @@ -1518,7 +1532,7 @@ export class StashpadSettingTab extends PluginSettingTab { const stashpads = this.plugin.discoverStashpadFolders(); if (stashpads.length === 0) { new Setting(parent) - .setName("Color Aliases per Stashpad") + .setName("Color aliases per Stashpad") .setDesc("No Stashpads discovered yet — create one above first."); return; } @@ -1532,7 +1546,7 @@ export class StashpadSettingTab extends PluginSettingTab { })(); new Setting(parent) - .setName("Color Aliases per Stashpad") + .setName("Color aliases per Stashpad") .setDesc("Which Stashpad's colors to label.") .addDropdown((dd) => { for (const f of stashpads) dd.addOption(f, f); @@ -1669,6 +1683,121 @@ export class StashpadSettingTab extends PluginSettingTab { ]; } + /** OKF (Open Knowledge Format) tab. Phase 1: master toggle + docs + how-to. + * Frontmatter/index.md/export land in later phases (docs/branches/okf.md). */ + private okfItems(): SettingDefinitionItem[] { + return [ + this.sectionDef("Open Knowledge Format (OKF)", + "Turn a Stashpad folder into a browsable OKF bundle — markdown concept files with OKF frontmatter, a generated index.md, and relative-markdown cross-links — that LLMs/agents can read. Complements (never replaces) Stashpad's own frontmatter and links.", + (host) => this.renderOkfSection(host), + ["okf", "open knowledge format", "knowledge", "catalog", "index", "export", "bundle", "tarball", "agent", "google"]), + ]; + } + + /** Append `text` to an element/fragment, rendering `backtick` spans as <code> + * (monospace) via text nodes — safe for interpolated values (no innerHTML). */ + private appendCode(el: HTMLElement | DocumentFragment, text: string): void { + text.split(/`([^`]+)`/g).forEach((part, i) => { + if (i % 2 === 1) el.createEl("code", { text: part }); + else if (part) el.appendText(part); + }); + } + /** A setting-description fragment with `backtick` → <code>, for setDesc(). */ + private codeDesc(text: string): DocumentFragment { + const f = document.createDocumentFragment(); + this.appendCode(f, text); + return f; + } + + private renderOkfSection(parent: HTMLElement): void { + parent.createDiv({ cls: "stashpad-beta-row" }).createEl("span", { cls: "stashpad-beta-badge", text: "BETA" }); + + new Setting(parent) + .setName("Enable OKF") + .setDesc(this.codeDesc("Master switch. When on, you choose which folders use OKF by assigning the OKF template to them in Settings → Templates (all / some / none — your call). Those folders then get OKF frontmatter and a maintained `index.md`. Turning this off leaves existing OKF files in place; it just stops maintaining them.")) + .addToggle((t) => t.setValue(this.plugin.settings.okfEnabled).onChange(async (v) => { + this.plugin.settings.okfEnabled = v; + await this.plugin.saveSettings(); + if (v) { try { await this.plugin.ensureOkfTemplate(); } catch (e) { console.warn("[Stashpad] OKF template create failed", e); } } + new Notice(v + ? `OKF on. Next: assign the template "${this.plugin.okfTemplatePathOrDefault()}" to a folder — use “Create template + open Templates” below. Heads-up: OKF frontmatter + index.md refresh automatically but NOT instantly (a few seconds after changes); hit Rebuild for an immediate pass.` + : "OKF disabled.", v ? 0 : 4000); // persistent CTA on enable (stays until dismissed) + this.update?.(); + })); + + if (this.plugin.settings.okfEnabled) { + const okfPath = this.plugin.okfTemplatePathOrDefault(); + const okfCount = this.plugin.okfActiveFolders().length; + const steps = parent.createEl("div", { cls: "setting-item-description stashpad-okf-howto" }); + steps.createEl("p", { text: "How to use OKF in a folder:" }); + const ol = steps.createEl("ol"); + this.appendCode(ol.createEl("li"), `Open Templates and set a folder's template to \`${okfPath}\` (archive folders are skipped).`); + this.appendCode(ol.createEl("li"), "Hit Rebuild below to write OKF frontmatter (`okfParent`/`okfChildren` + `okfType`/`okfTitle`/`okfTimestamp`) and generate that folder's `index.md`."); + this.appendCode(ol.createEl("li"), "Right-click a note (or a selection) → “Export as OKF…” to save a `.zip` / `.tar.gz` bundle (or `.stash`)."); + steps.createEl("p", { cls: "stashpad-okf-soon", text: "OKF frontmatter + index.md refresh automatically a few seconds after you add, move, or delete notes — NOT instantly. Use Rebuild for an immediate pass." }); + if (okfCount === 0) { + const cta = parent.createEl("p", { cls: "stashpad-okf-cta" }); + this.appendCode(cta, "👉 No folder is using OKF yet. Click “Create template + open Templates” below, then set a folder's template to `" + okfPath + "`."); + } else { + steps.createEl("p", { cls: "stashpad-okf-soon", text: `Currently ${okfCount} folder${okfCount === 1 ? "" : "s"} actively using OKF.` }); + } + + new Setting(parent) + .setName("Assign OKF to folders") + .setDesc(this.codeDesc(`Creates the OKF template if needed (never duplicates it), then opens Templates — set a folder's template to \`${okfPath}\` there.`)) + .addButton((b) => { b.setButtonText("Create template + open Templates").setCta(); b.onClick(async () => { + let path: string; + try { path = await this.plugin.ensureOkfTemplate(); } + catch (e) { new Notice(`Couldn't create the OKF template: ${(e as Error).message}`); return; } + new Notice(`OKF template ready at "${path}" — set a folder's template to that path.`); + this.update?.(); + this.openSettingsPage("Templates"); + }); }); + + new Setting(parent) + .setName("Rebuild OKF frontmatter") + .setDesc(this.codeDesc("Write/refresh OKF fields for every folder using the OKF template — `okfParent`/`okfChildren` relative links (managed) plus `okfType`/`okfTitle`/`okfTimestamp` defaults (yours to edit after). Heads-up: adding, moving, or deleting notes already auto-refreshes the folder, but NOT instantly — it waits ~a few seconds after you stop. Use this button for an immediate rebuild (e.g. right after first assigning the template). Complements Stashpad's own links; nothing is removed.")) + .addButton((b) => b.setButtonText("Rebuild now").onClick(async () => { + const r = await this.plugin.rebuildAllOkf(); + new Notice(r.folders === 0 + ? "No folders use the OKF template yet — assign it in Templates first." + : `OKF: updated ${r.written} of ${r.checked} notes across ${r.folders} folder${r.folders === 1 ? "" : "s"}.`); + this.update?.(); + })); + } + + // Docs + const docs = new Setting(parent).setName("Learn about OKF").setDesc("Google's open, vendor-neutral spec for sharing curated knowledge with agents."); + docs.addButton((b) => b.setButtonText("Spec / repo").onClick(() => window.open("https://github.com/GoogleCloudPlatform/knowledge-catalog/tree/main/okf"))); + docs.addButton((b) => b.setButtonText("Announcement").onClick(() => window.open("https://cloud.google.com/blog/products/data-analytics/how-the-open-knowledge-format-can-improve-data-sharing/"))); + } + + /** Best-effort jump to another Stashpad settings sub-page by its visible name. + * Obsidian exposes no public sub-page nav, so we reset to the Stashpad page + * list (openTabById) then click the matching entry; falls back to a hint. */ + private openSettingsPage(pageName: string): void { + // Obsidian has no public API to open a plugin's own settings SUB-PAGE (see + // docs/obsidian-limitations.md). Best-effort: reset to the Stashpad page list, + // then click the matching entry — but ONLY inside the active tab's CONTENT + // pane, never the left sidebar (whose core/community plugin tabs, e.g. the core + // "Templates" plugin, would otherwise match by name and mis-navigate). If we + // can't find it in-content, we DON'T guess — we just point the way. + const hint = () => new Notice(`Open Settings → Stashpad → ${pageName}.`); + try { + const setting = (this.app as App & { setting?: { openTabById?: (id: string) => void; modalEl?: HTMLElement } }).setting; + if (!setting?.openTabById) { hint(); return; } + setting.openTabById("stashpad"); + window.setTimeout(() => { + const content = setting.modalEl?.querySelector<HTMLElement>(".vertical-tab-content"); + if (!content) { hint(); return; } + const hit = Array.from(content.querySelectorAll<HTMLElement>("*")) + .find((e) => e.childElementCount === 0 && e.textContent?.trim() === pageName && !e.closest(".vertical-tab-header")); + const link = hit?.closest<HTMLElement>("[class*='nav'], .setting-item, button, a"); + if (link && !link.closest(".vertical-tab-header")) link.click(); else hint(); + }, 60); + } catch { hint(); } + } + private renderAuthorshipSection(parent: HTMLElement): void { parent.createEl("h3", { text: "Authorship" }); parent.createEl("p", { @@ -1827,6 +1956,13 @@ export class StashpadSettingTab extends PluginSettingTab { .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."); + if (this.plugin.settings.okfEnabled) { + const okfPath = this.plugin.okfTemplatePathOrDefault(); + this.appendCode(parent.createEl("p", { cls: "setting-item-description" }), + `💡 OKF tip: type \`${okfPath}\` into a folder's template field below to turn that folder into an OKF bundle (OKF frontmatter + a maintained \`index.md\`). Assign it to all, some, or none of your folders — it's per-folder. Manage OKF itself in Settings → OKF.`, + ); + } + const list = parent.createDiv({ cls: "stashpad-note-templates-list" }); const renderRow = (folder: string): void => { @@ -1849,6 +1985,17 @@ export class StashpadSettingTab extends PluginSettingTab { // Obsidian version that ships with the plugin. const sugg = inputWrap.createDiv({ cls: "stashpad-note-template-suggest" }); sugg.style.display = "none"; + let currentMatches: string[] = []; + let itemEls: HTMLElement[] = []; + let activeIdx = -1; + const isOpen = (): boolean => sugg.style.display !== "none" && currentMatches.length > 0; + const highlight = (i: number): void => { + activeIdx = i; + itemEls.forEach((el, idx) => el.toggleClass("is-active", idx === i)); + if (i >= 0 && itemEls[i]) itemEls[i].scrollIntoView({ block: "nearest" }); + }; + const closeSugg = (): void => { sugg.style.display = "none"; activeIdx = -1; }; + const choose = async (m: string): Promise<void> => { input.value = m; await save(); closeSugg(); }; // Inline warning area — surfaces overlap with Stashpad's // auto-managed frontmatter so the user can fix the template before @@ -1867,28 +2014,26 @@ export class StashpadSettingTab extends PluginSettingTab { const renderSuggestions = (): void => { sugg.empty(); + itemEls = []; // 0.76.26: Sift — all-tokens, any-order match (see docs/sift.md). const tokens = input.value.trim().toLowerCase().split(/\s+/).filter(Boolean); const sift = (p: string): boolean => { const h = p.toLowerCase(); return tokens.every((t) => h.includes(t)); }; - const matches = allMd() - .filter((p) => sift(p)) - .slice(0, 12); - if (matches.length === 0) { sugg.style.display = "none"; return; } + currentMatches = allMd().filter((p) => sift(p)).slice(0, 12); + if (currentMatches.length === 0) { closeSugg(); return; } sugg.style.display = ""; - for (const m of matches) { + currentMatches.forEach((m, idx) => { const item = sugg.createDiv({ cls: "stashpad-note-template-suggest-item", text: m }); + itemEls.push(item); + item.addEventListener("mousemove", () => highlight(idx)); // mousedown (not click) so the input's blur doesn't close the // popover before the click registers. - item.addEventListener("mousedown", async (ev) => { - ev.preventDefault(); - input.value = m; - await save(); - sugg.style.display = "none"; - }); - } + item.addEventListener("mousedown", async (ev) => { ev.preventDefault(); await choose(m); }); + }); + activeIdx = activeIdx >= 0 && activeIdx < currentMatches.length ? activeIdx : -1; + if (activeIdx >= 0) highlight(activeIdx); }; const save = async (): Promise<void> => { @@ -1935,9 +2080,46 @@ export class StashpadSettingTab extends PluginSettingTab { }; input.addEventListener("focus", renderSuggestions); - input.addEventListener("input", renderSuggestions); - input.addEventListener("blur", () => { setTimeout(() => { sugg.style.display = "none"; }, 150); }); + input.addEventListener("input", () => { activeIdx = -1; renderSuggestions(); }); + input.addEventListener("blur", () => { setTimeout(closeSugg, 150); }); input.addEventListener("change", () => { void save(); }); + input.addEventListener("keydown", (e) => { + if (e.key === "ArrowDown") { + e.preventDefault(); + if (!isOpen()) { renderSuggestions(); if (currentMatches.length) highlight(0); } + else highlight((activeIdx + 1) % currentMatches.length); + } else if (e.key === "ArrowUp") { + if (!isOpen()) return; + e.preventDefault(); + highlight((activeIdx - 1 + currentMatches.length) % currentMatches.length); + } else if (e.key === "Enter") { + if (isOpen() && activeIdx >= 0) { e.preventDefault(); void choose(currentMatches[activeIdx]); } + } else if (e.key === "Escape") { + if (isOpen()) { e.preventDefault(); closeSugg(); } + } else if (e.key === "Tab" && !e.shiftKey) { + // Per-segment ("per word") completion: extend the input toward the + // active (or first) match by one path segment, narrowing the list. + // Only swallow Tab when we actually complete — otherwise let it move + // focus as usual. + if (!isOpen()) return; + const target = currentMatches[activeIdx >= 0 ? activeIdx : 0]; + const cur = input.value; + let next: string; + if (target.toLowerCase().startsWith(cur.toLowerCase())) { + const slash = target.indexOf("/", cur.length); + next = slash >= 0 ? target.slice(0, slash + 1) : target; + } else { + next = target; // token (non-prefix) match — complete it fully + } + if (next && next !== cur) { + e.preventDefault(); + input.value = next; + activeIdx = -1; + renderSuggestions(); + if (currentMatches.length === 1) highlight(0); + } + } + }); // Initial validation on render so existing saved templates show // warnings without requiring a re-edit. validateTemplate(); diff --git a/src/types.ts b/src/types.ts index b36bc49..b7ebcc6 100644 --- a/src/types.ts +++ b/src/types.ts @@ -110,6 +110,10 @@ export const RESERVED_FRONTMATTER: readonly string[] = [ // 0.88.0: marks a note that came in via import (used by the "imported only" // view filter). Stashpad-managed; a clone of an imported note isn't imported. "imported", + // 0.101.x: OKF relative-markdown cross-links, derived from the tree and + // Stashpad-managed (rebuilt by the OKF pass). The user-editable OKF fields + // (okfType/okfTitle/okfTimestamp) are intentionally NOT reserved. + "okfParent", "okfChildren", ] as const; /** Reserved Stashpad subfolder names (machine-managed; not user notes). diff --git a/src/view.ts b/src/view.ts index e81e351..bb90c15 100644 --- a/src/view.ts +++ b/src/view.ts @@ -9114,6 +9114,7 @@ export class StashpadView extends ItemView { // Implementations live in commands/io-cmds.ts; these thin delegators keep // the public method names stable for the keydown dispatcher + main.ts. cmdExportStash(rootNode?: TreeNode): Promise<void> { return ioCmds.cmdExportStash(this, rootNode); } + cmdExportOkf(rootNode?: TreeNode): Promise<void> { return ioCmds.cmdExportOkf(this, rootNode); } cmdImportStash(): Promise<void> { return ioCmds.cmdImportStash(this); } processStashFile(file: TFile): Promise<void> { return ioCmds.processStashFile(this, file); } @@ -9686,6 +9687,12 @@ export class StashpadView extends ItemView { if (!this.selection.has(node.id)) { this.selection.clear(); this.selection.add(node.id); this.lastSelected = node.id; } void this.cmdExportStash(); })); + if (this.plugin.settings.okfEnabled) { + menu.addItem((it: any) => it.setTitle("Export as OKF…").setIcon("book-marked").onClick(() => { + if (!this.selection.has(node.id)) { this.selection.clear(); this.selection.add(node.id); this.lastSelected = node.id; } + void this.cmdExportOkf(); + })); + } // 0.98.1: encrypt (lock) this note + its whole subtree into one .stashenc // bundle, in place. Only shown once a vault encryption password is set up. if (this.plugin.encryption?.isConfigured?.()) { diff --git a/styles.css b/styles.css index 86782df..b653a99 100644 --- a/styles.css +++ b/styles.css @@ -131,7 +131,7 @@ display: flex; flex-direction: column; gap: 6px; - padding: 4px 0 12px; + padding: 4px 14px 12px; } .stashpad-color-alias-row { display: flex; @@ -191,7 +191,7 @@ display: flex; flex-direction: column; gap: 6px; - padding: 4px 0 12px; + padding: 4px 14px 12px; } .stashpad-note-template-row { display: flex; @@ -243,9 +243,13 @@ overflow: hidden; text-overflow: ellipsis; } -.stashpad-note-template-suggest-item:hover { +.stashpad-note-template-suggest-item:hover, +.stashpad-note-template-suggest-item.is-active { background: var(--background-modifier-hover); } +.stashpad-note-template-suggest-item.is-active { + background: var(--background-modifier-active-hover, var(--background-modifier-hover)); +} .stashpad-note-template-warn { flex: 1 0 100%; font-size: var(--font-ui-smaller); @@ -2300,9 +2304,43 @@ /* 0.97.2/0.97.4: keep the Encryption section's intro text off the left edge and below the page's top fade (it was clipping the first line). */ +/* PROVISION — text flushing in custom-rendered settings sections. + sectionDef() removes `.setting-item` from its host, so raw createEl text / + headings / lists rendered directly into a `.stashpad-settings-section` lose the + horizontal inset that Obsidian's Setting rows have and sit flush against the + modal edge. This rule re-insets all such DIRECT children to 14px (matching the + Setting rows). GOING FORWARD: render plain text/headings into a + `.stashpad-settings-section` host and they align automatically — don't hand-pad + per element, and don't render naked text outside a section host. (Setting rows + are untouched — they're `.setting-item`, not selected here.) */ +.stashpad-settings-section > p, +.stashpad-settings-section > h2, +.stashpad-settings-section > h3, +.stashpad-settings-section > h4, +.stashpad-settings-section > ol, +.stashpad-settings-section > ul, +.stashpad-settings-section > .setting-item-description { + padding-left: 14px; + padding-right: 14px; +} +.stashpad-ai-disclaimer { + margin: 4px 14px 12px; padding: 10px 12px; border-radius: var(--radius-m, 6px); + border: 1px solid var(--color-red, #e24b4a); + background: var(--background-modifier-error, rgba(226, 75, 74, 0.1)); + color: var(--text-normal); font-size: 13px; line-height: 1.5; +} .stashpad-encryption-section { padding: 12px 2px 0; } .stashpad-encryption-section > .setting-item-description { padding: 4px 14px 10px; line-height: 1.4; } .stashpad-beta-row { display: flex; align-items: center; gap: 8px; padding: 2px 14px 6px; } +.stashpad-okf-howto { padding: 4px 14px 8px; } +.stashpad-okf-fmt { display: flex; align-items: center; gap: 8px; margin: 6px 0; } +.stashpad-okf-cta { + margin: 2px 14px 12px; padding: 9px 12px; border-radius: var(--radius-m, 6px); + border: 1px solid var(--interactive-accent); background: var(--background-modifier-hover); + font-size: 13px; line-height: 1.5; +} +.stashpad-okf-fmt label { cursor: pointer; } +.stashpad-okf-howto ol { margin: 4px 0 0; padding-left: 1.4em; } .stashpad-beta-badge { display: inline-block; font-size: 10px; font-weight: 700; letter-spacing: 0.06em; line-height: 1; padding: 3px 6px; border-radius: 4px; text-transform: uppercase;