diff --git a/.gitignore b/.gitignore index e43b0f9..ad6a722 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,5 @@ .DS_Store +node_modules/ +data.json +.deploy-target +*.log diff --git a/esbuild.config.mjs b/esbuild.config.mjs new file mode 100644 index 0000000..4cf423f --- /dev/null +++ b/esbuild.config.mjs @@ -0,0 +1,23 @@ +import esbuild from "esbuild"; + +const prod = process.argv[2] === "production"; + +const ctx = await esbuild.context({ + entryPoints: ["src/main.ts"], + bundle: true, + external: ["obsidian", "electron", "@codemirror/*", "@lezer/*"], + format: "cjs", + target: "es2020", + logLevel: "info", + sourcemap: prod ? false : "inline", + treeShaking: true, + minify: prod, + outfile: "main.js", +}); + +if (prod) { + await ctx.rebuild(); + process.exit(0); +} else { + await ctx.watch(); +} diff --git a/main.js b/main.js index 6bc11c6..06e0d06 100644 --- a/main.js +++ b/main.js @@ -1,51 +1,51 @@ -"use strict";var Ge=Object.create;var zt=Object.defineProperty;var Xe=Object.getOwnPropertyDescriptor;var Je=Object.getOwnPropertyNames;var Qe=Object.getPrototypeOf,ts=Object.prototype.hasOwnProperty;var es=(g,m)=>()=>(g&&(m=g(g=0)),m);var ss=(g,m)=>()=>(m||g((m={exports:{}}).exports,m),m.exports),xe=(g,m)=>{for(var t in m)zt(g,t,{get:m[t],enumerable:!0})},Te=(g,m,t,e)=>{if(m&&typeof m=="object"||typeof m=="function")for(let s of Je(m))!ts.call(g,s)&&s!==t&&zt(g,s,{get:()=>m[s],enumerable:!(e=Xe(m,s))||e.enumerable});return g};var is=(g,m,t)=>(t=g!=null?Ge(Qe(g)):{},Te(m||!g||!g.__esModule?zt(t,"default",{value:g,enumerable:!0}):t,g)),rs=g=>Te(zt({},"__esModule",{value:!0}),g);var Zt={};xe(Zt,{newId:()=>bt});function bt(g=6){let m="",t=new Uint8Array(g);crypto.getRandomValues(t);for(let e=0;e{"use strict";_e="abcdefghijkmnpqrstuvwxyz23456789"});var Ne=ss((Re,ye)=>{(function(g){typeof Re=="object"&&typeof ye<"u"?ye.exports=g():typeof define=="function"&&define.amd?define([],g):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=g()})(function(){return function g(m,t,e){function s(n,a){if(!t[n]){if(!m[n]){var o=typeof require=="function"&&require;if(!a&&o)return o(n,!0);if(i)return i(n,!0);var c=new Error("Cannot find module '"+n+"'");throw c.code="MODULE_NOT_FOUND",c}var l=t[n]={exports:{}};m[n][0].call(l.exports,function(h){var d=m[n][1][h];return s(d||h)},l,l.exports,g,m,t,e)}return t[n].exports}for(var i=typeof require=="function"&&require,r=0;r>2,l=(3&n)<<4|a>>4,h=1>6:64,d=2>4,a=(15&c)<<4|(l=i.indexOf(r.charAt(d++)))>>2,o=(3&l)<<6|(h=i.indexOf(r.charAt(d++))),y[v++]=n,l!==64&&(y[v++]=a),h!==64&&(y[v++]=o);return y}},{"./support":30,"./utils":32}],2:[function(g,m,t){"use strict";var e=g("./external"),s=g("./stream/DataWorker"),i=g("./stream/Crc32Probe"),r=g("./stream/DataLengthProbe");function n(a,o,c,l,h){this.compressedSize=a,this.uncompressedSize=o,this.crc32=c,this.compression=l,this.compressedContent=h}n.prototype={getContentWorker:function(){var a=new s(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new r("data_length")),o=this;return a.on("end",function(){if(this.streamInfo.data_length!==o.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new s(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},n.createWorkerFrom=function(a,o,c){return a.pipe(new i).pipe(new r("uncompressedSize")).pipe(o.compressWorker(c)).pipe(new r("compressedSize")).withStreamInfo("compression",o)},m.exports=n},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(g,m,t){"use strict";var e=g("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=g("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(g,m,t){"use strict";var e=g("./utils"),s=function(){for(var i,r=[],n=0;n<256;n++){i=n;for(var a=0;a<8;a++)i=1&i?3988292384^i>>>1:i>>>1;r[n]=i}return r}();m.exports=function(i,r){return i!==void 0&&i.length?e.getTypeOf(i)!=="string"?function(n,a,o,c){var l=s,h=c+o;n^=-1;for(var d=c;d>>8^l[255&(n^a[d])];return-1^n}(0|r,i,i.length,0):function(n,a,o,c){var l=s,h=c+o;n^=-1;for(var d=c;d>>8^l[255&(n^a.charCodeAt(d))];return-1^n}(0|r,i,i.length,0):0}},{"./utils":32}],5:[function(g,m,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(g,m,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:g("lie"),m.exports={Promise:e}},{lie:37}],7:[function(g,m,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",s=g("pako"),i=g("./utils"),r=g("./stream/GenericWorker"),n=e?"uint8array":"array";function a(o,c){r.call(this,"FlateWorker/"+o),this._pako=null,this._pakoAction=o,this._pakoOptions=c,this.meta={}}t.magic="\b\0",i.inherits(a,r),a.prototype.processChunk=function(o){this.meta=o.meta,this._pako===null&&this._createPako(),this._pako.push(i.transformTo(n,o.data),!1)},a.prototype.flush=function(){r.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},a.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this._pako=null},a.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var o=this;this._pako.onData=function(c){o.push({data:c,meta:o.meta})}},t.compressWorker=function(o){return new a("Deflate",o)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(g,m,t){"use strict";function e(l,h){var d,v="";for(d=0;d>>=8;return v}function s(l,h,d,v,u,y){var w,b,C=l.file,E=l.compression,I=y!==n.utf8encode,N=i.transformTo("string",y(C.name)),D=i.transformTo("string",n.utf8encode(C.name)),$=C.comment,q=i.transformTo("string",y($)),x=i.transformTo("string",n.utf8encode($)),T=D.length!==C.name.length,f=x.length!==$.length,P="",G="",z="",tt=C.dir,U=C.date,Q={crc32:0,compressedSize:0,uncompressedSize:0};h&&!d||(Q.crc32=l.crc32,Q.compressedSize=l.compressedSize,Q.uncompressedSize=l.uncompressedSize);var M=0;h&&(M|=8),I||!T&&!f||(M|=2048);var A=0,J=0;tt&&(A|=16),u==="UNIX"?(J=798,A|=function(Z,ot){var ut=Z;return Z||(ut=ot?16893:33204),(65535&ut)<<16}(C.unixPermissions,tt)):(J=20,A|=function(Z){return 63&(Z||0)}(C.dosPermissions)),w=U.getUTCHours(),w<<=6,w|=U.getUTCMinutes(),w<<=5,w|=U.getUTCSeconds()/2,b=U.getUTCFullYear()-1980,b<<=4,b|=U.getUTCMonth()+1,b<<=5,b|=U.getUTCDate(),T&&(G=e(1,1)+e(a(N),4)+D,P+="up"+e(G.length,2)+G),f&&(z=e(1,1)+e(a(q),4)+x,P+="uc"+e(z.length,2)+z);var K="";return K+=` -\0`,K+=e(M,2),K+=E.magic,K+=e(w,2),K+=e(b,2),K+=e(Q.crc32,4),K+=e(Q.compressedSize,4),K+=e(Q.uncompressedSize,4),K+=e(N.length,2),K+=e(P.length,2),{fileRecord:o.LOCAL_FILE_HEADER+K+N+P,dirRecord:o.CENTRAL_FILE_HEADER+e(J,2)+K+e(q.length,2)+"\0\0\0\0"+e(A,4)+e(v,4)+N+P+q}}var i=g("../utils"),r=g("../stream/GenericWorker"),n=g("../utf8"),a=g("../crc32"),o=g("../signature");function c(l,h,d,v){r.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=h,this.zipPlatform=d,this.encodeFileName=v,this.streamFiles=l,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}i.inherits(c,r),c.prototype.push=function(l){var h=l.meta.percent||0,d=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(l):(this.bytesWritten+=l.data.length,r.prototype.push.call(this,{data:l.data,meta:{currentFile:this.currentFile,percent:d?(h+100*(d-v-1))/d:100}}))},c.prototype.openedSource=function(l){this.currentSourceOffset=this.bytesWritten,this.currentFile=l.file.name;var h=this.streamFiles&&!l.file.dir;if(h){var d=s(l,h,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:d.fileRecord,meta:{percent:0}})}else this.accumulate=!0},c.prototype.closedSource=function(l){this.accumulate=!1;var h=this.streamFiles&&!l.file.dir,d=s(l,h,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(d.dirRecord),h)this.push({data:function(v){return o.DATA_DESCRIPTOR+e(v.crc32,4)+e(v.compressedSize,4)+e(v.uncompressedSize,4)}(l),meta:{percent:100}});else for(this.push({data:d.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},c.prototype.flush=function(){for(var l=this.bytesWritten,h=0;h=this.index;r--)n=(n<<8)+this.byteAt(r);return this.index+=i,n},readString:function(i){return e.transformTo("string",this.readData(i))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var i=this.readInt(4);return new Date(Date.UTC(1980+(i>>25&127),(i>>21&15)-1,i>>16&31,i>>11&31,i>>5&63,(31&i)<<1))}},m.exports=s},{"../utils":32}],19:[function(g,m,t){"use strict";var e=g("./Uint8ArrayReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.readData=function(i){this.checkOffset(i);var r=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,r},m.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(g,m,t){"use strict";var e=g("./DataReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.byteAt=function(i){return this.data.charCodeAt(this.zero+i)},s.prototype.lastIndexOfSignature=function(i){return this.data.lastIndexOf(i)-this.zero},s.prototype.readAndCheckSignature=function(i){return i===this.readData(4)},s.prototype.readData=function(i){this.checkOffset(i);var r=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,r},m.exports=s},{"../utils":32,"./DataReader":18}],21:[function(g,m,t){"use strict";var e=g("./ArrayReader");function s(i){e.call(this,i)}g("../utils").inherits(s,e),s.prototype.readData=function(i){if(this.checkOffset(i),i===0)return new Uint8Array(0);var r=this.data.subarray(this.zero+this.index,this.zero+this.index+i);return this.index+=i,r},m.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(g,m,t){"use strict";var e=g("../utils"),s=g("../support"),i=g("./ArrayReader"),r=g("./StringReader"),n=g("./NodeBufferReader"),a=g("./Uint8ArrayReader");m.exports=function(o){var c=e.getTypeOf(o);return e.checkSupport(c),c!=="string"||s.uint8array?c==="nodebuffer"?new n(o):s.uint8array?new a(e.transformTo("uint8array",o)):new i(e.transformTo("array",o)):new r(o)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(g,m,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(g,m,t){"use strict";var e=g("./GenericWorker"),s=g("../utils");function i(r){e.call(this,"ConvertWorker to "+r),this.destType=r}s.inherits(i,e),i.prototype.processChunk=function(r){this.push({data:s.transformTo(this.destType,r.data),meta:r.meta})},m.exports=i},{"../utils":32,"./GenericWorker":28}],25:[function(g,m,t){"use strict";var e=g("./GenericWorker"),s=g("../crc32");function i(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}g("../utils").inherits(i,e),i.prototype.processChunk=function(r){this.streamInfo.crc32=s(r.data,this.streamInfo.crc32||0),this.push(r)},m.exports=i},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(g,m,t){"use strict";var e=g("../utils"),s=g("./GenericWorker");function i(r){s.call(this,"DataLengthProbe for "+r),this.propName=r,this.withStreamInfo(r,0)}e.inherits(i,s),i.prototype.processChunk=function(r){if(r){var n=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=n+r.data.length}s.prototype.processChunk.call(this,r)},m.exports=i},{"../utils":32,"./GenericWorker":28}],27:[function(g,m,t){"use strict";var e=g("../utils"),s=g("./GenericWorker");function i(r){s.call(this,"DataWorker");var n=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,r.then(function(a){n.dataIsReady=!0,n.data=a,n.max=a&&a.length||0,n.type=e.getTypeOf(a),n.isPaused||n._tickAndRepeat()},function(a){n.error(a)})}e.inherits(i,s),i.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},i.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},i.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},i.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var r=null,n=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":r=this.data.substring(this.index,n);break;case"uint8array":r=this.data.subarray(this.index,n);break;case"array":case"nodebuffer":r=this.data.slice(this.index,n)}return this.index=n,this.push({data:r,meta:{percent:this.max?this.index/this.max*100:0}})},m.exports=i},{"../utils":32,"./GenericWorker":28}],28:[function(g,m,t){"use strict";function e(s){this.name=s||"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(s){this.emit("data",s)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(s){this.emit("error",s)}return!0},error:function(s){return!this.isFinished&&(this.isPaused?this.generatedError=s:(this.isFinished=!0,this.emit("error",s),this.previous&&this.previous.error(s),this.cleanUp()),!0)},on:function(s,i){return this._listeners[s].push(i),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(s,i){if(this._listeners[s])for(var r=0;r "+s:s}},m.exports=e},{}],29:[function(g,m,t){"use strict";var e=g("../utils"),s=g("./ConvertWorker"),i=g("./GenericWorker"),r=g("../base64"),n=g("../support"),a=g("../external"),o=null;if(n.nodestream)try{o=g("../nodejs/NodejsStreamOutputAdapter")}catch{}function c(h,d){return new a.Promise(function(v,u){var y=[],w=h._internalType,b=h._outputType,C=h._mimeType;h.on("data",function(E,I){y.push(E),d&&d(I)}).on("error",function(E){y=[],u(E)}).on("end",function(){try{var E=function(I,N,D){switch(I){case"blob":return e.newBlob(e.transformTo("arraybuffer",N),D);case"base64":return r.encode(N);default:return e.transformTo(I,N)}}(b,function(I,N){var D,$=0,q=null,x=0;for(D=0;D"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(e),t.blob=s.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!g("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(g,m,t){"use strict";for(var e=g("./utils"),s=g("./support"),i=g("./nodejsUtils"),r=g("./stream/GenericWorker"),n=new Array(256),a=0;a<256;a++)n[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;n[254]=n[254]=1;function o(){r.call(this,"utf-8 decode"),this.leftOver=null}function c(){r.call(this,"utf-8 encode")}t.utf8encode=function(l){return s.nodebuffer?i.newBufferFrom(l,"utf-8"):function(h){var d,v,u,y,w,b=h.length,C=0;for(y=0;y>>6:(v<65536?d[w++]=224|v>>>12:(d[w++]=240|v>>>18,d[w++]=128|v>>>12&63),d[w++]=128|v>>>6&63),d[w++]=128|63&v);return d}(l)},t.utf8decode=function(l){return s.nodebuffer?e.transformTo("nodebuffer",l).toString("utf-8"):function(h){var d,v,u,y,w=h.length,b=new Array(2*w);for(d=v=0;d>10&1023,b[v++]=56320|1023&u)}return b.length!==v&&(b.subarray?b=b.subarray(0,v):b.length=v),e.applyFromCharCode(b)}(l=e.transformTo(s.uint8array?"uint8array":"array",l))},e.inherits(o,r),o.prototype.processChunk=function(l){var h=e.transformTo(s.uint8array?"uint8array":"array",l.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var d=h;(h=new Uint8Array(d.length+this.leftOver.length)).set(this.leftOver,0),h.set(d,this.leftOver.length)}else h=this.leftOver.concat(h);this.leftOver=null}var v=function(y,w){var b;for((w=w||y.length)>y.length&&(w=y.length),b=w-1;0<=b&&(192&y[b])==128;)b--;return b<0||b===0?w:b+n[y[b]]>w?b:w}(h),u=h;v!==h.length&&(s.uint8array?(u=h.subarray(0,v),this.leftOver=h.subarray(v,h.length)):(u=h.slice(0,v),this.leftOver=h.slice(v,h.length))),this.push({data:t.utf8decode(u),meta:l.meta})},o.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=o,e.inherits(c,r),c.prototype.processChunk=function(l){this.push({data:t.utf8encode(l.data),meta:l.meta})},t.Utf8EncodeWorker=c},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(g,m,t){"use strict";var e=g("./support"),s=g("./base64"),i=g("./nodejsUtils"),r=g("./external");function n(d){return d}function a(d,v){for(var u=0;u>8;this.dir=!!(16&this.externalFileAttributes),l==0&&(this.dosPermissions=63&this.externalFileAttributes),l==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var l=e(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=l.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=l.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=l.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=l.readInt(4))}},readExtraFields:function(l){var h,d,v,u=l.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});l.index+4>>6:(l<65536?c[v++]=224|l>>>12:(c[v++]=240|l>>>18,c[v++]=128|l>>>12&63),c[v++]=128|l>>>6&63),c[v++]=128|63&l);return c},t.buf2binstring=function(o){return a(o,o.length)},t.binstring2buf=function(o){for(var c=new e.Buf8(o.length),l=0,h=c.length;l>10&1023,y[h++]=56320|1023&d)}return a(y,h)},t.utf8border=function(o,c){var l;for((c=c||o.length)>o.length&&(c=o.length),l=c-1;0<=l&&(192&o[l])==128;)l--;return l<0||l===0?c:l+r[o[l]]>c?l:c}},{"./common":41}],43:[function(g,m,t){"use strict";m.exports=function(e,s,i,r){for(var n=65535&e|0,a=e>>>16&65535|0,o=0;i!==0;){for(i-=o=2e3>>1:s>>>1;i[r]=s}return i}();m.exports=function(s,i,r,n){var a=e,o=n+r;s^=-1;for(var c=n;c>>8^a[255&(s^i[c])];return-1^s}},{}],46:[function(g,m,t){"use strict";var e,s=g("../utils/common"),i=g("./trees"),r=g("./adler32"),n=g("./crc32"),a=g("./messages"),o=0,c=4,l=0,h=-2,d=-1,v=4,u=2,y=8,w=9,b=286,C=30,E=19,I=2*b+1,N=15,D=3,$=258,q=$+D+1,x=42,T=113,f=1,P=2,G=3,z=4;function tt(p,R){return p.msg=a[R],R}function U(p){return(p<<1)-(4p.avail_out&&(L=p.avail_out),L!==0&&(s.arraySet(p.output,R.pending_buf,R.pending_out,L,p.next_out),p.next_out+=L,R.pending_out+=L,p.total_out+=L,p.avail_out-=L,R.pending-=L,R.pending===0&&(R.pending_out=0))}function A(p,R){i._tr_flush_block(p,0<=p.block_start?p.block_start:-1,p.strstart-p.block_start,R),p.block_start=p.strstart,M(p.strm)}function J(p,R){p.pending_buf[p.pending++]=R}function K(p,R){p.pending_buf[p.pending++]=R>>>8&255,p.pending_buf[p.pending++]=255&R}function Z(p,R){var L,k,S=p.max_chain_length,F=p.strstart,B=p.prev_length,H=p.nice_match,_=p.strstart>p.w_size-q?p.strstart-(p.w_size-q):0,j=p.window,Y=p.w_mask,W=p.prev,X=p.strstart+$,at=j[F+B-1],it=j[F+B];p.prev_length>=p.good_match&&(S>>=2),H>p.lookahead&&(H=p.lookahead);do if(j[(L=R)+B]===it&&j[L+B-1]===at&&j[L]===j[F]&&j[++L]===j[F+1]){F+=2,L++;do;while(j[++F]===j[++L]&&j[++F]===j[++L]&&j[++F]===j[++L]&&j[++F]===j[++L]&&j[++F]===j[++L]&&j[++F]===j[++L]&&j[++F]===j[++L]&&j[++F]===j[++L]&&F_&&--S!=0);return B<=p.lookahead?B:p.lookahead}function ot(p){var R,L,k,S,F,B,H,_,j,Y,W=p.w_size;do{if(S=p.window_size-p.lookahead-p.strstart,p.strstart>=W+(W-q)){for(s.arraySet(p.window,p.window,W,W,0),p.match_start-=W,p.strstart-=W,p.block_start-=W,R=L=p.hash_size;k=p.head[--R],p.head[R]=W<=k?k-W:0,--L;);for(R=L=W;k=p.prev[--R],p.prev[R]=W<=k?k-W:0,--L;);S+=W}if(p.strm.avail_in===0)break;if(B=p.strm,H=p.window,_=p.strstart+p.lookahead,j=S,Y=void 0,Y=B.avail_in,j=D)for(F=p.strstart-p.insert,p.ins_h=p.window[F],p.ins_h=(p.ins_h<=D&&(p.ins_h=(p.ins_h<=D)if(k=i._tr_tally(p,p.strstart-p.match_start,p.match_length-D),p.lookahead-=p.match_length,p.match_length<=p.max_lazy_match&&p.lookahead>=D){for(p.match_length--;p.strstart++,p.ins_h=(p.ins_h<=D&&(p.ins_h=(p.ins_h<=D&&p.match_length<=p.prev_length){for(S=p.strstart+p.lookahead-D,k=i._tr_tally(p,p.strstart-1-p.prev_match,p.prev_length-D),p.lookahead-=p.prev_length-1,p.prev_length-=2;++p.strstart<=S&&(p.ins_h=(p.ins_h<p.pending_buf_size-5&&(L=p.pending_buf_size-5);;){if(p.lookahead<=1){if(ot(p),p.lookahead===0&&R===o)return f;if(p.lookahead===0)break}p.strstart+=p.lookahead,p.lookahead=0;var k=p.block_start+L;if((p.strstart===0||p.strstart>=k)&&(p.lookahead=p.strstart-k,p.strstart=k,A(p,!1),p.strm.avail_out===0)||p.strstart-p.block_start>=p.w_size-q&&(A(p,!1),p.strm.avail_out===0))return f}return p.insert=0,R===c?(A(p,!0),p.strm.avail_out===0?G:z):(p.strstart>p.block_start&&(A(p,!1),p.strm.avail_out),f)}),new nt(4,4,8,4,ut),new nt(4,5,16,8,ut),new nt(4,6,32,32,ut),new nt(4,4,16,16,st),new nt(8,16,32,32,st),new nt(8,16,128,128,st),new nt(8,32,128,256,st),new nt(32,128,258,1024,st),new nt(32,258,258,4096,st)],t.deflateInit=function(p,R){return gt(p,R,y,15,8,0)},t.deflateInit2=gt,t.deflateReset=vt,t.deflateResetKeep=lt,t.deflateSetHeader=function(p,R){return p&&p.state?p.state.wrap!==2?h:(p.state.gzhead=R,l):h},t.deflate=function(p,R){var L,k,S,F;if(!p||!p.state||5>8&255),J(k,k.gzhead.time>>16&255),J(k,k.gzhead.time>>24&255),J(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),J(k,255&k.gzhead.os),k.gzhead.extra&&k.gzhead.extra.length&&(J(k,255&k.gzhead.extra.length),J(k,k.gzhead.extra.length>>8&255)),k.gzhead.hcrc&&(p.adler=n(p.adler,k.pending_buf,k.pending,0)),k.gzindex=0,k.status=69):(J(k,0),J(k,0),J(k,0),J(k,0),J(k,0),J(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),J(k,3),k.status=T);else{var B=y+(k.w_bits-8<<4)<<8;B|=(2<=k.strategy||k.level<2?0:k.level<6?1:k.level===6?2:3)<<6,k.strstart!==0&&(B|=32),B+=31-B%31,k.status=T,K(k,B),k.strstart!==0&&(K(k,p.adler>>>16),K(k,65535&p.adler)),p.adler=1}if(k.status===69)if(k.gzhead.extra){for(S=k.pending;k.gzindex<(65535&k.gzhead.extra.length)&&(k.pending!==k.pending_buf_size||(k.gzhead.hcrc&&k.pending>S&&(p.adler=n(p.adler,k.pending_buf,k.pending-S,S)),M(p),S=k.pending,k.pending!==k.pending_buf_size));)J(k,255&k.gzhead.extra[k.gzindex]),k.gzindex++;k.gzhead.hcrc&&k.pending>S&&(p.adler=n(p.adler,k.pending_buf,k.pending-S,S)),k.gzindex===k.gzhead.extra.length&&(k.gzindex=0,k.status=73)}else k.status=73;if(k.status===73)if(k.gzhead.name){S=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>S&&(p.adler=n(p.adler,k.pending_buf,k.pending-S,S)),M(p),S=k.pending,k.pending===k.pending_buf_size)){F=1;break}F=k.gzindexS&&(p.adler=n(p.adler,k.pending_buf,k.pending-S,S)),F===0&&(k.gzindex=0,k.status=91)}else k.status=91;if(k.status===91)if(k.gzhead.comment){S=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>S&&(p.adler=n(p.adler,k.pending_buf,k.pending-S,S)),M(p),S=k.pending,k.pending===k.pending_buf_size)){F=1;break}F=k.gzindexS&&(p.adler=n(p.adler,k.pending_buf,k.pending-S,S)),F===0&&(k.status=103)}else k.status=103;if(k.status===103&&(k.gzhead.hcrc?(k.pending+2>k.pending_buf_size&&M(p),k.pending+2<=k.pending_buf_size&&(J(k,255&p.adler),J(k,p.adler>>8&255),p.adler=0,k.status=T)):k.status=T),k.pending!==0){if(M(p),p.avail_out===0)return k.last_flush=-1,l}else if(p.avail_in===0&&U(R)<=U(L)&&R!==c)return tt(p,-5);if(k.status===666&&p.avail_in!==0)return tt(p,-5);if(p.avail_in!==0||k.lookahead!==0||R!==o&&k.status!==666){var H=k.strategy===2?function(_,j){for(var Y;;){if(_.lookahead===0&&(ot(_),_.lookahead===0)){if(j===o)return f;break}if(_.match_length=0,Y=i._tr_tally(_,0,_.window[_.strstart]),_.lookahead--,_.strstart++,Y&&(A(_,!1),_.strm.avail_out===0))return f}return _.insert=0,j===c?(A(_,!0),_.strm.avail_out===0?G:z):_.last_lit&&(A(_,!1),_.strm.avail_out===0)?f:P}(k,R):k.strategy===3?function(_,j){for(var Y,W,X,at,it=_.window;;){if(_.lookahead<=$){if(ot(_),_.lookahead<=$&&j===o)return f;if(_.lookahead===0)break}if(_.match_length=0,_.lookahead>=D&&0<_.strstart&&(W=it[X=_.strstart-1])===it[++X]&&W===it[++X]&&W===it[++X]){at=_.strstart+$;do;while(W===it[++X]&&W===it[++X]&&W===it[++X]&&W===it[++X]&&W===it[++X]&&W===it[++X]&&W===it[++X]&&W===it[++X]&&X_.lookahead&&(_.match_length=_.lookahead)}if(_.match_length>=D?(Y=i._tr_tally(_,1,_.match_length-D),_.lookahead-=_.match_length,_.strstart+=_.match_length,_.match_length=0):(Y=i._tr_tally(_,0,_.window[_.strstart]),_.lookahead--,_.strstart++),Y&&(A(_,!1),_.strm.avail_out===0))return f}return _.insert=0,j===c?(A(_,!0),_.strm.avail_out===0?G:z):_.last_lit&&(A(_,!1),_.strm.avail_out===0)?f:P}(k,R):e[k.level].func(k,R);if(H!==G&&H!==z||(k.status=666),H===f||H===G)return p.avail_out===0&&(k.last_flush=-1),l;if(H===P&&(R===1?i._tr_align(k):R!==5&&(i._tr_stored_block(k,0,0,!1),R===3&&(Q(k.head),k.lookahead===0&&(k.strstart=0,k.block_start=0,k.insert=0))),M(p),p.avail_out===0))return k.last_flush=-1,l}return R!==c?l:k.wrap<=0?1:(k.wrap===2?(J(k,255&p.adler),J(k,p.adler>>8&255),J(k,p.adler>>16&255),J(k,p.adler>>24&255),J(k,255&p.total_in),J(k,p.total_in>>8&255),J(k,p.total_in>>16&255),J(k,p.total_in>>24&255)):(K(k,p.adler>>>16),K(k,65535&p.adler)),M(p),0=L.w_size&&(F===0&&(Q(L.head),L.strstart=0,L.block_start=0,L.insert=0),j=new s.Buf8(L.w_size),s.arraySet(j,R,Y-L.w_size,L.w_size,0),R=j,Y=L.w_size),B=p.avail_in,H=p.next_in,_=p.input,p.avail_in=Y,p.next_in=0,p.input=R,ot(L);L.lookahead>=D;){for(k=L.strstart,S=L.lookahead-(D-1);L.ins_h=(L.ins_h<>>=D=N>>>24,w-=D,(D=N>>>16&255)===0)P[a++]=65535&N;else{if(!(16&D)){if(!(64&D)){N=b[(65535&N)+(y&(1<>>=D,w-=D),w<15&&(y+=f[r++]<>>=D=N>>>24,w-=D,!(16&(D=N>>>16&255))){if(!(64&D)){N=C[(65535&N)+(y&(1<>>=D,w-=D,(D=a-o)>3,y&=(1<<(w-=$<<3))-1,e.next_in=r,e.next_out=a,e.avail_in=r>>24&255)+(x>>>8&65280)+((65280&x)<<8)+((255&x)<<24)}function y(){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 w(x){var T;return x&&x.state?(T=x.state,x.total_in=x.total_out=T.total=0,x.msg="",T.wrap&&(x.adler=1&T.wrap),T.mode=h,T.last=0,T.havedict=0,T.dmax=32768,T.head=null,T.hold=0,T.bits=0,T.lencode=T.lendyn=new e.Buf32(d),T.distcode=T.distdyn=new e.Buf32(v),T.sane=1,T.back=-1,c):l}function b(x){var T;return x&&x.state?((T=x.state).wsize=0,T.whave=0,T.wnext=0,w(x)):l}function C(x,T){var f,P;return x&&x.state?(P=x.state,T<0?(f=0,T=-T):(f=1+(T>>4),T<48&&(T&=15)),T&&(T<8||15=z.wsize?(e.arraySet(z.window,T,f-z.wsize,z.wsize,0),z.wnext=0,z.whave=z.wsize):(P<(G=z.wsize-z.wnext)&&(G=P),e.arraySet(z.window,T,f-P,G,z.wnext),(P-=G)?(e.arraySet(z.window,T,f-P,P,0),z.wnext=P,z.whave=z.wsize):(z.wnext+=G,z.wnext===z.wsize&&(z.wnext=0),z.whave>>8&255,f.check=i(f.check,F,2,0),A=M=0,f.mode=2;break}if(f.flags=0,f.head&&(f.head.done=!1),!(1&f.wrap)||(((255&M)<<8)+(M>>8))%31){x.msg="incorrect header check",f.mode=30;break}if((15&M)!=8){x.msg="unknown compression method",f.mode=30;break}if(A-=4,p=8+(15&(M>>>=4)),f.wbits===0)f.wbits=p;else if(p>f.wbits){x.msg="invalid window size",f.mode=30;break}f.dmax=1<>8&1),512&f.flags&&(F[0]=255&M,F[1]=M>>>8&255,f.check=i(f.check,F,2,0)),A=M=0,f.mode=3;case 3:for(;A<32;){if(U===0)break t;U--,M+=P[z++]<>>8&255,F[2]=M>>>16&255,F[3]=M>>>24&255,f.check=i(f.check,F,4,0)),A=M=0,f.mode=4;case 4:for(;A<16;){if(U===0)break t;U--,M+=P[z++]<>8),512&f.flags&&(F[0]=255&M,F[1]=M>>>8&255,f.check=i(f.check,F,2,0)),A=M=0,f.mode=5;case 5:if(1024&f.flags){for(;A<16;){if(U===0)break t;U--,M+=P[z++]<>>8&255,f.check=i(f.check,F,2,0)),A=M=0}else f.head&&(f.head.extra=null);f.mode=6;case 6:if(1024&f.flags&&(U<(Z=f.length)&&(Z=U),Z&&(f.head&&(p=f.head.extra_len-f.length,f.head.extra||(f.head.extra=new Array(f.head.extra_len)),e.arraySet(f.head.extra,P,z,Z,p)),512&f.flags&&(f.check=i(f.check,P,Z,z)),U-=Z,z+=Z,f.length-=Z),f.length))break t;f.length=0,f.mode=7;case 7:if(2048&f.flags){if(U===0)break t;for(Z=0;p=P[z+Z++],f.head&&p&&f.length<65536&&(f.head.name+=String.fromCharCode(p)),p&&Z>9&1,f.head.done=!0),x.adler=f.check=0,f.mode=12;break;case 10:for(;A<32;){if(U===0)break t;U--,M+=P[z++]<>>=7&A,A-=7&A,f.mode=27;break}for(;A<3;){if(U===0)break t;U--,M+=P[z++]<>>=1)){case 0:f.mode=14;break;case 1:if($(f),f.mode=20,T!==6)break;M>>>=2,A-=2;break t;case 2:f.mode=17;break;case 3:x.msg="invalid block type",f.mode=30}M>>>=2,A-=2;break;case 14:for(M>>>=7&A,A-=7&A;A<32;){if(U===0)break t;U--,M+=P[z++]<>>16^65535)){x.msg="invalid stored block lengths",f.mode=30;break}if(f.length=65535&M,A=M=0,f.mode=15,T===6)break t;case 15:f.mode=16;case 16:if(Z=f.length){if(U>>=5,A-=5,f.ndist=1+(31&M),M>>>=5,A-=5,f.ncode=4+(15&M),M>>>=4,A-=4,286>>=3,A-=3}for(;f.have<19;)f.lens[B[f.have++]]=0;if(f.lencode=f.lendyn,f.lenbits=7,L={bits:f.lenbits},R=n(0,f.lens,0,19,f.lencode,0,f.work,L),f.lenbits=L.bits,R){x.msg="invalid code lengths set",f.mode=30;break}f.have=0,f.mode=19;case 19:for(;f.have>>16&255,pt=65535&S,!((st=S>>>24)<=A);){if(U===0)break t;U--,M+=P[z++]<>>=st,A-=st,f.lens[f.have++]=pt;else{if(pt===16){for(k=st+2;A>>=st,A-=st,f.have===0){x.msg="invalid bit length repeat",f.mode=30;break}p=f.lens[f.have-1],Z=3+(3&M),M>>>=2,A-=2}else if(pt===17){for(k=st+3;A>>=st)),M>>>=3,A-=3}else{for(k=st+7;A>>=st)),M>>>=7,A-=7}if(f.have+Z>f.nlen+f.ndist){x.msg="invalid bit length repeat",f.mode=30;break}for(;Z--;)f.lens[f.have++]=p}}if(f.mode===30)break;if(f.lens[256]===0){x.msg="invalid code -- missing end-of-block",f.mode=30;break}if(f.lenbits=9,L={bits:f.lenbits},R=n(a,f.lens,0,f.nlen,f.lencode,0,f.work,L),f.lenbits=L.bits,R){x.msg="invalid literal/lengths set",f.mode=30;break}if(f.distbits=6,f.distcode=f.distdyn,L={bits:f.distbits},R=n(o,f.lens,f.nlen,f.ndist,f.distcode,0,f.work,L),f.distbits=L.bits,R){x.msg="invalid distances set",f.mode=30;break}if(f.mode=20,T===6)break t;case 20:f.mode=21;case 21:if(6<=U&&258<=Q){x.next_out=tt,x.avail_out=Q,x.next_in=z,x.avail_in=U,f.hold=M,f.bits=A,r(x,K),tt=x.next_out,G=x.output,Q=x.avail_out,z=x.next_in,P=x.input,U=x.avail_in,M=f.hold,A=f.bits,f.mode===12&&(f.back=-1);break}for(f.back=0;nt=(S=f.lencode[M&(1<>>16&255,pt=65535&S,!((st=S>>>24)<=A);){if(U===0)break t;U--,M+=P[z++]<>lt)])>>>16&255,pt=65535&S,!(lt+(st=S>>>24)<=A);){if(U===0)break t;U--,M+=P[z++]<>>=lt,A-=lt,f.back+=lt}if(M>>>=st,A-=st,f.back+=st,f.length=pt,nt===0){f.mode=26;break}if(32&nt){f.back=-1,f.mode=12;break}if(64&nt){x.msg="invalid literal/length code",f.mode=30;break}f.extra=15&nt,f.mode=22;case 22:if(f.extra){for(k=f.extra;A>>=f.extra,A-=f.extra,f.back+=f.extra}f.was=f.length,f.mode=23;case 23:for(;nt=(S=f.distcode[M&(1<>>16&255,pt=65535&S,!((st=S>>>24)<=A);){if(U===0)break t;U--,M+=P[z++]<>lt)])>>>16&255,pt=65535&S,!(lt+(st=S>>>24)<=A);){if(U===0)break t;U--,M+=P[z++]<>>=lt,A-=lt,f.back+=lt}if(M>>>=st,A-=st,f.back+=st,64&nt){x.msg="invalid distance code",f.mode=30;break}f.offset=pt,f.extra=15&nt,f.mode=24;case 24:if(f.extra){for(k=f.extra;A>>=f.extra,A-=f.extra,f.back+=f.extra}if(f.offset>f.dmax){x.msg="invalid distance too far back",f.mode=30;break}f.mode=25;case 25:if(Q===0)break t;if(Z=K-Q,f.offset>Z){if((Z=f.offset-Z)>f.whave&&f.sane){x.msg="invalid distance too far back",f.mode=30;break}ot=Z>f.wnext?(Z-=f.wnext,f.wsize-Z):f.wnext-Z,Z>f.length&&(Z=f.length),ut=f.window}else ut=G,ot=tt-f.offset,Z=f.length;for(QI?(D=ot[ut+v[T]],A[J+v[T]]):(D=96,0),y=1<>tt)+(w-=y)]=N<<24|D<<16|$|0,w!==0;);for(y=1<>=1;if(y!==0?(M&=y-1,M+=y):M=0,T++,--K[x]==0){if(x===P)break;x=o[c+v[T]]}if(G>>7)]}function J(S,F){S.pending_buf[S.pending++]=255&F,S.pending_buf[S.pending++]=F>>>8&255}function K(S,F,B){S.bi_valid>u-B?(S.bi_buf|=F<>u-S.bi_valid,S.bi_valid+=B-u):(S.bi_buf|=F<>>=1,B<<=1,0<--F;);return B>>>1}function ut(S,F,B){var H,_,j=new Array(v+1),Y=0;for(H=1;H<=v;H++)j[H]=Y=Y+B[H-1]<<1;for(_=0;_<=F;_++){var W=S[2*_+1];W!==0&&(S[2*_]=ot(j[W]++,W))}}function st(S){var F;for(F=0;F>1;1<=B;B--)lt(S,j,B);for(_=X;B=S.heap[1],S.heap[1]=S.heap[S.heap_len--],lt(S,j,1),H=S.heap[1],S.heap[--S.heap_max]=B,S.heap[--S.heap_max]=H,j[2*_]=j[2*B]+j[2*H],S.depth[_]=(S.depth[B]>=S.depth[H]?S.depth[B]:S.depth[H])+1,j[2*B+1]=j[2*H+1]=_,S.heap[1]=_++,lt(S,j,1),2<=S.heap_len;);S.heap[--S.heap_max]=S.heap[1],function(it,mt){var It,yt,At,ct,$t,de,wt=mt.dyn_tree,ke=mt.max_code,Ke=mt.stat_desc.static_tree,Ye=mt.stat_desc.has_stree,qe=mt.stat_desc.extra_bits,Ce=mt.stat_desc.extra_base,Dt=mt.stat_desc.max_length,Bt=0;for(ct=0;ct<=v;ct++)it.bl_count[ct]=0;for(wt[2*it.heap[it.heap_max]+1]=0,It=it.heap_max+1;It>=7;_>>=1)if(1&at&&W.dyn_ltree[2*X]!==0)return s;if(W.dyn_ltree[18]!==0||W.dyn_ltree[20]!==0||W.dyn_ltree[26]!==0)return i;for(X=32;X>>3,(j=S.static_len+3+7>>>3)<=_&&(_=j)):_=j=B+5,B+4<=_&&F!==-1?k(S,F,B,H):S.strategy===4||j===_?(K(S,2+(H?1:0),3),vt(S,q,x)):(K(S,4+(H?1:0),3),function(W,X,at,it){var mt;for(K(W,X-257,5),K(W,at-1,5),K(W,it-4,4),mt=0;mt>>8&255,S.pending_buf[S.d_buf+2*S.last_lit+1]=255&F,S.pending_buf[S.l_buf+S.last_lit]=255&B,S.last_lit++,F===0?S.dyn_ltree[2*B]++:(S.matches++,F--,S.dyn_ltree[2*(f[B]+o+1)]++,S.dyn_dtree[2*A(F)]++),S.last_lit===S.lit_bufsize-1},t._tr_align=function(S){K(S,2,3),Z(S,w,q),function(F){F.bi_valid===16?(J(F,F.bi_buf),F.bi_buf=0,F.bi_valid=0):8<=F.bi_valid&&(F.pending_buf[F.pending++]=255&F.bi_buf,F.bi_buf>>=8,F.bi_valid-=8)}(S)}},{"../utils/common":41}],53:[function(g,m,t){"use strict";m.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(g,m,t){(function(e){(function(s,i){"use strict";if(!s.setImmediate){var r,n,a,o,c=1,l={},h=!1,d=s.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(s);v=v&&v.setTimeout?v:s,r={}.toString.call(s.process)==="[object process]"?function(b){process.nextTick(function(){y(b)})}:function(){if(s.postMessage&&!s.importScripts){var b=!0,C=s.onmessage;return s.onmessage=function(){b=!1},s.postMessage("","*"),s.onmessage=C,b}}()?(o="setImmediate$"+Math.random()+"$",s.addEventListener?s.addEventListener("message",w,!1):s.attachEvent("onmessage",w),function(b){s.postMessage(o+b,"*")}):s.MessageChannel?((a=new MessageChannel).port1.onmessage=function(b){y(b.data)},function(b){a.port2.postMessage(b)}):d&&"onreadystatechange"in d.createElement("script")?(n=d.documentElement,function(b){var C=d.createElement("script");C.onreadystatechange=function(){y(b),C.onreadystatechange=null,n.removeChild(C),C=null},n.appendChild(C)}):function(b){setTimeout(y,0,b)},v.setImmediate=function(b){typeof b!="function"&&(b=new Function(""+b));for(var C=new Array(arguments.length-1),E=0;E"u"?e===void 0?this:e:self)}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})});var Ss={};xe(Ss,{default:()=>ce});module.exports=rs(Ss);var ht=require("obsidian");var kt="stashpad-view",V="__root__";var O=require("obsidian");var Ht=class{constructor(m){this.app=m;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(V,{id:V,parent:null,children:[],file:null,created:""})}setOrderProvider(m){this.orderProvider=m}onChange(m){return this.listeners.add(m),()=>this.listeners.delete(m)}emit(){for(let m of this.listeners)m()}rebuild(m){m!==void 0&&(this.currentFolder=m);let t=this.currentFolder,e=this.byPath,s=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(V,{id:V,parent:null,children:[],file:null,created:""});let i=this.app.vault.getMarkdownFiles().filter(r=>!t||r.path.startsWith(t+"/")||r.path===t);for(let r of i){let n=this.app.metadataCache.getFileCache(r)?.frontmatter,a=n?.id;if(!a){let c=e.get(r.path),l=c?s.get(c):void 0,h=this.synthetic.get(r.path),d=l??h;d&&(this.nodes.set(d.id,{...d,children:[],file:r}),this.byPath.set(r.path,d.id));continue}if(this.synthetic.delete(r.path),a===V){let c=this.nodes.get(V);c.file=r,c.created=n?.created??"",this.byPath.set(r.path,V);continue}let o=n?.parent??null;this.nodes.set(a,{id:a,parent:o??V,children:[],file:r,created:n?.created??""}),this.byPath.set(r.path,a)}for(let r of this.nodes.values()){if(r.id===V)continue;let n=r.parent??V;(this.nodes.get(n)??this.nodes.get(V)).children.push(r.id)}for(let r of this.nodes.values())if(r.children.sort((n,a)=>{let o=this.nodes.get(n),c=this.nodes.get(a);return(o.created||"").localeCompare(c.created||"")}),this.orderProvider){let n=this.orderProvider(r.id);if(n.length>0){let a=new Map;n.forEach((o,c)=>a.set(o,c)),r.children.sort((o,c)=>{let l=a.has(o)?a.get(o):1/0,h=a.has(c)?a.get(c):1/0;return l===h?0:l-h})}}this.emit()}insertSynthetic(m){if(!m.file)return;let t=m.file.path;this.synthetic.set(t,m),this.nodes.set(m.id,m),this.byPath.set(t,m.id);let e=m.parent??V,s=this.nodes.get(e);s&&!s.children.includes(m.id)&&s.children.push(m.id),this.emit()}get(m){return this.nodes.get(m)}getRoot(){return this.nodes.get(V)}getChildren(m){let t=this.nodes.get(m);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}pathTo(m){let t=[],e=this.nodes.get(m);for(;e&&e.id!==V;)t.unshift(e),e=e.parent?this.nodes.get(e.parent):void 0;return t}idForPath(m){return this.byPath.get(m)}snapshot(){let m={};for(let t of this.nodes.values())t.id===V||!t.file||(m[t.id]={parent:t.parent===V?null:t.parent,path:t.file.path});return m}hookMetadataCache(m){let t=i=>{let r=this.currentFolder,n=(typeof i=="string"?i:i?.path)||null;return r?typeof n!="string"?!1:n===r||n.startsWith(r+"/"):!0},e=()=>{this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,this.rebuild(),m()},16))},s=(i,r)=>{!t(i)&&!t(r)||e()};return this.app.metadataCache.on("changed",s),this.app.vault.on("create",s),this.app.vault.on("delete",s),this.app.vault.on("rename",s),()=>{this.app.metadataCache.off("changed",s),this.app.vault.off("create",s),this.app.vault.off("delete",s),this.app.vault.off("rename",s),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}};var Fe=".stashpad-order.json",Ut=class{constructor(m){this.app=m;this.cache=new Map}async load(m){if(this.cache.has(m))return this.cache.get(m);let t=`${m}/${Fe}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=await e.read(t),r=JSON.parse(i);if(r&&typeof r=="object"&&!Array.isArray(r))for(let[n,a]of Object.entries(r))Array.isArray(a)&&a.every(o=>typeof o=="string")&&(s[n]=a)}}catch(i){console.warn("Stashpad: order load failed",i)}return this.cache.set(m,s),s}async save(m){let t=this.cache.get(m)??{},e={};for(let[r,n]of Object.entries(t))n.length>0&&(e[r]=n);this.cache.set(m,e);let s=`${m}/${Fe}`,i=this.app.vault.adapter;try{Object.keys(e).length===0?await i.exists(s)&&await i.remove(s):await i.write(s,JSON.stringify(e,null,2))}catch(r){console.warn("Stashpad: order save failed",r)}}getOrder(m,t){return this.cache.get(m)?.[t]?.slice()??[]}setOrder(m,t,e){let s=this.cache.get(m)??{};s[t]=e.slice(),this.cache.set(m,s)}appendChild(m,t,e){let s=this.cache.get(m)??{},i=s[t]??[];i.includes(e)||i.push(e),s[t]=i,this.cache.set(m,s)}removeChild(m,t){let e=this.cache.get(m);if(e)for(let s of Object.values(e)){let i=s.indexOf(t);i>=0&&s.splice(i,1)}}invalidate(m){this.cache.delete(m)}};var Wt={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"},he=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],ns=new Set(he),Ee=".stashpad-sort.json",jt=class{constructor(m){this.app=m;this.cache=new Map}async load(m){if(this.cache.has(m))return this.cache.get(m);let t=`${m}/${Ee}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=JSON.parse(await e.read(t));if(i&&typeof i=="object"&&!Array.isArray(i))for(let[r,n]of Object.entries(i))typeof n=="string"&&ns.has(n)&&(s[r]=n)}}catch(i){console.warn("Stashpad: sort load failed",i)}return this.cache.set(m,s),s}async save(m){let t=this.cache.get(m)??{},e=`${m}/${Ee}`,s=this.app.vault.adapter;try{Object.keys(t).length===0?await s.exists(e)&&await s.remove(e):await s.write(e,JSON.stringify(t,null,2))}catch(i){console.warn("Stashpad: sort save failed",i)}}getMode(m,t){return this.cache.get(m)?.[t]??"manual"}setMode(m,t,e){let s=this.cache.get(m)??{};e==="manual"?delete s[t]:s[t]=e,this.cache.set(m,s)}removeParent(m,t){let e=this.cache.get(m);e&&delete e[t]}invalidate(m){this.cache.delete(m)}};Tt();var St=["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"];function Vt(g,m=St){let t=m instanceof Set?m:new Set(m.map(a=>a.toLowerCase())),e=(g.split(/\r?\n/).find(a=>a.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ](s|t|re|ll|ve|d|m)\b/gi,""),i=new Set(["s","t","re","ll","ve","d","m"]),r=s.replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(a=>a&&!t.has(a.toLowerCase())&&!i.has(a.toLowerCase())).map(a=>a.length>=2&&/^[A-Z0-9]+$/.test(a)?a:a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()),n="";for(let a of r){let o=n?`${n}-${a}`:a;if(o.length>50)break;n=o}return n||"Untitled"}function Kt(g,m){return`${g}-${m}.md`}function Yt(g){let m=g.match(/-([a-z0-9]{4,12})$/);return m?m[1]:null}var qt=class{constructor(m,t){this.tree=m;this.log=t}async sweep(m){let t=await this.log.readState(),e=this.tree.snapshot(),s=r=>{if(!m)return!0;let n=m.replace(/\/+$/,"");return r===n||r.startsWith(n+"/")};for(let[r,n]of Object.entries(e)){let a=t[r];a?a.parent!==n.parent?await this.log.append({type:"parent_change",id:r,payload:{from:a.parent,to:n.parent}}):a.path!==n.path&&await this.log.append({type:"rename",id:r,payload:{from:a.path,to:n.path}}):await this.log.append({type:"create",id:r,payload:{path:n.path,parent:n.parent}})}for(let[r,n]of Object.entries(t))!e[r]&&s(n.path)&&await this.log.append({type:"missing",id:r,payload:{lastPath:n.path}});let i={};for(let[r,n]of Object.entries(t))s(n.path)||(i[r]=n);for(let[r,n]of Object.entries(e))i[r]=n;await this.log.writeState(i)}};var et=require("obsidian");var dt=require("obsidian"),Ft=class Ft extends dt.Modal{constructor(t,e,s){super(t);this.text=e;this.jsonlPath=s;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 o of this.text.trim().split(/\r?\n/))if(o)try{this.events.push(JSON.parse(o))}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 s=t.createEl("button",{text:"Open in default app"});s.onclick=()=>this.shellAct("open");let i=t.createEl("button",{text:"Copy raw JSONL"}),r=null;i.onclick=async()=>{await navigator.clipboard.writeText(this.text),i.setText("Copied"),r!=null&&window.clearTimeout(r),r=window.setTimeout(()=>{i.setText("Copy raw JSONL"),r=null},1500)};let n=t.createEl("button",{text:"Export copy"});n.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(Ft.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 r of this.events)e.set(r.type,(e.get(r.type)??0)+1);let s=[...e.entries()].sort((r,n)=>n[1]-r[1]||r[0].localeCompare(n[0])),i=t.createEl("option",{text:`All types (${this.events.length})`});i.value="";for(let[r,n]of s){let a=t.createEl("option",{text:`${r} (${n})`});a.value=r}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 s=this.shownCount;s{this.appendMore(Ft.PAGE),this.renderFooter()},t>Ft.PAGE){let s=this.footerEl.createEl("button",{text:`Load all (${t})`});s.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:s}=window.require("electron");t==="reveal"?s.showItemInFolder(e):s.openPath(e)}catch(e){new dt.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,dt.moment)().format("YYYY-MM-DD_HHmmss"),e=this.jsonlPath.replace(/\/[^/]+$/,"")||"",s=e?`${e}/${t}-log.jsonl`:`${t}-log.jsonl`;return await this.app.vault.adapter.write(s,this.text),new dt.Notice(`Exported log \u2192 ${s}`),s}catch(t){return new dt.Notice(`Export failed: ${t.message}`),null}}clearLog(){new Lt(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(s){new dt.Notice(`Clear failed: ${s.message}`);return}this.text="",this.events=[],this.typeFilter=null,this.shownCount=0,this.refreshTypeFilter(),this.refreshList(),this.footerEl&&this.footerEl.empty(),new dt.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let s=(0,dt.moment)(t.ts).isValid()?(0,dt.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,i=document.createElement("span");i.className="stashpad-log-ts",i.textContent=s,e.appendChild(i);let r=document.createElement("span");r.className="stashpad-log-type",r.textContent=t.type,e.appendChild(r);let n=document.createElement("span");n.className="stashpad-log-author",n.textContent=t.author?t.author:"\u2014",t.author||n.classList.add("is-empty"),e.appendChild(n);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 s=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,i=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${i}${s?` \u2014 also removed ${s} attachment${s===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let s=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${s}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let s=e.count??1,i=e.dir??"?",r=e.parent??t.id??"?";return`Reordered ${s} note${s===1?"":"s"} (${i}) under ${r}`}case"complete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${s} note${s===1?"":"s"} complete${i}`}case"uncomplete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${s} note${s===1?"":"s"}${i}`}case"stash_export":{let s=e.noteCount??"?";return`Exported ${s} note${s===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let s=e.noteCount??"?",i=[];e.attachmentsWritten&&i.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&i.push(`${e.collisionsRenamed} renamed`);let r=i.length?` (${i.join(", ")})`:"";return`Imported ${s} note${s===1?"":"s"} from ${e.from??"?"} \u2192 ${e.into??"?"}${r}`}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()}};Ft.PAGE=100;var Gt=Ft,Mt=class extends dt.Modal{constructor(t,e,s,i,r,n){super(t);this.noteTitle=e;this.descendantCount=s;this.attachmentCount=i;this.offerAttachmentDelete=r;this.onChoose=n}onOpen(){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 n=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=n.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},n.createSpan({text:" Also delete attachments"})}let s=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=s.createEl("button",{text:"Cancel"});i.onclick=()=>this.close();let r=s.createEl("button",{cls:"mod-warning",text:"Delete"});r.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},Xt=class extends dt.Modal{constructor(t,e,s,i){super(t);this.body=e;this.onSplitAtLine=s;this.onSplitAtChar=i;this.mode="line";this.cursorTextarea=null;this.lines=e.replace(/\r\n/g,` +"use strict";var Je=Object.create;var Ut=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var ts=Object.getOwnPropertyNames;var es=Object.getPrototypeOf,ss=Object.prototype.hasOwnProperty;var is=(v,p)=>()=>(v&&(p=v(v=0)),p);var rs=(v,p)=>()=>(p||v((p={exports:{}}).exports,p),p.exports),Ee=(v,p)=>{for(var t in p)Ut(v,t,{get:p[t],enumerable:!0})},_e=(v,p,t,e)=>{if(p&&typeof p=="object"||typeof p=="function")for(let s of ts(p))!ss.call(v,s)&&s!==t&&Ut(v,s,{get:()=>p[s],enumerable:!(e=Qe(p,s))||e.enumerable});return v};var ns=(v,p,t)=>(t=v!=null?Je(es(v)):{},_e(p||!v||!v.__esModule?Ut(t,"default",{value:v,enumerable:!0}):t,v)),as=v=>_e(Ut({},"__esModule",{value:!0}),v);var Zt={};Ee(Zt,{newId:()=>bt});function bt(v=6){let p="",t=new Uint8Array(v);crypto.getRandomValues(t);for(let e=0;e{"use strict";De="abcdefghijkmnpqrstuvwxyz23456789"});var ze=rs((Be,Se)=>{(function(v){typeof Be=="object"&&typeof Se<"u"?Se.exports=v():typeof define=="function"&&define.amd?define([],v):(typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:this).JSZip=v()})(function(){return function v(p,t,e){function s(n,a){if(!t[n]){if(!p[n]){var o=typeof require=="function"&&require;if(!a&&o)return o(n,!0);if(i)return i(n,!0);var l=new Error("Cannot find module '"+n+"'");throw l.code="MODULE_NOT_FOUND",l}var c=t[n]={exports:{}};p[n][0].call(c.exports,function(d){var h=p[n][1][d];return s(h||d)},c,c.exports,v,p,t,e)}return t[n].exports}for(var i=typeof require=="function"&&require,r=0;r>2,c=(3&n)<<4|a>>4,d=1>6:64,h=2>4,a=(15&l)<<4|(c=i.indexOf(r.charAt(h++)))>>2,o=(3&c)<<6|(d=i.indexOf(r.charAt(h++))),y[g++]=n,c!==64&&(y[g++]=a),d!==64&&(y[g++]=o);return y}},{"./support":30,"./utils":32}],2:[function(v,p,t){"use strict";var e=v("./external"),s=v("./stream/DataWorker"),i=v("./stream/Crc32Probe"),r=v("./stream/DataLengthProbe");function n(a,o,l,c,d){this.compressedSize=a,this.uncompressedSize=o,this.crc32=l,this.compression=c,this.compressedContent=d}n.prototype={getContentWorker:function(){var a=new s(e.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new r("data_length")),o=this;return a.on("end",function(){if(this.streamInfo.data_length!==o.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),a},getCompressedWorker:function(){return new s(e.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},n.createWorkerFrom=function(a,o,l){return a.pipe(new i).pipe(new r("uncompressedSize")).pipe(o.compressWorker(l)).pipe(new r("compressedSize")).withStreamInfo("compression",o)},p.exports=n},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(v,p,t){"use strict";var e=v("./stream/GenericWorker");t.STORE={magic:"\0\0",compressWorker:function(){return new e("STORE compression")},uncompressWorker:function(){return new e("STORE decompression")}},t.DEFLATE=v("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(v,p,t){"use strict";var e=v("./utils"),s=function(){for(var i,r=[],n=0;n<256;n++){i=n;for(var a=0;a<8;a++)i=1&i?3988292384^i>>>1:i>>>1;r[n]=i}return r}();p.exports=function(i,r){return i!==void 0&&i.length?e.getTypeOf(i)!=="string"?function(n,a,o,l){var c=s,d=l+o;n^=-1;for(var h=l;h>>8^c[255&(n^a[h])];return-1^n}(0|r,i,i.length,0):function(n,a,o,l){var c=s,d=l+o;n^=-1;for(var h=l;h>>8^c[255&(n^a.charCodeAt(h))];return-1^n}(0|r,i,i.length,0):0}},{"./utils":32}],5:[function(v,p,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(v,p,t){"use strict";var e=null;e=typeof Promise<"u"?Promise:v("lie"),p.exports={Promise:e}},{lie:37}],7:[function(v,p,t){"use strict";var e=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",s=v("pako"),i=v("./utils"),r=v("./stream/GenericWorker"),n=e?"uint8array":"array";function a(o,l){r.call(this,"FlateWorker/"+o),this._pako=null,this._pakoAction=o,this._pakoOptions=l,this.meta={}}t.magic="\b\0",i.inherits(a,r),a.prototype.processChunk=function(o){this.meta=o.meta,this._pako===null&&this._createPako(),this._pako.push(i.transformTo(n,o.data),!1)},a.prototype.flush=function(){r.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},a.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this._pako=null},a.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var o=this;this._pako.onData=function(l){o.push({data:l,meta:o.meta})}},t.compressWorker=function(o){return new a("Deflate",o)},t.uncompressWorker=function(){return new a("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(v,p,t){"use strict";function e(c,d){var h,g="";for(h=0;h>>=8;return g}function s(c,d,h,g,u,y){var w,b,C=c.file,_=c.compression,T=y!==n.utf8encode,R=i.transformTo("string",y(C.name)),P=i.transformTo("string",n.utf8encode(C.name)),$=C.comment,Y=i.transformTo("string",y($)),x=i.transformTo("string",n.utf8encode($)),F=P.length!==C.name.length,m=x.length!==$.length,M="",G="",z="",tt=C.dir,U=C.date,Q={crc32:0,compressedSize:0,uncompressedSize:0};d&&!h||(Q.crc32=c.crc32,Q.compressedSize=c.compressedSize,Q.uncompressedSize=c.uncompressedSize);var L=0;d&&(L|=8),T||!F&&!m||(L|=2048);var D=0,J=0;tt&&(D|=16),u==="UNIX"?(J=798,D|=function(Z,ot){var ut=Z;return Z||(ut=ot?16893:33204),(65535&ut)<<16}(C.unixPermissions,tt)):(J=20,D|=function(Z){return 63&(Z||0)}(C.dosPermissions)),w=U.getUTCHours(),w<<=6,w|=U.getUTCMinutes(),w<<=5,w|=U.getUTCSeconds()/2,b=U.getUTCFullYear()-1980,b<<=4,b|=U.getUTCMonth()+1,b<<=5,b|=U.getUTCDate(),F&&(G=e(1,1)+e(a(R),4)+P,M+="up"+e(G.length,2)+G),m&&(z=e(1,1)+e(a(Y),4)+x,M+="uc"+e(z.length,2)+z);var K="";return K+=` +\0`,K+=e(L,2),K+=_.magic,K+=e(w,2),K+=e(b,2),K+=e(Q.crc32,4),K+=e(Q.compressedSize,4),K+=e(Q.uncompressedSize,4),K+=e(R.length,2),K+=e(M.length,2),{fileRecord:o.LOCAL_FILE_HEADER+K+R+M,dirRecord:o.CENTRAL_FILE_HEADER+e(J,2)+K+e(Y.length,2)+"\0\0\0\0"+e(D,4)+e(g,4)+R+M+Y}}var i=v("../utils"),r=v("../stream/GenericWorker"),n=v("../utf8"),a=v("../crc32"),o=v("../signature");function l(c,d,h,g){r.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=d,this.zipPlatform=h,this.encodeFileName=g,this.streamFiles=c,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}i.inherits(l,r),l.prototype.push=function(c){var d=c.meta.percent||0,h=this.entriesCount,g=this._sources.length;this.accumulate?this.contentBuffer.push(c):(this.bytesWritten+=c.data.length,r.prototype.push.call(this,{data:c.data,meta:{currentFile:this.currentFile,percent:h?(d+100*(h-g-1))/h:100}}))},l.prototype.openedSource=function(c){this.currentSourceOffset=this.bytesWritten,this.currentFile=c.file.name;var d=this.streamFiles&&!c.file.dir;if(d){var h=s(c,d,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:h.fileRecord,meta:{percent:0}})}else this.accumulate=!0},l.prototype.closedSource=function(c){this.accumulate=!1;var d=this.streamFiles&&!c.file.dir,h=s(c,d,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(h.dirRecord),d)this.push({data:function(g){return o.DATA_DESCRIPTOR+e(g.crc32,4)+e(g.compressedSize,4)+e(g.uncompressedSize,4)}(c),meta:{percent:100}});else for(this.push({data:h.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},l.prototype.flush=function(){for(var c=this.bytesWritten,d=0;d=this.index;r--)n=(n<<8)+this.byteAt(r);return this.index+=i,n},readString:function(i){return e.transformTo("string",this.readData(i))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var i=this.readInt(4);return new Date(Date.UTC(1980+(i>>25&127),(i>>21&15)-1,i>>16&31,i>>11&31,i>>5&63,(31&i)<<1))}},p.exports=s},{"../utils":32}],19:[function(v,p,t){"use strict";var e=v("./Uint8ArrayReader");function s(i){e.call(this,i)}v("../utils").inherits(s,e),s.prototype.readData=function(i){this.checkOffset(i);var r=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,r},p.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(v,p,t){"use strict";var e=v("./DataReader");function s(i){e.call(this,i)}v("../utils").inherits(s,e),s.prototype.byteAt=function(i){return this.data.charCodeAt(this.zero+i)},s.prototype.lastIndexOfSignature=function(i){return this.data.lastIndexOf(i)-this.zero},s.prototype.readAndCheckSignature=function(i){return i===this.readData(4)},s.prototype.readData=function(i){this.checkOffset(i);var r=this.data.slice(this.zero+this.index,this.zero+this.index+i);return this.index+=i,r},p.exports=s},{"../utils":32,"./DataReader":18}],21:[function(v,p,t){"use strict";var e=v("./ArrayReader");function s(i){e.call(this,i)}v("../utils").inherits(s,e),s.prototype.readData=function(i){if(this.checkOffset(i),i===0)return new Uint8Array(0);var r=this.data.subarray(this.zero+this.index,this.zero+this.index+i);return this.index+=i,r},p.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(v,p,t){"use strict";var e=v("../utils"),s=v("../support"),i=v("./ArrayReader"),r=v("./StringReader"),n=v("./NodeBufferReader"),a=v("./Uint8ArrayReader");p.exports=function(o){var l=e.getTypeOf(o);return e.checkSupport(l),l!=="string"||s.uint8array?l==="nodebuffer"?new n(o):s.uint8array?new a(e.transformTo("uint8array",o)):new i(e.transformTo("array",o)):new r(o)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(v,p,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(v,p,t){"use strict";var e=v("./GenericWorker"),s=v("../utils");function i(r){e.call(this,"ConvertWorker to "+r),this.destType=r}s.inherits(i,e),i.prototype.processChunk=function(r){this.push({data:s.transformTo(this.destType,r.data),meta:r.meta})},p.exports=i},{"../utils":32,"./GenericWorker":28}],25:[function(v,p,t){"use strict";var e=v("./GenericWorker"),s=v("../crc32");function i(){e.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}v("../utils").inherits(i,e),i.prototype.processChunk=function(r){this.streamInfo.crc32=s(r.data,this.streamInfo.crc32||0),this.push(r)},p.exports=i},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(v,p,t){"use strict";var e=v("../utils"),s=v("./GenericWorker");function i(r){s.call(this,"DataLengthProbe for "+r),this.propName=r,this.withStreamInfo(r,0)}e.inherits(i,s),i.prototype.processChunk=function(r){if(r){var n=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=n+r.data.length}s.prototype.processChunk.call(this,r)},p.exports=i},{"../utils":32,"./GenericWorker":28}],27:[function(v,p,t){"use strict";var e=v("../utils"),s=v("./GenericWorker");function i(r){s.call(this,"DataWorker");var n=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,r.then(function(a){n.dataIsReady=!0,n.data=a,n.max=a&&a.length||0,n.type=e.getTypeOf(a),n.isPaused||n._tickAndRepeat()},function(a){n.error(a)})}e.inherits(i,s),i.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},i.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,e.delay(this._tickAndRepeat,[],this)),!0)},i.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(e.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},i.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var r=null,n=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":r=this.data.substring(this.index,n);break;case"uint8array":r=this.data.subarray(this.index,n);break;case"array":case"nodebuffer":r=this.data.slice(this.index,n)}return this.index=n,this.push({data:r,meta:{percent:this.max?this.index/this.max*100:0}})},p.exports=i},{"../utils":32,"./GenericWorker":28}],28:[function(v,p,t){"use strict";function e(s){this.name=s||"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(s){this.emit("data",s)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(s){this.emit("error",s)}return!0},error:function(s){return!this.isFinished&&(this.isPaused?this.generatedError=s:(this.isFinished=!0,this.emit("error",s),this.previous&&this.previous.error(s),this.cleanUp()),!0)},on:function(s,i){return this._listeners[s].push(i),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(s,i){if(this._listeners[s])for(var r=0;r "+s:s}},p.exports=e},{}],29:[function(v,p,t){"use strict";var e=v("../utils"),s=v("./ConvertWorker"),i=v("./GenericWorker"),r=v("../base64"),n=v("../support"),a=v("../external"),o=null;if(n.nodestream)try{o=v("../nodejs/NodejsStreamOutputAdapter")}catch{}function l(d,h){return new a.Promise(function(g,u){var y=[],w=d._internalType,b=d._outputType,C=d._mimeType;d.on("data",function(_,T){y.push(_),h&&h(T)}).on("error",function(_){y=[],u(_)}).on("end",function(){try{var _=function(T,R,P){switch(T){case"blob":return e.newBlob(e.transformTo("arraybuffer",R),P);case"base64":return r.encode(R);default:return e.transformTo(T,R)}}(b,function(T,R){var P,$=0,Y=null,x=0;for(P=0;P"u")t.blob=!1;else{var e=new ArrayBuffer(0);try{t.blob=new Blob([e],{type:"application/zip"}).size===0}catch{try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(e),t.blob=s.getBlob("application/zip").size===0}catch{t.blob=!1}}}try{t.nodestream=!!v("readable-stream").Readable}catch{t.nodestream=!1}},{"readable-stream":16}],31:[function(v,p,t){"use strict";for(var e=v("./utils"),s=v("./support"),i=v("./nodejsUtils"),r=v("./stream/GenericWorker"),n=new Array(256),a=0;a<256;a++)n[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;n[254]=n[254]=1;function o(){r.call(this,"utf-8 decode"),this.leftOver=null}function l(){r.call(this,"utf-8 encode")}t.utf8encode=function(c){return s.nodebuffer?i.newBufferFrom(c,"utf-8"):function(d){var h,g,u,y,w,b=d.length,C=0;for(y=0;y>>6:(g<65536?h[w++]=224|g>>>12:(h[w++]=240|g>>>18,h[w++]=128|g>>>12&63),h[w++]=128|g>>>6&63),h[w++]=128|63&g);return h}(c)},t.utf8decode=function(c){return s.nodebuffer?e.transformTo("nodebuffer",c).toString("utf-8"):function(d){var h,g,u,y,w=d.length,b=new Array(2*w);for(h=g=0;h>10&1023,b[g++]=56320|1023&u)}return b.length!==g&&(b.subarray?b=b.subarray(0,g):b.length=g),e.applyFromCharCode(b)}(c=e.transformTo(s.uint8array?"uint8array":"array",c))},e.inherits(o,r),o.prototype.processChunk=function(c){var d=e.transformTo(s.uint8array?"uint8array":"array",c.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var h=d;(d=new Uint8Array(h.length+this.leftOver.length)).set(this.leftOver,0),d.set(h,this.leftOver.length)}else d=this.leftOver.concat(d);this.leftOver=null}var g=function(y,w){var b;for((w=w||y.length)>y.length&&(w=y.length),b=w-1;0<=b&&(192&y[b])==128;)b--;return b<0||b===0?w:b+n[y[b]]>w?b:w}(d),u=d;g!==d.length&&(s.uint8array?(u=d.subarray(0,g),this.leftOver=d.subarray(g,d.length)):(u=d.slice(0,g),this.leftOver=d.slice(g,d.length))),this.push({data:t.utf8decode(u),meta:c.meta})},o.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:t.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},t.Utf8DecodeWorker=o,e.inherits(l,r),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(v,p,t){"use strict";var e=v("./support"),s=v("./base64"),i=v("./nodejsUtils"),r=v("./external");function n(h){return h}function a(h,g){for(var u=0;u>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===s.MAX_VALUE_32BITS&&(this.uncompressedSize=c.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=c.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=c.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=c.readInt(4))}},readExtraFields:function(c){var d,h,g,u=c.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});c.index+4>>6:(c<65536?l[g++]=224|c>>>12:(l[g++]=240|c>>>18,l[g++]=128|c>>>12&63),l[g++]=128|c>>>6&63),l[g++]=128|63&c);return l},t.buf2binstring=function(o){return a(o,o.length)},t.binstring2buf=function(o){for(var l=new e.Buf8(o.length),c=0,d=l.length;c>10&1023,y[d++]=56320|1023&h)}return a(y,d)},t.utf8border=function(o,l){var c;for((l=l||o.length)>o.length&&(l=o.length),c=l-1;0<=c&&(192&o[c])==128;)c--;return c<0||c===0?l:c+r[o[c]]>l?c:l}},{"./common":41}],43:[function(v,p,t){"use strict";p.exports=function(e,s,i,r){for(var n=65535&e|0,a=e>>>16&65535|0,o=0;i!==0;){for(i-=o=2e3>>1:s>>>1;i[r]=s}return i}();p.exports=function(s,i,r,n){var a=e,o=n+r;s^=-1;for(var l=n;l>>8^a[255&(s^i[l])];return-1^s}},{}],46:[function(v,p,t){"use strict";var e,s=v("../utils/common"),i=v("./trees"),r=v("./adler32"),n=v("./crc32"),a=v("./messages"),o=0,l=4,c=0,d=-2,h=-1,g=4,u=2,y=8,w=9,b=286,C=30,_=19,T=2*b+1,R=15,P=3,$=258,Y=$+P+1,x=42,F=113,m=1,M=2,G=3,z=4;function tt(f,N){return f.msg=a[N],N}function U(f){return(f<<1)-(4f.avail_out&&(O=f.avail_out),O!==0&&(s.arraySet(f.output,N.pending_buf,N.pending_out,O,f.next_out),f.next_out+=O,N.pending_out+=O,f.total_out+=O,f.avail_out-=O,N.pending-=O,N.pending===0&&(N.pending_out=0))}function D(f,N){i._tr_flush_block(f,0<=f.block_start?f.block_start:-1,f.strstart-f.block_start,N),f.block_start=f.strstart,L(f.strm)}function J(f,N){f.pending_buf[f.pending++]=N}function K(f,N){f.pending_buf[f.pending++]=N>>>8&255,f.pending_buf[f.pending++]=255&N}function Z(f,N){var O,k,S=f.max_chain_length,E=f.strstart,B=f.prev_length,H=f.nice_match,I=f.strstart>f.w_size-Y?f.strstart-(f.w_size-Y):0,W=f.window,q=f.w_mask,V=f.prev,X=f.strstart+$,at=W[E+B-1],it=W[E+B];f.prev_length>=f.good_match&&(S>>=2),H>f.lookahead&&(H=f.lookahead);do if(W[(O=N)+B]===it&&W[O+B-1]===at&&W[O]===W[E]&&W[++O]===W[E+1]){E+=2,O++;do;while(W[++E]===W[++O]&&W[++E]===W[++O]&&W[++E]===W[++O]&&W[++E]===W[++O]&&W[++E]===W[++O]&&W[++E]===W[++O]&&W[++E]===W[++O]&&W[++E]===W[++O]&&EI&&--S!=0);return B<=f.lookahead?B:f.lookahead}function ot(f){var N,O,k,S,E,B,H,I,W,q,V=f.w_size;do{if(S=f.window_size-f.lookahead-f.strstart,f.strstart>=V+(V-Y)){for(s.arraySet(f.window,f.window,V,V,0),f.match_start-=V,f.strstart-=V,f.block_start-=V,N=O=f.hash_size;k=f.head[--N],f.head[N]=V<=k?k-V:0,--O;);for(N=O=V;k=f.prev[--N],f.prev[N]=V<=k?k-V:0,--O;);S+=V}if(f.strm.avail_in===0)break;if(B=f.strm,H=f.window,I=f.strstart+f.lookahead,W=S,q=void 0,q=B.avail_in,W=P)for(E=f.strstart-f.insert,f.ins_h=f.window[E],f.ins_h=(f.ins_h<=P&&(f.ins_h=(f.ins_h<=P)if(k=i._tr_tally(f,f.strstart-f.match_start,f.match_length-P),f.lookahead-=f.match_length,f.match_length<=f.max_lazy_match&&f.lookahead>=P){for(f.match_length--;f.strstart++,f.ins_h=(f.ins_h<=P&&(f.ins_h=(f.ins_h<=P&&f.match_length<=f.prev_length){for(S=f.strstart+f.lookahead-P,k=i._tr_tally(f,f.strstart-1-f.prev_match,f.prev_length-P),f.lookahead-=f.prev_length-1,f.prev_length-=2;++f.strstart<=S&&(f.ins_h=(f.ins_h<f.pending_buf_size-5&&(O=f.pending_buf_size-5);;){if(f.lookahead<=1){if(ot(f),f.lookahead===0&&N===o)return m;if(f.lookahead===0)break}f.strstart+=f.lookahead,f.lookahead=0;var k=f.block_start+O;if((f.strstart===0||f.strstart>=k)&&(f.lookahead=f.strstart-k,f.strstart=k,D(f,!1),f.strm.avail_out===0)||f.strstart-f.block_start>=f.w_size-Y&&(D(f,!1),f.strm.avail_out===0))return m}return f.insert=0,N===l?(D(f,!0),f.strm.avail_out===0?G:z):(f.strstart>f.block_start&&(D(f,!1),f.strm.avail_out),m)}),new nt(4,4,8,4,ut),new nt(4,5,16,8,ut),new nt(4,6,32,32,ut),new nt(4,4,16,16,st),new nt(8,16,32,32,st),new nt(8,16,128,128,st),new nt(8,32,128,256,st),new nt(32,128,258,1024,st),new nt(32,258,258,4096,st)],t.deflateInit=function(f,N){return gt(f,N,y,15,8,0)},t.deflateInit2=gt,t.deflateReset=vt,t.deflateResetKeep=lt,t.deflateSetHeader=function(f,N){return f&&f.state?f.state.wrap!==2?d:(f.state.gzhead=N,c):d},t.deflate=function(f,N){var O,k,S,E;if(!f||!f.state||5>8&255),J(k,k.gzhead.time>>16&255),J(k,k.gzhead.time>>24&255),J(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),J(k,255&k.gzhead.os),k.gzhead.extra&&k.gzhead.extra.length&&(J(k,255&k.gzhead.extra.length),J(k,k.gzhead.extra.length>>8&255)),k.gzhead.hcrc&&(f.adler=n(f.adler,k.pending_buf,k.pending,0)),k.gzindex=0,k.status=69):(J(k,0),J(k,0),J(k,0),J(k,0),J(k,0),J(k,k.level===9?2:2<=k.strategy||k.level<2?4:0),J(k,3),k.status=F);else{var B=y+(k.w_bits-8<<4)<<8;B|=(2<=k.strategy||k.level<2?0:k.level<6?1:k.level===6?2:3)<<6,k.strstart!==0&&(B|=32),B+=31-B%31,k.status=F,K(k,B),k.strstart!==0&&(K(k,f.adler>>>16),K(k,65535&f.adler)),f.adler=1}if(k.status===69)if(k.gzhead.extra){for(S=k.pending;k.gzindex<(65535&k.gzhead.extra.length)&&(k.pending!==k.pending_buf_size||(k.gzhead.hcrc&&k.pending>S&&(f.adler=n(f.adler,k.pending_buf,k.pending-S,S)),L(f),S=k.pending,k.pending!==k.pending_buf_size));)J(k,255&k.gzhead.extra[k.gzindex]),k.gzindex++;k.gzhead.hcrc&&k.pending>S&&(f.adler=n(f.adler,k.pending_buf,k.pending-S,S)),k.gzindex===k.gzhead.extra.length&&(k.gzindex=0,k.status=73)}else k.status=73;if(k.status===73)if(k.gzhead.name){S=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>S&&(f.adler=n(f.adler,k.pending_buf,k.pending-S,S)),L(f),S=k.pending,k.pending===k.pending_buf_size)){E=1;break}E=k.gzindexS&&(f.adler=n(f.adler,k.pending_buf,k.pending-S,S)),E===0&&(k.gzindex=0,k.status=91)}else k.status=91;if(k.status===91)if(k.gzhead.comment){S=k.pending;do{if(k.pending===k.pending_buf_size&&(k.gzhead.hcrc&&k.pending>S&&(f.adler=n(f.adler,k.pending_buf,k.pending-S,S)),L(f),S=k.pending,k.pending===k.pending_buf_size)){E=1;break}E=k.gzindexS&&(f.adler=n(f.adler,k.pending_buf,k.pending-S,S)),E===0&&(k.status=103)}else k.status=103;if(k.status===103&&(k.gzhead.hcrc?(k.pending+2>k.pending_buf_size&&L(f),k.pending+2<=k.pending_buf_size&&(J(k,255&f.adler),J(k,f.adler>>8&255),f.adler=0,k.status=F)):k.status=F),k.pending!==0){if(L(f),f.avail_out===0)return k.last_flush=-1,c}else if(f.avail_in===0&&U(N)<=U(O)&&N!==l)return tt(f,-5);if(k.status===666&&f.avail_in!==0)return tt(f,-5);if(f.avail_in!==0||k.lookahead!==0||N!==o&&k.status!==666){var H=k.strategy===2?function(I,W){for(var q;;){if(I.lookahead===0&&(ot(I),I.lookahead===0)){if(W===o)return m;break}if(I.match_length=0,q=i._tr_tally(I,0,I.window[I.strstart]),I.lookahead--,I.strstart++,q&&(D(I,!1),I.strm.avail_out===0))return m}return I.insert=0,W===l?(D(I,!0),I.strm.avail_out===0?G:z):I.last_lit&&(D(I,!1),I.strm.avail_out===0)?m:M}(k,N):k.strategy===3?function(I,W){for(var q,V,X,at,it=I.window;;){if(I.lookahead<=$){if(ot(I),I.lookahead<=$&&W===o)return m;if(I.lookahead===0)break}if(I.match_length=0,I.lookahead>=P&&0I.lookahead&&(I.match_length=I.lookahead)}if(I.match_length>=P?(q=i._tr_tally(I,1,I.match_length-P),I.lookahead-=I.match_length,I.strstart+=I.match_length,I.match_length=0):(q=i._tr_tally(I,0,I.window[I.strstart]),I.lookahead--,I.strstart++),q&&(D(I,!1),I.strm.avail_out===0))return m}return I.insert=0,W===l?(D(I,!0),I.strm.avail_out===0?G:z):I.last_lit&&(D(I,!1),I.strm.avail_out===0)?m:M}(k,N):e[k.level].func(k,N);if(H!==G&&H!==z||(k.status=666),H===m||H===G)return f.avail_out===0&&(k.last_flush=-1),c;if(H===M&&(N===1?i._tr_align(k):N!==5&&(i._tr_stored_block(k,0,0,!1),N===3&&(Q(k.head),k.lookahead===0&&(k.strstart=0,k.block_start=0,k.insert=0))),L(f),f.avail_out===0))return k.last_flush=-1,c}return N!==l?c:k.wrap<=0?1:(k.wrap===2?(J(k,255&f.adler),J(k,f.adler>>8&255),J(k,f.adler>>16&255),J(k,f.adler>>24&255),J(k,255&f.total_in),J(k,f.total_in>>8&255),J(k,f.total_in>>16&255),J(k,f.total_in>>24&255)):(K(k,f.adler>>>16),K(k,65535&f.adler)),L(f),0=O.w_size&&(E===0&&(Q(O.head),O.strstart=0,O.block_start=0,O.insert=0),W=new s.Buf8(O.w_size),s.arraySet(W,N,q-O.w_size,O.w_size,0),N=W,q=O.w_size),B=f.avail_in,H=f.next_in,I=f.input,f.avail_in=q,f.next_in=0,f.input=N,ot(O);O.lookahead>=P;){for(k=O.strstart,S=O.lookahead-(P-1);O.ins_h=(O.ins_h<>>=P=R>>>24,w-=P,(P=R>>>16&255)===0)M[a++]=65535&R;else{if(!(16&P)){if(!(64&P)){R=b[(65535&R)+(y&(1<>>=P,w-=P),w<15&&(y+=m[r++]<>>=P=R>>>24,w-=P,!(16&(P=R>>>16&255))){if(!(64&P)){R=C[(65535&R)+(y&(1<>>=P,w-=P,(P=a-o)>3,y&=(1<<(w-=$<<3))-1,e.next_in=r,e.next_out=a,e.avail_in=r>>24&255)+(x>>>8&65280)+((65280&x)<<8)+((255&x)<<24)}function y(){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 w(x){var F;return x&&x.state?(F=x.state,x.total_in=x.total_out=F.total=0,x.msg="",F.wrap&&(x.adler=1&F.wrap),F.mode=d,F.last=0,F.havedict=0,F.dmax=32768,F.head=null,F.hold=0,F.bits=0,F.lencode=F.lendyn=new e.Buf32(h),F.distcode=F.distdyn=new e.Buf32(g),F.sane=1,F.back=-1,l):c}function b(x){var F;return x&&x.state?((F=x.state).wsize=0,F.whave=0,F.wnext=0,w(x)):c}function C(x,F){var m,M;return x&&x.state?(M=x.state,F<0?(m=0,F=-F):(m=1+(F>>4),F<48&&(F&=15)),F&&(F<8||15=z.wsize?(e.arraySet(z.window,F,m-z.wsize,z.wsize,0),z.wnext=0,z.whave=z.wsize):(M<(G=z.wsize-z.wnext)&&(G=M),e.arraySet(z.window,F,m-M,G,z.wnext),(M-=G)?(e.arraySet(z.window,F,m-M,M,0),z.wnext=M,z.whave=z.wsize):(z.wnext+=G,z.wnext===z.wsize&&(z.wnext=0),z.whave>>8&255,m.check=i(m.check,E,2,0),D=L=0,m.mode=2;break}if(m.flags=0,m.head&&(m.head.done=!1),!(1&m.wrap)||(((255&L)<<8)+(L>>8))%31){x.msg="incorrect header check",m.mode=30;break}if((15&L)!=8){x.msg="unknown compression method",m.mode=30;break}if(D-=4,f=8+(15&(L>>>=4)),m.wbits===0)m.wbits=f;else if(f>m.wbits){x.msg="invalid window size",m.mode=30;break}m.dmax=1<>8&1),512&m.flags&&(E[0]=255&L,E[1]=L>>>8&255,m.check=i(m.check,E,2,0)),D=L=0,m.mode=3;case 3:for(;D<32;){if(U===0)break t;U--,L+=M[z++]<>>8&255,E[2]=L>>>16&255,E[3]=L>>>24&255,m.check=i(m.check,E,4,0)),D=L=0,m.mode=4;case 4:for(;D<16;){if(U===0)break t;U--,L+=M[z++]<>8),512&m.flags&&(E[0]=255&L,E[1]=L>>>8&255,m.check=i(m.check,E,2,0)),D=L=0,m.mode=5;case 5:if(1024&m.flags){for(;D<16;){if(U===0)break t;U--,L+=M[z++]<>>8&255,m.check=i(m.check,E,2,0)),D=L=0}else m.head&&(m.head.extra=null);m.mode=6;case 6:if(1024&m.flags&&(U<(Z=m.length)&&(Z=U),Z&&(m.head&&(f=m.head.extra_len-m.length,m.head.extra||(m.head.extra=new Array(m.head.extra_len)),e.arraySet(m.head.extra,M,z,Z,f)),512&m.flags&&(m.check=i(m.check,M,Z,z)),U-=Z,z+=Z,m.length-=Z),m.length))break t;m.length=0,m.mode=7;case 7:if(2048&m.flags){if(U===0)break t;for(Z=0;f=M[z+Z++],m.head&&f&&m.length<65536&&(m.head.name+=String.fromCharCode(f)),f&&Z>9&1,m.head.done=!0),x.adler=m.check=0,m.mode=12;break;case 10:for(;D<32;){if(U===0)break t;U--,L+=M[z++]<>>=7&D,D-=7&D,m.mode=27;break}for(;D<3;){if(U===0)break t;U--,L+=M[z++]<>>=1)){case 0:m.mode=14;break;case 1:if($(m),m.mode=20,F!==6)break;L>>>=2,D-=2;break t;case 2:m.mode=17;break;case 3:x.msg="invalid block type",m.mode=30}L>>>=2,D-=2;break;case 14:for(L>>>=7&D,D-=7&D;D<32;){if(U===0)break t;U--,L+=M[z++]<>>16^65535)){x.msg="invalid stored block lengths",m.mode=30;break}if(m.length=65535&L,D=L=0,m.mode=15,F===6)break t;case 15:m.mode=16;case 16:if(Z=m.length){if(U>>=5,D-=5,m.ndist=1+(31&L),L>>>=5,D-=5,m.ncode=4+(15&L),L>>>=4,D-=4,286>>=3,D-=3}for(;m.have<19;)m.lens[B[m.have++]]=0;if(m.lencode=m.lendyn,m.lenbits=7,O={bits:m.lenbits},N=n(0,m.lens,0,19,m.lencode,0,m.work,O),m.lenbits=O.bits,N){x.msg="invalid code lengths set",m.mode=30;break}m.have=0,m.mode=19;case 19:for(;m.have>>16&255,pt=65535&S,!((st=S>>>24)<=D);){if(U===0)break t;U--,L+=M[z++]<>>=st,D-=st,m.lens[m.have++]=pt;else{if(pt===16){for(k=st+2;D>>=st,D-=st,m.have===0){x.msg="invalid bit length repeat",m.mode=30;break}f=m.lens[m.have-1],Z=3+(3&L),L>>>=2,D-=2}else if(pt===17){for(k=st+3;D>>=st)),L>>>=3,D-=3}else{for(k=st+7;D>>=st)),L>>>=7,D-=7}if(m.have+Z>m.nlen+m.ndist){x.msg="invalid bit length repeat",m.mode=30;break}for(;Z--;)m.lens[m.have++]=f}}if(m.mode===30)break;if(m.lens[256]===0){x.msg="invalid code -- missing end-of-block",m.mode=30;break}if(m.lenbits=9,O={bits:m.lenbits},N=n(a,m.lens,0,m.nlen,m.lencode,0,m.work,O),m.lenbits=O.bits,N){x.msg="invalid literal/lengths set",m.mode=30;break}if(m.distbits=6,m.distcode=m.distdyn,O={bits:m.distbits},N=n(o,m.lens,m.nlen,m.ndist,m.distcode,0,m.work,O),m.distbits=O.bits,N){x.msg="invalid distances set",m.mode=30;break}if(m.mode=20,F===6)break t;case 20:m.mode=21;case 21:if(6<=U&&258<=Q){x.next_out=tt,x.avail_out=Q,x.next_in=z,x.avail_in=U,m.hold=L,m.bits=D,r(x,K),tt=x.next_out,G=x.output,Q=x.avail_out,z=x.next_in,M=x.input,U=x.avail_in,L=m.hold,D=m.bits,m.mode===12&&(m.back=-1);break}for(m.back=0;nt=(S=m.lencode[L&(1<>>16&255,pt=65535&S,!((st=S>>>24)<=D);){if(U===0)break t;U--,L+=M[z++]<>lt)])>>>16&255,pt=65535&S,!(lt+(st=S>>>24)<=D);){if(U===0)break t;U--,L+=M[z++]<>>=lt,D-=lt,m.back+=lt}if(L>>>=st,D-=st,m.back+=st,m.length=pt,nt===0){m.mode=26;break}if(32&nt){m.back=-1,m.mode=12;break}if(64&nt){x.msg="invalid literal/length code",m.mode=30;break}m.extra=15&nt,m.mode=22;case 22:if(m.extra){for(k=m.extra;D>>=m.extra,D-=m.extra,m.back+=m.extra}m.was=m.length,m.mode=23;case 23:for(;nt=(S=m.distcode[L&(1<>>16&255,pt=65535&S,!((st=S>>>24)<=D);){if(U===0)break t;U--,L+=M[z++]<>lt)])>>>16&255,pt=65535&S,!(lt+(st=S>>>24)<=D);){if(U===0)break t;U--,L+=M[z++]<>>=lt,D-=lt,m.back+=lt}if(L>>>=st,D-=st,m.back+=st,64&nt){x.msg="invalid distance code",m.mode=30;break}m.offset=pt,m.extra=15&nt,m.mode=24;case 24:if(m.extra){for(k=m.extra;D>>=m.extra,D-=m.extra,m.back+=m.extra}if(m.offset>m.dmax){x.msg="invalid distance too far back",m.mode=30;break}m.mode=25;case 25:if(Q===0)break t;if(Z=K-Q,m.offset>Z){if((Z=m.offset-Z)>m.whave&&m.sane){x.msg="invalid distance too far back",m.mode=30;break}ot=Z>m.wnext?(Z-=m.wnext,m.wsize-Z):m.wnext-Z,Z>m.length&&(Z=m.length),ut=m.window}else ut=G,ot=tt-m.offset,Z=m.length;for(QT?(P=ot[ut+g[F]],D[J+g[F]]):(P=96,0),y=1<>tt)+(w-=y)]=R<<24|P<<16|$|0,w!==0;);for(y=1<>=1;if(y!==0?(L&=y-1,L+=y):L=0,F++,--K[x]==0){if(x===M)break;x=o[l+g[F]]}if(G>>7)]}function J(S,E){S.pending_buf[S.pending++]=255&E,S.pending_buf[S.pending++]=E>>>8&255}function K(S,E,B){S.bi_valid>u-B?(S.bi_buf|=E<>u-S.bi_valid,S.bi_valid+=B-u):(S.bi_buf|=E<>>=1,B<<=1,0<--E;);return B>>>1}function ut(S,E,B){var H,I,W=new Array(g+1),q=0;for(H=1;H<=g;H++)W[H]=q=q+B[H-1]<<1;for(I=0;I<=E;I++){var V=S[2*I+1];V!==0&&(S[2*I]=ot(W[V]++,V))}}function st(S){var E;for(E=0;E>1;1<=B;B--)lt(S,W,B);for(I=X;B=S.heap[1],S.heap[1]=S.heap[S.heap_len--],lt(S,W,1),H=S.heap[1],S.heap[--S.heap_max]=B,S.heap[--S.heap_max]=H,W[2*I]=W[2*B]+W[2*H],S.depth[I]=(S.depth[B]>=S.depth[H]?S.depth[B]:S.depth[H])+1,W[2*B+1]=W[2*H+1]=I,S.heap[1]=I++,lt(S,W,1),2<=S.heap_len;);S.heap[--S.heap_max]=S.heap[1],function(it,mt){var At,yt,Dt,ct,zt,ue,wt=mt.dyn_tree,Fe=mt.max_code,Ye=mt.stat_desc.static_tree,Ge=mt.stat_desc.has_stree,Xe=mt.stat_desc.extra_bits,Te=mt.stat_desc.extra_base,Pt=mt.stat_desc.max_length,Ht=0;for(ct=0;ct<=g;ct++)it.bl_count[ct]=0;for(wt[2*it.heap[it.heap_max]+1]=0,At=it.heap_max+1;At>=7;I>>=1)if(1&at&&V.dyn_ltree[2*X]!==0)return s;if(V.dyn_ltree[18]!==0||V.dyn_ltree[20]!==0||V.dyn_ltree[26]!==0)return i;for(X=32;X>>3,(W=S.static_len+3+7>>>3)<=I&&(I=W)):I=W=B+5,B+4<=I&&E!==-1?k(S,E,B,H):S.strategy===4||W===I?(K(S,2+(H?1:0),3),vt(S,Y,x)):(K(S,4+(H?1:0),3),function(V,X,at,it){var mt;for(K(V,X-257,5),K(V,at-1,5),K(V,it-4,4),mt=0;mt>>8&255,S.pending_buf[S.d_buf+2*S.last_lit+1]=255&E,S.pending_buf[S.l_buf+S.last_lit]=255&B,S.last_lit++,E===0?S.dyn_ltree[2*B]++:(S.matches++,E--,S.dyn_ltree[2*(m[B]+o+1)]++,S.dyn_dtree[2*D(E)]++),S.last_lit===S.lit_bufsize-1},t._tr_align=function(S){K(S,2,3),Z(S,w,Y),function(E){E.bi_valid===16?(J(E,E.bi_buf),E.bi_buf=0,E.bi_valid=0):8<=E.bi_valid&&(E.pending_buf[E.pending++]=255&E.bi_buf,E.bi_buf>>=8,E.bi_valid-=8)}(S)}},{"../utils/common":41}],53:[function(v,p,t){"use strict";p.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(v,p,t){(function(e){(function(s,i){"use strict";if(!s.setImmediate){var r,n,a,o,l=1,c={},d=!1,h=s.document,g=Object.getPrototypeOf&&Object.getPrototypeOf(s);g=g&&g.setTimeout?g:s,r={}.toString.call(s.process)==="[object process]"?function(b){process.nextTick(function(){y(b)})}:function(){if(s.postMessage&&!s.importScripts){var b=!0,C=s.onmessage;return s.onmessage=function(){b=!1},s.postMessage("","*"),s.onmessage=C,b}}()?(o="setImmediate$"+Math.random()+"$",s.addEventListener?s.addEventListener("message",w,!1):s.attachEvent("onmessage",w),function(b){s.postMessage(o+b,"*")}):s.MessageChannel?((a=new MessageChannel).port1.onmessage=function(b){y(b.data)},function(b){a.port2.postMessage(b)}):h&&"onreadystatechange"in h.createElement("script")?(n=h.documentElement,function(b){var C=h.createElement("script");C.onreadystatechange=function(){y(b),C.onreadystatechange=null,n.removeChild(C),C=null},n.appendChild(C)}):function(b){setTimeout(y,0,b)},g.setImmediate=function(b){typeof b!="function"&&(b=new Function(""+b));for(var C=new Array(arguments.length-1),_=0;_"u"?e===void 0?this:e:self)}).call(this,typeof global<"u"?global:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})});var xs={};Ee(xs,{default:()=>pe});module.exports=as(xs);var ht=require("obsidian");var kt="stashpad-view",j="__root__";var A=require("obsidian");var Ct=require("obsidian");function os(v,p){let t=v.vault.getAbstractFileByPath(p);if(!(t instanceof Ct.TFolder))return[];let e=[],s=[t];for(;s.length;){let i=s.pop();for(let r of i.children)r instanceof Ct.TFile?r.extension==="md"&&e.push(r):r instanceof Ct.TFolder&&s.push(r)}return e}var jt=class{constructor(p){this.app=p;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(j,{id:j,parent:null,children:[],file:null,created:""})}setOrderProvider(p){this.orderProvider=p}onChange(p){return this.listeners.add(p),()=>this.listeners.delete(p)}emit(){for(let p of this.listeners)p()}rebuild(p){p!==void 0&&(this.currentFolder=p);let t=this.currentFolder,e=this.byPath,s=this.nodes;this.nodes=new Map,this.byPath=new Map,this.nodes.set(j,{id:j,parent:null,children:[],file:null,created:""});let i=t?os(this.app,t):this.app.vault.getMarkdownFiles();for(let r of i){let n=this.app.metadataCache.getFileCache(r)?.frontmatter,a=n?.id;if(!a){let l=e.get(r.path),c=l?s.get(l):void 0,d=this.synthetic.get(r.path),h=c??d;h&&(this.nodes.set(h.id,{...h,children:[],file:r}),this.byPath.set(r.path,h.id));continue}if(this.synthetic.delete(r.path),a===j){let l=this.nodes.get(j);l.file=r,l.created=n?.created??"",this.byPath.set(r.path,j);continue}let o=n?.parent??null;this.nodes.set(a,{id:a,parent:o??j,children:[],file:r,created:n?.created??""}),this.byPath.set(r.path,a)}for(let r of this.nodes.values()){if(r.id===j)continue;let n=r.parent??j;(this.nodes.get(n)??this.nodes.get(j)).children.push(r.id)}for(let r of this.nodes.values())if(r.children.sort((n,a)=>{let o=this.nodes.get(n),l=this.nodes.get(a);return(o.created||"").localeCompare(l.created||"")}),this.orderProvider){let n=this.orderProvider(r.id);if(n.length>0){let a=new Map;n.forEach((o,l)=>a.set(o,l)),r.children.sort((o,l)=>{let c=a.has(o)?a.get(o):1/0,d=a.has(l)?a.get(l):1/0;return c===d?0:c-d})}}this.emit()}insertSynthetic(p){if(!p.file)return;let t=p.file.path;this.synthetic.set(t,p),this.nodes.set(p.id,p),this.byPath.set(t,p.id);let e=p.parent??j,s=this.nodes.get(e);s&&!s.children.includes(p.id)&&s.children.push(p.id),this.emit()}get(p){return this.nodes.get(p)}getRoot(){return this.nodes.get(j)}getChildren(p){let t=this.nodes.get(p);return t?t.children.map(e=>this.nodes.get(e)).filter(e=>!!e):[]}pathTo(p){let t=[],e=this.nodes.get(p);for(;e&&e.id!==j;)t.unshift(e),e=e.parent?this.nodes.get(e.parent):void 0;return t}idForPath(p){return this.byPath.get(p)}snapshot(){let p={};for(let t of this.nodes.values())t.id===j||!t.file||(p[t.id]={parent:t.parent===j?null:t.parent,path:t.file.path});return p}hookMetadataCache(p){let t=o=>{let l=this.currentFolder;return l?typeof o!="string"?!1:o===l||o.startsWith(l+"/"):!0},e=!1,s=()=>{e=!0,this.coalesceTimer==null&&(this.coalesceTimer=window.setTimeout(()=>{this.coalesceTimer=null,e&&(e=!1,this.emit(),p())},16))},i=o=>{o instanceof Ct.TFile&&t(o.path)&&o.extension==="md"&&this.applyChange(o)&&s()},r=o=>{o instanceof Ct.TFile&&t(o.path)&&o.extension==="md"&&this.applyChange(o)&&s()},n=o=>{let l=o?.path;typeof l=="string"&&t(l)&&this.applyDelete(l)&&s()},a=(o,l)=>{if(!(o instanceof Ct.TFile))return;let c=typeof l=="string"?l:null;!t(o.path)&&!t(c)||this.applyRename(o,c??"")&&s()};return this.app.metadataCache.on("changed",i),this.app.vault.on("create",r),this.app.vault.on("delete",n),this.app.vault.on("rename",a),()=>{this.app.metadataCache.off("changed",i),this.app.vault.off("create",r),this.app.vault.off("delete",n),this.app.vault.off("rename",a),this.coalesceTimer!=null&&(window.clearTimeout(this.coalesceTimer),this.coalesceTimer=null)}}applyChange(p){let t=this.app.metadataCache.getFileCache(p)?.frontmatter,e=t?.id,s=this.byPath.get(p.path);if(!e){if(s){let l=this.nodes.get(s);if(l&&l.file!==p)return l.file=p,!0}return!1}if(this.synthetic.delete(p.path),e===j){let l=this.nodes.get(j),c=t?.created??"",d=!1;return l.file!==p&&(l.file=p,d=!0),l.created!==c&&(l.created=c,d=!0),this.byPath.get(p.path)!==j&&(this.byPath.set(p.path,j),d=!0),d}let i=t?.parent??j,r=t?.created??"";if(!(i===j||this.nodes.has(i)))return this.rebuild(),!0;if(s&&s!==e)return this.rebuild(),!0;let a=this.nodes.get(e);if(!a){let l={id:e,parent:i,children:[],file:p,created:r};return this.nodes.set(e,l),this.byPath.set(p.path,e),this.attachToParent(l),this.resortChildrenOf(i),!0}let o=!1;if(a.file!==p&&(a.file=p,o=!0),a.created!==r&&(a.created=r,this.resortChildrenOf(a.parent??j),o=!0),a.parent!==i){let l=a.parent??j;this.detachFromParent(a),a.parent=i,this.attachToParent(a),this.resortChildrenOf(l),this.resortChildrenOf(i),o=!0}return o}applyDelete(p){let t=this.byPath.get(p);if(!t)return!1;let e=this.nodes.get(t);if(!e)return this.byPath.delete(p),this.synthetic.delete(p),!0;this.detachFromParent(e);let s=this.nodes.get(j);for(let i of e.children){let r=this.nodes.get(i);r&&(r.parent=j,s.children.includes(i)||s.children.push(i))}return e.children.length>0&&this.resortChildrenOf(j),this.nodes.delete(t),this.byPath.delete(p),this.synthetic.delete(p),!0}applyRename(p,t){let e=this.currentFolder,s=!e||t===e||t.startsWith(e+"/"),i=!e||p.path===e||p.path.startsWith(e+"/");if(!s&&!i)return!1;if(s&&!i)return this.applyDelete(t);if(!s&&i)return this.applyChange(p);let r=this.byPath.get(t);if(!r)return this.applyChange(p);this.byPath.delete(t),this.byPath.set(p.path,r);let n=this.nodes.get(r);return n&&(n.file=p),!0}detachFromParent(p){let t=this.nodes.get(p.parent??j);if(!t)return;let e=t.children.indexOf(p.id);e>=0&&t.children.splice(e,1)}attachToParent(p){let t=this.nodes.get(p.parent??j);t||(t=this.nodes.get(j)),t.children.includes(p.id)||t.children.push(p.id)}resortChildrenOf(p){let t=this.nodes.get(p);if(t&&(t.children.sort((e,s)=>{let i=this.nodes.get(e),r=this.nodes.get(s);return(i.created||"").localeCompare(r.created||"")}),this.orderProvider)){let e=this.orderProvider(p);if(e.length>0){let s=new Map;e.forEach((i,r)=>s.set(i,r)),t.children.sort((i,r)=>{let n=s.has(i)?s.get(i):1/0,a=s.has(r)?s.get(r):1/0;return n===a?0:n-a})}}}};var Ie=".stashpad-order.json",Wt=class{constructor(p){this.app=p;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(p){if(this.cache.has(p))return this.cache.get(p);let t=`${p}/${Ie}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=await e.read(t),r=JSON.parse(i);if(r&&typeof r=="object"&&!Array.isArray(r))for(let[n,a]of Object.entries(r))Array.isArray(a)&&a.every(o=>typeof o=="string")&&(s[n]=a)}}catch(i){console.warn("Stashpad: order load failed",i)}return this.cache.set(p,s),s}async save(p){this.scheduleWrite(p)}async flush(p){let t=this.pendingTimers.get(p);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(p)),await this.writeNow(p)}scheduleWrite(p){let t=this.pendingTimers.get(p);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(p),this.writeNow(p)},150);this.pendingTimers.set(p,e)}async writeNow(p){let e=(this.writeInFlight.get(p)??Promise.resolve()).then(()=>this.doWrite(p));this.writeInFlight.set(p,e);try{await e}finally{this.writeInFlight.get(p)===e&&this.writeInFlight.delete(p)}}async doWrite(p){let t=this.cache.get(p)??{},e={};for(let[r,n]of Object.entries(t))n.length>0&&(e[r]=n);this.cache.set(p,e);let s=`${p}/${Ie}`,i=this.app.vault.adapter;try{if(Object.keys(e).length===0)try{await i.remove(s)}catch{}else await i.write(s,JSON.stringify(e,null,2))}catch(r){console.warn("Stashpad: order save failed",r)}}getOrder(p,t){return this.cache.get(p)?.[t]?.slice()??[]}setOrder(p,t,e){let s=this.cache.get(p)??{};s[t]=e.slice(),this.cache.set(p,s)}appendChild(p,t,e){let s=this.cache.get(p)??{},i=s[t]??[];i.includes(e)||i.push(e),s[t]=i,this.cache.set(p,s)}removeChild(p,t){let e=this.cache.get(p);if(e)for(let s of Object.values(e)){let i=s.indexOf(t);i>=0&&s.splice(i,1)}}invalidate(p){this.cache.delete(p)}};var Mt={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"},fe=["manual","created-asc","created-desc","modified-asc","modified-desc","title-az","title-za"],ls=new Set(fe),Ae=".stashpad-sort.json",Vt=class{constructor(p){this.app=p;this.cache=new Map;this.pendingTimers=new Map;this.writeInFlight=new Map}async load(p){if(this.cache.has(p))return this.cache.get(p);let t=`${p}/${Ae}`,e=this.app.vault.adapter,s={};try{if(await e.exists(t)){let i=JSON.parse(await e.read(t));if(i&&typeof i=="object"&&!Array.isArray(i))for(let[r,n]of Object.entries(i))typeof n=="string"&&ls.has(n)&&(s[r]=n)}}catch(i){console.warn("Stashpad: sort load failed",i)}return this.cache.set(p,s),s}async save(p){this.scheduleWrite(p)}async flush(p){let t=this.pendingTimers.get(p);t!=null&&(window.clearTimeout(t),this.pendingTimers.delete(p)),await this.writeNow(p)}scheduleWrite(p){let t=this.pendingTimers.get(p);t!=null&&window.clearTimeout(t);let e=window.setTimeout(()=>{this.pendingTimers.delete(p),this.writeNow(p)},150);this.pendingTimers.set(p,e)}async writeNow(p){let e=(this.writeInFlight.get(p)??Promise.resolve()).then(()=>this.doWrite(p));this.writeInFlight.set(p,e);try{await e}finally{this.writeInFlight.get(p)===e&&this.writeInFlight.delete(p)}}async doWrite(p){let t=this.cache.get(p)??{},e=`${p}/${Ae}`,s=this.app.vault.adapter;try{if(Object.keys(t).length===0)try{await s.remove(e)}catch{}else await s.write(e,JSON.stringify(t,null,2))}catch(i){console.warn("Stashpad: sort save failed",i)}}getMode(p,t){return this.cache.get(p)?.[t]??"manual"}setMode(p,t,e){let s=this.cache.get(p)??{};e==="manual"?delete s[t]:s[t]=e,this.cache.set(p,s)}removeParent(p,t){let e=this.cache.get(p);e&&delete e[t]}invalidate(p){this.cache.delete(p)}};Tt();var St=["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"];function Kt(v,p=St){let t=p instanceof Set?p:new Set(p.map(a=>a.toLowerCase())),e=(v.split(/\r?\n/).find(a=>a.trim().length>0)??"").trim();if(!e)return"Untitled";let s=e.replace(/['‘-‛ʼ](s|t|re|ll|ve|d|m)\b/gi,""),i=new Set(["s","t","re","ll","ve","d","m"]),r=s.replace(/[^A-Za-z0-9\s]+/g," ").split(/\s+/).filter(a=>a&&!t.has(a.toLowerCase())&&!i.has(a.toLowerCase())).map(a=>a.length>=2&&/^[A-Z0-9]+$/.test(a)?a:a.charAt(0).toUpperCase()+a.slice(1).toLowerCase()),n="";for(let a of r){let o=n?`${n}-${a}`:a;if(o.length>50)break;n=o}return n||"Untitled"}function qt(v,p){return`${v}-${p}.md`}function Yt(v){let p=v.match(/-([a-z0-9]{4,12})$/);return p?p[1]:null}var Gt=class{constructor(p,t){this.tree=p;this.log=t}async sweep(p){let t=await this.log.readState(),e=this.tree.snapshot(),s=r=>{if(!p)return!0;let n=p.replace(/\/+$/,"");return r===n||r.startsWith(n+"/")};for(let[r,n]of Object.entries(e)){let a=t[r];a?a.parent!==n.parent?await this.log.append({type:"parent_change",id:r,payload:{from:a.parent,to:n.parent}}):a.path!==n.path&&await this.log.append({type:"rename",id:r,payload:{from:a.path,to:n.path}}):await this.log.append({type:"create",id:r,payload:{path:n.path,parent:n.parent}})}for(let[r,n]of Object.entries(t))!e[r]&&s(n.path)&&await this.log.append({type:"missing",id:r,payload:{lastPath:n.path}});let i={};for(let[r,n]of Object.entries(t))s(n.path)||(i[r]=n);for(let[r,n]of Object.entries(e))i[r]=n;await this.log.writeState(i)}};var et=require("obsidian");var dt=require("obsidian"),Et=class Et extends dt.Modal{constructor(t,e,s){super(t);this.text=e;this.jsonlPath=s;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 o of this.text.trim().split(/\r?\n/))if(o)try{this.events.push(JSON.parse(o))}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 s=t.createEl("button",{text:"Open in default app"});s.onclick=()=>this.shellAct("open");let i=t.createEl("button",{text:"Copy raw JSONL"}),r=null;i.onclick=async()=>{await navigator.clipboard.writeText(this.text),i.setText("Copied"),r!=null&&window.clearTimeout(r),r=window.setTimeout(()=>{i.setText("Copy raw JSONL"),r=null},1500)};let n=t.createEl("button",{text:"Export copy"});n.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(Et.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 r of this.events)e.set(r.type,(e.get(r.type)??0)+1);let s=[...e.entries()].sort((r,n)=>n[1]-r[1]||r[0].localeCompare(n[0])),i=t.createEl("option",{text:`All types (${this.events.length})`});i.value="";for(let[r,n]of s){let a=t.createEl("option",{text:`${r} (${n})`});a.value=r}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 s=this.shownCount;s{this.appendMore(Et.PAGE),this.renderFooter()},t>Et.PAGE){let s=this.footerEl.createEl("button",{text:`Load all (${t})`});s.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:s}=window.require("electron");t==="reveal"?s.showItemInFolder(e):s.openPath(e)}catch(e){new dt.Notice(`Couldn't ${t}: ${e.message}`)}}async exportCopy(){try{let t=(0,dt.moment)().format("YYYY-MM-DD_HHmmss"),e=this.jsonlPath.replace(/\/[^/]+$/,"")||"",s=e?`${e}/${t}-log.jsonl`:`${t}-log.jsonl`;return await this.app.vault.adapter.write(s,this.text),new dt.Notice(`Exported log \u2192 ${s}`),s}catch(t){return new dt.Notice(`Export failed: ${t.message}`),null}}clearLog(){new Rt(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(s){new dt.Notice(`Clear failed: ${s.message}`);return}this.text="",this.events=[],this.typeFilter=null,this.shownCount=0,this.refreshTypeFilter(),this.refreshList(),this.footerEl&&this.footerEl.empty(),new dt.Notice("Log cleared.")}}).open()}renderEvent(t){let e=document.createElement("div");e.className=`stashpad-log-row stashpad-log-${t.type}`;let s=(0,dt.moment)(t.ts).isValid()?(0,dt.moment)(t.ts).format("YYYY-MM-DD HH:mm:ss"):t.ts,i=document.createElement("span");i.className="stashpad-log-ts",i.textContent=s,e.appendChild(i);let r=document.createElement("span");r.className="stashpad-log-type",r.textContent=t.type,e.appendChild(r);let n=document.createElement("span");n.className="stashpad-log-author",n.textContent=t.author?t.author:"\u2014",t.author||n.classList.add("is-empty"),e.appendChild(n);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 s=Array.isArray(e.attachmentsRemoved)?e.attachmentsRemoved.length:0,i=e.mergedInto?` (merged into ${e.mergedInto})`:"";return`Deleted ${t.id}${i}${s?` \u2014 also removed ${s} attachment${s===1?"":"s"}`:""}`}case"missing":return`Missing: ${e.lastPath??t.id}`;case"parent_change":{let s=e.reason?` (${e.reason})`:"";return`Moved ${t.id} from ${e.from??"null"} \u2192 ${e.to??"null"}${s}`}case"rename":return`Renamed ${e.from??"?"} \u2192 ${e.to??"?"}`;case"reorder":{let s=e.count??1,i=e.dir??"?",r=e.parent??t.id??"?";return`Reordered ${s} note${s===1?"":"s"} (${i}) under ${r}`}case"complete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Marked ${s} note${s===1?"":"s"} complete${i}`}case"uncomplete":{let s=e.count??1,i=e.undo?" (undo)":e.redo?" (redo)":"";return`Unmarked ${s} note${s===1?"":"s"}${i}`}case"stash_export":{let s=e.noteCount??"?";return`Exported ${s} note${s===1?"":"s"} \u2192 ${e.path??"?"}`}case"stash_import":{let s=e.noteCount??"?",i=[];e.attachmentsWritten&&i.push(`${e.attachmentsWritten} attachment${e.attachmentsWritten===1?"":"s"}`),e.collisionsRenamed&&i.push(`${e.collisionsRenamed} renamed`);let r=i.length?` (${i.join(", ")})`:"";return`Imported ${s} note${s===1?"":"s"} from ${e.from??"?"} \u2192 ${e.into??"?"}${r}`}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()}};Et.PAGE=100;var Xt=Et,Ot=class extends dt.Modal{constructor(t,e,s,i,r,n){super(t);this.noteTitle=e;this.descendantCount=s;this.attachmentCount=i;this.offerAttachmentDelete=r;this.onChoose=n}onOpen(){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 n=this.contentEl.createEl("label",{cls:"stashpad-modal-check"}),a=n.createEl("input",{type:"checkbox"});a.checked=e,a.onchange=()=>{e=a.checked},n.createSpan({text:" Also delete attachments"})}let s=this.contentEl.createDiv({cls:"stashpad-modal-btns"}),i=s.createEl("button",{text:"Cancel"});i.onclick=()=>this.close();let r=s.createEl("button",{cls:"mod-warning",text:"Delete"});r.onclick=()=>{this.close(),this.onChoose(e)}}onClose(){this.contentEl.empty()}},Jt=class extends dt.Modal{constructor(t,e,s,i){super(t);this.body=e;this.onSplitAtLine=s;this.onSplitAtChar=i;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 dt.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 r=t.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&r.addClass("is-active"),r.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 s=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});s.onmousedown=r=>r.preventDefault(),s.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let i=this.contentEl.createDiv({cls:"stashpad-split-help"});dt.Platform.isMobile?i.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):i.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 i=Math.max(1,Math.min(this.lines.length-1,e));i!==this.lineCursorIdx&&(this.lineCursorIdx=i,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 s=parseFloat(getComputedStyle(e).lineHeight)||22,i=dt.Platform.isMobile?3:12,r=2,n=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,s*i+16);e.style.height=`${Math.max(a,s*r+16)}px`};requestAnimationFrame(()=>{n();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",n)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},pe=class extends dt.Modal{constructor(t,e,s){super(t);this.onResult=s;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 s=t.createEl("input",{type:"color"});s.value=this.value,s.addClass("stashpad-custom-color-wheel"),e.onclick=()=>s.click();let i=t.createEl("input",{type:"text"});i.addClass("stashpad-custom-color-hex"),i.placeholder="#RRGGBB",i.value=this.value,i.maxLength=7;let r=l=>{let h=l.startsWith("#")?l:"#"+l;/^#[0-9a-f]{6}$/i.test(h)&&(this.value=h,e.style.background=h,s.value=h,i.value!==h&&(i.value=h))};s.oninput=()=>r(s.value),i.oninput=()=>r(i.value);let n=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=n.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let o=n.createEl("button",{cls:"mod-cta",text:"Save"});o.title="Apply this color to the selection (without adding to your palette).",o.onclick=()=>this.commit({addToPalette:!1});let c=n.createEl("button",{cls:"mod-cta",text:"Add to palette"});c.title="Apply and save this color so it appears as a tile next time.",c.onclick=()=>this.commit({addToPalette:!0}),this.scope.register([],"Enter",l=>{l.preventDefault(),this.commit({addToPalette:!1})}),this.scope.register(["Mod"],"Enter",l=>{l.preventDefault(),this.commit({addToPalette:!0})}),requestAnimationFrame(()=>i.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()}},Pt=class Pt extends dt.Modal{constructor(t,e,s,i,r){super(t);this.currentColor=e;this.customPalette=s;this.onPick=i;this.onDeleteCustom=r;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 s=[...Pt.DEFAULT_PALETTE,...this.customPalette];for(let a of s){let o=t.createDiv({cls:"stashpad-color-tile"});o.style.background=a,o.title=a;let c=!Pt.DEFAULT_PALETTE.some(h=>h.toLowerCase()===a.toLowerCase()),l=this.items.length;if(o.onclick=()=>this.activate(l),c&&this.onDeleteCustom){let h=o.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});h.title="Remove from palette",h.onclick=d=>{d.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:c?"custom":"preset",color:a,el:o})}let i=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});i.title="Custom color\u2026";let r=this.items.length;i.onclick=()=>this.activate(r),this.items.push({kind:"add",color:null,el:i});let n=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=n>=0?n: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 pe(this.app,this.currentColor,(s,i)=>{this.onPick(s,i)}).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(),s=this.items[0].el.getBoundingClientRect();if(s.width<=0)return 1;let i=s.top,r=0;for(let n of this.items){let a=n.el.getBoundingClientRect();if(Math.abs(a.top-i)<1)r++;else break}return Math.max(1,r)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(s=>s.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.close(),this.onChoose(!1)};let s=t.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty()}};var ue=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function fe(g){if(!g)return"(none)";let m=g.replace(/\bMod\b/g,ue?"Cmd":"Ctrl");return ue&&(m=m.replace(/\bAlt\b/g,"Option")),m}function Ie(g,m,t={allowSingleKey:!0}){let e=g.placeholder;g.placeholder="Press a key\u2026 (Backspace to cancel)",g.value="",g.classList.add("is-recording");let s=()=>{g.placeholder=e,g.classList.remove("is-recording"),g.removeEventListener("keydown",i,!0),g.removeEventListener("blur",r)},i=n=>{if(n.key==="Control"||n.key==="Shift"||n.key==="Alt"||n.key==="Meta"||n.key==="OS")return;if(n.preventDefault(),n.stopPropagation(),n.key==="Backspace"&&!n.metaKey&&!n.ctrlKey&&!n.altKey&&!n.shiftKey){s();return}let a=[];ue?(n.metaKey&&a.push("Mod"),n.ctrlKey&&a.push("Ctrl")):n.ctrlKey&&a.push("Mod"),n.altKey&&a.push("Alt"),n.shiftKey&&a.push("Shift");let o=as(n.key);if(!o||a.length===0&&!t.allowSingleKey)return;a.push(o);let c=a.join("+");s(),m(c)},r=()=>s();return g.addEventListener("keydown",i,!0),g.addEventListener("blur",r),s}function as(g){return g?g.length===1?g.toUpperCase():g:""}Tt();var Ot=null,Jt=new Set;function Qt(g){if(Ot!==g){Ot=g;for(let m of Jt)m()}}function Et(){return Ot}function Ae(g){if(Ot===g){Ot=null;for(let m of Jt)m()}}function De(g){return Jt.add(g),()=>Jt.delete(g)}var Rt=[{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 \u2014 marks selected/focused notes as complete.",defaultPrimary:"Mod+Enter"},{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+; \u2014 open the color picker for the selection.",defaultPrimary:"Shift+;"},{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:"Switch this Stashpad tab to another folder",desc:"Open the folder picker so this tab shows a different Stashpad.",defaultPrimary:""},{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:""}];function ge(){let g={};for(let m of Rt)g[m.id]={primary:m.defaultPrimary,secondary:"",preferRight:!1};return g}var Ct={folder:"stashpad",importDropFolder:"_imports",exportFolder:"_exports",useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,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,drafts:{},lastSubmitted:{},bindings:ge()},Pe=JSON.parse(JSON.stringify(Ct)),me=new Set;function ft(){return Pe}function ve(g){Pe=g;for(let m of me)m()}function Me(g){return me.add(g),()=>me.delete(g)}function ee(g){try{let m=g.internalPlugins?.plugins?.templates;if(!m?.enabled)return null;let t=m.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var te=class extends et.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){let{containerEl:t}=this;t.empty(),t.createEl("h2",{text:"Stashpad",cls:"stashpad-settings-title"}),this.renderAuthorshipSection(t),t.createEl("h3",{text:"Log"}),new et.Setting(t).setName("Open log file").setDesc("Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.").addButton(i=>i.setButtonText("Open log").onClick(async()=>{let r=this.app.vault.adapter,n=this.plugin.pluginPrivatePath("log.jsonl");if(!await r.exists(n)){new et.Notice("No log yet \u2014 make some changes first.");return}let a=await r.read(n);new Gt(this.app,a,n).open()})),t.createEl("h3",{text:"General"}),new et.Setting(t).setName("Stashpad notes folder").setDesc("Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.").addText(i=>i.setValue(this.plugin.settings.folder).setPlaceholder("stashpad").onChange(async r=>{let n=(r||"").trim().replace(/^\/+|\/+$/g,"")||Ct.folder,a=n.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(a)){new et.Notice(`"${n}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=n,await this.plugin.saveSettings()})),new et.Setting(t).setName("Stash import subfolder").setDesc("Subfolder name (relative to each Stashpad folder) where dropped .stash files auto-import. Created on demand. Leave blank to disable auto-import.").addText(i=>i.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports").onChange(async r=>{this.plugin.settings.importDropFolder=(r||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})),new et.Setting(t).setName("Stash export subfolder").setDesc("Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.").addText(i=>i.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async r=>{let n=(r||"").trim().replace(/^\/+|\/+$/g,"")||Ct.exportFolder;this.plugin.settings.exportFolder=n,await this.plugin.saveSettings()})),new et.Setting(t).setName("Rebootstrap existing Stashpad folders").setDesc("Walk every folder that has a home note and create any missing infrastructure (_imports, _exports, drafts file). Safe to run anytime.").addButton(i=>i.setButtonText("Rebootstrap now").onClick(async()=>{i.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:r}=await this.plugin.rebootstrapAllFolders();new et.Notice(`Stashpad: rebootstrapped ${r.length} folder${r.length===1?"":"s"}.`)}catch(r){new et.Notice(`Stashpad: rebootstrap failed (${r.message})`)}finally{i.setDisabled(!1).setButtonText("Rebootstrap now")}})),new et.Setting(t).setName("Use Templates plugin date/time formats").setDesc("When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.").addToggle(i=>i.setValue(this.plugin.settings.useTemplatesFormat).onChange(async r=>{this.plugin.settings.useTemplatesFormat=r,await this.plugin.saveSettings()}));let e=ee(this.app);t.createDiv({cls:"setting-item-description stashpad-settings-note"}).setText(e?`Templates plugin: date = "${e.dateFormat}", time = "${e.timeFormat}"`:"Templates plugin not enabled."),new et.Setting(t).setName("Confirm cross-parent drag-and-drop").setDesc("When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).").addToggle(i=>i.setValue(this.plugin.settings.confirmCrossParentDrag).onChange(async r=>{this.plugin.settings.confirmCrossParentDrag=r,await this.plugin.saveSettings()})),new et.Setting(t).setName("Confirm bulk deletes").setDesc("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).").addToggle(i=>i.setValue(this.plugin.settings.confirmBulkDelete).onChange(async r=>{this.plugin.settings.confirmBulkDelete=r,await this.plugin.saveSettings()})),new et.Setting(t).setName("Offer to delete attachments with note").setDesc(`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.`).addToggle(i=>i.setValue(this.plugin.settings.confirmAttachmentDelete).onChange(async r=>{this.plugin.settings.confirmAttachmentDelete=r,await this.plugin.saveSettings()}));{let i=null,r=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:St).join(` -`);new et.Setting(t).setName("Slug stop-words").setDesc("Words removed from auto-generated note titles (filenames). One per line.").addTextArea(n=>{n.setValue(r),i=n.inputEl,i.rows=6,i.style.fontFamily="var(--font-monospace)",n.onChange(async a=>{let o=(a||"").split(/\r?\n/).map(c=>c.trim().toLowerCase()).filter(Boolean);this.plugin.settings.slugStopWords=o,await this.plugin.saveSettings()})}).addExtraButton(n=>n.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...St],i&&(i.value=St.join(` -`)),await this.plugin.saveSettings()}))}{let i=this.plugin.discoverStashpadFolders();if(new et.Setting(t).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."),i.length===0)t.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 n=t.createDiv({cls:"stashpad-folder-list"});for(let a of i)this.renderFolderScopeRow(n,a)}let r=null;new et.Setting(t).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(n=>{n.setPlaceholder("my-stashpad"),r=n.inputEl}).addButton(n=>n.setButtonText("Create").setCta().onClick(async()=>{let a=(r?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!a){new et.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(a),new et.Notice(`Created Stashpad "${a}".`),r&&(r.value=""),await this.plugin.waitForStashpadFolder(a,2e3),this.display()}catch(o){new et.Notice(`Couldn't create: ${o.message}`)}}))}this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t),new et.Setting(t).setName("Autofocus composer after sending").setDesc("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.").addToggle(i=>i.setValue(this.plugin.settings.autofocusComposerAfterSend).onChange(async r=>{this.plugin.settings.autofocusComposerAfterSend=r,await this.plugin.saveSettings()})),new et.Setting(t).setName("Prefix timestamps when copying").setDesc("Include each note's timestamp before its body when copying with C or Y.").addToggle(i=>i.setValue(this.plugin.settings.prefixTimestampsOnCopy).onChange(async r=>{this.plugin.settings.prefixTimestampsOnCopy=r,await this.plugin.saveSettings()})),t.createEl("h3",{text:"Keyboard shortcuts"}),t.createEl("p",{cls:"setting-item-description",text:"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. When both slots are set, the pill on the right decides which one is active."});for(let i of Rt)this.renderBindingRow(t,i)}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let s=(()=>{let n=Et()?.noteFolder;return n&&e.includes(n)?n:e[0]})();new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(n=>{for(let a of e)n.addOption(a,a);n.setValue(s),n.onChange(a=>{s=a,r()})}),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 i=t.createDiv({cls:"stashpad-color-aliases-list"}),r=()=>{i.empty();let n=this.plugin.collectColorsInFolder(s),a=new Map(n.map(h=>[h.hex,h.count])),o=this.plugin.settings.colorAliases?.[s.replace(/\/+$/,"")]??{},c=new Set([...a.keys(),...Object.keys(o)]);if(c.size===0){i.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${s}" yet. Set a per-note color (Shift+; or right-click \u2192 Set color) and it'll appear here.`});return}let l=[...c].map(h=>({hex:h,count:a.get(h)??0}));l.sort((h,d)=>d.count-h.count||h.hex.localeCompare(d.hex));for(let h of l)this.renderColorAliasRow(i,s,h.hex,h.count,r)};r()}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 /_authors/."}),new et.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(s=>{s.setValue(this.plugin.settings.authorName).onChange(async i=>{this.plugin.settings.authorName=i.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=bt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.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(s=>{s.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new et.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(s=>{s.setValue(this.plugin.settings.authorRole).onChange(async i=>{this.plugin.settings.authorRole=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(s=>{s.setValue(this.plugin.settings.authorDepartment).onChange(async i=>{this.plugin.settings.authorDepartment=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Show author in note footer").addToggle(s=>s.setValue(this.plugin.settings.showAuthor).onChange(async i=>{this.plugin.settings.showAuthor=i,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show contributors in note footer").addToggle(s=>s.setValue(this.plugin.settings.showContributors).onChange(async i=>{this.plugin.settings.showContributors=i,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show last edit time in note footer").addToggle(s=>s.setValue(this.plugin.settings.showLastEdit).onChange(async i=>{this.plugin.settings.showLastEdit=i,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let s=t.createDiv({cls:"stashpad-authored-folders-list"});for(let i of e){let r=s.createDiv({cls:"stashpad-authored-folder-row"}),n=r.createEl("a",{cls:"stashpad-authored-folder-link",text:i.folder});n.onclick=o=>{o.preventDefault(),this.plugin.activateViewForFolder(i.folder)};let a=[];i.authored>0&&a.push(`authored ${i.authored}`),i.contributed>0&&a.push(`contributed to ${i.contributed}`),r.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new et.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 s=t.createDiv({cls:"stashpad-note-templates-list"}),i=r=>{let n=r.replace(/\/+$/,""),a=s.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(r);let c=a.createDiv({cls:"stashpad-note-template-input-wrap"}),l=c.createEl("input",{type:"text",cls:"stashpad-note-template-input",attr:{placeholder:"path/to/template.md (leave blank to disable)"}});l.value=(this.plugin.settings.noteTemplates??{})[n]??"";let h=c.createDiv({cls:"stashpad-note-template-suggest"});h.style.display="none";let d=a.createDiv({cls:"stashpad-note-template-warn"});d.style.display="none";let v=()=>this.app.vault.getMarkdownFiles().map(b=>b.path).filter(b=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(b)).sort(),u=()=>{h.empty();let b=l.value.trim().toLowerCase(),C=v().filter(E=>!b||E.toLowerCase().includes(b)).slice(0,12);if(C.length===0){h.style.display="none";return}h.style.display="";for(let E of C)h.createDiv({cls:"stashpad-note-template-suggest-item",text:E}).addEventListener("mousedown",async N=>{N.preventDefault(),l.value=E,await y(),h.style.display="none"})},y=async()=>{let b=l.value.trim(),C={...this.plugin.settings.noteTemplates??{}};b?C[n]=b:delete C[n],this.plugin.settings.noteTemplates=C,await this.plugin.saveSettings(),w()},w=()=>{d.empty(),d.style.display="none";let b=l.value.trim();if(!b)return;let C=this.app.vault.getAbstractFileByPath(b);if(!C||C.extension!=="md"){d.style.display="",d.setText(`\u26A0 "${b}" is not a markdown file in this vault.`);return}let E=this.app.metadataCache.getFileCache(C)?.frontmatter??{},N=["id","parent","created","attachments","position"].filter(D=>{let $=E[D];return!($==null||typeof $=="string"&&$.trim()===""||Array.isArray($)&&$.length===0)});N.length!==0&&(d.style.display="",d.setText(`\u26A0 Template defines ${N.join(", ")} \u2014 Stashpad always sets ${N.length===1?"this":"these"} on new notes, so the template value${N.length===1?"":"s"} will be ignored.`))};l.addEventListener("focus",u),l.addEventListener("input",u),l.addEventListener("blur",()=>{setTimeout(()=>{h.style.display="none"},150)}),l.addEventListener("change",()=>{y()}),w()};for(let r of e)i(r)}renderColorAliasRow(t,e,s,i,r){let n=t.createDiv({cls:"stashpad-color-alias-row"});i===0&&n.addClass("is-unused");let a=n.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=s,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let h=this.plugin.settings.customPalette??[];new _t(this.app,s,h,async d=>{if((d??null)===null&&i===0){await this.plugin.setColorAlias(e,s,""),r();return}if(d&&d.toLowerCase()===s){r();return}let v=await this.plugin.recolorAllInFolder(e,s,d??null);if(v>0)new et.Notice(`Recolored ${v} note${v===1?"":"s"}.`);else if(i===0){let u=this.plugin.getColorAlias(e,s);u&&(await this.plugin.setColorAlias(e,s,""),d&&await this.plugin.setColorAlias(e,d,u))}r()},async d=>{let v=(this.plugin.settings.customPalette??[]).filter(u=>u.toLowerCase()!==d.toLowerCase());return this.plugin.settings.customPalette=v,await this.plugin.saveSettings(),v}).open()};let o=n.createDiv({cls:"stashpad-color-alias-meta"});o.createSpan({cls:"stashpad-color-alias-hex",text:s}),o.createSpan({cls:"stashpad-color-alias-count",text:i===0?"\xB7 unused":`\xB7 ${i} note${i===1?"":"s"}`});let c=n.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});c.value=this.plugin.getColorAlias(e,s)??"",c.onchange=async()=>{await this.plugin.setColorAlias(e,s,c.value),!c.value.trim()&&i===0&&r()};let l=n.createEl("button",{cls:"stashpad-color-alias-del",text:"\xD7",attr:{title:"Delete alias"}});c.value||(l.style.visibility="hidden"),l.onclick=async()=>{await this.plugin.setColorAlias(e,s,""),i===0?r():(c.value="",l.style.visibility="hidden")}}renderFolderScopeRow(t,e){let s=t.createDiv({cls:"stashpad-folder-row"});s.createSpan({cls:"stashpad-folder-row-label",text:e});let i=s.createSpan({cls:"stashpad-folder-row-state"}),r=s.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let n=r.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),o=()=>{let l=a();r.toggleClass("is-right",l),r.setAttribute("aria-checked",String(l)),n.setText(l?"X":"\u2713"),i.setText(l?"Excluded":"Included"),i.toggleClass("is-excluded",l),r.title=l?"Excluded \u2014 notes here won't appear in cross-Stashpad search. Click to include.":"Included \u2014 notes here appear in cross-Stashpad search. Click to exclude."},c=async()=>{let l=new Set(this.plugin.settings.searchExcludedFolders??[]);l.has(e)?l.delete(e):l.add(e),this.plugin.settings.searchExcludedFolders=[...l].sort(),o(),await this.plugin.saveSettings()};r.onclick=()=>void c(),r.onkeydown=l=>{(l.key===" "||l.key==="Enter")&&(l.preventDefault(),c())},o()}renderBindingRow(t,e){let s=new et.Setting(t).setName(e.label).setDesc(e.desc),i=()=>this.plugin.settings.bindings[e.id],r,n,a=()=>{},o=d=>{let v=s.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=v.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=fe(i()[d]),u.classList.add("stashpad-binding-input"),u.onclick=()=>{Ie(u,async w=>{this.plugin.settings.bindings[e.id][d]=w,u.value=fe(w),await this.plugin.saveSettings(),a()})};let y=v.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});return y.title="Clear this slot",y.onclick=async()=>{this.plugin.settings.bindings[e.id][d]="",u.value="",await this.plugin.saveSettings(),a()},u};r=o("primary"),n=o("secondary");let c=s.controlEl.createDiv({cls:"stashpad-binding-pill"});c.setAttribute("role","switch"),c.setAttribute("tabindex","0");let l=c.createDiv({cls:"stashpad-binding-pill-knob"});a=()=>{let d=i(),v=!!(d.primary&&d.secondary);c.toggleClass("is-disabled",!v),c.toggleClass("is-right",d.preferRight),c.setAttribute("aria-checked",String(d.preferRight)),c.setAttribute("aria-disabled",String(!v)),l.setText(d.preferRight?"R":"L"),c.title=v?d.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let h=async()=>{let d=i();!d.primary||!d.secondary||(this.plugin.settings.bindings[e.id].preferRight=!d.preferRight,a(),await this.plugin.saveSettings())};c.onclick=()=>void h(),c.onkeydown=d=>{(d.key===" "||d.key==="Enter")&&(d.preventDefault(),h())},a()}};var Le=require("obsidian");var xt=class extends Le.SuggestModal{constructor(t,e,s,i){super(t);this.tree=e;this.titleFn=s;this.opts=i;this.notes=[];this.setPlaceholder(i.placeholder??(i.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}loadAll(){let t=(s,i)=>{let r=this.tree.get(s);r?.file&&s!==V?this.notes.push({node:r,title:`${" ".repeat(i)}${this.titleFn(r)}`,body:""}):r?.file&&s===V&&this.notes.push({node:r,title:"Home",body:""});for(let n of this.tree.getChildren(s))t(n.id,i+1)},e=this.tree.getRoot();e.file&&this.notes.push({node:e,title:"Home",body:""});for(let s of this.tree.getChildren(V))t(s.id,1);for(let s of this.notes)s.node?.file&&this.app.vault.cachedRead(s.node.file).then(i=>{s.body=this.stripFm(i)});if(this.opts.crossFolderNotes){let s=this.opts.crossFolderNotes();for(let i of s)this.notes.push({node:null,title:i.title,body:i.body,cross:i});for(let i of this.notes)!i.cross||i.body||this.app.vault.cachedRead(i.cross.file).then(r=>{i.body=this.stripFm(r)})}}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(),s=this.notes.filter(l=>!l.cross),i=this.notes.filter(l=>l.cross),r=(l,h)=>({id:l.cross?`cross:${l.cross.id}`:l.node.id,label:l.title,node:l.node,kind:"note",bodyPreview:this.previewFromBody(l.body,h),matchLine:h,crossFolder:l.cross?.folder,crossFile:l.cross?.file}),n=l=>{let h=[];for(let d of l)if(this.opts.mode==="search"){if(!e){h.push(r(d,-1));continue}let v=d.title.toLowerCase().includes(e),u=d.body.split(/\r?\n/),y=-1;for(let w=0;wl.label.trim().toLowerCase()===e)&&o.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),o}previewFromBody(t,e){let s=t.split(/\r?\n/).filter(n=>n.trim().length>0);if(!s.length)return"";if(e<0)return s.slice(0,3).join(` +`),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 dt.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 r=t.createEl("button",{text:"Line split",cls:"stashpad-split-mode-btn"});this.mode==="line"&&r.addClass("is-active"),r.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 s=t.createEl("button",{text:"Split",cls:"stashpad-split-confirm-btn mod-cta"});s.onmousedown=r=>r.preventDefault(),s.onclick=()=>{this.mode==="line"?this.commitLine():this.commitCursor()},this.mode==="line"?this.renderLineMode():this.renderCursorMode();let i=this.contentEl.createDiv({cls:"stashpad-split-help"});dt.Platform.isMobile?i.setText(this.mode==="line"?"Tap a line to position the divider, then Split.":"Tap inside the text to position the cursor, then Split."):i.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 i=Math.max(1,Math.min(this.lines.length-1,e));i!==this.lineCursorIdx&&(this.lineCursorIdx=i,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 s=parseFloat(getComputedStyle(e).lineHeight)||22,i=dt.Platform.isMobile?3:12,r=2,n=()=>{e.style.height="auto";let a=Math.min(e.scrollHeight,s*i+16);e.style.height=`${Math.max(a,s*r+16)}px`};requestAnimationFrame(()=>{n();let a=Math.floor(e.value.length/2);e.focus(),e.setSelectionRange(a,a)}),e.addEventListener("input",n)}onClose(){this.cursorTextarea=null,this.contentEl.empty()}},me=class extends dt.Modal{constructor(t,e,s){super(t);this.onResult=s;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 s=t.createEl("input",{type:"color"});s.value=this.value,s.addClass("stashpad-custom-color-wheel"),e.onclick=()=>s.click();let i=t.createEl("input",{type:"text"});i.addClass("stashpad-custom-color-hex"),i.placeholder="#RRGGBB",i.value=this.value,i.maxLength=7;let r=c=>{let d=c.startsWith("#")?c:"#"+c;/^#[0-9a-f]{6}$/i.test(d)&&(this.value=d,e.style.background=d,s.value=d,i.value!==d&&(i.value=d))};s.oninput=()=>r(s.value),i.oninput=()=>r(i.value);let n=this.contentEl.createDiv({cls:"stashpad-color-footer"}),a=n.createEl("button",{text:"Cancel"});a.onclick=()=>{this.delivered=!0,this.close()};let o=n.createEl("button",{cls:"mod-cta",text:"Save"});o.title="Apply this color to the selection (without adding to your palette).",o.onclick=()=>this.commit({addToPalette:!1});let l=n.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(()=>i.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()}},Lt=class Lt extends dt.Modal{constructor(t,e,s,i,r){super(t);this.currentColor=e;this.customPalette=s;this.onPick=i;this.onDeleteCustom=r;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 s=[...Lt.DEFAULT_PALETTE,...this.customPalette];for(let a of s){let o=t.createDiv({cls:"stashpad-color-tile"});o.style.background=a,o.title=a;let l=!Lt.DEFAULT_PALETTE.some(d=>d.toLowerCase()===a.toLowerCase()),c=this.items.length;if(o.onclick=()=>this.activate(c),l&&this.onDeleteCustom){let d=o.createSpan({cls:"stashpad-color-tile-del",text:"\xD7"});d.title="Remove from palette",d.onclick=h=>{h.stopPropagation(),this.handleDelete(a)}}this.items.push({kind:l?"custom":"preset",color:a,el:o})}let i=t.createDiv({cls:"stashpad-color-tile stashpad-color-add"});i.title="Custom color\u2026";let r=this.items.length;i.onclick=()=>this.activate(r),this.items.push({kind:"add",color:null,el:i});let n=this.items.findIndex(a=>this.currentColor===null?a.kind==="none":this.currentColor?a.color!==null&&a.color.toLowerCase()===this.currentColor.toLowerCase():!1);this.focusIdx=n>=0?n: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 me(this.app,this.currentColor,(s,i)=>{this.onPick(s,i)}).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(),s=this.items[0].el.getBoundingClientRect();if(s.width<=0)return 1;let i=s.top,r=0;for(let n of this.items){let a=n.el.getBoundingClientRect();if(Math.abs(a.top-i)<1)r++;else break}return Math.max(1,r)}async handleDelete(t){if(this.onDeleteCustom)try{let e=await this.onDeleteCustom(t);this.customPalette=Array.isArray(e)?e:this.customPalette.filter(s=>s.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.close(),this.onChoose(!1)};let s=t.createEl("button",{cls:"mod-cta",text:this.confirmText});s.onclick=()=>{this.close(),this.onChoose(!0)},requestAnimationFrame(()=>s.focus())}onClose(){this.contentEl.empty()}};var ge=(()=>{try{return typeof navigator<"u"&&/Mac|iPhone|iPad|iPod/i.test(navigator.platform||navigator.userAgent||"")}catch{return!1}})();function ve(v){if(!v)return"(none)";let p=v.replace(/\bMod\b/g,ge?"Cmd":"Ctrl");return ge&&(p=p.replace(/\bAlt\b/g,"Option")),p}function Pe(v,p,t={allowSingleKey:!0}){let e=v.placeholder;v.placeholder="Press a key\u2026 (Backspace to cancel)",v.value="",v.classList.add("is-recording");let s=()=>{v.placeholder=e,v.classList.remove("is-recording"),v.removeEventListener("keydown",i,!0),v.removeEventListener("blur",r)},i=n=>{if(n.key==="Control"||n.key==="Shift"||n.key==="Alt"||n.key==="Meta"||n.key==="OS")return;if(n.preventDefault(),n.stopPropagation(),n.key==="Backspace"&&!n.metaKey&&!n.ctrlKey&&!n.altKey&&!n.shiftKey){s();return}let a=[];ge?(n.metaKey&&a.push("Mod"),n.ctrlKey&&a.push("Ctrl")):n.ctrlKey&&a.push("Mod"),n.altKey&&a.push("Alt"),n.shiftKey&&a.push("Shift");let o=cs(n.key);if(!o||a.length===0&&!t.allowSingleKey)return;a.push(o);let l=a.join("+");s(),p(l)},r=()=>s();return v.addEventListener("keydown",i,!0),v.addEventListener("blur",r),s}function cs(v){return v?v.length===1?v.toUpperCase():v:""}Tt();var Nt=null,Qt=new Set;function te(v){if(Nt!==v){Nt=v;for(let p of Qt)p()}}function _t(){return Nt}function Me(v){if(Nt===v){Nt=null;for(let p of Qt)p()}}function Le(v){return Qt.add(v),()=>Qt.delete(v)}var $t=[{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 \u2014 marks selected/focused notes as complete.",defaultPrimary:"Mod+Enter"},{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+; \u2014 open the color picker for the selection.",defaultPrimary:"Shift+;"},{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:"Switch this Stashpad tab to another folder",desc:"Open the folder picker so this tab shows a different Stashpad.",defaultPrimary:""},{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:""}];function we(){let v={};for(let p of $t)v[p.id]={primary:p.defaultPrimary,secondary:"",preferRight:!1};return v}var xt={folder:"stashpad",importDropFolder:"_imports",exportFolder:"_exports",useTemplatesFormat:!1,prefixTimestampsOnCopy:!0,splitOnLines:!1,confirmCrossParentDrag:!0,confirmBulkDelete:!0,confirmAttachmentDelete:!0,autofocusComposerAfterSend:!0,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:{},drafts:{},lastSubmitted:{},bindings:we()},Oe=JSON.parse(JSON.stringify(xt)),ye=new Set;function ft(){return Oe}function be(v){Oe=v;for(let p of ye)p()}function Re(v){return ye.add(v),()=>ye.delete(v)}function se(v){try{let p=v.internalPlugins?.plugins?.templates;if(!p?.enabled)return null;let t=p.instance?.options??{};return{dateFormat:t.dateFormat||"YYYY-MM-DD",timeFormat:t.timeFormat||"HH:mm"}}catch{return null}}var ee=class extends et.PluginSettingTab{constructor(t,e){super(t,e);this.plugin=e}display(){let{containerEl:t}=this;t.empty(),t.createEl("h2",{text:"Stashpad",cls:"stashpad-settings-title"}),this.renderAuthorshipSection(t),t.createEl("h3",{text:"Log"}),new et.Setting(t).setName("Open log file").setDesc("Append-only history of creates, deletes, parent changes, renames. Stored alongside the plugin's other private files.").addButton(i=>i.setButtonText("Open log").onClick(async()=>{let r=this.app.vault.adapter,n=this.plugin.pluginPrivatePath("log.jsonl");if(!await r.exists(n)){new et.Notice("No log yet \u2014 make some changes first.");return}let a=await r.read(n);new Xt(this.app,a,n).open()})),t.createEl("h3",{text:"General"}),new et.Setting(t).setName("Stashpad notes folder").setDesc("Vault-relative folder where Stashpad stores its notes and attachments. Created on demand.").addText(i=>i.setValue(this.plugin.settings.folder).setPlaceholder("stashpad").onChange(async r=>{let n=(r||"").trim().replace(/^\/+|\/+$/g,"")||xt.folder,a=n.split("/").filter(Boolean).pop()??"";if(new Set([this.plugin.settings.importDropFolder,this.plugin.settings.exportFolder,"_attachments","_processed"].map(l=>(l??"").trim().replace(/^\/+|\/+$/g,"")).filter(Boolean)).has(a)){new et.Notice(`"${n}" uses a reserved Stashpad subfolder name. Pick something else.`);return}this.plugin.settings.folder=n,await this.plugin.saveSettings()})),new et.Setting(t).setName("Stash import subfolder").setDesc("Subfolder name (relative to each Stashpad folder) where dropped .stash files auto-import. Created on demand. Leave blank to disable auto-import.").addText(i=>i.setValue(this.plugin.settings.importDropFolder).setPlaceholder("_imports").onChange(async r=>{this.plugin.settings.importDropFolder=(r||"").trim().replace(/^\/+|\/+$/g,""),await this.plugin.saveSettings()})),new et.Setting(t).setName("Stash export subfolder").setDesc("Subfolder name (relative to each Stashpad folder) where exports land. Must differ from the import subfolder above.").addText(i=>i.setValue(this.plugin.settings.exportFolder).setPlaceholder("_exports").onChange(async r=>{let n=(r||"").trim().replace(/^\/+|\/+$/g,"")||xt.exportFolder;this.plugin.settings.exportFolder=n,await this.plugin.saveSettings()})),new et.Setting(t).setName("Rebootstrap existing Stashpad folders").setDesc("Walk every folder that has a home note and create any missing infrastructure (_imports, _exports, drafts file). Safe to run anytime.").addButton(i=>i.setButtonText("Rebootstrap now").onClick(async()=>{i.setDisabled(!0).setButtonText("Working\u2026");try{let{touched:r}=await this.plugin.rebootstrapAllFolders();new et.Notice(`Stashpad: rebootstrapped ${r.length} folder${r.length===1?"":"s"}.`)}catch(r){new et.Notice(`Stashpad: rebootstrap failed (${r.message})`)}finally{i.setDisabled(!1).setButtonText("Rebootstrap now")}})),new et.Setting(t).setName("Use Templates plugin date/time formats").setDesc("When on, timestamps use the formats configured in the core Templates plugin. Off: YYYY.MM.DD + HH:mm A.").addToggle(i=>i.setValue(this.plugin.settings.useTemplatesFormat).onChange(async r=>{this.plugin.settings.useTemplatesFormat=r,await this.plugin.saveSettings()}));let e=se(this.app);t.createDiv({cls:"setting-item-description stashpad-settings-note"}).setText(e?`Templates plugin: date = "${e.dateFormat}", time = "${e.timeFormat}"`:"Templates plugin not enabled."),new et.Setting(t).setName("Confirm cross-parent drag-and-drop").setDesc("When dragging notes onto a note that has a different parent, ask before re-parenting (turn off to allow direct moves).").addToggle(i=>i.setValue(this.plugin.settings.confirmCrossParentDrag).onChange(async r=>{this.plugin.settings.confirmCrossParentDrag=r,await this.plugin.saveSettings()})),new et.Setting(t).setName("Confirm bulk deletes").setDesc("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).").addToggle(i=>i.setValue(this.plugin.settings.confirmBulkDelete).onChange(async r=>{this.plugin.settings.confirmBulkDelete=r,await this.plugin.saveSettings()})),new et.Setting(t).setName("Offer to delete attachments with note").setDesc(`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.`).addToggle(i=>i.setValue(this.plugin.settings.confirmAttachmentDelete).onChange(async r=>{this.plugin.settings.confirmAttachmentDelete=r,await this.plugin.saveSettings()}));{let i=null,r=(this.plugin.settings.slugStopWords?.length?this.plugin.settings.slugStopWords:St).join(` +`);new et.Setting(t).setName("Slug stop-words").setDesc("Words removed from auto-generated note titles (filenames). One per line.").addTextArea(n=>{n.setValue(r),i=n.inputEl,i.rows=6,i.style.fontFamily="var(--font-monospace)",n.onChange(async a=>{let o=(a||"").split(/\r?\n/).map(l=>l.trim().toLowerCase()).filter(Boolean);this.plugin.settings.slugStopWords=o,await this.plugin.saveSettings()})}).addExtraButton(n=>n.setIcon("rotate-ccw").setTooltip("Reset to defaults").onClick(async()=>{this.plugin.settings.slugStopWords=[...St],i&&(i.value=St.join(` +`)),await this.plugin.saveSettings()}))}{let i=this.plugin.discoverStashpadFolders();if(new et.Setting(t).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."),i.length===0)t.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 n=t.createDiv({cls:"stashpad-folder-list"});for(let a of i)this.renderFolderScopeRow(n,a)}let r=null;new et.Setting(t).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(n=>{n.setPlaceholder("my-stashpad"),r=n.inputEl}).addButton(n=>n.setButtonText("Create").setCta().onClick(async()=>{let a=(r?.value??"").trim().replace(/^\/+|\/+$/g,"");if(!a){new et.Notice("Enter a folder name first.");return}try{await this.plugin.createNewStashpad(a),new et.Notice(`Created Stashpad "${a}".`),r&&(r.value=""),await this.plugin.waitForStashpadFolder(a,2e3),this.display()}catch(o){new et.Notice(`Couldn't create: ${o.message}`)}}))}this.renderColorAliasesSection(t),this.renderNoteTemplatesSection(t),new et.Setting(t).setName("Autofocus composer after sending").setDesc("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.").addToggle(i=>i.setValue(this.plugin.settings.autofocusComposerAfterSend).onChange(async r=>{this.plugin.settings.autofocusComposerAfterSend=r,await this.plugin.saveSettings()})),new et.Setting(t).setName("Prefix timestamps when copying").setDesc("Include each note's timestamp before its body when copying with C or Y.").addToggle(i=>i.setValue(this.plugin.settings.prefixTimestampsOnCopy).onChange(async r=>{this.plugin.settings.prefixTimestampsOnCopy=r,await this.plugin.saveSettings()})),t.createEl("h3",{text:"Keyboard shortcuts"}),t.createEl("p",{cls:"setting-item-description",text:"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. When both slots are set, the pill on the right decides which one is active."});for(let i of $t)this.renderBindingRow(t,i)}renderColorAliasesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0){new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("No Stashpads discovered yet \u2014 create one above first.");return}let s=(()=>{let n=_t()?.noteFolder;return n&&e.includes(n)?n:e[0]})();new et.Setting(t).setName("Color Aliases per Stashpad").setDesc("Which Stashpad's colors to label.").addDropdown(n=>{for(let a of e)n.addOption(a,a);n.setValue(s),n.onChange(a=>{s=a,r()})}),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 i=t.createDiv({cls:"stashpad-color-aliases-list"}),r=()=>{i.empty();let n=this.plugin.collectColorsInFolder(s),a=new Map(n.map(d=>[d.hex,d.count])),o=this.plugin.settings.colorAliases?.[s.replace(/\/+$/,"")]??{},l=new Set([...a.keys(),...Object.keys(o)]);if(l.size===0){i.createEl("p",{cls:"setting-item-description",text:`No colors used or aliased in "${s}" yet. Set a per-note color (Shift+; or right-click \u2192 Set color) and it'll appear here.`});return}let c=[...l].map(d=>({hex:d,count:a.get(d)??0}));c.sort((d,h)=>h.count-d.count||d.hex.localeCompare(h.hex));for(let d of c)this.renderColorAliasRow(i,s,d.hex,d.count,r)};r()}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 /_authors/."}),new et.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(s=>{s.setValue(this.plugin.settings.authorName).onChange(async i=>{this.plugin.settings.authorName=i.trim(),this.plugin.settings.authorName&&!this.plugin.settings.authorId&&(this.plugin.settings.authorId=bt()),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.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(s=>{s.setValue(this.plugin.settings.authorId).setDisabled(!0)}),new et.Setting(t).setName("Title / role").setDesc('Optional. Shown on your author page (e.g. "Engineer", "PM", "Designer").').addText(s=>{s.setValue(this.plugin.settings.authorRole).onChange(async i=>{this.plugin.settings.authorRole=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Department / team").setDesc('Optional. Shown on your author page (e.g. "Engineering", "Growth").').addText(s=>{s.setValue(this.plugin.settings.authorDepartment).onChange(async i=>{this.plugin.settings.authorDepartment=i.trim(),await this.plugin.saveSettings(),await this.plugin.syncAuthorFilesToName()})}),new et.Setting(t).setName("Show author in note footer").addToggle(s=>s.setValue(this.plugin.settings.showAuthor).onChange(async i=>{this.plugin.settings.showAuthor=i,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show contributors in note footer").addToggle(s=>s.setValue(this.plugin.settings.showContributors).onChange(async i=>{this.plugin.settings.showContributors=i,await this.plugin.saveSettings()})),new et.Setting(t).setName("Show last edit time in note footer").addToggle(s=>s.setValue(this.plugin.settings.showLastEdit).onChange(async i=>{this.plugin.settings.showLastEdit=i,await this.plugin.saveSettings()}));let e=this.plugin.collectAuthoredFolders();if(e.length>0){t.createEl("h4",{text:"Folders you've worked in"});let s=t.createDiv({cls:"stashpad-authored-folders-list"});for(let i of e){let r=s.createDiv({cls:"stashpad-authored-folder-row"}),n=r.createEl("a",{cls:"stashpad-authored-folder-link",text:i.folder});n.onclick=o=>{o.preventDefault(),this.plugin.activateViewForFolder(i.folder)};let a=[];i.authored>0&&a.push(`authored ${i.authored}`),i.contributed>0&&a.push(`contributed to ${i.contributed}`),r.createSpan({cls:"stashpad-authored-folder-counts",text:` \xB7 ${a.join(", ")}`})}}}renderNoteTemplatesSection(t){let e=this.plugin.discoverStashpadFolders();if(e.length===0)return;new et.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 s=t.createDiv({cls:"stashpad-note-templates-list"}),i=r=>{let n=r.replace(/\/+$/,""),a=s.createDiv({cls:"stashpad-note-template-row"});a.createSpan({cls:"stashpad-note-template-folder"}).setText(r);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??{})[n]??"";let d=l.createDiv({cls:"stashpad-note-template-suggest"});d.style.display="none";let h=a.createDiv({cls:"stashpad-note-template-warn"});h.style.display="none";let g=()=>this.app.vault.getMarkdownFiles().map(b=>b.path).filter(b=>!/\/(_imports|_exports|_attachments|\.stashpad)\//.test(b)).sort(),u=()=>{d.empty();let b=c.value.trim().toLowerCase(),C=g().filter(_=>!b||_.toLowerCase().includes(b)).slice(0,12);if(C.length===0){d.style.display="none";return}d.style.display="";for(let _ of C)d.createDiv({cls:"stashpad-note-template-suggest-item",text:_}).addEventListener("mousedown",async R=>{R.preventDefault(),c.value=_,await y(),d.style.display="none"})},y=async()=>{let b=c.value.trim(),C={...this.plugin.settings.noteTemplates??{}};b?C[n]=b:delete C[n],this.plugin.settings.noteTemplates=C,await this.plugin.saveSettings(),w()},w=()=>{h.empty(),h.style.display="none";let b=c.value.trim();if(!b)return;let C=this.app.vault.getAbstractFileByPath(b);if(!C||C.extension!=="md"){h.style.display="",h.setText(`\u26A0 "${b}" is not a markdown file in this vault.`);return}let _=this.app.metadataCache.getFileCache(C)?.frontmatter??{},R=["id","parent","created","attachments","position"].filter(P=>{let $=_[P];return!($==null||typeof $=="string"&&$.trim()===""||Array.isArray($)&&$.length===0)});R.length!==0&&(h.style.display="",h.setText(`\u26A0 Template defines ${R.join(", ")} \u2014 Stashpad always sets ${R.length===1?"this":"these"} on new notes, so the template value${R.length===1?"":"s"} will be ignored.`))};c.addEventListener("focus",u),c.addEventListener("input",u),c.addEventListener("blur",()=>{setTimeout(()=>{d.style.display="none"},150)}),c.addEventListener("change",()=>{y()}),w()};for(let r of e)i(r)}renderColorAliasRow(t,e,s,i,r){let n=t.createDiv({cls:"stashpad-color-alias-row"});i===0&&n.addClass("is-unused");let a=n.createSpan({cls:"stashpad-color-alias-swatch"});a.style.background=s,a.title="Click to bulk-recolor every note of this color in this Stashpad",a.onclick=()=>{let d=this.plugin.settings.customPalette??[];new It(this.app,s,d,async h=>{if((h??null)===null&&i===0){await this.plugin.setColorAlias(e,s,""),r();return}if(h&&h.toLowerCase()===s){r();return}let g=await this.plugin.recolorAllInFolder(e,s,h??null);if(g>0)new et.Notice(`Recolored ${g} note${g===1?"":"s"}.`);else if(i===0){let u=this.plugin.getColorAlias(e,s);u&&(await this.plugin.setColorAlias(e,s,""),h&&await this.plugin.setColorAlias(e,h,u))}r()},async h=>{let g=(this.plugin.settings.customPalette??[]).filter(u=>u.toLowerCase()!==h.toLowerCase());return this.plugin.settings.customPalette=g,await this.plugin.saveSettings(),g}).open()};let o=n.createDiv({cls:"stashpad-color-alias-meta"});o.createSpan({cls:"stashpad-color-alias-hex",text:s}),o.createSpan({cls:"stashpad-color-alias-count",text:i===0?"\xB7 unused":`\xB7 ${i} note${i===1?"":"s"}`});let l=n.createEl("input",{type:"text",cls:"stashpad-color-alias-input",attr:{placeholder:"Alias (optional)"}});l.value=this.plugin.getColorAlias(e,s)??"",l.onchange=async()=>{await this.plugin.setColorAlias(e,s,l.value),!l.value.trim()&&i===0&&r()};let c=n.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,s,""),i===0?r():(l.value="",c.style.visibility="hidden")}}renderFolderScopeRow(t,e){let s=t.createDiv({cls:"stashpad-folder-row"});s.createSpan({cls:"stashpad-folder-row-label",text:e});let i=s.createSpan({cls:"stashpad-folder-row-state"}),r=s.createDiv({cls:"stashpad-binding-pill"});r.setAttribute("role","switch"),r.setAttribute("tabindex","0");let n=r.createDiv({cls:"stashpad-binding-pill-knob"}),a=()=>(this.plugin.settings.searchExcludedFolders??[]).includes(e),o=()=>{let c=a();r.toggleClass("is-right",c),r.setAttribute("aria-checked",String(c)),n.setText(c?"X":"\u2713"),i.setText(c?"Excluded":"Included"),i.toggleClass("is-excluded",c),r.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(),o(),await this.plugin.saveSettings()};r.onclick=()=>void l(),r.onkeydown=c=>{(c.key===" "||c.key==="Enter")&&(c.preventDefault(),l())},o()}renderBindingRow(t,e){let s=new et.Setting(t).setName(e.label).setDesc(e.desc),i=()=>this.plugin.settings.bindings[e.id],r,n,a=()=>{},o=h=>{let g=s.controlEl.createDiv({cls:"stashpad-binding-slot"}),u=g.createEl("input",{type:"text"});u.readOnly=!0,u.placeholder="Click & press a key",u.value=ve(i()[h]),u.classList.add("stashpad-binding-input"),u.onclick=()=>{Pe(u,async w=>{this.plugin.settings.bindings[e.id][h]=w,u.value=ve(w),await this.plugin.saveSettings(),a()})};let y=g.createEl("button",{cls:"stashpad-binding-clear",text:"\xD7"});return y.title="Clear this slot",y.onclick=async()=>{this.plugin.settings.bindings[e.id][h]="",u.value="",await this.plugin.saveSettings(),a()},u};r=o("primary"),n=o("secondary");let l=s.controlEl.createDiv({cls:"stashpad-binding-pill"});l.setAttribute("role","switch"),l.setAttribute("tabindex","0");let c=l.createDiv({cls:"stashpad-binding-pill-knob"});a=()=>{let h=i(),g=!!(h.primary&&h.secondary);l.toggleClass("is-disabled",!g),l.toggleClass("is-right",h.preferRight),l.setAttribute("aria-checked",String(h.preferRight)),l.setAttribute("aria-disabled",String(!g)),c.setText(h.preferRight?"R":"L"),l.title=g?h.preferRight?"Right slot active \u2014 click for left":"Left slot active \u2014 click for right":"Set both slots to enable the toggle"};let d=async()=>{let h=i();!h.primary||!h.secondary||(this.plugin.settings.bindings[e.id].preferRight=!h.preferRight,a(),await this.plugin.saveSettings())};l.onclick=()=>void d(),l.onkeydown=h=>{(h.key===" "||h.key==="Enter")&&(h.preventDefault(),d())},a()}};var Ne=require("obsidian");var Ft=class extends Ne.SuggestModal{constructor(t,e,s,i){super(t);this.tree=e;this.titleFn=s;this.opts=i;this.notes=[];this.setPlaceholder(i.placeholder??(i.mode==="search"?"Search notes\u2026":"Pick a note\u2026")),this.loadAll()}loadAll(){let t=(s,i)=>{let r=this.tree.get(s);r?.file&&s!==j?this.notes.push({node:r,title:`${" ".repeat(i)}${this.titleFn(r)}`,body:""}):r?.file&&s===j&&this.notes.push({node:r,title:"Home",body:""});for(let n of this.tree.getChildren(s))t(n.id,i+1)},e=this.tree.getRoot();e.file&&this.notes.push({node:e,title:"Home",body:""});for(let s of this.tree.getChildren(j))t(s.id,1);for(let s of this.notes)s.node?.file&&this.app.vault.cachedRead(s.node.file).then(i=>{s.body=this.stripFm(i)});if(this.opts.crossFolderNotes){let s=this.opts.crossFolderNotes();for(let i of s)this.notes.push({node:null,title:i.title,body:i.body,cross:i});for(let i of this.notes)!i.cross||i.body||this.app.vault.cachedRead(i.cross.file).then(r=>{i.body=this.stripFm(r)})}}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(),s=this.notes.filter(c=>!c.cross),i=this.notes.filter(c=>c.cross),r=(c,d)=>({id:c.cross?`cross:${c.cross.id}`:c.node.id,label:c.title,node:c.node,kind:"note",bodyPreview:this.previewFromBody(c.body,d),matchLine:d,crossFolder:c.cross?.folder,crossFile:c.cross?.file}),n=c=>{let d=[];for(let h of c)if(this.opts.mode==="search"){if(!e){d.push(r(h,-1));continue}let g=h.title.toLowerCase().includes(e),u=h.body.split(/\r?\n/),y=-1;for(let w=0;wc.label.trim().toLowerCase()===e)&&o.push({id:"__create__",label:`Create new: "${t}"`,node:null,kind:"create"}),o}previewFromBody(t,e){let s=t.split(/\r?\n/).filter(n=>n.trim().length>0);if(!s.length)return"";if(e<0)return s.slice(0,3).join(` `);let i=Math.max(0,e-1),r=Math.min(s.length,e+2);return s.slice(i,r).join(` -`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}t.crossFolder&&e.addClass("is-cross-folder");let s=this.notes.find(a=>t.crossFolder?a.cross?.id===t.id.replace(/^cross:/,""):a.node?.id===t.id),i=this.firstLineOfBody(s?.body??"")||t.label.trim(),r=e.createDiv({cls:"stashpad-suggest-title",text:i});t.crossFolder&&r.createSpan({cls:"stashpad-suggest-folder",text:` \xB7 ${t.crossFolder.split("/").pop()||t.crossFolder}`});let n="";t.crossFolder?n=s?.cross?.parentBlurb??"":n=this.parentBlurbFor(t.node),n&&e.createDiv({cls:"stashpad-suggest-preview"}).setText(`Parent: ${n}`)}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let s of e){let i=s.trim();if(i)return i}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===V)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let s=this.notes.find(i=>i.node?.id===e.id);return s?this.firstLineOfBody(s.body):""}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}this.opts.onPick(t)}};var Oe=require("obsidian"),se=class{constructor(m,t){this.app=m;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 m=this.detectTrigger();if(!m){this.close();return}this.openFor(m)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=m=>{m.key==="Escape"&&(!this.state||!this.items.length||(m.preventDefault(),m.stopPropagation(),m.stopImmediatePropagation(),this.close()))};this.onKeyDown=m=>{!this.state||!this.items.length||(m.key==="ArrowDown"?(m.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):m.key==="ArrowUp"?(m.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):m.key==="Enter"||m.key==="Tab"?(m.preventDefault(),m.stopPropagation(),this.commit()):m.key==="Escape"&&(m.preventDefault(),m.stopPropagation(),m.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let m=this.ta.ownerDocument??document;m.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>m.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))}detach(){this.close(),this.ta.removeEventListener("input",this.onInput),this.ta.removeEventListener("keydown",this.onKeyDown,!0),this.ta.removeEventListener("blur",this.onBlur);for(let m of this.vaultListeners)m();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;this.fileIndex=this.app.vault.getMarkdownFiles().map(t=>({basename:t.basename,lower:t.basename.toLowerCase(),file:t}));let m=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(m).sort((t,e)=>(m[e]||0)-(m[t]||0)),this.indexBuilt=!0}detectTrigger(){let m=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=m.slice(0,t),s=e.match(/\[\[([^\]\[\n]*)$/);if(s){let r=s[1];return{kind:"link",query:r,replaceStart:t-r.length-2,replaceEnd:t}}let i=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(i){let r=i[2];return{kind:"tag",query:r,replaceStart:t-r.length-1,replaceEnd:t}}return null}buildItems(m){this.buildIndex();let t=m.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],s=i=>{if(!e.length)return!0;for(let r of e)if(!i.includes(r))return!1;return!0};return m.kind==="link"?this.fileIndex.filter(r=>s(r.lower)).slice(0,30).map(r=>({label:r.basename,insert:`[[${r.basename}]]`,subtitle:r.file.path})):this.tagIndex.filter(r=>s(r.toLowerCase())).slice(0,30).map(r=>({label:r,insert:r,subtitle:""}))}openFor(m){if(this.state=m,this.items=this.buildItems(m),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let m=new Oe.Scope(this.app.scope);m.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=m,this.app.keymap?.pushScope(m)}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 m=this.popupEl;m.empty();for(let t=0;t{i.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let m=this.popupEl.children;for(let e=0;en.id)};return t.file("manifest.json",JSON.stringify(r,null,2)),i.length&&t.file("warnings.txt",i.join(` -`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function re(g,m,t,e){let s=await be.default.loadAsync(m),i=s.file("manifest.json");if(!i)throw new Error("Not a valid .stash package: missing manifest.json");let r=JSON.parse(await i.async("string"));if(typeof r.stashSchema!="number"||r.stashSchema>Be)throw new Error(`Unsupported .stash schema: v${r.stashSchema}`);await $e(g,t);let n=Object.values(s.files).filter(w=>!w.dir&&w.name.startsWith("notes/")&&w.name.endsWith(".md")),a=[];for(let w of n){let b=await w.async("string"),{fm:C,body:E}=Ue(b);a.push({originalName:w.name.slice(6),fm:C,body:E})}let o=new Map,c=0;for(let w of a){let b=w.fm.id;b&&(e.has(b)||o.has(b)?(o.set(b,`${b}-${bt(4)}-Imported`),c++):o.set(b,b))}let l=new Date().toISOString(),h=[],d=`${t}/_attachments`,v=0,u=Object.values(s.files).filter(w=>!w.dir&&w.name.startsWith("attachments/"));u.length>0&&await $e(g,d);for(let w of u){let b=w.name.slice(12);if(!b)continue;let C=`${d}/${b}`;if(await g.vault.adapter.exists(C))continue;let E=await w.async("arraybuffer");await g.vault.createBinary(C,E),v++}let y=0;for(let w of a){let b=w.fm.id;if(!b){h.push(`Skipped ${w.originalName} \u2014 no id in frontmatter`);continue}let C=o.get(b),E=w.fm.parent??null,I=E;E&&E!==V&&o.has(E)?I=o.get(E):E&&E!==V&&!o.has(E)&&(I=V);let N=ds(w.body,d),D={...w.fm,id:C,parent:I,import_date:l};Array.isArray(D.attachments)&&(D.attachments=D.attachments.map(T=>`${d}/${He(T)}`));let $=je(D,N),q=C===b?w.originalName:us(w.originalName,b,C),x=`${t}/${q}`;await g.vault.adapter.exists(x)&&(q=`${q.replace(/\.md$/,"")}-${bt(4)}.md`,x=`${t}/${q}`),await g.vault.create(x,$),y++}return{notesWritten:y,attachmentsWritten:v,collisionsRenamed:c,warnings:h}}function os(g){let m=new Set,t=[];for(let e of g)m.has(e.id)||(m.add(e.id),t.push(e));return t}function ls(g){let m=new Set,t;for(we.lastIndex=0;(t=we.exec(g))!==null;)m.add(t[1]);return[...m]}function cs(g,m,t){return g.replace(new RegExp(`!\\[\\[${ps(m)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,s)=>`![[${t}${s??""}]]`)}function ds(g,m){return g.replace(we,(t,e,s)=>e.includes("/")?t:t.replace(e,`${m}/${e}`))}function hs(g,m,t){let e=Ue(g);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return g;let s=e.fm.attachments.map(r=>{let n=m.metadataCache.getFirstLinkpathDest(r,t);return n?n.name:He(r)}),i={...e.fm,attachments:s};return je(i,e.body)}function ps(g){return g.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function He(g){let m=g.lastIndexOf("/");return m<0?g:g.slice(m+1)}function us(g,m,t){return g.includes(m)?g.replace(m,t):g.replace(/\.md$/,`-${t}.md`)}function Ue(g){if(!g.startsWith("---"))return{fm:{},body:g};let m=g.indexOf(` ----`,3);if(m<0)return{fm:{},body:g};let t=g.slice(3,m).replace(/^\n/,""),e=g.slice(m+4),s={};try{s=(0,ie.parseYaml)(t)??{}}catch{s={}}let i=e.startsWith(` -`)?e.slice(1):e;return{fm:s,body:i}}function je(g,m){return`--- -${(0,ie.stringifyYaml)(g).trimEnd()} +`)}renderSuggestion(t,e){if(e.addClass("stashpad-suggest-item"),t.kind==="create"){e.createDiv({cls:"stashpad-suggest-create",text:t.label});return}t.crossFolder&&e.addClass("is-cross-folder");let s=this.notes.find(a=>t.crossFolder?a.cross?.id===t.id.replace(/^cross:/,""):a.node?.id===t.id),i=this.firstLineOfBody(s?.body??"")||t.label.trim(),r=e.createDiv({cls:"stashpad-suggest-title",text:i});t.crossFolder&&r.createSpan({cls:"stashpad-suggest-folder",text:` \xB7 ${t.crossFolder.split("/").pop()||t.crossFolder}`});let n="";t.crossFolder?n=s?.cross?.parentBlurb??"":n=this.parentBlurbFor(t.node),n&&e.createDiv({cls:"stashpad-suggest-preview"}).setText(`Parent: ${n}`)}firstLineOfBody(t){if(!t)return"";let e=t.split(/\r?\n/);for(let s of e){let i=s.trim();if(i)return i}return""}parentBlurbFor(t){if(!t||!t.parent||t.parent===j)return"";let e=this.tree.get(t.parent);if(!e||!e.file)return"";let s=this.notes.find(i=>i.node?.id===e.id);return s?this.firstLineOfBody(s.body):""}onChooseSuggestion(t){if(t.kind==="create"&&this.opts.onCreate){this.opts.onCreate(this.inputEl?.value??"");return}this.opts.onPick(t)}};var $e=require("obsidian"),ie=class{constructor(p,t){this.app=p;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 p=this.detectTrigger();if(!p){this.close();return}this.openFor(p)};this.onBlur=()=>{setTimeout(()=>this.close(),120)};this.onDocEscape=p=>{p.key==="Escape"&&(!this.state||!this.items.length||(p.preventDefault(),p.stopPropagation(),p.stopImmediatePropagation(),this.close()))};this.onKeyDown=p=>{!this.state||!this.items.length||(p.key==="ArrowDown"?(p.preventDefault(),this.activeIdx=(this.activeIdx+1)%this.items.length,this.refreshActive()):p.key==="ArrowUp"?(p.preventDefault(),this.activeIdx=(this.activeIdx-1+this.items.length)%this.items.length,this.refreshActive()):p.key==="Enter"||p.key==="Tab"?(p.preventDefault(),p.stopPropagation(),this.commit()):p.key==="Escape"&&(p.preventDefault(),p.stopPropagation(),p.stopImmediatePropagation(),this.close()))}}attach(){this.ta.addEventListener("input",this.onInput),this.ta.addEventListener("keydown",this.onKeyDown,!0),this.ta.addEventListener("blur",this.onBlur);let p=this.ta.ownerDocument??document;p.addEventListener("keydown",this.onDocEscape,!0),this.vaultListeners.push(()=>p.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))}detach(){this.close(),this.ta.removeEventListener("input",this.onInput),this.ta.removeEventListener("keydown",this.onKeyDown,!0),this.ta.removeEventListener("blur",this.onBlur);for(let p of this.vaultListeners)p();this.vaultListeners=[]}buildIndex(){if(this.indexBuilt)return;this.fileIndex=this.app.vault.getMarkdownFiles().map(t=>({basename:t.basename,lower:t.basename.toLowerCase(),file:t}));let p=this.app.metadataCache.getTags?.()??{};this.tagIndex=Object.keys(p).sort((t,e)=>(p[e]||0)-(p[t]||0)),this.indexBuilt=!0}detectTrigger(){let p=this.ta.value,t=this.ta.selectionStart;if(t==null)return null;let e=p.slice(0,t),s=e.match(/\[\[([^\]\[\n]*)$/);if(s){let r=s[1];return{kind:"link",query:r,replaceStart:t-r.length-2,replaceEnd:t}}let i=e.match(/(^|\s)#([A-Za-z0-9_/\-]+)$/);if(i){let r=i[2];return{kind:"tag",query:r,replaceStart:t-r.length-1,replaceEnd:t}}return null}buildItems(p){this.buildIndex();let t=p.query.toLowerCase().trim(),e=t?t.split(/\s+/).filter(Boolean):[],s=i=>{if(!e.length)return!0;for(let r of e)if(!i.includes(r))return!1;return!0};return p.kind==="link"?this.fileIndex.filter(r=>s(r.lower)).slice(0,30).map(r=>({label:r.basename,insert:`[[${r.basename}]]`,subtitle:r.file.path})):this.tagIndex.filter(r=>s(r.toLowerCase())).slice(0,30).map(r=>({label:r,insert:r,subtitle:""}))}openFor(p){if(this.state=p,this.items=this.buildItems(p),this.activeIdx=0,!this.items.length){this.close();return}this.renderPopup(),this.pushScope()}pushScope(){if(this.scope)return;let p=new $e.Scope(this.app.scope);p.register([],"Escape",t=>(t.preventDefault(),this.close(),!1)),this.scope=p,this.app.keymap?.pushScope(p)}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 p=this.popupEl;p.empty();for(let t=0;t{i.preventDefault(),this.activeIdx=t,this.commit()}}this.position()}refreshActive(){if(!this.popupEl)return;let p=this.popupEl.children;for(let e=0;en.id)};return t.file("manifest.json",JSON.stringify(r,null,2)),i.length&&t.file("warnings.txt",i.join(` +`)),t.generateAsync({type:"uint8array",compression:"DEFLATE",compressionOptions:{level:6}})}async function ne(v,p,t,e){let s=await Ce.default.loadAsync(p),i=s.file("manifest.json");if(!i)throw new Error("Not a valid .stash package: missing manifest.json");let r=JSON.parse(await i.async("string"));if(typeof r.stashSchema!="number"||r.stashSchema>Ue)throw new Error(`Unsupported .stash schema: v${r.stashSchema}`);await He(v,t);let n=Object.values(s.files).filter(w=>!w.dir&&w.name.startsWith("notes/")&&w.name.endsWith(".md")),a=[];for(let w of n){let b=await w.async("string"),{fm:C,body:_}=Ve(b);a.push({originalName:w.name.slice(6),fm:C,body:_})}let o=new Map,l=0;for(let w of a){let b=w.fm.id;b&&(e.has(b)||o.has(b)?(o.set(b,`${b}-${bt(4)}-Imported`),l++):o.set(b,b))}let c=new Date().toISOString(),d=[],h=`${t}/_attachments`,g=0,u=Object.values(s.files).filter(w=>!w.dir&&w.name.startsWith("attachments/"));u.length>0&&await He(v,h);for(let w of u){let b=w.name.slice(12);if(!b)continue;let C=`${h}/${b}`;if(await v.vault.adapter.exists(C))continue;let _=await w.async("arraybuffer");await v.vault.createBinary(C,_),g++}let y=0;for(let w of a){let b=w.fm.id;if(!b){d.push(`Skipped ${w.originalName} \u2014 no id in frontmatter`);continue}let C=o.get(b),_=w.fm.parent??null,T=_;_&&_!==j&&o.has(_)?T=o.get(_):_&&_!==j&&!o.has(_)&&(T=j);let R=us(w.body,h),P={...w.fm,id:C,parent:T,import_date:c};Array.isArray(P.attachments)&&(P.attachments=P.attachments.map(F=>`${h}/${We(F)}`));let $=Ze(P,R),Y=C===b?w.originalName:gs(w.originalName,b,C),x=`${t}/${Y}`;await v.vault.adapter.exists(x)&&(Y=`${Y.replace(/\.md$/,"")}-${bt(4)}.md`,x=`${t}/${Y}`),await v.vault.create(x,$),y++}return{notesWritten:y,attachmentsWritten:g,collisionsRenamed:l,warnings:d}}function ds(v){let p=new Set,t=[];for(let e of v)p.has(e.id)||(p.add(e.id),t.push(e));return t}function hs(v){let p=new Set,t;for(ke.lastIndex=0;(t=ke.exec(v))!==null;)p.add(t[1]);return[...p]}function ps(v,p,t){return v.replace(new RegExp(`!\\[\\[${ms(p)}(\\|[^\\]]+)?\\]\\]`,"g"),(e,s)=>`![[${t}${s??""}]]`)}function us(v,p){return v.replace(ke,(t,e,s)=>e.includes("/")?t:t.replace(e,`${p}/${e}`))}function fs(v,p,t){let e=Ve(v);if(!e.fm.attachments||!Array.isArray(e.fm.attachments))return v;let s=e.fm.attachments.map(r=>{let n=p.metadataCache.getFirstLinkpathDest(r,t);return n?n.name:We(r)}),i={...e.fm,attachments:s};return Ze(i,e.body)}function ms(v){return v.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function We(v){let p=v.lastIndexOf("/");return p<0?v:v.slice(p+1)}function gs(v,p,t){return v.includes(p)?v.replace(p,t):v.replace(/\.md$/,`-${t}.md`)}function Ve(v){if(!v.startsWith("---"))return{fm:{},body:v};let p=v.indexOf(` +---`,3);if(p<0)return{fm:{},body:v};let t=v.slice(3,p).replace(/^\n/,""),e=v.slice(p+4),s={};try{s=(0,re.parseYaml)(t)??{}}catch{s={}}let i=e.startsWith(` +`)?e.slice(1):e;return{fm:s,body:i}}function Ze(v,p){return`--- +${(0,re.stringifyYaml)(v).trimEnd()} --- -${m}`}async function $e(g,m){!m||await g.vault.adapter.exists(m)||await g.vault.createFolder(m)}var fs=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]);function ms(g){return!!(g instanceof Element&&g.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt")||document.body.querySelector(".modal-bg")||document.body.querySelector(".modal-container .modal")||document.body.querySelector(".suggestion-container")||document.body.querySelector(".menu.mod-active"))}var We=[{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"}],ae=class extends O.ItemView{constructor(t,e){super(t);this.focusId=V;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.noteFolder="stashpad";this.folderOverride=null;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.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.inListPicker=null;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.stickToListBottom=!1;this.listResizeObserver=null;this.scrollByFocus=new Map;this.pendingScrollRestore=null;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navForwardStack=[];this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||ms(t.target))return;let e=ft().bindings;if(rt(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(rt(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(rt(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(rt(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(rt(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(rt(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(rt(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(rt(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let s=t.target,i=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!i){let o=this.composerInputEl;if(o){t.preventDefault(),t.stopPropagation(),o.focus();let c=o.value.length;o.setSelectionRange(c,c);return}}let r=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.tagName==="BUTTON"||s.tagName==="SELECT");if(t.key==="Escape"&&s instanceof HTMLElement&&(s.tagName==="BUTTON"||s.tagName==="SELECT")&&this.viewRoot.contains(s)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null;let o=this.listEl,c=!!o&&o.scrollTop+o.clientHeight>=o.scrollHeight-2,l=o?.scrollTop??0;if(this.render(),o){let h=c?o.scrollHeight:l;o.scrollTop=h,requestAnimationFrame(()=>{o.scrollTop=c?o.scrollHeight:l}),setTimeout(()=>{o.scrollTop=c?o.scrollHeight:l},60),this.revealCursorRow()}return}if(this.inListPicker&&!r){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=Math.min(this.currentChildren.length-1,this.inListPicker.activeIdx+1),this.render();return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=Math.max(0,this.inListPicker.activeIdx-1),this.render();return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}return}if(r)return;if(rt(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(rt(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(rt(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(rt(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(rt(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(rt(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(rt(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(rt(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(rt(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(rt(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let o=this.composerInputEl;if(o){o.focus();let c=o.value.length;o.setSelectionRange(c,c)}return}if(t.key==="ArrowDown"){t.preventDefault(),this.cursorIdx>=this.currentChildren.length-1?this.cursorIdx=0:this.cursorIdx++,this.selectCursor(t.shiftKey);return}if(t.key==="ArrowUp"){t.preventDefault(),this.cursorIdx<=0?this.cursorIdx=this.currentChildren.length-1:this.cursorIdx--,this.selectCursor(t.shiftKey);return}if(t.altKey&&t.key==="ArrowLeft"){t.preventDefault(),this.navigateBack();return}if(t.altKey&&t.key==="ArrowRight"){t.preventDefault(),this.navigateForward();return}if(t.key==="ArrowRight"){let o=this.currentChildren[this.cursorIdx];o&&(t.preventDefault(),this.navigateTo(o.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let o=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,o){let c=this.currentChildren.findIndex(l=>l.id===o);this.selection.add(o),this.lastSelected=o,c>=0&&(this.cursorIdx=c)}this.render(),this.revealCursorRow();return}let n=ft().bindings;if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(rt(t,n.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(rt(t,n.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(rt(t,n.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(rt(t,n.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(rt(t,n.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(rt(t,n.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(rt(t,n.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let o=this.tree.get(this.focusId);o?.file&&this.cmdOpenInEditor(o)}else this.cmdOpenInEditor();return}if(rt(t,n.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(rt(t,n.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(rt(t,n.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(rt(t,n.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(rt(t,n.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}}let a=this.tree.get(this.focusId);if(a?.file){if(rt(t,n.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(rt(t,n.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0;this.pendingFocusIds=null;this.knownBodies=new Map;this.contribTimers=new Map;this.onFileModify=t=>{!(t instanceof O.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&(this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.scheduleContribution(t),this.debouncedRender())};this.onFileCreate=t=>{!(t instanceof O.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new Ht(this.app),this.log=e.newLog(),this.integrity=new qt(this.tree,this.log),this.order=new Ut(this.app),this.sortStore=new jt(this.app),this.tree.setOrderProvider(s=>{let i=this.noteFolder,r=this.sortStore.getMode(i,s);return r==="manual"?this.order.getOrder(i,s):this.computeSortedIds(s,r)}),this.debouncedRender=(0,O.debounce)(()=>this.render(),80)}getViewType(){return kt}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==V){let s=this.tree.get(this.focusId);if(s){let i=this.titleForNode(s).trim(),r=i.length>40?i.slice(0,40)+"\u2026":i;if(r)return`${e} \u2014 ${r}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let s=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;s&&s.textContent!==t&&s.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",()=>Qt(this)),this.viewRoot.addEventListener("click",()=>Qt(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())}),Qt(this);let e=null,s=()=>{e||(e=new O.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.selection.size>1){let r=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,r){let n=this.currentChildren.findIndex(a=>a.id===r);this.selection.add(r),this.lastSelected=r,n>=0&&(this.cursorIdx=n)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},i=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",s),this.viewRoot.addEventListener("focusout",r=>{let n=r.relatedTarget;n&&this.viewRoot&&this.viewRoot.contains(n)||i()}),this.register(()=>i()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.detachSettings=Me(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",n=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&n===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&n!==""&&(this.composerDraft=n),!!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(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder(),this.scrollByFocus.has(this.focusId)||(this.scrollToBottomOnNextRender=!0),this.render(),this.registerDomEvent(window,"beforeunload",()=>{this.flushDrafts()}),this.registerDomEvent(window,"blur",()=>{this.flushDrafts()}),this.focusComposer(),this.registerEvent(this.app.workspace.on("active-leaf-change",r=>{r===this.leaf&&this.focusComposer()}))}focusView(){requestAnimationFrame(()=>{this.viewRoot?.isConnected&&(document.activeElement instanceof HTMLElement&&(document.activeElement.tagName==="INPUT"||document.activeElement.tagName==="TEXTAREA")||this.viewRoot.focus({preventScroll:!0}))})}focusComposer(){let t=()=>{if(!this.viewRoot?.isConnected)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(){Ae(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.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=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();for(let t of this.contribTimers.values())clearTimeout(t);this.contribTimers.clear();try{await this.flushDrafts()}catch{}}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}}async setState(t,e){let s=t??null;s&&("folderOverride"in s&&(this.folderOverride=s.folderOverride??null),s.timeFilter&&(this.timeFilter=s.timeFilter),s.focusId&&(this.focusId=s.focusId),"tagFilter"in s&&(this.tagFilter=s.tagFilter??null),"colorFilter"in s&&(this.colorFilter=s.colorFilter??null),"timeFilterCalendar"in s&&(this.timeFilterCalendar=!!s.timeFilterCalendar));let i=(this.plugin?.settings?.folder??"stashpad").trim().replace(/^\/+|\/+$/g,""),r=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;this.noteFolder=r||i||"stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot&&(this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.render())}focus(){this.viewRoot?.focus({preventScroll:!0})}loadConfig(){let t=(this.plugin?.settings?.folder??"stashpad").trim().replace(/^\/+|\/+$/g,""),s=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"stashpad";s!==this.noteFolder?(this.noteFolder=s,this.tree.rebuild(this.noteFolder)):this.noteFolder=s}async setFolderOverride(t){let e=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(e&&this.isReservedFolder(e)){new O.Notice(`"${e}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((e||null)!==(this.folderOverride||null)){this.folderOverride=e,this.focusId=V,this.scrollByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),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(){let t=this.listVaultFolders(),e=(this.plugin.settings.folder||"stashpad").trim().replace(/^\/+|\/+$/g,"")||"stashpad",s=[{kind:"default",folder:e,label:`Use plugin default \u2014 ${e}`},...t.map(n=>({kind:"folder",folder:n,label:n}))],i=this,r=new class extends O.SuggestModal{getSuggestions(n){let a=n.trim().toLowerCase(),o=a?s.filter(l=>l.label.toLowerCase().includes(a)):s.slice(),c=n.trim().replace(/^\/+|\/+$/g,"");if(c&&!t.some(l=>l.toLowerCase()===c.toLowerCase())&&!i.isReservedFolder(c)){let l=Ze(c);o.push({kind:"create",folder:c,label:`+ Create folder \u201C${l}\u201D`})}return o}renderSuggestion(n,a){a.createDiv({cls:"stashpad-suggest-title",text:n.label}),n.kind==="create"&&a.addClass("stashpad-suggest-create")}async onChooseSuggestion(n){if(n.kind==="default"){i.setFolderOverride(null);return}if(n.kind==="create"){try{let a=Ze(n.folder);await i.ensureFolder(a),await i.setFolderOverride(a)}catch(a){new O.Notice(`Stashpad: couldn't create folder (${a.message})`)}return}i.setFolderOverride(n.folder)}}(this.app);r.setPlaceholder("Pick a folder, or type a new path to create one\u2026"),r.open()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof O.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,s)=>e.localeCompare(s))}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(i=>(i??"").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 O.Notice("Nothing to undo.");return}let e=t.peekUndoLabel();t.undo().then(()=>new O.Notice(`Undid: ${e}`)).catch(s=>new O.Notice(`Undo failed: ${s.message}`))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new O.Notice("Nothing to redo.");return}let e=t.peekRedoLabel();t.redo().then(()=>new O.Notice(`Redid: ${e}`)).catch(s=>new O.Notice(`Redo failed: ${s.message}`))}async snapshotNotes(t,e){let s=[],i=new Set;for(let n of t)!n.file||i.has(n.file.path)||(i.add(n.file.path),s.push({path:n.file.path,content:await this.app.vault.read(n.file)}));let r=[];if(e){let n=new Set;for(let a of t){if(!a.file)continue;let o=await this.app.vault.read(a.file);for(let c of this.extractAttachments(this.stripFrontmatter(o))){let l=this.app.metadataCache.getFirstLinkpathDest(c,"");l&&!n.has(l.path)&&(n.add(l.path),r.push({path:l.path,data:await this.app.vault.readBinary(l)}))}}}return{notes:s,attachments:r}}async restoreSnapshots(t,e){for(let i of t.attachments)try{await this.app.vault.adapter.exists(i.path)||await this.app.vault.createBinary(i.path,i.data)}catch{}for(let i of t.notes)try{await this.app.vault.adapter.exists(i.path)||await this.app.vault.create(i.path,i.content)}catch{}let s=()=>{e&&e.some(r=>this.tree.get(r))&&(this.pendingFocusIds=e.slice())};s(),this.tree.rebuild(this.noteFolder),this.render(),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render()},100),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render()},400)}async trashNotesAndAttachments(t){for(let e of t.notes){let s=this.app.vault.getAbstractFileByPath(e.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}for(let e of t.attachments){let s=this.app.vault.getAbstractFileByPath(e.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}this.tree.rebuild(this.noteFolder),this.render()}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 i={...this.plugin.settings.drafts??{}};t.length===0?delete i[e]:i[e]=t,this.plugin.settings.drafts=i,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,O.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}filterChildren(t){let e=this.timeFilterCutoff(),s=this.tagFilter?.toLowerCase(),i=this.colorFilter?.toLowerCase()??null;return!e&&!s&&!i?t:t.filter(r=>{if(e&&r.created){let n=Date.parse(r.created);if(!Number.isNaN(n)&&n({raw:i,count:r,label:this.formatTagLabel(i)}));return s.sort((i,r)=>r.count-i.count||i.label.localeCompare(r.label)),s}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let i of e){let r=this.colorForNode(i);if(!r)continue;let n=r.toLowerCase();t.set(n,(t.get(n)??0)+1)}let s=[...t.entries()].map(([i,r])=>({hex:i,count:r}));return s.sort((i,r)=>r.count-i.count||i.hex.localeCompare(r.hex)),s}defaultCursorToLast(){let t=this.tree.get(this.focusId)??this.tree.getRoot(),e=this.filterChildren(this.tree.getChildren(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)}render(){this.loadConfig();let t=this.viewRoot,e=this.listEl?.scrollTop??0;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let i=!!this.listEl&&this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2;t.empty(),t.toggleClass("is-mobile",O.Platform.isMobile),this.renderTimeFilterBar(t),this.renderBreadcrumb(t);let r=this.tree.get(this.focusId)??this.tree.getRoot();if(r.file&&!O.Platform.isMobile&&this.renderFocusedHeader(t,r),this.currentChildren=this.filterChildren(this.tree.getChildren(r.id)),this.autoSelectNewest&&this.currentChildren.length>0){let a=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(a.id),this.lastSelected=a.id,this.autoSelectNewest=!1}else if(this.pendingFocusIds){let a=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let o=-1;for(let c of a){let l=this.currentChildren.findIndex(h=>h.id===c);l>=0&&(this.selection.add(c),o<0&&(o=l))}this.cursorIdx=o,o>=0&&(this.lastSelected=a.find(c=>this.currentChildren.some(l=>l.id===c))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let n=t.createDiv({cls:"stashpad-list"});if(this.listEl=n,n.addEventListener("dragover",a=>{if(!this.dragSourceIds)return;let o=a.target;if(o&&o.closest&&o.closest(".stashpad-note"))return;a.preventDefault(),a.dataTransfer&&(a.dataTransfer.dropEffect="move");let c=Array.from(n.querySelectorAll(".stashpad-note"));if(c.length!==0){for(let l of c){let h=l.getBoundingClientRect();if(a.clientY{if(!this.dragSourceIds)return;a.preventDefault();let o=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let c=this.dragPlaceholder.nextElementSibling,l=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),c&&c.classList.contains("stashpad-note")){let h=c.dataset.id;h&&this.reorderToTarget(o,h,"before")}else if(l&&l.classList.contains("stashpad-note")){let h=l.dataset.id;h&&this.reorderToTarget(o,h,"after")}}),r.file&&O.Platform.isMobile&&(this.renderFocusedHeaderMini(n,r),this.renderFocusedHeader(n,r)),this.currentChildren.length===0)n.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else for(let a=0;a{let c=this.composerInputEl;if(c&&(c.focus({preventScroll:!0}),a!=null)){let l=Math.min(a,c.value.length);try{c.setSelectionRange(l,l)}catch{}}})}if(this.scrollToBottomOnNextRender)this.scrollToBottomOnNextRender=!1,this.scrollListToBottom();else if(this.listEl&&this.pendingScrollRestore!=null){let a=this.pendingScrollRestore;this.pendingScrollRestore=null,this.listEl.scrollTop=a}else if(this.listEl&&i){let a=this.listEl,o=()=>{a.scrollTop=a.scrollHeight};o(),requestAnimationFrame(o),setTimeout(o,60)}else this.listEl&&e>0&&(this.listEl.scrollTop=e);if(this.listEl){this.listResizeObserver?.disconnect();let a=this.listEl,o=a.scrollTop,c=new ResizeObserver(()=>{if(this.stickToListBottom){a.scrollTop=a.scrollHeight,o=a.scrollTop;return}let h=Math.max(0,a.scrollHeight-a.clientHeight);a.scrollTop{h.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let l=0;a.addEventListener("touchstart",h=>{l=h.touches[0]?.clientY??0},{passive:!0}),a.addEventListener("touchmove",h=>{let d=h.touches[0]?.clientY??l;d>l&&(this.stickToListBottom=!1),l=d},{passive:!0}),a.addEventListener("keydown",h=>{(h.key==="ArrowUp"||h.key==="PageUp"||h.key==="Home")&&(this.stickToListBottom=!1)})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),s=e.createEl("button",{cls:"stashpad-folder-btn"}),i=!!this.folderOverride,r=this.noteFolder.split("/").pop()||this.noteFolder||"stashpad";(0,O.setIcon)(s.createSpan({cls:"stashpad-btn-icon"}),"folder"),s.createSpan({text:r,cls:"stashpad-btn-text"}),s.title=i?`Folder (override): ${this.noteFolder} +${p}`}async function He(v,p){!p||await v.vault.adapter.exists(p)||await v.vault.createFolder(p)}var vs=new Set(["png","jpg","jpeg","gif","webp","svg","bmp","avif"]),ae={nested:"Nested",flat:"Flat",everything:"Everything"};function ys(v){return!!(v instanceof Element&&v.closest(".modal, .modal-container, .suggestion-container, .menu, .prompt")||document.body.querySelector(".modal-bg")||document.body.querySelector(".modal-container .modal")||document.body.querySelector(".suggestion-container")||document.body.querySelector(".menu.mod-active"))}var oe=[{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"}],ce=class extends A.ItemView{constructor(t,e){super(t);this.focusId=j;this.timeFilter="all";this.timeFilterCalendar=!1;this.tagFilter=null;this.colorFilter=null;this.noteFolder="stashpad";this.folderOverride=null;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.currentChildren=[];this.modeSplit=null;this.modeEnterSubmits=!0;this.nextDestination=null;this.inListPicker=null;this.listEl=null;this.composerInputEl=null;this.composerDraft="";this.draftsLoadedFor=null;this.autoSelectNewest=!1;this.scrollToBottomOnNextRender=!1;this.stickToListBottom=!1;this.stickyRowObserver=null;this.listResizeObserver=null;this.scrollByFocus=new Map;this.pendingScrollRestore=null;this.expandedNotes=new Set;this.focusComposerOnNextRender=!1;this.composerAutocomplete=null;this.firstSelectedId=null;this.mobileSelectMode=!1;this.focusedMiniObserver=null;this.pendingComposerCaret=null;this.navForwardStack=[];this.renderCache=new Map;this.onDocKeyDown=t=>{if(!this.viewRoot.isConnected||this.app.workspace.activeLeaf!==this.leaf||ys(t.target))return;let e=ft().bindings;if(rt(t,e.toggleSplit)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.toggleSplit();return}if(rt(t,e.pickDestination)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openDestinationPicker();return}if(rt(t,e.search)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchModal();return}if(rt(t,e.searchInParent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.openSearchInParentModal();return}if(rt(t,e.exportStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdExportStash();return}if(rt(t,e.importStash)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdImportStash();return}if(rt(t,e.pickFolder)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenFolderPicker();return}if(rt(t,e.cloneStashpadTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCloneStashpadTab();return}let s=t.target,i=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA");if(t.key===" "&&!t.metaKey&&!t.ctrlKey&&!t.altKey&&!t.shiftKey&&!i){let o=this.composerInputEl;if(o){t.preventDefault(),t.stopPropagation(),o.focus();let l=o.value.length;o.setSelectionRange(l,l);return}}let r=!!s&&(s.tagName==="INPUT"||s.tagName==="TEXTAREA"||s.tagName==="BUTTON"||s.tagName==="SELECT");if(t.key==="Escape"&&s instanceof HTMLElement&&(s.tagName==="BUTTON"||s.tagName==="SELECT")&&this.viewRoot.contains(s)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.viewRoot.focus();return}if(this.inListPicker&&t.key==="Escape"){t.preventDefault(),t.stopPropagation(),this.inListPicker=null;let o=this.listEl,l=!!o&&o.scrollTop+o.clientHeight>=o.scrollHeight-2,c=o?.scrollTop??0;if(this.render(),o){let d=l?o.scrollHeight:c;o.scrollTop=d,requestAnimationFrame(()=>{o.scrollTop=l?o.scrollHeight:c}),setTimeout(()=>{o.scrollTop=l?o.scrollHeight:c},60),this.revealCursorRow()}return}if(this.inListPicker&&!r){if(t.key==="ArrowDown"){t.preventDefault(),this.inListPicker.activeIdx=Math.min(this.currentChildren.length-1,this.inListPicker.activeIdx+1),this.render();return}if(t.key==="ArrowUp"){t.preventDefault(),this.inListPicker.activeIdx=Math.max(0,this.inListPicker.activeIdx-1),this.render();return}if(t.key==="Enter"){t.preventDefault(),this.commitInListPicker();return}return}if(r)return;if(rt(t,e.delete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdDelete();return}if(rt(t,e.toggleComplete)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleComplete();return}if(rt(t,e.moveToTop)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToTop();return}if(rt(t,e.moveToBottom)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveToBottom();return}if(rt(t,e.moveUp)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveUp();return}if(rt(t,e.moveDown)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMoveDown();return}if(rt(t,e.outdent)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOutdent();return}if(rt(t,e.setColor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSetColor();return}if(rt(t,e.undo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdUndo();return}if(rt(t,e.redo)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdRedo();return}if(t.key===" "){t.preventDefault();let o=this.composerInputEl;if(o){o.focus();let l=o.value.length;o.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 o=this.currentChildren[this.cursorIdx];o&&(t.preventDefault(),this.navigateTo(o.id));return}if(t.key==="ArrowLeft"||t.key==="Backspace"){t.preventDefault(),this.navigateUp();return}if(t.key==="Escape"){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation();let o=this.firstSelectedId??(this.selection.size>0?this.selection.values().next().value:null);if(this.selection.clear(),this.firstSelectedId=null,o){let l=this.currentChildren.findIndex(c=>c.id===o);this.selection.add(o),this.lastSelected=o,l>=0&&(this.cursorIdx=l)}this.render(),this.revealCursorRow();return}let n=ft().bindings;if(this.selection.size>0||this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]){if(rt(t,n.move)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMovePicker();return}if(rt(t,n.pickMove)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInListPicker();return}if(rt(t,n.merge)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdMerge();return}if(rt(t,n.copy)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopy();return}if(rt(t,n.copyTree)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyTree();return}if(rt(t,n.copyOutline)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdCopyOutline();return}if(rt(t,n.openEditor)){if(t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),t.shiftKey){let o=this.tree.get(this.focusId);o?.file&&this.cmdOpenInEditor(o)}else this.cmdOpenInEditor();return}if(rt(t,n.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab();return}if(rt(t,n.split)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdSplit();return}if(rt(t,n.clone)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdClone();return}if(rt(t,n.insertTemplate)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdInsertTemplate();return}if(rt(t,n.toggleExpand)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdToggleExpand();return}}let a=this.tree.get(this.focusId);if(a?.file){if(rt(t,n.openEditor)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInEditor(a);return}if(rt(t,n.openTab)){t.preventDefault(),t.stopPropagation(),t.stopImmediatePropagation(),this.cmdOpenInNewStashpadTab(a);return}}};this.dragSourceIds=null;this.dragPlaceholder=null;this.dragRowHeight=0;this.pendingFocusIds=null;this.knownBodies=new Map;this.contribTimers=new Map;this.onFileModify=t=>{!(t instanceof A.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&(this.scheduleSlugRename(t),this.scheduleAttachmentSync(t),this.scheduleContribution(t),this.debouncedRender())};this.onFileCreate=t=>{!(t instanceof A.TFile)||t.extension!=="md"||t.path.startsWith(this.noteFolder+"/")&&this.debouncedRender()};this.plugin=e,this.tree=new jt(this.app),this.log=e.newLog(),this.integrity=new Gt(this.tree,this.log),this.order=new Wt(this.app),this.sortStore=new Vt(this.app),this.tree.setOrderProvider(s=>{let i=this.noteFolder,r=this.sortStore.getMode(i,s);return r==="manual"?this.order.getOrder(i,s):this.computeSortedIds(s,r)}),this.debouncedRender=(0,A.debounce)(()=>this.render(),80)}getViewType(){return kt}getDisplayText(){let t=(this.noteFolder||"").trim(),e=t.split("/").pop()||t||"Stashpad";if(this.focusId&&this.focusId!==j){let s=this.tree.get(this.focusId);if(s){let i=this.titleForNode(s).trim(),r=i.length>40?i.slice(0,40)+"\u2026":i;if(r)return`${e} \u2014 ${r}`}}return e}refreshHeaderTitle(){let t=this.getDisplayText();try{this.leaf.updateHeader?.()}catch{}let s=(this.headerEl??this.containerEl?.querySelector?.(".view-header"))?.querySelector?.(".view-header-title")??this.titleEl;s&&s.textContent!==t&&s.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",()=>te(this)),this.viewRoot.addEventListener("click",()=>te(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())}),te(this);let e=null,s=()=>{e||(e=new A.Scope(this.app.scope),e.register([],"Escape",()=>{if(this.selection.size>1){let r=this.firstSelectedId??this.selection.values().next().value??null;if(this.selection.clear(),this.firstSelectedId=null,r){let n=this.currentChildren.findIndex(a=>a.id===r);this.selection.add(r),this.lastSelected=r,n>=0&&(this.cursorIdx=n)}this.render(),this.revealCursorRow()}return!1}),this.app.keymap?.pushScope(e))},i=()=>{if(e){try{this.app.keymap?.popScope(e)}catch{}e=null}};this.viewRoot.addEventListener("focusin",s),this.viewRoot.addEventListener("focusout",r=>{let n=r.relatedTarget;n&&this.viewRoot&&this.viewRoot.contains(n)||i()}),this.register(()=>i()),this.detachTreeHook=this.tree.hookMetadataCache(()=>this.debouncedRender()),this.detachSettings=Re(()=>{this.loadConfig();let r=this.plugin.settings.drafts?.[this.noteFolder]??"",n=this.composerInputEl?.value??"";r===""&&this.composerDraft!==""&&n===""?(this.composerDraft="",this.composerInputEl&&(this.composerInputEl.value="")):r===""&&n!==""&&(this.composerDraft=n),!!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(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.plugin.maybeSweepFolder(this.noteFolder),this.defaultCursorToLast(),this.refreshHeaderTitle(),await this.loadDraftsForFolder(),this.scrollByFocus.has(this.focusId)||(this.scrollToBottomOnNextRender=!0),this.render(),this.registerDomEvent(window,"beforeunload",()=>{this.flushDrafts()}),this.registerDomEvent(window,"blur",()=>{this.flushDrafts()}),this.focusComposer(),this.registerEvent(this.app.workspace.on("active-leaf-change",r=>{r===this.leaf&&this.focusComposer()}))}focusView(){requestAnimationFrame(()=>{this.viewRoot?.isConnected&&(document.activeElement instanceof HTMLElement&&(document.activeElement.tagName==="INPUT"||document.activeElement.tagName==="TEXTAREA")||this.viewRoot.focus({preventScroll:!0}))})}focusComposer(){let t=()=>{if(!this.viewRoot?.isConnected)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(){Me(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.focusedMiniObserver?.disconnect(),this.focusedMiniObserver=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();for(let t of this.contribTimers.values())clearTimeout(t);this.contribTimers.clear();try{await this.flushDrafts()}catch{}try{await this.order.flush(this.noteFolder)}catch{}try{await this.sortStore.flush(this.noteFolder)}catch{}}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}}async setState(t,e){let s=t??null;s&&("folderOverride"in s&&(this.folderOverride=s.folderOverride??null),s.timeFilter&&(this.timeFilter=s.timeFilter),s.focusId&&(this.focusId=s.focusId),"tagFilter"in s&&(this.tagFilter=s.tagFilter??null),"colorFilter"in s&&(this.colorFilter=s.colorFilter??null),"timeFilterCalendar"in s&&(this.timeFilterCalendar=!!s.timeFilterCalendar));let i=(this.plugin?.settings?.folder??"stashpad").trim().replace(/^\/+|\/+$/g,""),r=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null;this.noteFolder=r||i||"stashpad",await super.setState(t,e),this.refreshHeaderTitle(),this.viewRoot&&(this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),this.defaultCursorToLast(),this.draftsLoadedFor=null,this.composerDraft="",await this.loadDraftsForFolder(),this.render())}focus(){this.viewRoot?.focus({preventScroll:!0})}loadConfig(){let t=(this.plugin?.settings?.folder??"stashpad").trim().replace(/^\/+|\/+$/g,""),s=this.folderOverride?.trim().replace(/^\/+|\/+$/g,"")||null||t||"stashpad";s!==this.noteFolder?(this.noteFolder=s,this.tree.rebuild(this.noteFolder)):this.noteFolder=s}async setFolderOverride(t){let e=t?.trim().replace(/^\/+|\/+$/g,"")||null;if(e&&this.isReservedFolder(e)){new A.Notice(`"${e}" is a reserved Stashpad subfolder (imports/exports/attachments). Pick a different folder.`);return}if((e||null)!==(this.folderOverride||null)){this.folderOverride=e,this.focusId=j,this.scrollByFocus.clear(),this.selection.clear(),this.cursorIdx=-1,this.lastSelected=null,this.composerDraft="",await this.flushDrafts(),this.draftsLoadedFor=null,this.loadConfig(),await this.bootstrapFolder(),this.tree.rebuild(this.noteFolder),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(){let t=this.listVaultFolders(),e=(this.plugin.settings.folder||"stashpad").trim().replace(/^\/+|\/+$/g,"")||"stashpad",s=[{kind:"default",folder:e,label:`Use plugin default \u2014 ${e}`},...t.map(n=>({kind:"folder",folder:n,label:n}))],i=this,r=new class extends A.SuggestModal{getSuggestions(n){let a=n.trim().toLowerCase(),o=a?s.filter(c=>c.label.toLowerCase().includes(a)):s.slice(),l=n.trim().replace(/^\/+|\/+$/g,"");if(l&&!t.some(c=>c.toLowerCase()===l.toLowerCase())&&!i.isReservedFolder(l)){let c=Ke(l);o.push({kind:"create",folder:l,label:`+ Create folder \u201C${c}\u201D`})}return o}renderSuggestion(n,a){a.createDiv({cls:"stashpad-suggest-title",text:n.label}),n.kind==="create"&&a.addClass("stashpad-suggest-create")}async onChooseSuggestion(n){if(n.kind==="default"){i.setFolderOverride(null);return}if(n.kind==="create"){try{let a=Ke(n.folder);await i.ensureFolder(a),await i.setFolderOverride(a)}catch(a){new A.Notice(`Stashpad: couldn't create folder (${a.message})`)}return}i.setFolderOverride(n.folder)}}(this.app);r.setPlaceholder("Pick a folder, or type a new path to create one\u2026"),r.open()}listVaultFolders(){let t=[];for(let e of this.app.vault.getAllLoadedFiles())if(e instanceof A.TFolder){if(e.path==="/"||e.path===""||e.path.startsWith(".")||this.isReservedFolder(e.path))continue;t.push(e.path)}return t.sort((e,s)=>e.localeCompare(s))}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(i=>(i??"").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 A.Notice("Nothing to undo.");return}let e=t.peekUndoLabel();t.undo().then(()=>new A.Notice(`Undid: ${e}`)).catch(s=>new A.Notice(`Undo failed: ${s.message}`))}cmdRedo(){let t=this.plugin.getUndoStack(this.noteFolder);if(!t.canRedo()){new A.Notice("Nothing to redo.");return}let e=t.peekRedoLabel();t.redo().then(()=>new A.Notice(`Redid: ${e}`)).catch(s=>new A.Notice(`Redo failed: ${s.message}`))}async snapshotNotes(t,e){let s=[],i=new Set;for(let o of t)!o.file||i.has(o.file.path)||(i.add(o.file.path),s.push(o.file));let r=await Promise.all(s.map(o=>this.app.vault.read(o))),n=s.map((o,l)=>({path:o.path,content:r[l]})),a=[];if(e){let o=new Set,l=[];for(let d of r)for(let h of this.extractAttachments(this.stripFrontmatter(d))){let g=this.app.metadataCache.getFirstLinkpathDest(h,"");g&&!o.has(g.path)&&(o.add(g.path),l.push(g))}let c=await Promise.all(l.map(d=>this.app.vault.readBinary(d)));for(let d=0;d{e&&e.some(r=>this.tree.get(r))&&(this.pendingFocusIds=e.slice())};s(),this.tree.rebuild(this.noteFolder),this.render(),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render()},100),setTimeout(()=>{s(),this.tree.rebuild(this.noteFolder),this.render()},400)}async trashNotesAndAttachments(t){for(let e of t.notes){let s=this.app.vault.getAbstractFileByPath(e.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}for(let e of t.attachments){let s=this.app.vault.getAbstractFileByPath(e.path);if(s)try{await this.app.fileManager.trashFile(s)}catch{}}this.tree.rebuild(this.noteFolder),this.render()}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 i={...this.plugin.settings.drafts??{}};t.length===0?delete i[e]:i[e]=t,this.plugin.settings.drafts=i,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,A.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()}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()}hasIncompleteDescendant(t){for(let e of t.children){let s=this.tree.get(e);if(s&&(!this.isCompleted(s)||this.hasIncompleteDescendant(s)))return!0}return!1}collectEmbeddedAttachmentPaths(){let t=new Set,e=this.noteFolder,s=this.app.vault.getAbstractFileByPath(e);if(!(s instanceof A.TFolder))return t;let i=[s];for(;i.length;){let r=i.pop();for(let n of r.children){if(n instanceof A.TFolder){i.push(n);continue}if(!(n instanceof A.TFile)||n.extension!=="md")continue;let a=this.app.metadataCache.getFileCache(n)?.frontmatter;if(!(!a||!Array.isArray(a.attachments)))for(let o of a.attachments){if(typeof o!="string")continue;let l=this.app.metadataCache.getFirstLinkpathDest(o,n.path);l?t.add(l.path):t.add(o)}}}return t}collectFileItems(t){let e=this.noteFolder,s=this.app.vault.getAbstractFileByPath(e);if(!(s instanceof A.TFolder))return[];let i=this.currentIncludeAttachments(),r=i?new Set:this.collectEmbeddedAttachmentPaths(),n=new Set(["_authors","_imports","_exports","_processed"]),a=[],o=[s];for(;o.length;){let l=o.pop();for(let c of l.children){if(c instanceof A.TFolder){let d=c.name;if(l===s&&n.has(d)||l===s&&d==="_attachments"&&!i)continue;o.push(c);continue}c instanceof A.TFile&&c.extension!=="md"&&(c.name===".stashpad-order.json"||c.name===".stashpad-sort.json"||!i&&r.has(c.path)||a.push(c))}}return a}populateListBody(t,e){e.file&&A.Platform.isMobile&&(this.renderFocusedHeaderMini(t,e),this.renderFocusedHeader(t,e));let i=this.currentViewMode()==="everything"?this.collectFileItems(e.id):[];if(this.currentChildren.length===0&&i.length===0)t.createDiv({cls:"stashpad-empty",text:"No notes here yet. Type below to add one."});else if(i.length===0)for(let r=0;r({kind:"note",ts:Number.isFinite(Date.parse(a.created))?Date.parse(a.created):0,idx:o})),...i.map(a=>({kind:"file",ts:a.stat.ctime,file:a}))];n.sort((a,o)=>a.ts-o.ts);for(let a of n)a.kind==="note"?this.renderNote(t,this.currentChildren[a.idx],a.idx):this.renderFileRow(t,a.file)}e.file&&A.Platform.isMobile&&this.installFocusedMiniObserver(t)}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,s=this.listEl.scrollTop;this.listEl.empty(),this.populateListBody(this.listEl,t),e?this.listEl.scrollTop=this.listEl.scrollHeight:this.listEl.scrollTop=s}renderFileRow(t,e){let s=t.createDiv({cls:"stashpad-file-row"});s.dataset.path=e.path,s.createDiv({cls:"stashpad-file-meta"}).createSpan({cls:"stashpad-file-time",text:this.formatTime(new Date(e.stat.ctime).toISOString())});let r=s.createDiv({cls:"stashpad-file-body"});r.createSpan({cls:"stashpad-file-name",text:e.name}),r.createSpan({cls:"stashpad-file-ext",text:e.extension.toUpperCase()}),s.title=`${e.path} \u2014 click to open`,s.onclick=n=>{n.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(),s=this.currentHideChildless(),i=this.tree.getChildren(t),r=s?i.filter(o=>o.children.length>0):i;if(e==="nested")return r;let n=[],a=o=>{n.push(o);for(let l of this.tree.getChildren(o.id))a(l)};for(let o of r)a(o);return n}filterChildren(t){let e=this.timeFilterCutoff(),s=this.tagFilter?.toLowerCase(),i=this.colorFilter?.toLowerCase()??null,r=this.currentHideCompleted();return!e&&!s&&!i&&!r?t:t.filter(n=>{if(e&&n.created){let a=Date.parse(n.created);if(!Number.isNaN(a)&&a({raw:i,count:r,label:this.formatTagLabel(i)}));return s.sort((i,r)=>r.count-i.count||i.label.localeCompare(r.label)),s}formatTagLabel(t){return t&&t.split("/").map(e=>e.replace(/([a-z0-9])([A-Z])/g,"$1 $2").split(/[-_\s]+/).filter(Boolean).map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ")).join(" / ")}collectFolderColors(){let t=new Map,e=this.tree.getChildren(this.focusId);for(let i of e){let r=this.colorForNode(i);if(!r)continue;let n=r.toLowerCase();t.set(n,(t.get(n)??0)+1)}let s=[...t.entries()].map(([i,r])=>({hex:i,count:r}));return s.sort((i,r)=>r.count-i.count||i.hex.localeCompare(r.hex)),s}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)}render(){this.loadConfig();let t=this.viewRoot,e=this.listEl?.scrollTop??0;!!this.composerInputEl&&document.activeElement===this.composerInputEl&&(this.focusComposerOnNextRender=!0,this.pendingComposerCaret=this.composerInputEl?.selectionStart??null);let i=!!this.listEl&&(this.stickToListBottom||this.listEl.scrollTop+this.listEl.clientHeight>=this.listEl.scrollHeight-2);t.empty(),t.toggleClass("is-mobile",A.Platform.isMobile),this.renderTimeFilterBar(t),this.renderBreadcrumb(t);let r=this.tree.get(this.focusId)??this.tree.getRoot();if(r.file&&!A.Platform.isMobile&&this.renderFocusedHeader(t,r),this.currentChildren=this.filterChildren(this.collectViewItems(r.id)),this.autoSelectNewest&&this.currentChildren.length>0){let a=this.currentChildren[this.currentChildren.length-1];this.cursorIdx=this.currentChildren.length-1,this.selection.clear(),this.selection.add(a.id),this.lastSelected=a.id,this.autoSelectNewest=!1}else if(this.pendingFocusIds){let a=this.pendingFocusIds;this.pendingFocusIds=null,this.selection.clear();let o=-1;for(let l of a){let c=this.currentChildren.findIndex(d=>d.id===l);c>=0&&(this.selection.add(l),o<0&&(o=c))}this.cursorIdx=o,o>=0&&(this.lastSelected=a.find(l=>this.currentChildren.some(c=>c.id===l))??null)}else this.cursorIdx>=this.currentChildren.length&&(this.cursorIdx=this.currentChildren.length-1);let n=t.createDiv({cls:"stashpad-list"});if(this.listEl=n,n.addEventListener("dragover",a=>{if(!this.dragSourceIds)return;let o=a.target;if(o&&o.closest&&o.closest(".stashpad-note"))return;a.preventDefault(),a.dataTransfer&&(a.dataTransfer.dropEffect="move");let l=Array.from(n.querySelectorAll(".stashpad-note"));if(l.length!==0){for(let c of l){let d=c.getBoundingClientRect();if(a.clientY{if(!this.dragSourceIds)return;a.preventDefault();let o=this.dragSourceIds.slice();if(this.dragSourceIds=null,!this.dragPlaceholder)return;let l=this.dragPlaceholder.nextElementSibling,c=this.dragPlaceholder.previousElementSibling;if(this.removeDragPlaceholder(),l&&l.classList.contains("stashpad-note")){let d=l.dataset.id;d&&this.reorderToTarget(o,d,"before")}else if(c&&c.classList.contains("stashpad-note")){let d=c.dataset.id;d&&this.reorderToTarget(o,d,"after")}}),this.populateListBody(n,r),this.renderComposer(t),A.Platform.isMobile&&this.renderMobileNav(t),this.focusComposerOnNextRender){this.focusComposerOnNextRender=!1;let a=this.pendingComposerCaret;this.pendingComposerCaret=null;let o=this.composerInputEl;if(o&&o.isConnected){if(o.focus({preventScroll:!0}),a!=null){let l=Math.min(a,o.value.length);try{o.setSelectionRange(l,l)}catch{}}}else requestAnimationFrame(()=>{let l=this.composerInputEl;if(l&&(l.focus({preventScroll:!0}),a!=null)){let c=Math.min(a,l.value.length);try{l.setSelectionRange(c,c)}catch{}}})}if(this.scrollToBottomOnNextRender)this.scrollToBottomOnNextRender=!1,this.scrollListToBottom();else if(this.listEl&&this.pendingScrollRestore!=null){let a=this.pendingScrollRestore;this.pendingScrollRestore=null,this.listEl.scrollTop=a}else this.listEl&&i?this.scrollListToBottom():this.listEl&&e>0&&(this.listEl.scrollTop=e);if(this.listEl){this.listResizeObserver?.disconnect();let a=this.listEl,o=a.scrollTop,l=new ResizeObserver(()=>{if(this.stickToListBottom){a.scrollTop=a.scrollHeight,o=a.scrollTop;return}let d=Math.max(0,a.scrollHeight-a.clientHeight);a.scrollTop{d.deltaY<0&&(this.stickToListBottom=!1)},{passive:!0});let c=0;a.addEventListener("touchstart",d=>{c=d.touches[0]?.clientY??0},{passive:!0}),a.addEventListener("touchmove",d=>{let h=d.touches[0]?.clientY??c;h>c&&(this.stickToListBottom=!1),c=h},{passive:!0}),a.addEventListener("keydown",d=>{(d.key==="ArrowUp"||d.key==="PageUp"||d.key==="Home")&&(this.stickToListBottom=!1)})}}renderTimeFilterBar(t){let e=t.createDiv({cls:"stashpad-time-filter-bar"}),s=e.createEl("button",{cls:"stashpad-folder-btn"}),i=!!this.folderOverride,r=this.noteFolder.split("/").pop()||this.noteFolder||"stashpad";(0,A.setIcon)(s.createSpan({cls:"stashpad-btn-icon"}),"folder"),s.createSpan({text:r,cls:"stashpad-btn-text"}),s.title=i?`Folder (override): ${this.noteFolder} Click to change or revert to default.`:`Folder: ${this.noteFolder} -Click to override for this tab.`,i&&s.addClass("is-override"),s.onclick=c=>{c.preventDefault(),this.openFolderPicker()},this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e);let n=e.createDiv({cls:"stashpad-time-filter-btns"}),a=n.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,O.setIcon)(a,this.timeFilterCalendar?"calendar":"history"),a.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&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let c of We){let l=this.timeFilterCalendar?c.calShort:c.rollShort,h=this.timeFilterCalendar?c.calLong:c.rollLong,d=n.createEl("button",{cls:"stashpad-time-filter-btn",text:l});d.title=h,this.timeFilter===c.key&&d.addClass("is-active"),d.onclick=v=>{v.preventDefault(),this.setTimeFilter(c.key)}}let o=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let c of We){let l=this.timeFilterCalendar?c.calLong:c.rollLong,h=o.createEl("option",{text:l});h.value=c.key,this.timeFilter===c.key&&(h.selected=!0)}o.onchange=()=>this.setTimeFilter(o.value)}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),s=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),i=this.mobileSelectMode;(0,O.setIcon)(s,i?"check-square":"square"),s.title=i?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",i&&s.addClass("is-active"),s.onclick=n=>{if(n.preventDefault(),this.mobileSelectMode){let a=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),a){let o=this.currentChildren.findIndex(c=>c.id===a);this.selection.add(a),this.lastSelected=a,o>=0&&(this.cursorIdx=o)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let a=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),a&&(this.selection.add(a.id),this.lastSelected=a.id,this.firstSelectedId=a.id),this.render(),new O.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let r=e.createEl("button",{cls:"stashpad-mobile-action-btn"});(0,O.setIcon)(r,"zap"),r.title="Actions (move, delete, undo, \u2026)",r.onclick=n=>{n.preventDefault(),this.openMobileActionsMenu(r)}}openMobileActionsMenu(t){let e=new O.Menu,s=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],i=this.selection.size<=1;e.addItem(n=>n.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(n=>n.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!s).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(n=>n.setTitle("Open in editor").setIcon("pencil").setDisabled(!s).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(n=>n.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!s).onClick(()=>this.cmdMovePicker())),e.addItem(n=>n.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!s).onClick(()=>this.cmdInListPicker())),e.addItem(n=>n.setTitle("Outdent").setIcon("outdent").setDisabled(!s).onClick(()=>void this.cmdOutdent())),e.addItem(n=>n.setTitle("Set color\u2026").setIcon("palette").setDisabled(!s).onClick(()=>this.cmdSetColor())),e.addItem(n=>n.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!s).onClick(()=>void this.cmdToggleComplete())),e.addSeparator(),e.addItem(n=>n.setTitle("Copy").setIcon("copy").setDisabled(!s).onClick(()=>void this.cmdCopy())),e.addItem(n=>n.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!s).onClick(()=>void this.cmdCopyTree())),e.addItem(n=>n.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!s).onClick(()=>void this.cmdClone())),e.addItem(n=>n.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(n=>n.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(n=>n.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!s||!i).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(n=>n.setTitle("Delete").setIcon("trash-2").setDisabled(!s).onClick(()=>void this.cmdDelete()));let r=t.getBoundingClientRect();e.showAtPosition({x:r.left,y:r.bottom+4})}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),s=e.createEl("option",{text:"All tags"});s.value="",this.tagFilter||(s.selected=!0);let i=this.collectFolderTags();if(i.length===0)e.disabled=!0,s.text="No tags";else for(let r of i){let n=e.createEl("option",{text:`${r.label} (${r.count})`});n.value=r.raw,this.tagFilter&&this.tagFilter.toLowerCase()===r.raw.toLowerCase()&&(n.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),s=t.createDiv({cls:"stashpad-color-filter-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0"),(()=>{s.empty();let n=s.createSpan({cls:"stashpad-color-filter-swatch"}),a=s.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let o=this.colorFilter.toLowerCase();n.style.background=o;let c=this.plugin.getColorAlias(this.noteFolder,o);a.setText(c??o)}else e.length===0?(n.addClass("is-empty"),a.setText("No colors"),s.addClass("is-disabled")):(n.addClass("is-empty"),a.setText("All colors"))})();let r=n=>{n.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(s,e)};s.onclick=r,s.onkeydown=n=>{(n.key==="Enter"||n.key===" ")&&r(n)}}openColorFilterMenu(t,e){let s=t.ownerDocument??document;s.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let i=s.body.createDiv({cls:"stashpad-color-filter-popover"}),r=t.getBoundingClientRect();i.style.left=`${Math.max(8,r.left)}px`,i.style.top=`${r.bottom+4}px`,i.style.minWidth=`${r.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content";let n=(l,h,d)=>{let v=i.createDiv({cls:"stashpad-color-filter-popover-row"}),u=v.createSpan({cls:"stashpad-color-filter-swatch"});h?u.style.background=h:u.addClass("is-empty");let y=v.createSpan({cls:"stashpad-color-filter-popover-label"});y.setText(l),h&&(y.style.color=h),v.onclick=w=>{w.preventDefault(),w.stopPropagation(),d(),o()}};n("All colors",null,()=>this.setColorFilter(null));for(let l of e){let h=this.plugin.getColorAlias(this.noteFolder,l.hex),d=h?`${h} (${l.count})`:`${l.hex} (${l.count})`;n(d,l.hex,()=>this.setColorFilter(l.hex))}let a=new O.Scope(this.app.scope);a.register([],"Escape",l=>(l.preventDefault(),o(),!1)),this.app.keymap?.pushScope(a);let o=()=>{i.remove(),s.removeEventListener("mousedown",c,!0);try{this.app.keymap?.popScope(a)}catch{}},c=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&o()};setTimeout(()=>{s.addEventListener("mousedown",c,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,s=this.focusId,i=this.sortStore.getMode(e,s),r=t.createDiv({cls:"stashpad-sort-btn"});r.setAttribute("role","button"),r.setAttribute("tabindex","0");let n=r.createSpan({cls:"stashpad-sort-icon"});(0,O.setIcon)(n,"arrow-up-down"),r.createSpan({cls:"stashpad-sort-label"}).setText(Wt[i]),i!=="manual"&&r.addClass("is-active"),r.title=i==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${Wt[i]}. Drag-reorder will revert this parent to Manual.`;let o=c=>{c.preventDefault(),this.openSortMenu(r)};r.onclick=o,r.onkeydown=c=>{(c.key==="Enter"||c.key===" ")&&o(c)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(h=>h.remove());let s=e.body.createDiv({cls:"stashpad-sort-popover"}),i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let r=this.noteFolder,n=this.focusId,a=this.sortStore.getMode(r,n),o=()=>{s.remove(),e.removeEventListener("mousedown",c,!0);try{this.app.keymap?.popScope(l)}catch{}},c=h=>{!s.contains(h.target)&&h.target!==t&&!t.contains(h.target)&&o()};for(let h of he){let d=s.createDiv({cls:"stashpad-sort-popover-row"});h===a&&d.addClass("is-active"),d.createSpan({cls:"stashpad-sort-popover-label",text:Wt[h]}),d.onclick=async v=>{v.preventDefault(),v.stopPropagation(),o(),h!==a&&(this.sortStore.setMode(r,n,h),await this.sortStore.save(r),this.tree.rebuild(r),this.render())}}let l=new O.Scope(this.app.scope);l.register([],"Escape",h=>(h.preventDefault(),o(),!1)),this.app.keymap?.pushScope(l),setTimeout(()=>{e.addEventListener("mousedown",c,!0)},0)}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.cursorIdx=-1,this.selection.clear(),this.firstSelectedId=null,this.persistFocus(),this.render())}setColorFilter(t){let e=t?t.toLowerCase():null;(this.colorFilter??null)!==e&&(this.colorFilter=e,this.cursorIdx=-1,this.selection.clear(),this.firstSelectedId=null,this.persistFocus(),this.render())}setTimeFilter(t){this.timeFilter!==t&&(this.timeFilter=t,this.cursorIdx=-1,this.selection.clear(),this.persistFocus(),this.render())}renderBreadcrumb(t){let e=t.createDiv({cls:"stashpad-breadcrumb"});this.renderActionsCluster(e);let s=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(O.Platform.isMobile?((0,O.setIcon)(s,"home"),s.title="Home"):s.setText("Home"),s.onclick=()=>this.navigateTo(V),this.focusId===V)return;let i=28,r=100,n=this.tree.pathTo(this.focusId),a=n.map(c=>{let l=this.titleForNode(c),h=l.length>i?l.slice(0,i-1)+"\u2026":l;return{id:c.id,label:h}}),o=c=>c.reduce((l,h)=>l+h.label.length+3,0);if(o(a)>r&&a.length>2){let c=!1;for(;o(a)>r&&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=n.map(l=>this.titleForNode(l)).join(" / ");else{let l=c.id,h=e.createSpan({cls:"stashpad-crumb",text:c.label});h.title=c.label,h.onclick=()=>this.navigateTo(l),h.oncontextmenu=d=>{d.preventDefault(),this.openCrumbMenu(d,l)},O.Platform.isMobile&&this.attachLongPress(h,()=>this.openCrumbMenu(null,l))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",c=>{c.preventDefault(),this.openCrumbMenu(c,V)}),O.Platform.isMobile){let c=e.querySelector(".stashpad-crumb-home");c&&this.attachLongPress(c,()=>this.openCrumbMenu(null,V))}}attachLongPress(t,e){let s=null,i=0,r=0,n=()=>{s!=null&&(window.clearTimeout(s),s=null)};t.addEventListener("touchstart",a=>{let o=a.touches[0];i=o?.clientX??0,r=o?.clientY??0,n(),s=window.setTimeout(()=>{s=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let o=a.touches[0];o&&(Math.abs(o.clientX-i)>10||Math.abs(o.clientY-r)>10)&&n()},{passive:!0}),t.addEventListener("touchend",n),t.addEventListener("touchcancel",n)}openCrumbMenu(t,e){let s=this.tree.get(e);if(!s)return;let i=new O.Menu;if(i.addItem(r=>r.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),i.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(s))),s.file&&i.addItem(r=>r.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(s))),t&&(t.clientX>0||t.clientY>0))i.showAtMouseEvent(t);else{let n=(t?.target??null)?.getBoundingClientRect();i.showAtPosition({x:n?.left??8,y:(n?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused-mini"});i.dataset.id=e.id,i.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let n=i.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,O.setIcon)(n,"pencil"),n.title="Edit in new tab",n.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(s)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),s=t.querySelector(".stashpad-focused-mini");!e||!s||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(i=>{for(let r of i)s.toggleClass("is-visible",!r.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused"}),n=i.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});n.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),n.createDiv({cls:"stashpad-focused-grip-spacer"});let a=i.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",h=>this.handleRenderedClick(h,e));let o=i.createDiv({cls:"stashpad-focused-actions"}),c=o.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,O.setIcon)(c,"pencil"),c.title="Edit in new tab",c.onclick=()=>void this.openFileAtEnd(s);let l=o.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,O.setIcon)(l,"copy"),l.title="Open this Stashpad in a new tab (clone)",l.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:O.Platform.isMobile,toggleHost:o,toggleAnchor:c})}titleForNode(t){if(!t.file)return"Untitled";let s=this.app.metadataCache.getFileCache(t.file)?.headings?.[0]?.heading;return s||t.file.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," ")||"Untitled"}computeSortedIds(t,e){return this.tree.getChildren(t).slice().sort((i,r)=>this.compareForSort(i,r,e)).map(i=>i.id)}compareForSort(t,e,s){switch(s){case"created-asc":return(t.created||"").localeCompare(e.created||"");case"created-desc":return(e.created||"").localeCompare(t.created||"");case"modified-asc":case"modified-desc":{let i=this.modifiedFor(t)||t.created||"",r=this.modifiedFor(e)||e.created||"";return s==="modified-asc"?i.localeCompare(r):r.localeCompare(i)}case"title-az":case"title-za":{let i=this.titleForNode(t),r=this.titleForNode(e),n={numeric:!0,sensitivity:"base"};return s==="title-az"?i.localeCompare(r,void 0,n):r.localeCompare(i,void 0,n)}default:return 0}}modifiedFor(t){if(!t.file)return"";let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return(typeof e?.modified=="string"?e.modified:"")||""}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,s){if(!e.file)return;let i=e.file,r=this.tree.getChildren(e.id).length,n=this.selection.has(e.id),a=s===this.cursorIdx,o=this.inListPicker?.activeIdx===s,c=t.createDiv({cls:"stashpad-note"});n&&c.addClass("is-selected"),a&&c.addClass("is-cursor"),o&&c.addClass("is-pick-target"),this.isCompleted(e)&&c.addClass("is-completed"),c.dataset.idx=String(s),c.dataset.id=e.id,c.draggable=!0,this.attachRowDnD(c,e,s),c.addEventListener("click",C=>this.handleRowClick(C,s,e));let l=c.createDiv({cls:"stashpad-note-meta"}),h=l.createDiv({cls:"stashpad-note-meta-top"});h.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let d=this.colorForNode(e),v=h.createDiv({cls:"stashpad-note-grip"});if(d&&v.addClass("has-color"),(0,O.setIcon)(v,"grip-vertical"),v.title=d?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",v.draggable=!0,d&&v.style.setProperty("--stashpad-note-color",d),r>0){let C=l.createSpan({cls:"stashpad-note-enter"});d&&(C.style.color=d),(0,O.setIcon)(C.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),C.createSpan({text:` ${r}`}),C.onclick=E=>{E.stopPropagation(),this.navigateTo(e.id)}}d&&(c.addClass("has-color"),c.style.setProperty("--stashpad-note-color",d));let u=c.createDiv({cls:"stashpad-note-body"}),y=c.createDiv({cls:"stashpad-note-actions"}),w=y.createEl("button",{cls:"stashpad-pencil"});(0,O.setIcon)(w,"pencil"),w.title="Edit in new tab",w.onclick=C=>{C.stopPropagation(),this.openFileAtEnd(i)};let b=y.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,O.setIcon)(b,"arrow-right"),b.title="Open in Stashpad view",b.onclick=C=>{C.stopPropagation(),this.navigateTo(e.id)},this.renderNoteBody(u,e,{clamp:!0,toggleHost:y,toggleAnchor:w}),c.oncontextmenu=C=>{C.preventDefault(),this.openNoteMenu(C,e)}}renderNoteBody(t,e,s={clamp:!0}){if(!e.file)return;let i=e.file,r=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=r,this.app.vault.cachedRead(i).then(async n=>{if(t.__stashpadRenderToken!==r)return;let a=this.stripFrontmatter(n),{text:o,attachments:c}=this.splitAttachments(a);t.empty();let l=t.createDiv({cls:"stashpad-note-text"}),h=this.expandedNotes.has(e.id);s.clamp&&!h&&l.addClass("is-clamped"),await O.MarkdownRenderer.render(this.app,o,l,i.path,this),t.__stashpadRenderToken===r&&(c.length>0&&this.renderAttachmentRail(t,c),this.renderAuthorshipFooter(t,e),s.clamp&&requestAnimationFrame(()=>{if(!(l.scrollHeight>l.clientHeight+4)&&!h){l.removeClass("is-clamped");return}let v=!!s.toggleHost,u=s.toggleHost??t;u.querySelector(".stashpad-expand-toggle")?.remove();let y=u.createEl("button",{cls:"stashpad-expand-toggle"});y.title=h?"Show less":"Show more",v||O.Platform.isMobile?((0,O.setIcon)(y,h?"chevron-up":"chevron-down"),y.addClass("is-icon"),v&&y.addClass("is-inline")):y.setText(h?"Show less":"Show more"),s.toggleAnchor&&s.toggleAnchor.parentElement===u&&u.insertBefore(y,s.toggleAnchor),y.onclick=w=>{w.stopPropagation(),this.expandedNotes.has(e.id)?this.expandedNotes.delete(e.id):this.expandedNotes.add(e.id),t.empty(),this.renderNoteBody(t,e,s)}}))})}splitAttachments(t){let e=[];return{text:t.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,r)=>(e.push(r),"")).replace(/\n{3,}/g,` +Click to override for this tab.`,i&&s.addClass("is-override"),s.onclick=l=>{l.preventDefault(),this.openFolderPicker()},A.Platform.isMobile?this.renderMobileFiltersButton(e):(this.renderTagFilterDropdown(e),this.renderColorFilterDropdown(e),this.renderSortDropdown(e),this.renderViewDropdown(e));let n=e.createDiv({cls:"stashpad-time-filter-btns"}),a=n.createEl("button",{cls:"stashpad-time-filter-btn stashpad-time-filter-cal"});(0,A.setIcon)(a,this.timeFilterCalendar?"calendar":"history"),a.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&&a.addClass("is-active"),a.onclick=l=>{l.preventDefault(),this.timeFilterCalendar=!this.timeFilterCalendar,this.persistFocus(),this.render()};for(let l of oe){let c=this.timeFilterCalendar?l.calShort:l.rollShort,d=this.timeFilterCalendar?l.calLong:l.rollLong,h=n.createEl("button",{cls:"stashpad-time-filter-btn",text:c});h.title=d,this.timeFilter===l.key&&h.addClass("is-active"),h.onclick=g=>{g.preventDefault(),this.setTimeFilter(l.key)}}let o=e.createEl("select",{cls:"stashpad-time-filter-select"});for(let l of oe){let c=this.timeFilterCalendar?l.calLong:l.rollLong,d=o.createEl("option",{text:c});d.value=l.key,this.timeFilter===l.key&&(d.selected=!0)}o.onchange=()=>this.setTimeFilter(o.value)}renderActionsCluster(t){let e=t.createDiv({cls:"stashpad-mobile-actions"}),s=e.createEl("button",{cls:"stashpad-mobile-action-btn"}),i=this.mobileSelectMode;(0,A.setIcon)(s,i?"check-square":"square"),s.title=i?`${this.selection.size} selected \u2014 tap to exit (keeps the first selection)`:"Enter select mode (tap notes to add)",i&&s.addClass("is-active"),s.onclick=n=>{if(n.preventDefault(),this.mobileSelectMode){let a=this.firstSelectedId??this.selection.values().next().value;if(this.selection.clear(),a){let o=this.currentChildren.findIndex(l=>l.id===a);this.selection.add(a),this.lastSelected=a,o>=0&&(this.cursorIdx=o)}this.firstSelectedId=null,this.mobileSelectMode=!1,this.render()}else{let a=this.currentChildren[Math.max(0,this.cursorIdx)];this.mobileSelectMode=!0,this.selection.clear(),a&&(this.selection.add(a.id),this.lastSelected=a.id,this.firstSelectedId=a.id),this.render(),new A.Notice("Select mode: tap notes to add, press \u26A1 for actions")}};let r=e.createEl("button",{cls:"stashpad-mobile-action-btn"});(0,A.setIcon)(r,"zap"),r.title="Actions (move, delete, undo, \u2026)",r.onclick=n=>{n.preventDefault(),this.openMobileActionsMenu(r)}}openMobileActionsMenu(t){let e=new A.Menu,s=this.selection.size>0||this.cursorIdx>=0&&!!this.currentChildren[this.cursorIdx],i=this.selection.size<=1;e.addItem(n=>n.setTitle("Undo").setIcon("undo").onClick(()=>this.cmdUndo())),e.addItem(n=>n.setTitle("Redo").setIcon("redo").onClick(()=>this.cmdRedo())),e.addSeparator(),e.addItem(n=>n.setTitle("Open in new Stashpad tab").setIcon("list-tree").setDisabled(!s).onClick(()=>this.cmdOpenInNewStashpadTab())),e.addItem(n=>n.setTitle("Open in editor").setIcon("pencil").setDisabled(!s).onClick(()=>this.cmdOpenInEditor())),e.addSeparator(),e.addItem(n=>n.setTitle("Move\u2026").setIcon("arrow-right-circle").setDisabled(!s).onClick(()=>this.cmdMovePicker())),e.addItem(n=>n.setTitle("Nest under\u2026 (in-list)").setIcon("indent").setDisabled(!s).onClick(()=>this.cmdInListPicker())),e.addItem(n=>n.setTitle("Outdent").setIcon("outdent").setDisabled(!s).onClick(()=>void this.cmdOutdent())),e.addItem(n=>n.setTitle("Set color\u2026").setIcon("palette").setDisabled(!s).onClick(()=>this.cmdSetColor())),e.addItem(n=>n.setTitle("Toggle complete").setIcon("check-circle").setDisabled(!s).onClick(()=>void this.cmdToggleComplete())),e.addSeparator(),e.addItem(n=>n.setTitle("Copy").setIcon("copy").setDisabled(!s).onClick(()=>void this.cmdCopy())),e.addItem(n=>n.setTitle("Copy tree").setIcon("copy-plus").setDisabled(!s).onClick(()=>void this.cmdCopyTree())),e.addItem(n=>n.setTitle("Clone (duplicate / copy)").setIcon("files").setDisabled(!s).onClick(()=>void this.cmdClone())),e.addItem(n=>n.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),e.addItem(n=>n.setTitle("Merge").setIcon("merge").setDisabled(this.selection.size<2).onClick(()=>void this.cmdMerge())),e.addItem(n=>n.setTitle("Split note\u2026").setIcon("scissors").setDisabled(!s||!i).onClick(()=>void this.cmdSplit())),e.addSeparator(),e.addItem(n=>n.setTitle("Delete").setIcon("trash-2").setDisabled(!s).onClick(()=>void this.cmdDelete()));let r=t.getBoundingClientRect();e.showAtPosition({x:r.left,y:r.bottom+4})}renderTagFilterDropdown(t){let e=t.createEl("select",{cls:"stashpad-tag-filter-select"}),s=e.createEl("option",{text:"All tags"});s.value="",this.tagFilter||(s.selected=!0);let i=this.collectFolderTags();if(i.length===0)e.disabled=!0,s.text="No tags";else for(let r of i){let n=e.createEl("option",{text:`${r.label} (${r.count})`});n.value=r.raw,this.tagFilter&&this.tagFilter.toLowerCase()===r.raw.toLowerCase()&&(n.selected=!0)}e.onchange=()=>this.setTagFilter(e.value||null)}renderColorFilterDropdown(t){let e=this.collectFolderColors(),s=t.createDiv({cls:"stashpad-color-filter-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0"),(()=>{s.empty();let n=s.createSpan({cls:"stashpad-color-filter-swatch"}),a=s.createSpan({cls:"stashpad-color-filter-label"});if(this.colorFilter){let o=this.colorFilter.toLowerCase();n.style.background=o;let l=this.plugin.getColorAlias(this.noteFolder,o);a.setText(l??o)}else e.length===0?(n.addClass("is-empty"),a.setText("No colors"),s.addClass("is-disabled")):(n.addClass("is-empty"),a.setText("All colors"))})();let r=n=>{n.preventDefault(),!(e.length===0&&!this.colorFilter)&&this.openColorFilterMenu(s,e)};s.onclick=r,s.onkeydown=n=>{(n.key==="Enter"||n.key===" ")&&r(n)}}openColorFilterMenu(t,e){let s=t.ownerDocument??document;s.querySelectorAll(".stashpad-color-filter-popover").forEach(l=>l.remove());let i=s.body.createDiv({cls:"stashpad-color-filter-popover"}),r=t.getBoundingClientRect();i.style.left=`${Math.max(8,r.left)}px`,i.style.top=`${r.bottom+4}px`,i.style.minWidth=`${r.width}px`,i.style.maxWidth="min(280px, calc(100vw - 16px))",i.style.width="max-content",this.populateColorMenuBody(i,e,a);let n=new A.Scope(this.app.scope);n.register([],"Escape",l=>(l.preventDefault(),a(),!1)),this.app.keymap?.pushScope(n);let a=()=>{i.remove(),s.removeEventListener("mousedown",o,!0);try{this.app.keymap?.popScope(n)}catch{}},o=l=>{!i.contains(l.target)&&l.target!==t&&!t.contains(l.target)&&a()};setTimeout(()=>{s.addEventListener("mousedown",o,!0)},0)}renderSortDropdown(t){let e=this.noteFolder,s=this.focusId,i=this.sortStore.getMode(e,s),r=this.currentViewMode(),n=r!=="nested",a=t.createDiv({cls:"stashpad-sort-btn"});a.setAttribute("role","button"),a.setAttribute("tabindex",n?"-1":"0"),n&&a.addClass("is-disabled");let o=a.createSpan({cls:"stashpad-sort-icon"});(0,A.setIcon)(o,"arrow-up-down");let l=a.createSpan({cls:"stashpad-sort-label"});n?(l.setText("Sort: \u2014"),a.title=`Sort is per-parent and applies only to Nested view. The current view (${ae[r]}) shows a synthesized flat list sorted by created time \u2014 switch back to Nested to change sort.`):(l.setText(Mt[i]),i!=="manual"&&a.addClass("is-active"),a.title=i==="manual"?"Sort children of this view. Click to change. Drag-reorder always reverts the affected parent to Manual.":`Currently: ${Mt[i]}. Drag-reorder will revert this parent to Manual.`);let c=d=>{n||(d.preventDefault(),this.openSortMenu(a))};a.onclick=c,a.onkeydown=d=>{n||(d.key==="Enter"||d.key===" ")&&c(d)}}openSortMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-sort-popover").forEach(o=>o.remove());let s=e.body.createDiv({cls:"stashpad-sort-popover"}),i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(280px, calc(100vw - 16px))",s.style.width="max-content";let r=()=>{s.remove(),e.removeEventListener("mousedown",n,!0);try{this.app.keymap?.popScope(a)}catch{}},n=o=>{!s.contains(o.target)&&o.target!==t&&!t.contains(o.target)&&r()};this.populateSortMenuBody(s,r);let a=new A.Scope(this.app.scope);a.register([],"Escape",o=>(o.preventDefault(),r(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",n,!0)},0)}renderMobileFiltersButton(t){let e=t.createDiv({cls:"stashpad-mobile-filters-btn"});e.setAttribute("role","button"),e.setAttribute("tabindex","0");let s=e.createSpan({cls:"stashpad-mobile-filters-icon"});(0,A.setIcon)(s,"sliders-horizontal"),e.title="Filters / view options";let i=!!this.tagFilter,r=!!this.colorFilter,n=this.timeFilter!=="all",a=this.sortStore.getMode(this.noteFolder,this.focusId)!=="manual",o=this.currentViewMode()!=="nested"||this.currentHideChildless()||this.currentHideCompleted()||this.currentIncludeAttachments();(i||r||n||a||o)&&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(h=>h.remove());let s=e.body.createDiv({cls:"stashpad-mobile-filters-popover"}),i=t.getBoundingClientRect(),r=e.defaultView??window;s.style.right=`${Math.max(8,r.innerWidth-i.right)}px`,s.style.left="auto",s.style.top=`${i.bottom+4}px`,s.style.maxWidth="min(360px, calc(100vw - 16px))",s.style.width="max-content",s.style.minWidth="260px";let n=()=>{s.remove(),e.removeEventListener("mousedown",a,!0);try{this.app.keymap?.popScope(d)}catch{}},a=h=>{!s.contains(h.target)&&h.target!==t&&!t.contains(h.target)&&n()},o=[{key:"tag",title:"Tag filter",summary:()=>this.tagFilter?`#${this.tagFilter}`:"All tags",populate:h=>this.populateTagMenuBody(h,n)},{key:"color",title:"Color filter",summary:()=>this.colorFilter?this.plugin.getColorAlias(this.noteFolder,this.colorFilter)??this.colorFilter:"All colors",populate:h=>this.populateColorMenuBody(h,this.collectFolderColors(),n)},{key:"time",title:"Time filter",summary:()=>{let h=oe.find(g=>g.key===this.timeFilter);return h?this.timeFilterCalendar?h.calShort:h.rollShort:"All"},populate:h=>this.populateTimeMenuBody(h,n)},{key:"sort",title:"Sort",summary:()=>this.currentViewMode()!=="nested"?"\u2014 (Nested only)":Mt[this.sortStore.getMode(this.noteFolder,this.focusId)],populate:h=>{if(this.currentViewMode()!=="nested"){h.createDiv({cls:"stashpad-mobile-filters-note",text:"Sort applies only in Nested view."});return}this.populateSortMenuBody(h,n)}},{key:"view",title:"View",summary:()=>ae[this.currentViewMode()],populate:h=>this.populateViewMenuBody(h,n)}],l="",c=()=>{s.empty();for(let h of o){let g=s.createDiv({cls:"stashpad-mobile-filters-section"}),u=g.createDiv({cls:"stashpad-mobile-filters-header"}),y=u.createSpan({cls:"stashpad-mobile-filters-chev"});if((0,A.setIcon)(y,l===h.key?"chevron-down":"chevron-right"),u.createSpan({cls:"stashpad-mobile-filters-title",text:h.title}),u.createSpan({cls:"stashpad-mobile-filters-summary",text:h.summary()}),u.onclick=w=>{w.preventDefault(),w.stopPropagation(),l=l===h.key?"":h.key,c()},l===h.key){let w=g.createDiv({cls:"stashpad-mobile-filters-body"});h.populate(w)}}};c();let d=new A.Scope(this.app.scope);d.register([],"Escape",h=>(h.preventDefault(),n(),!1)),this.app.keymap?.pushScope(d),setTimeout(()=>{e.addEventListener("mousedown",a,!0)},0)}renderViewDropdown(t){let e=this.currentViewMode(),s=t.createDiv({cls:"stashpad-view-btn"});s.setAttribute("role","button"),s.setAttribute("tabindex","0");let i=s.createSpan({cls:"stashpad-view-icon"});(0,A.setIcon)(i,e==="flat"?"list":e==="everything"?"layout-grid":"list-tree"),s.createSpan({cls:"stashpad-view-label"}).setText(ae[e]),e!=="nested"&&s.addClass("is-active"),s.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 n=a=>{a.preventDefault(),this.openViewMenu(s)};s.onclick=n,s.onkeydown=a=>{(a.key==="Enter"||a.key===" ")&&n(a)}}openViewMenu(t){let e=t.ownerDocument??document;e.querySelectorAll(".stashpad-view-popover").forEach(o=>o.remove());let s=e.body.createDiv({cls:"stashpad-view-popover"});A.Platform.isMobile&&s.addClass("is-mobile");let i=t.getBoundingClientRect();s.style.left=`${Math.max(8,i.left)}px`,s.style.top=`${i.bottom+4}px`,s.style.minWidth=`${i.width}px`,s.style.maxWidth="min(320px, calc(100vw - 16px))",s.style.width="max-content";let r=()=>{s.remove(),e.removeEventListener("mousedown",n,!0);try{this.app.keymap?.popScope(a)}catch{}},n=o=>{!s.contains(o.target)&&o.target!==t&&!t.contains(o.target)&&r()};this.populateViewMenuBody(s,r);let a=new A.Scope(this.app.scope);a.register([],"Escape",o=>(o.preventDefault(),r(),!1)),this.app.keymap?.pushScope(a),setTimeout(()=>{e.addEventListener("mousedown",n,!0)},0)}populateViewMenuBody(t,e){let s=this.currentViewMode(),i=(d,h)=>{let g=t.createDiv({cls:"stashpad-view-popover-row"});d===s&&g.addClass("is-active"),g.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:ae[d]}),g.createDiv({cls:"stashpad-view-popover-desc",text:h}),g.onclick=async y=>{y.preventDefault(),y.stopPropagation(),e(),d!==s&&(await this.setViewMode(d),this.render())}};i("nested","Tree of immediate children (default)."),i("flat","All descendants of the current focus, flat by sort."),i("everything","All descendants PLUS non-Stashpad files in the folder."),t.createDiv({cls:"stashpad-view-popover-divider"});let r=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),n=r.createEl("input",{type:"checkbox"});n.checked=this.currentHideChildless(),r.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Hide childless notes"}),r.createDiv({cls:"stashpad-view-popover-desc",text:s==="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."}),r.onclick=async d=>{d.target!==n&&(d.preventDefault(),n.checked=!n.checked),await this.setHideChildless(n.checked),this.refreshList()};let a=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),o=a.createEl("input",{type:"checkbox"});o.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 d=>{d.target!==o&&(d.preventDefault(),o.checked=!o.checked),await this.setHideCompleted(o.checked),this.refreshList()},t.createDiv({cls:"stashpad-view-popover-divider"});let l=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"});s!=="everything"&&l.addClass("is-disabled");let c=l.createEl("input",{type:"checkbox"});c.checked=this.currentIncludeAttachments(),c.disabled=s!=="everything",l.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Include attachments"}),l.createDiv({cls:"stashpad-view-popover-desc",text:s==="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."}),l.onclick=async d=>{s==="everything"&&(d.target!==c&&(d.preventDefault(),c.checked=!c.checked),await this.setIncludeAttachments(c.checked),this.refreshList())}}setTagFilter(t){(this.tagFilter??null)!==(t??null)&&(this.tagFilter=t,this.cursorIdx=-1,this.selection.clear(),this.firstSelectedId=null,this.persistFocus(),this.render())}populateSortMenuBody(t,e){let s=this.noteFolder,i=this.focusId,r=this.sortStore.getMode(s,i);for(let n of fe){let a=t.createDiv({cls:"stashpad-sort-popover-row"});n===r&&a.addClass("is-active"),a.createSpan({cls:"stashpad-sort-popover-label",text:Mt[n]}),a.onclick=async o=>{o.preventDefault(),o.stopPropagation(),e(),n!==r&&(this.sortStore.setMode(s,i,n),await this.sortStore.save(s),this.tree.rebuild(s),this.render())}}}populateTimeMenuBody(t,e){let s=t.createDiv({cls:"stashpad-view-popover-row stashpad-view-popover-toggle"}),i=s.createEl("input",{type:"checkbox"});i.checked=this.timeFilterCalendar,s.createDiv({cls:"stashpad-view-popover-main"}).createSpan({cls:"stashpad-view-popover-label",text:"Calendar mode"}),s.createDiv({cls:"stashpad-view-popover-desc",text:"Use calendar boundaries (start of today/week/month/year). Off = rolling windows back from now."}),s.onclick=r=>{r.target!==i&&(r.preventDefault(),i.checked=!i.checked),this.timeFilterCalendar=i.checked,this.persistFocus(),this.refreshList()};for(let r of oe){let n=t.createDiv({cls:"stashpad-sort-popover-row"});this.timeFilter===r.key&&n.addClass("is-active");let a=this.timeFilterCalendar?r.calLong:r.rollLong;n.createSpan({cls:"stashpad-sort-popover-label",text:a}),n.onclick=o=>{o.preventDefault(),o.stopPropagation(),e(),this.timeFilter!==r.key&&this.setTimeFilter(r.key)}}}populateColorMenuBody(t,e,s){let i=(r,n,a)=>{let o=t.createDiv({cls:"stashpad-color-filter-popover-row"}),l=o.createSpan({cls:"stashpad-color-filter-swatch"});n?l.style.background=n:l.addClass("is-empty");let c=o.createSpan({cls:"stashpad-color-filter-popover-label"});c.setText(r),n&&(c.style.color=n),o.onclick=d=>{d.preventDefault(),d.stopPropagation(),a(),s()}};i("All colors",null,()=>this.setColorFilter(null));for(let r of e){let n=this.plugin.getColorAlias(this.noteFolder,r.hex),a=n?`${n} (${r.count})`:`${r.hex} (${r.count})`;i(a,r.hex,()=>this.setColorFilter(r.hex))}}populateTagMenuBody(t,e){let s=this.collectFolderTags(),i=(r,n)=>{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(r),(this.tagFilter??"")===(n??"")&&a.addClass("is-active"),a.onclick=c=>{c.preventDefault(),c.stopPropagation(),this.setTagFilter(n),e()}};i(s.length===0?"No tags":"All tags",null);for(let r of s)i(`${r.label} (${r.count})`,r.raw)}setColorFilter(t){let e=t?t.toLowerCase():null;(this.colorFilter??null)!==e&&(this.colorFilter=e,this.cursorIdx=-1,this.selection.clear(),this.firstSelectedId=null,this.persistFocus(),this.render())}setTimeFilter(t){this.timeFilter!==t&&(this.timeFilter=t,this.cursorIdx=-1,this.selection.clear(),this.persistFocus(),this.render())}renderBreadcrumb(t){let e=t.createDiv({cls:"stashpad-breadcrumb"});this.renderActionsCluster(e);let s=e.createSpan({cls:"stashpad-crumb stashpad-crumb-home"});if(A.Platform.isMobile?((0,A.setIcon)(s,"home"),s.title="Home"):s.setText("Home"),s.onclick=()=>this.navigateTo(j),this.focusId===j)return;let i=28,r=100,n=this.tree.pathTo(this.focusId),a=n.map(l=>{let c=this.titleForNode(l),d=c.length>i?c.slice(0,i-1)+"\u2026":c;return{id:l.id,label:d}}),o=l=>l.reduce((c,d)=>c+d.label.length+3,0);if(o(a)>r&&a.length>2){let l=!1;for(;o(a)>r&&a.length>2;)a.splice(1,1),l||(a.splice(1,0,{id:"__ellipsis__",label:"\u2026",isEllipsis:!0}),l=!0)}for(let l of a)if(e.createSpan({cls:"stashpad-crumb-sep",text:" / "}),l.isEllipsis)e.createSpan({cls:"stashpad-crumb stashpad-crumb-ellipsis",text:l.label}).title=n.map(c=>this.titleForNode(c)).join(" / ");else{let c=l.id,d=e.createSpan({cls:"stashpad-crumb",text:l.label});d.title=l.label,d.onclick=()=>this.navigateTo(c),d.oncontextmenu=h=>{h.preventDefault(),this.openCrumbMenu(h,c)},A.Platform.isMobile&&this.attachLongPress(d,()=>this.openCrumbMenu(null,c))}if(e.querySelector(".stashpad-crumb-home")?.addEventListener("contextmenu",l=>{l.preventDefault(),this.openCrumbMenu(l,j)}),A.Platform.isMobile){let l=e.querySelector(".stashpad-crumb-home");l&&this.attachLongPress(l,()=>this.openCrumbMenu(null,j))}}attachLongPress(t,e){let s=null,i=0,r=0,n=()=>{s!=null&&(window.clearTimeout(s),s=null)};t.addEventListener("touchstart",a=>{let o=a.touches[0];i=o?.clientX??0,r=o?.clientY??0,n(),s=window.setTimeout(()=>{s=null,e()},500)},{passive:!0}),t.addEventListener("touchmove",a=>{let o=a.touches[0];o&&(Math.abs(o.clientX-i)>10||Math.abs(o.clientY-r)>10)&&n()},{passive:!0}),t.addEventListener("touchend",n),t.addEventListener("touchcancel",n)}openCrumbMenu(t,e){let s=this.tree.get(e);if(!s)return;let i=new A.Menu;if(i.addItem(r=>r.setTitle("Navigate here").setIcon("arrow-right-circle").onClick(()=>this.navigateTo(e))),i.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("list-tree").onClick(()=>this.cmdOpenInNewStashpadTab(s))),s.file&&i.addItem(r=>r.setTitle("Open in editor (new tab)").setIcon("pencil").onClick(()=>this.cmdOpenInEditor(s))),t&&(t.clientX>0||t.clientY>0))i.showAtMouseEvent(t);else{let n=(t?.target??null)?.getBoundingClientRect();i.showAtPosition({x:n?.left??8,y:(n?.bottom??60)+4})}}renderFocusedHeaderMini(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused-mini"});i.dataset.id=e.id,i.createDiv({cls:"stashpad-focused-mini-text"}).setText(this.titleForNode(e).trim());let n=i.createEl("button",{cls:"stashpad-pencil stashpad-focused-mini-pencil"});(0,A.setIcon)(n,"pencil"),n.title="Edit in new tab",n.onclick=a=>{a.stopPropagation(),this.openFileAtEnd(s)}}installFocusedMiniObserver(t){let e=t.querySelector(".stashpad-focused"),s=t.querySelector(".stashpad-focused-mini");!e||!s||(this.focusedMiniObserver&&this.focusedMiniObserver.disconnect(),this.focusedMiniObserver=new IntersectionObserver(i=>{for(let r of i)s.toggleClass("is-visible",!r.isIntersecting)},{root:t,threshold:.05}),this.focusedMiniObserver.observe(e))}renderFocusedHeader(t,e){if(!e.file)return;let s=e.file,i=t.createDiv({cls:"stashpad-focused"}),n=i.createDiv({cls:"stashpad-focused-meta"}).createDiv({cls:"stashpad-focused-meta-top"});n.createSpan({cls:"stashpad-focused-time stashpad-note-time",text:this.formatTime(e.created)}),n.createDiv({cls:"stashpad-focused-grip-spacer"});let a=i.createDiv({cls:"stashpad-focused-body"});a.addEventListener("click",d=>this.handleRenderedClick(d,e));let o=i.createDiv({cls:"stashpad-focused-actions"}),l=o.createEl("button",{cls:"stashpad-pencil stashpad-focused-pencil"});(0,A.setIcon)(l,"pencil"),l.title="Edit in new tab",l.onclick=()=>void this.openFileAtEnd(s);let c=o.createEl("button",{cls:"stashpad-pencil stashpad-focused-dup"});(0,A.setIcon)(c,"copy"),c.title="Open this Stashpad in a new tab (clone)",c.onclick=()=>this.cmdOpenInNewStashpadTab(e),this.renderNoteBody(a,e,{clamp:A.Platform.isMobile,toggleHost:o,toggleAnchor:l})}renderRowBreadcrumb(t,e){let s=this.tree.pathTo(e.id),i=s.findIndex(a=>a.id===this.focusId),r=s.slice(i+1,s.length-1);if(r.length===0)return;let n=t.createDiv({cls:"stashpad-row-breadcrumb"});r.forEach((a,o)=>{let l=n.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)},othis.compareForSort(i,r,e)).map(i=>i.id)}compareForSort(t,e,s){switch(s){case"created-asc":return(t.created||"").localeCompare(e.created||"");case"created-desc":return(e.created||"").localeCompare(t.created||"");case"modified-asc":case"modified-desc":{let i=this.modifiedFor(t)||t.created||"",r=this.modifiedFor(e)||e.created||"";return s==="modified-asc"?i.localeCompare(r):r.localeCompare(i)}case"title-az":case"title-za":{let i=this.titleForNode(t),r=this.titleForNode(e),n={numeric:!0,sensitivity:"base"};return s==="title-az"?i.localeCompare(r,void 0,n):r.localeCompare(i,void 0,n)}default:return 0}}modifiedFor(t){if(!t.file)return"";let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter;return(typeof e?.modified=="string"?e.modified:"")||""}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,s){if(!e.file)return;let i=e.file,r=this.tree.getChildren(e.id).length,n=this.selection.has(e.id),a=s===this.cursorIdx,o=this.inListPicker?.activeIdx===s,l=t.createDiv({cls:"stashpad-note"});n&&l.addClass("is-selected"),a&&l.addClass("is-cursor"),o&&l.addClass("is-pick-target"),this.isCompleted(e)&&l.addClass("is-completed"),l.dataset.idx=String(s),l.dataset.id=e.id;let c=this.currentViewMode()==="nested";l.draggable=c,c&&this.attachRowDnD(l,e,s),l.addEventListener("click",T=>this.handleRowClick(T,s,e));let d=l.createDiv({cls:"stashpad-note-meta"}),h=d.createDiv({cls:"stashpad-note-meta-top"});h.createSpan({cls:"stashpad-note-time",text:this.formatTime(e.created)});let g=this.colorForNode(e),u=h.createDiv({cls:"stashpad-note-grip"});if(g&&u.addClass("has-color"),(0,A.setIcon)(u,"grip-vertical"),u.title=g?"Drag to reorder \xB7 right-click to change color":"Drag to reorder",u.draggable=c,c||(u.title=g?"Right-click to change color \xB7 drag disabled in this view mode":"Drag disabled in this view mode"),g&&u.style.setProperty("--stashpad-note-color",g),r>0){let T=d.createSpan({cls:"stashpad-note-enter"});g&&(T.style.color=g),(0,A.setIcon)(T.createSpan({cls:"stashpad-btn-icon"}),"corner-down-right"),T.createSpan({text:` ${r}`}),T.onclick=R=>{R.stopPropagation(),this.navigateTo(e.id)}}if(g)l.addClass("has-color"),l.style.setProperty("--stashpad-note-color",g);else{let T=this.inheritedColorForNode(e);T&&T.depth>0&&(l.addClass("has-inherited-color"),l.style.setProperty("--stashpad-inherited-color",T.hex),l.style.setProperty("--stashpad-inherited-depth",String(T.depth)))}let y=l.createDiv({cls:"stashpad-note-body"});this.currentViewMode()!=="nested"&&this.renderRowBreadcrumb(y,e);let w=y.createDiv({cls:"stashpad-note-body-content"}),b=l.createDiv({cls:"stashpad-note-actions"}),C=b.createEl("button",{cls:"stashpad-pencil"});(0,A.setIcon)(C,"pencil"),C.title="Edit in new tab",C.onclick=T=>{T.stopPropagation(),this.openFileAtEnd(i)};let _=b.createEl("button",{cls:"stashpad-pencil stashpad-enter-btn"});(0,A.setIcon)(_,"arrow-right"),_.title="Open in Stashpad view",_.onclick=T=>{T.stopPropagation(),this.navigateTo(e.id)},this.renderNoteBody(w,e,{clamp:!0,toggleHost:b,toggleAnchor:C}),l.oncontextmenu=T=>{T.preventDefault(),this.openNoteMenu(T,e)}}async getOrComputeRender(t){let e=this.renderCache.get(t.path);if(e&&e.mtime===t.stat.mtime)return e;let s=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(s),{text:r,attachments:n}=this.splitAttachments(i),a=createDiv({cls:"stashpad-note-text"});await A.MarkdownRenderer.render(this.app,r,a,t.path,this);let o=a.innerHTML,l={mtime:t.stat.mtime,text:r,attachments:n,html:o};return this.renderCache.set(t.path,l),l}renderNoteBody(t,e,s={clamp:!0}){if(!e.file)return;let i=e.file,r=(t.__stashpadRenderToken??0)+1;t.__stashpadRenderToken=r,this.getOrComputeRender(i).then(n=>{if(t.__stashpadRenderToken!==r)return;let{text:a,attachments:o,html:l}=n;t.empty();let c=t.createDiv({cls:"stashpad-note-text"}),d=this.expandedNotes.has(e.id);s.clamp&&!d&&c.addClass("is-clamped"),c.innerHTML=l,o.length>0&&this.renderAttachmentRail(t,o),this.renderAuthorshipFooter(t,e),s.clamp&&requestAnimationFrame(()=>{if(!(c.scrollHeight>c.clientHeight+4)&&!d){c.removeClass("is-clamped");return}let g=!!s.toggleHost,u=s.toggleHost??t;u.querySelector(".stashpad-expand-toggle")?.remove();let y=u.createEl("button",{cls:"stashpad-expand-toggle"});y.title=d?"Show less":"Show more",g||A.Platform.isMobile?((0,A.setIcon)(y,d?"chevron-up":"chevron-down"),y.addClass("is-icon"),g&&y.addClass("is-inline")):y.setText(d?"Show less":"Show more"),s.toggleAnchor&&s.toggleAnchor.parentElement===u&&u.insertBefore(y,s.toggleAnchor),y.onclick=w=>{w.stopPropagation(),this.expandedNotes.has(e.id)?this.expandedNotes.delete(e.id):this.expandedNotes.add(e.id),t.empty(),this.renderNoteBody(t,e,s)}})})}splitAttachments(t){let e=[];return{text:t.replace(/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,(i,r)=>(e.push(r),"")).replace(/\n{3,}/g,` -`).trim(),attachments:e}}renderAttachmentRail(t,e){let s=t.createDiv({cls:"stashpad-rail"});for(let i of e){let r=this.app.metadataCache.getFirstLinkpathDest(i,""),n=(i.split(".").pop()??"").toLowerCase(),a=s.createDiv({cls:"stashpad-att"});if(a.title=i,r&&fs.has(n)){let o=a.createEl("img",{cls:"stashpad-att-img"});o.src=this.app.vault.getResourcePath(r),o.alt=i}else{a.createDiv({cls:"stashpad-att-ext",text:n.toUpperCase()||"?"});let o=(i.split("/").pop()??i).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:o})}a.onclick=o=>{o.stopPropagation(),r&&this.app.workspace.getLeaf("tab").openFile(r)}}}renderComposer(t){let e=ft(),s=this.modeEnterSubmits,i=this.modeSplit??e.splitOnLines,r=null,n=t.createDiv({cls:"stashpad-composer"}),a=n.createDiv({cls:"stashpad-composer-input-wrap"}),o=a.createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(s,i)}});o.value=this.composerDraft;let c=null,l=()=>{c&&(c.remove(),c=null)};r!==null&&r.length>0&&(c=a.createEl("button",{cls:"stashpad-composer-clear"}),(0,O.setIcon)(c,"x"),c.title="Clear restored draft",c.onmousedown=T=>T.preventDefault(),c.onclick=T=>{T.preventDefault(),o.value="",this.composerDraft="",this.saveDraft(""),l(),o.focus()},requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(0,o.value.length)})),this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,O.debounce)(T=>{this.saveDraft(T)},250)),o.addEventListener("input",()=>{this.composerDraft=o.value,this.debouncedSaveDraft(o.value),l()}),o.addEventListener("blur",()=>{this.saveDraft(o.value)});let h=null,d=()=>{h||(h=new O.Scope(this.app.scope),h.register([],"Escape",()=>(o.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),this.app.keymap?.pushScope(h))},v=()=>{if(h){try{this.app.keymap?.popScope(h)}catch{}h=null}};o.addEventListener("focus",d),o.addEventListener("blur",v),document.activeElement===o&&d(),O.Platform.isMobile&&(o.addEventListener("focus",()=>document.body.classList.add("stashpad-keyboard-open")),o.addEventListener("blur",()=>document.body.classList.remove("stashpad-keyboard-open"))),this.composerInputEl=o,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new se(this.app,o),this.composerAutocomplete.attach();let u=async T=>{let f="";for(let P of T){let G=await this.importAttachment(P);if(!G)continue;let z=o.value+f,tt=z&&!z.endsWith(` +`).trim(),attachments:e}}renderAttachmentRail(t,e){let s=t.createDiv({cls:"stashpad-rail"});for(let i of e){let r=this.app.metadataCache.getFirstLinkpathDest(i,""),n=(i.split(".").pop()??"").toLowerCase(),a=s.createDiv({cls:"stashpad-att"});if(a.title=i,r&&vs.has(n)){let o=a.createEl("img",{cls:"stashpad-att-img"});o.src=this.app.vault.getResourcePath(r),o.alt=i}else{a.createDiv({cls:"stashpad-att-ext",text:n.toUpperCase()||"?"});let o=(i.split("/").pop()??i).replace(/\.[^.]+$/,"");a.createDiv({cls:"stashpad-att-name",text:o})}a.onclick=o=>{o.stopPropagation(),r&&this.app.workspace.getLeaf("tab").openFile(r)}}}renderComposer(t){let e=ft(),s=this.modeEnterSubmits,i=this.modeSplit??e.splitOnLines,r=null,n=t.createDiv({cls:"stashpad-composer"}),a=n.createDiv({cls:"stashpad-composer-input-wrap"}),o=a.createEl("textarea",{cls:"stashpad-composer-input",attr:{rows:"2",placeholder:this.composerPlaceholder(s,i)}});o.value=this.composerDraft;let l=null,c=()=>{l&&(l.remove(),l=null)};r!==null&&r.length>0&&(l=a.createEl("button",{cls:"stashpad-composer-clear"}),(0,A.setIcon)(l,"x"),l.title="Clear restored draft",l.onmousedown=F=>F.preventDefault(),l.onclick=F=>{F.preventDefault(),o.value="",this.composerDraft="",this.saveDraft(""),c(),o.focus()},requestAnimationFrame(()=>{o.focus(),o.setSelectionRange(0,o.value.length)})),this.debouncedSaveDraft||(this.debouncedSaveDraft=(0,A.debounce)(F=>{this.saveDraft(F)},250)),o.addEventListener("input",()=>{this.composerDraft=o.value,this.debouncedSaveDraft(o.value),c()}),o.addEventListener("blur",()=>{this.saveDraft(o.value)});let d=null,h=()=>{d||(d=new A.Scope(this.app.scope),d.register([],"Escape",()=>(o.blur(),this.viewRoot?.focus({preventScroll:!0}),!1)),this.app.keymap?.pushScope(d))},g=()=>{if(d){try{this.app.keymap?.popScope(d)}catch{}d=null}};o.addEventListener("focus",h),o.addEventListener("blur",g),document.activeElement===o&&h(),A.Platform.isMobile&&(o.addEventListener("focus",()=>document.body.classList.add("stashpad-keyboard-open")),o.addEventListener("blur",()=>document.body.classList.remove("stashpad-keyboard-open"))),this.composerInputEl=o,this.composerAutocomplete&&this.composerAutocomplete.detach(),this.composerAutocomplete=new ie(this.app,o),this.composerAutocomplete.attach();let u=async F=>{let m="";for(let M of F){let G=await this.importAttachment(M);if(!G)continue;let z=o.value+m,tt=z&&!z.endsWith(` `)?` -`:"";f+=`${tt}${G} -`}f&&(o.value=o.value+f,this.composerDraft=o.value,this.saveDraft(o.value),o.focus(),o.setSelectionRange(o.value.length,o.value.length))};o.addEventListener("dragover",T=>{if(!(!T.dataTransfer||!Array.from(T.dataTransfer.types).includes("Files"))){T.preventDefault(),T.stopPropagation();try{T.dataTransfer.dropEffect="copy"}catch{}}}),o.addEventListener("drop",T=>{let f=Array.from(T.dataTransfer?.files??[]);f.length!==0&&(T.preventDefault(),T.stopPropagation(),u(f))}),o.addEventListener("paste",T=>{let f=[],P=T.clipboardData;if(P){for(let G of Array.from(P.files??[]))f.push(G);if(f.length===0){for(let G of Array.from(P.items??[]))if(G.kind==="file"){let z=G.getAsFile();z&&f.push(z)}}f.length!==0&&(T.preventDefault(),T.stopPropagation(),u(f))}});let y=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});y.style.display="none";let w=n.createDiv({cls:"stashpad-composer-btn-rail"}),b=w.createDiv({cls:"stashpad-composer-btn-group"}),C=b.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(C,"list-end"),C.title=i?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",i&&C.addClass("is-active"),C.onmousedown=T=>T.preventDefault(),C.onclick=T=>{T.preventDefault(),this.toggleSplit()};let E=b.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(E,"map-pin"),this.nextDestination&&E.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),E.title="Set destination (Mod+D)",this.nextDestination&&E.addClass("is-active"),E.onmousedown=T=>T.preventDefault(),E.onclick=T=>{T.preventDefault();let f=document.activeElement===o;if(this.openDestinationPicker(),f){let P=()=>{o.focus()};setTimeout(P,50),setTimeout(P,250)}};let I=b.createEl("button",{cls:"stashpad-composer-btn"});(0,O.setIcon)(I,s?"corner-down-left":"arrow-big-down-dash"),I.title=s?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",I.onmousedown=T=>T.preventDefault(),I.onclick=T=>{T.preventDefault(),this.modeEnterSubmits=!s,this.render(),this.composerInputEl?.focus()};let N=T=>{let f=o.value&&!o.value.endsWith(` +`:"";m+=`${tt}${G} +`}m&&(o.value=o.value+m,this.composerDraft=o.value,this.saveDraft(o.value),o.focus(),o.setSelectionRange(o.value.length,o.value.length))};o.addEventListener("dragover",F=>{if(!(!F.dataTransfer||!Array.from(F.dataTransfer.types).includes("Files"))){F.preventDefault(),F.stopPropagation();try{F.dataTransfer.dropEffect="copy"}catch{}}}),o.addEventListener("drop",F=>{let m=Array.from(F.dataTransfer?.files??[]);m.length!==0&&(F.preventDefault(),F.stopPropagation(),u(m))}),o.addEventListener("paste",F=>{let m=[],M=F.clipboardData;if(M){for(let G of Array.from(M.files??[]))m.push(G);if(m.length===0){for(let G of Array.from(M.items??[]))if(G.kind==="file"){let z=G.getAsFile();z&&m.push(z)}}m.length!==0&&(F.preventDefault(),F.stopPropagation(),u(m))}});let y=n.createEl("input",{cls:"stashpad-composer-file-input",type:"file",attr:{multiple:"true"}});y.style.display="none";let w=n.createDiv({cls:"stashpad-composer-btn-rail"}),b=w.createDiv({cls:"stashpad-composer-btn-group"}),C=b.createEl("button",{cls:"stashpad-composer-btn"});(0,A.setIcon)(C,"list-end"),C.title=i?"Split on newlines: ON (Mod+/)":"Split on newlines (Mod+/)",i&&C.addClass("is-active"),C.onmousedown=F=>F.preventDefault(),C.onclick=F=>{F.preventDefault(),this.toggleSplit()};let _=b.createEl("button",{cls:"stashpad-composer-btn"});(0,A.setIcon)(_,"map-pin"),this.nextDestination&&_.createSpan({text:` ${this.destinationLabel()}`,cls:"stashpad-btn-text"}),_.title="Set destination (Mod+D)",this.nextDestination&&_.addClass("is-active"),_.onmousedown=F=>F.preventDefault(),_.onclick=F=>{F.preventDefault();let m=document.activeElement===o;if(this.openDestinationPicker(),m){let M=()=>{o.focus()};setTimeout(M,50),setTimeout(M,250)}};let T=b.createEl("button",{cls:"stashpad-composer-btn"});(0,A.setIcon)(T,s?"corner-down-left":"arrow-big-down-dash"),T.title=s?"Enter sends (click to switch to Shift+Enter)":"Shift+Enter sends (click to switch to Enter)",T.onmousedown=F=>F.preventDefault(),T.onclick=F=>{F.preventDefault(),this.modeEnterSubmits=!s,this.render(),this.composerInputEl?.focus()};let R=F=>{let m=o.value&&!o.value.endsWith(` `)?` -`:"";o.value+=`${f}${T} -`,this.composerDraft=o.value},D=b.createEl("button",{cls:"stashpad-composer-btn"});if((0,O.setIcon)(D,"paperclip"),D.title="Attach files",D.onmousedown=T=>T.preventDefault(),D.onclick=T=>{T.preventDefault();let f=document.activeElement===o;if(y.click(),f){let P=()=>{o.focus()};setTimeout(P,100),setTimeout(P,500)}},y.addEventListener("change",async()=>{let T=Array.from(y.files??[]);y.value="";for(let f of T){let P=await this.importAttachment(f);P&&N(P)}o.focus()}),O.Platform.isMobile){let T=w.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,O.setIcon)(T,"chevron-left"),T.title="Show more composer options",w.insertBefore(T,b);let f=P=>{w.toggleClass("is-expanded",P),T.title=P?"Hide options":"Show more composer options",(0,O.setIcon)(T,P?"chevron-right":"chevron-left")};T.onmousedown=P=>P.preventDefault(),T.onclick=P=>{P.preventDefault(),f(!w.hasClass("is-expanded"))},f(!1)}let $=w.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});$.title="Send (Enter)",(0,O.setIcon)($,"arrow-up");let q=async()=>{let T=o.value.trim();if(!T)return;o.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(T)}catch{}let f=this.modeSplit??ft().splitOnLines,P=this.nextDestination;if(this.nextDestination=null,this.autoSelectNewest=!0,this.scrollToBottomOnNextRender=!0,f)for(let G of T.split(/\r?\n/)){let z=G.trim();z&&await this.createNoteUnder(z,P)}else await this.createNoteUnder(T,P);ft().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0)};$.onclick=()=>void q(),o.addEventListener("keydown",T=>{let f=this.modeEnterSubmits;if(o.value.length===0){let P=ft().bindings;if(rt(T,P.undo)){T.preventDefault(),T.stopPropagation(),T.stopImmediatePropagation(),this.cmdUndo();return}if(rt(T,P.redo)){T.preventDefault(),T.stopPropagation(),T.stopImmediatePropagation(),this.cmdRedo();return}}if(T.key==="Escape"){T.preventDefault(),T.stopPropagation(),o.blur(),this.viewRoot.focus({preventScroll:!0});return}if(T.key==="ArrowUp"&&o.selectionStart===0&&o.selectionEnd===0){T.preventDefault(),o.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0&&(this.cursorIdx=this.currentChildren.length-1,this.selectCursor(!1));return}T.key==="Enter"&&!T.isComposing&&(f?!T.shiftKey:T.shiftKey)&&(T.preventDefault(),T.stopPropagation(),T.stopImmediatePropagation(),q())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(s,i))}composerPlaceholder(t,e){return O.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 s=t?"Enter":"Shift+Enter",i=t?"Shift+Enter":"Enter",r=ft().bindings,n=h=>{let d=r[h];return d.primary&&d.secondary?d.preferRight?d.secondary:d.primary:d.primary||d.secondary},a=Se(n("toggleSplit")),o=Se(n("pickDestination")),c=Se(n("search")),l=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${s} sends \xB7 ${i} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${o} destination \xB7 ${c} search${l}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestination===V)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(V),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let s=t.target,i=s?.closest?.(".tag");if(i){t.preventDefault(),t.stopPropagation();let a=(i.getAttribute("href")||i.textContent||"").replace(/^#/,"").trim();if(a){let o=this.app.internalPlugins?.plugins?.["global-search"],c=o?.instance?.openGlobalSearch?.bind(o.instance);c&&c(`tag:#${a}`)}return}let r=s?.closest?.(".internal-link");if(r){t.preventDefault(),t.stopPropagation();let n=r.getAttribute("data-href")||r.getAttribute("href");if(n){let a=e.file?.path||"";this.app.workspace.openLinkText(n,a,!0)}}}handleRowClick(t,e,s){let i=t.target,r=i?.closest?.(".tag");if(r){t.preventDefault(),t.stopPropagation();let c=(r.getAttribute("href")||r.textContent||"").replace(/^#/,"").trim();if(c){let l=this.app.internalPlugins?.plugins?.["global-search"],h=l?.instance?.openGlobalSearch?.bind(l.instance);h&&h(`tag:#${c}`)}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 c=s.file?.path||"";this.app.workspace.openLinkText(o,c,!0)}return}if(i?.tagName==="A"&&i.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}this.cursorIdx=e;let a=this.selection.size===0;if(t.shiftKey&&this.lastSelected){let o=this.currentChildren.findIndex(c=>c.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),o!==-1){let[c,l]=o{let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let s=this.listEl,i=s.getBoundingClientRect(),r=e.getBoundingClientRect(),n=4;r.topi.bottom-n&&(s.scrollTop+=r.bottom-i.bottom+n)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}selectCursor(t){let e=this.currentChildren[this.cursorIdx];e&&(t||this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id,this.render(),this.revealCursorRow())}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]:[]}toggleSplit(){let t=this.modeSplit??ft().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(){new xt(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:t=>{this.nextDestination=t.id,this.render(),this.composerInputEl?.focus()},onCreate:async t=>{let e=await this.createNoteUnder(t,this.focusId);e&&(this.nextDestination=e,this.render(),this.composerInputEl?.focus())}}).open()}openSearchInParentModal(){let t=this.focusId,e=i=>{if(i===t)return!0;let r=this.tree.get(i);for(;r&&r.id!==V;){if(r.parent===t||r.id===t)return!0;if(!r.parent)return!1;r=this.tree.get(r.parent)}return t===V},s=new Proxy(this.tree,{get:(i,r)=>r==="getRoot"?()=>i.get(t)??i.getRoot():r==="getChildren"?n=>i.getChildren(n):i[r]});new xt(this.app,s,i=>this.titleForNode(i),{mode:"search",placeholder:`Search in "${this.titleForNode(this.tree.get(t)??this.tree.getRoot()).trim()}"\u2026`,allowCreate:!1,onPick:i=>{i.node&&e(i.node.id)?this.navigateTo(i.node.id):i.node&&this.navigateTo(i.node.id)}}).open()}openSearchModal(){new xt(this.app,this.tree,t=>this.titleForNode(t),{mode:"search",placeholder:"Search Stashpad notes\u2026",allowCreate:!1,onPick:t=>{if(t.crossFolder&&t.crossFile){let e=t.id.replace(/^cross:/,"");this.switchToFolderAndFocus(t.crossFolder,e);return}t.node&&this.navigateTo(t.node.id)},crossFolderNotes:()=>this.collectCrossFolderNotes()}).open()}collectCrossFolderNotes(){let t=[],e=this.plugin.searchableFolders(this.noteFolder).filter(r=>r!==this.noteFolder);if(!e.length)return t;let s=new Set(e),i=new Map;for(let r of this.app.vault.getMarkdownFiles()){let n=r.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(n))continue;let a=i.get(n);a||(a=[],i.set(n,a)),a.push(r)}for(let r of e){let n=i.get(r)??[],a=new Map;for(let o of n){let c=this.app.metadataCache.getFileCache(o)?.frontmatter;typeof c?.id=="string"&&a.set(c.id,o)}for(let o of n){let c=this.app.metadataCache.getFileCache(o)?.frontmatter,l=typeof c?.id=="string"?c.id:"";if(!l)continue;let h=o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),d,v=c?.parent??null;if(v&&v!==V){let u=a.get(v);u&&(d=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}t.push({file:o,folder:r,id:l,title:h,body:"",parentBlurb:d})}}return t}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=[],s=[];for(let i of t){let r=i.parent?this.tree.get(i.parent):null;if(!r||r.id===V){s.push(i.id);continue}let n=r.parent??V;await this.changeParent(i,n),e.push(i)}if(e.length===0){new O.Notice(s.length?"Already at the top level.":"Nothing to outdent.");return}this.render(),s.length&&new O.Notice(`Outdented ${e.length} note${e.length===1?"":"s"} (${s.length} already at root).`)}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(r=>this.colorForNode(r)??"")),s=e.size===1&&Array.from(e)[0]||null,i=this.plugin.settings.customPalette??[];new _t(this.app,s,i,async(r,n)=>{for(let a of t)if(a.file)try{await this.app.fileManager.processFrontMatter(a.file,o=>{r?o.color=r:delete o.color})}catch(o){new O.Notice(`Couldn't set color for ${a.id}: ${o.message}`)}if(n.addToPalette&&typeof r=="string"){let a=[...this.plugin.settings.customPalette??[]],o=r.toLowerCase();a.some(c=>c.toLowerCase()===o)||(a.push(r),this.plugin.settings.customPalette=a,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:V,payload:{color:r}}))}this.render()},async r=>{let n=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==r.toLowerCase());return this.plugin.settings.customPalette=n,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:V,payload:{color:r}}),n}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new xt(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let i=e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,i),this.selection.clear(),this.render();return}let s=e.id;for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render()},onCreate:async e=>{let s=await this.createNoteUnder(e,this.focusId);if(s){for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render()}},crossFolderNotes:()=>this.collectCrossFolderNotes()}).open()}async moveAcrossFolders(t,e,s){if(!t.length)return;let i=(e||"").replace(/\/+$/,"");if(!i){new O.Notice("Target folder is empty");return}let r=[],n=new Set;for(let o of this.app.vault.getMarkdownFiles())(o.parent?.path?.replace(/\/+$/,"")??"")===i&&n.add(o.path);let a=(o,c)=>{if(!o.file)return;let l=o.file,h=`${i}/${l.name}`;if(n.has(h)){let d=l.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),v=d?d[1]:l.basename,u=d?d[2]:"";for(let y=1;y<1e3;y++){let w=`${v}-${y}${u}.md`,b=`${i}/${w}`;if(!n.has(b)){h=b;break}}}n.add(h),r.push({id:o.id,file:l,oldPath:l.path,newPath:h,oldParent:o.parent,isRoot:c});for(let d of this.tree.getChildren(o.id))a(d,!1)};for(let o of t)a(o,!0);if(r.length){await this.ensureFolder(i);for(let o of r)try{await this.app.fileManager.renameFile(o.file,o.newPath),o.isRoot&&await this.app.fileManager.processFrontMatter(o.file,c=>{c.parent=s}),await this.log.append({type:"parent_change",id:o.id,payload:{from:o.oldParent,to:o.isRoot?s:o.oldParent,crossFolder:{from:this.noteFolder,to:i}}})}catch(c){new O.Notice(`Move failed for ${o.id}: ${c.message}`)}this.tree.rebuild(this.noteFolder),new O.Notice(`Moved ${t.length} note${t.length===1?"":"s"} \u2192 ${i}`),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${r.length})`,undo:async()=>{for(let o of r){let c=this.app.vault.getAbstractFileByPath(o.newPath);if(c)try{await this.app.fileManager.renameFile(c,o.oldPath),o.isRoot&&await this.app.fileManager.processFrontMatter(c,l=>{l.parent=o.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let o of r){let c=this.app.vault.getAbstractFileByPath(o.oldPath);if(c)try{await this.app.fileManager.renameFile(c,o.newPath),o.isRoot&&await this.app.fileManager.processFrontMatter(c,l=>{l.parent=s})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;this.inListPicker={activeIdx:t},new O.Notice("Arrows to pick parent, Enter confirms, Esc cancels.");let e=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let s=this.listEl;s.scrollTop=e,requestAnimationFrame(()=>{s.scrollTop=e}),setTimeout(()=>{s.scrollTop=e},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(s=>s.id!==t.id);for(let s of e)await this.changeParent(s,t.id);this.selection.clear(),this.render()}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new O.Notice("Select 2+ notes to merge.");return}t.sort((u,y)=>(u.created||"").localeCompare(y.created||""));let e=t[0];if(!e.file)return;let s=e.file.path,i=await this.app.vault.read(e.file),r=await this.snapshotNotes(t.slice(1),!1),n=[],a=[];for(let u of t){if(!u.file)continue;let y=await this.app.vault.cachedRead(u.file);a.push(this.stripFrontmatter(y).trim())}let o=a.map(u=>u.trim()).filter(Boolean).join(` -`),c=await this.app.vault.read(e.file),l=c.startsWith("---")?c.indexOf(` ----`,3)+4:0,d=`${c.slice(0,l)} +`:"";o.value+=`${m}${F} +`,this.composerDraft=o.value},P=b.createEl("button",{cls:"stashpad-composer-btn"});if((0,A.setIcon)(P,"paperclip"),P.title="Attach files",P.onmousedown=F=>F.preventDefault(),P.onclick=F=>{F.preventDefault();let m=document.activeElement===o;if(y.click(),m){let M=()=>{o.focus()};setTimeout(M,100),setTimeout(M,500)}},y.addEventListener("change",async()=>{let F=Array.from(y.files??[]);y.value="";for(let m of F){let M=await this.importAttachment(m);M&&R(M)}o.focus()}),A.Platform.isMobile){let F=w.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-rail-toggle"});(0,A.setIcon)(F,"chevron-left"),F.title="Show more composer options",w.insertBefore(F,b);let m=M=>{w.toggleClass("is-expanded",M),F.title=M?"Hide options":"Show more composer options",(0,A.setIcon)(F,M?"chevron-right":"chevron-left")};F.onmousedown=M=>M.preventDefault(),F.onclick=M=>{M.preventDefault(),m(!w.hasClass("is-expanded"))},m(!1)}let $=w.createEl("button",{cls:"stashpad-composer-btn stashpad-composer-send"});$.title="Send (Enter)",(0,A.setIcon)($,"arrow-up");let Y=async()=>{let F=o.value.trim();if(!F)return;o.value="",this.composerDraft="";try{await this.saveDraft("")}catch{}try{await this.recordLastSubmitted(F)}catch{}let m=this.modeSplit??ft().splitOnLines,M=this.nextDestination;if(this.nextDestination=null,this.autoSelectNewest=!0,this.scrollToBottomOnNextRender=!0,m)for(let G of F.split(/\r?\n/)){let z=G.trim();z&&await this.createNoteUnder(z,M)}else await this.createNoteUnder(F,M);ft().autofocusComposerAfterSend&&(this.focusComposerOnNextRender=!0)};$.onclick=()=>void Y(),o.addEventListener("keydown",F=>{let m=this.modeEnterSubmits;if(o.value.length===0){let M=ft().bindings;if(rt(F,M.undo)){F.preventDefault(),F.stopPropagation(),F.stopImmediatePropagation(),this.cmdUndo();return}if(rt(F,M.redo)){F.preventDefault(),F.stopPropagation(),F.stopImmediatePropagation(),this.cmdRedo();return}}if(F.key==="Escape"){F.preventDefault(),F.stopPropagation(),o.blur(),this.viewRoot.focus({preventScroll:!0});return}if(F.key==="ArrowUp"&&o.selectionStart===0&&o.selectionEnd===0){F.preventDefault(),o.blur(),this.viewRoot.focus({preventScroll:!0}),this.currentChildren.length>0&&(this.cursorIdx=this.currentChildren.length-1,this.selectCursor(!1));return}F.key==="Enter"&&!F.isComposing&&(m?!F.shiftKey:F.shiftKey)&&(F.preventDefault(),F.stopPropagation(),F.stopImmediatePropagation(),Y())}),t.createDiv({cls:"stashpad-composer-help"}).setText(this.composerHelperText(s,i))}composerPlaceholder(t,e){return A.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 s=t?"Enter":"Shift+Enter",i=t?"Shift+Enter":"Enter",r=ft().bindings,n=d=>{let h=r[d];return h.primary&&h.secondary?h.preferRight?h.secondary:h.primary:h.primary||h.secondary},a=xe(n("toggleSplit")),o=xe(n("pickDestination")),l=xe(n("search")),c=this.nextDestination?` \u2022 destination: ${this.destinationLabel()}`:"";return`${s} sends \xB7 ${i} newline \xB7 ${a} split: ${e?"ON":"off"} \xB7 ${o} destination \xB7 ${l} search${c}`}destinationLabel(){if(!this.nextDestination)return"current";if(this.nextDestination===j)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(j),e.createEl("button",{text:"Back"}).onclick=()=>this.navigateUp(),e.createEl("button",{text:"Bookmarks"}).onclick=()=>this.openBookmarks()}handleRenderedClick(t,e){let s=t.target,i=s?.closest?.(".tag");if(i){t.preventDefault(),t.stopPropagation();let a=(i.getAttribute("href")||i.textContent||"").replace(/^#/,"").trim();if(a){let o=this.app.internalPlugins?.plugins?.["global-search"],l=o?.instance?.openGlobalSearch?.bind(o.instance);l&&l(`tag:#${a}`)}return}let r=s?.closest?.(".internal-link");if(r){t.preventDefault(),t.stopPropagation();let n=r.getAttribute("data-href")||r.getAttribute("href");if(n){let a=e.file?.path||"";this.app.workspace.openLinkText(n,a,!0)}}}handleRowClick(t,e,s){let i=t.target,r=i?.closest?.(".tag");if(r){t.preventDefault(),t.stopPropagation();let l=(r.getAttribute("href")||r.textContent||"").replace(/^#/,"").trim();if(l){let c=this.app.internalPlugins?.plugins?.["global-search"],d=c?.instance?.openGlobalSearch?.bind(c.instance);d&&d(`tag:#${l}`)}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 l=s.file?.path||"";this.app.workspace.openLinkText(o,l,!0)}return}if(i?.tagName==="A"&&i.href)return;if(t.stopPropagation(),this.inListPicker){this.inListPicker.activeIdx=e,this.commitInListPicker();return}this.cursorIdx=e;let a=this.selection.size===0;if(t.shiftKey&&this.lastSelected){let o=this.currentChildren.findIndex(l=>l.id===this.lastSelected);if(a&&(this.firstSelectedId=this.lastSelected),o!==-1){let[l,c]=o{let e=this.listEl?.querySelector(`[data-idx="${this.cursorIdx}"]`);if(!e||!this.listEl)return;let s=this.listEl,i=s.getBoundingClientRect(),r=e.getBoundingClientRect(),n=4;r.topi.bottom-n&&(s.scrollTop+=r.bottom-i.bottom+n)};t(),requestAnimationFrame(t),setTimeout(t,60),setTimeout(t,200)}selectCursor(t){let e=this.currentChildren[this.cursorIdx];e&&(t||this.selection.clear(),this.selection.add(e.id),this.lastSelected=e.id,this.render(),this.revealCursorRow())}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]:[]}toggleSplit(){let t=this.modeSplit??ft().splitOnLines;this.modeSplit=!t,this.render(),this.composerInputEl?.focus()}openDestinationPicker(){new Ft(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Send next note(s) under which note?",allowCreate:!0,onPick:t=>{this.nextDestination=t.id,this.render(),this.composerInputEl?.focus()},onCreate:async t=>{let e=await this.createNoteUnder(t,this.focusId);e&&(this.nextDestination=e,this.render(),this.composerInputEl?.focus())}}).open()}openSearchInParentModal(){let t=this.focusId,e=i=>{if(i===t)return!0;let r=this.tree.get(i);for(;r&&r.id!==j;){if(r.parent===t||r.id===t)return!0;if(!r.parent)return!1;r=this.tree.get(r.parent)}return t===j},s=new Proxy(this.tree,{get:(i,r)=>r==="getRoot"?()=>i.get(t)??i.getRoot():r==="getChildren"?n=>i.getChildren(n):i[r]});new Ft(this.app,s,i=>this.titleForNode(i),{mode:"search",placeholder:`Search in "${this.titleForNode(this.tree.get(t)??this.tree.getRoot()).trim()}"\u2026`,allowCreate:!1,onPick:i=>{i.node&&e(i.node.id)?this.navigateTo(i.node.id):i.node&&this.navigateTo(i.node.id)}}).open()}openSearchModal(){new Ft(this.app,this.tree,t=>this.titleForNode(t),{mode:"search",placeholder:"Search Stashpad notes\u2026",allowCreate:!1,onPick:t=>{if(t.crossFolder&&t.crossFile){let e=t.id.replace(/^cross:/,"");this.switchToFolderAndFocus(t.crossFolder,e);return}t.node&&this.navigateTo(t.node.id)},crossFolderNotes:()=>this.collectCrossFolderNotes()}).open()}collectCrossFolderNotes(){let t=[],e=this.plugin.searchableFolders(this.noteFolder).filter(r=>r!==this.noteFolder);if(!e.length)return t;let s=new Set(e),i=new Map;for(let r of this.app.vault.getMarkdownFiles()){let n=r.parent?.path?.replace(/\/+$/,"")??"";if(!s.has(n))continue;let a=i.get(n);a||(a=[],i.set(n,a)),a.push(r)}for(let r of e){let n=i.get(r)??[],a=new Map;for(let o of n){let l=this.app.metadataCache.getFileCache(o)?.frontmatter;typeof l?.id=="string"&&a.set(l.id,o)}for(let o of n){let l=this.app.metadataCache.getFileCache(o)?.frontmatter,c=typeof l?.id=="string"?l.id:"";if(!c)continue;let d=o.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "),h,g=l?.parent??null;if(g&&g!==j){let u=a.get(g);u&&(h=u.basename.replace(/-[a-z0-9]{4,12}$/,"").replace(/-/g," "))}t.push({file:o,folder:r,id:c,title:d,body:"",parentBlurb:h})}}return t}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=[],s=[];for(let i of t){let r=i.parent?this.tree.get(i.parent):null;if(!r||r.id===j){s.push(i.id);continue}let n=r.parent??j;await this.changeParent(i,n),e.push(i)}if(e.length===0){new A.Notice(s.length?"Already at the top level.":"Nothing to outdent.");return}this.render(),s.length&&new A.Notice(`Outdented ${e.length} note${e.length===1?"":"s"} (${s.length} already at root).`)}cmdSetColor(){let t=this.getActionTargets();if(!t.length)return;let e=new Set(t.map(r=>this.colorForNode(r)??"")),s=e.size===1&&Array.from(e)[0]||null,i=this.plugin.settings.customPalette??[];new It(this.app,s,i,async(r,n)=>{for(let a of t)if(a.file)try{await this.app.fileManager.processFrontMatter(a.file,o=>{r?o.color=r:delete o.color})}catch(o){new A.Notice(`Couldn't set color for ${a.id}: ${o.message}`)}if(n.addToPalette&&typeof r=="string"){let a=[...this.plugin.settings.customPalette??[]],o=r.toLowerCase();a.some(l=>l.toLowerCase()===o)||(a.push(r),this.plugin.settings.customPalette=a,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_add",id:j,payload:{color:r}}))}this.render()},async r=>{let n=(this.plugin.settings.customPalette??[]).filter(a=>a.toLowerCase()!==r.toLowerCase());return this.plugin.settings.customPalette=n,await this.plugin.persistSettingsQuiet(),await this.log.append({type:"palette_color_remove",id:j,payload:{color:r}}),n}).open()}cmdMovePicker(){let t=this.getActionTargets();t.length&&new Ft(this.app,this.tree,e=>this.titleForNode(e),{mode:"pick",placeholder:"Move to which note?",allowCreate:!0,onPick:async e=>{if(e.crossFolder){let i=e.id.replace(/^cross:/,"");await this.moveAcrossFolders(t,e.crossFolder,i),this.selection.clear(),this.render();return}let s=e.id;for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render()},onCreate:async e=>{let s=await this.createNoteUnder(e,this.focusId);if(s){for(let i of t)await this.changeParent(i,s);this.selection.clear(),this.render()}},crossFolderNotes:()=>this.collectCrossFolderNotes()}).open()}async moveAcrossFolders(t,e,s){if(!t.length)return;let i=(e||"").replace(/\/+$/,"");if(!i){new A.Notice("Target folder is empty");return}let r=[],n=new Set;for(let o of this.app.vault.getMarkdownFiles())(o.parent?.path?.replace(/\/+$/,"")??"")===i&&n.add(o.path);let a=(o,l)=>{if(!o.file)return;let c=o.file,d=`${i}/${c.name}`;if(n.has(d)){let h=c.basename.match(/^(.*)(-[a-z0-9]{4,12})$/),g=h?h[1]:c.basename,u=h?h[2]:"";for(let y=1;y<1e3;y++){let w=`${g}-${y}${u}.md`,b=`${i}/${w}`;if(!n.has(b)){d=b;break}}}n.add(d),r.push({id:o.id,file:c,oldPath:c.path,newPath:d,oldParent:o.parent,isRoot:l});for(let h of this.tree.getChildren(o.id))a(h,!1)};for(let o of t)a(o,!0);if(r.length){await this.ensureFolder(i);for(let o of r)try{await this.app.fileManager.renameFile(o.file,o.newPath),o.isRoot&&await this.app.fileManager.processFrontMatter(o.file,l=>{l.parent=s}),await this.log.append({type:"parent_change",id:o.id,payload:{from:o.oldParent,to:o.isRoot?s:o.oldParent,crossFolder:{from:this.noteFolder,to:i}}})}catch(l){new A.Notice(`Move failed for ${o.id}: ${l.message}`)}this.tree.rebuild(this.noteFolder),new A.Notice(`Moved ${t.length} note${t.length===1?"":"s"} \u2192 ${i}`),this.plugin.getUndoStack(this.noteFolder).push({label:`Cross-Stashpad move (${r.length})`,undo:async()=>{for(let o of r){let l=this.app.vault.getAbstractFileByPath(o.newPath);if(l)try{await this.app.fileManager.renameFile(l,o.oldPath),o.isRoot&&await this.app.fileManager.processFrontMatter(l,c=>{c.parent=o.oldParent})}catch{}}this.tree.rebuild(this.noteFolder),this.render()},redo:async()=>{for(let o of r){let l=this.app.vault.getAbstractFileByPath(o.oldPath);if(l)try{await this.app.fileManager.renameFile(l,o.newPath),o.isRoot&&await this.app.fileManager.processFrontMatter(l,c=>{c.parent=s})}catch{}}this.tree.rebuild(this.noteFolder),this.render()}})}}cmdInListPicker(){if(this.currentChildren.length===0)return;let t=this.cursorIdx>0?this.cursorIdx-1:0;this.inListPicker={activeIdx:t},new A.Notice("Arrows to pick parent, Enter confirms, Esc cancels.");let e=this.listEl?.scrollTop??0;if(this.render(),this.listEl){let s=this.listEl;s.scrollTop=e,requestAnimationFrame(()=>{s.scrollTop=e}),setTimeout(()=>{s.scrollTop=e},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(s=>s.id!==t.id);for(let s of e)await this.changeParent(s,t.id);this.selection.clear(),this.render()}async cmdMerge(){let t=this.getActionTargets();if(t.length<2){new A.Notice("Select 2+ notes to merge.");return}t.sort((u,y)=>(u.created||"").localeCompare(y.created||""));let e=t[0];if(!e.file)return;let s=e.file.path,i=await this.app.vault.read(e.file),r=await this.snapshotNotes(t.slice(1),!1),n=[],a=[];for(let u of t){if(!u.file)continue;let y=await this.app.vault.cachedRead(u.file);a.push(this.stripFrontmatter(y).trim())}let o=a.map(u=>u.trim()).filter(Boolean).join(` +`),l=await this.app.vault.read(e.file),c=l.startsWith("---")?l.indexOf(` +---`,3)+4:0,h=`${l.slice(0,c)} ${o} -`;await this.app.vault.modify(e.file,d);for(let u=1;u{await this.restoreSnapshots(r);let u=this.app.vault.getAbstractFileByPath(s);u&&await this.app.vault.modify(u,i);for(let y of n){let w=this.app.vault.getAbstractFileByPath(y.childPath);w&&await this.app.fileManager.processFrontMatter(w,b=>{b.parent=y.oldParent})}this.tree.rebuild(v),this.render()},redo:async()=>{await this.trashNotesAndAttachments(r);let u=this.app.vault.getAbstractFileByPath(s);u&&await this.app.vault.modify(u,d);for(let y of n){let w=this.app.vault.getAbstractFileByPath(y.childPath);w&&await this.app.fileManager.processFrontMatter(w,b=>{b.parent=e.id})}this.tree.rebuild(v),this.render()}})}async cmdCopy(){let t=this.getActionTargets();if(!t.length)return;let e=ft().prefixTimestampsOnCopy,s=[];for(let i of t){if(!i.file)continue;let r=await this.app.vault.cachedRead(i.file),n=this.stripFrontmatter(r).trim();s.push(e?`${this.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(s.join(` +`;await this.app.vault.modify(e.file,h);for(let u=1;u{await this.restoreSnapshots(r);let u=this.app.vault.getAbstractFileByPath(s);u&&await this.app.vault.modify(u,i);for(let y of n){let w=this.app.vault.getAbstractFileByPath(y.childPath);w&&await this.app.fileManager.processFrontMatter(w,b=>{b.parent=y.oldParent})}this.tree.rebuild(g),this.render()},redo:async()=>{await this.trashNotesAndAttachments(r);let u=this.app.vault.getAbstractFileByPath(s);u&&await this.app.vault.modify(u,h);for(let y of n){let w=this.app.vault.getAbstractFileByPath(y.childPath);w&&await this.app.fileManager.processFrontMatter(w,b=>{b.parent=e.id})}this.tree.rebuild(g),this.render()}})}async cmdCopy(){let t=this.getActionTargets();if(!t.length)return;let e=ft().prefixTimestampsOnCopy,s=[];for(let i of t){if(!i.file)continue;let r=await this.app.vault.cachedRead(i.file),n=this.stripFrontmatter(r).trim();s.push(e?`${this.formatTimeInline(i.created)} ${n}`:n)}await navigator.clipboard.writeText(s.join(` -`)),new O.Notice(`Copied ${t.length} note(s).`)}async cmdCopyTree(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new O.Notice("Nothing to copy.");return}let e=ft().prefixTimestampsOnCopy,s=[],i=async(r,n)=>{if(r.file){let a=await this.app.vault.cachedRead(r.file),o=this.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),c=e?`${this.formatTimeInline(r.created)} `:"";s.push(`${" ".repeat(n)}- ${c}${o}`)}for(let a of this.tree.getChildren(r.id))await i(a,n+1)};for(let r of t)await i(r,0);await navigator.clipboard.writeText(s.join(` -`)),new O.Notice(`Copied tree (${s.length} entries).`)}async cmdCopyOutline(){let t=this.getActionTargets();if(t.length===0){let i=this.tree.get(this.focusId);i?.file&&(t=[i])}if(t.length===0){new O.Notice("Nothing to copy.");return}let e=[],s=(i,r)=>{if(!i.file)return;let n=" ".repeat(r);e.push(`${n}- ![[${i.file.basename}]]`);for(let a of this.tree.getChildren(i.id))s(a,r+1)};for(let i of t)s(i,0);await navigator.clipboard.writeText(e.join(` -`)),new O.Notice(`Copied outline (${e.length} entr${e.length===1?"y":"ies"}).`)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(s=>!this.expandedNotes.has(s.id));for(let s of t)e?this.expandedNotes.add(s.id):this.expandedNotes.delete(s.id);this.render()}async cloneSubtree(t,e,s){if(!t.file)return null;let i=t.file,r=await this.app.vault.read(i),n=this.stripFrontmatter(r),a=this.app.metadataCache.getFileCache(i)?.frontmatter??{},o=bt(),c=Vt(n,this.activeStopwords()),l=Kt(c,o),h=`${this.noteFolder}/${l}`,d=new Date().toISOString(),v=this.extractAttachments(n),u=["---",`id: ${o}`,`parent: ${e}`,`created: ${d}`];if(v.length>0){u.push("attachments:");for(let w of v)u.push(` - "${w.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",n),await this.ensureFolder(this.noteFolder),await this.app.vault.create(h,u.join(` -`)),s.push(h);let y=this.app.vault.getAbstractFileByPath(h);if(y){try{await this.app.fileManager.processFrontMatter(y,w=>{for(let[b,C]of Object.entries(a))b==="id"||b==="parent"||b==="created"||b==="attachments"||b==="position"||(w[b]=C)})}catch(w){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",w)}try{this.tree.insertSynthetic({id:o,parent:e,children:[],file:y,created:d})}catch{}}for(let w of this.tree.getChildren(t.id))await this.cloneSubtree(w,o,s);return o}async cmdClone(){let t=this.getActionTargets();if(!t.length){new O.Notice("Nothing to clone.");return}let e=this.noteFolder,s=[],i=[];for(let a of t){if(!a.file)continue;let o=a.parent??this.focusId,c=await this.cloneSubtree(a,o,s);c&&i.push(c)}if(!i.length)return;this.tree.rebuild(e),this.pendingFocusIds=i.slice(),this.render();let r=s.map(a=>this.app.vault.getAbstractFileByPath(a)).filter(a=>!!a&&a.extension==="md").map(a=>({id:Yt(a.basename)??a.basename,parent:null,children:[],file:a,created:new Date().toISOString()})),n=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(e).push({label:`Clone ${i.length} note${i.length===1?"":"s"}`,undo:async()=>{for(let a of[...s].reverse()){let o=this.app.vault.getAbstractFileByPath(a);if(o)try{await this.app.fileManager.trashFile(o)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(n,i)}}),new O.Notice(`Cloned ${i.length} note${i.length===1?"":"s"} (${s.length} file${s.length===1?"":"s"}).`)}cmdInsertTemplate(){new xt(this.app,this.tree,t=>this.titleForNode(t),{mode:"pick",placeholder:"Insert which note as a template?",allowCreate:!1,onPick:async t=>{if(t.crossFolder){new O.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 s=this.noteFolder,i=[],r=await this.cloneSubtree(e,this.focusId,i);if(!r)return;this.tree.rebuild(s),this.pendingFocusIds=[r],this.render();let n=i.map(o=>this.app.vault.getAbstractFileByPath(o)).filter(o=>!!o&&o.extension==="md").map(o=>({id:Yt(o.basename)??o.basename,parent:null,children:[],file:o,created:new Date().toISOString()})),a=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(s).push({label:"Insert template",undo:async()=>{for(let o of[...i].reverse()){let c=this.app.vault.getAbstractFileByPath(o);if(c)try{await this.app.fileManager.trashFile(c)}catch{}}this.tree.rebuild(s),this.render()},redo:async()=>{await this.restoreSnapshots(a,[r])}}),new O.Notice(`Inserted template (${i.length} file${i.length===1?"":"s"}).`)}}).open()}navigateTo(t,e={}){if(this.listEl&&this.scrollByFocus.set(this.focusId,this.listEl.scrollTop),e.keepForwardStack||(this.navForwardStack=[]),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.pendingScrollRestore=this.scrollByFocus.get(t)??null,this.tagFilter){let s=this.tagFilter.toLowerCase();this.collectFolderTags().some(r=>r.raw.toLowerCase()===s)||(this.tagFilter=null)}if(this.colorFilter){let s=this.colorFilter.toLowerCase();this.collectFolderColors().some(r=>r.hex===s)||(this.colorFilter=null)}this.render(),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateBack(){this.navigateUp()}navigateForward(){let t=this.navForwardStack.pop();t&&this.tree.get(t)&&(this.tagFilter=null,this.colorFilter=null,this.navigateTo(t,{keepForwardStack:!0}))}navigateUp(){this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null)return this.navigateTo(V);let e=this.focusId;this.navForwardStack.push(e),this.listEl&&this.scrollByFocus.set(e,this.listEl.scrollTop),this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus(),this.pendingScrollRestore=this.scrollByFocus.get(this.focusId)??null;let s=this.filterChildren(this.tree.getChildren(this.focusId)),i=s.findIndex(r=>r.id===e);this.selection.clear(),i>=0?(this.cursorIdx=i,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=s.length-1,s.length>0&&(this.selection.add(s[s.length-1].id),this.lastSelected=s[s.length-1].id)),this.render(),this.refreshHeaderTitle(),this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),s=new O.Menu,i=0;for(let r of t){if(r.type!=="file"||e&&!e.has(r.path))continue;let n=this.tree.idForPath(r.path);n&&(s.addItem(a=>a.setTitle(r.title||r.path).onClick(()=>this.navigateTo(n))),i++)}i||s.addItem(r=>r.setTitle("(no bookmarks in scope)").setDisabled(!0)),s.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)}async ensureHomeNote(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(n=>n.path.startsWith(t+"/"));for(let n of e)if(this.app.metadataCache.getFileCache(n)?.frontmatter?.id===V)return n;let s=`${t}/home-${V}.md`,i=new Date().toISOString(),r=["---",`id: ${V}`,"parent: null",`created: ${i}`,"attachments: []","---","","# Home","","This is your Stashpad home note. Edit me freely \u2014 everything else nests below.",""].join(` -`);return this.app.vault.create(s,r)}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(s=>s.path.startsWith(t+"/"));for(let s of e){let i=this.app.metadataCache.getFileCache(s)?.frontmatter,r=i?.id;if(!r||r===V)continue;let n=i?.parent;(n==null||n===""||n==="null")&&(await this.app.fileManager.processFrontMatter(s,a=>{a.parent=V}),await this.log.append({type:"parent_change",id:r,payload:{from:null,to:V,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace.getLeaf("tab");await e.setViewState({type:kt,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),this.app.workspace.revealLeaf(e)}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let s of e)s.file&&this.openFileAtEnd(s.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new O.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,s=this.leaf,i=e.getLeaf("tab");await i.openFile(t,{active:!0}),e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i);let r=e.on("active-leaf-change",()=>{if((()=>{let l=!1;return e.iterateAllLeaves(h=>{h===i&&(l=!0)}),l})())return;e.offref(r),(()=>{let l=!1;return e.iterateAllLeaves(h=>{h===s&&(l=!0)}),l})()&&(e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s))}),a=i.view?.editor;a&&requestAnimationFrame(()=>{try{let o=a.lastLine(),c=a.getLine(o)?.length??0;a.setCursor({line:o,ch:c}),a.scrollIntoView({from:{line:o,ch:c},to:{line:o,ch:c}},!0),a.focus()}catch{}})}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 O.Notice("Nothing to toggle.");return}let s=t.some(a=>!this.isCompleted(a)),i=[],r=[];for(let a of t){if(!a.file)continue;let o=this.isCompleted(a);i.push({id:a.id,path:a.file.path,was:o}),o!==s&&(await this.app.fileManager.processFrontMatter(a.file,c=>{s?c.completed=!0:delete c.completed}),r.push(a.id))}this.render(),r.length>0&&(await this.log.append({type:s?"complete":"uncomplete",id:r[0],payload:{ids:r,count:r.length}}),new O.Notice(`${s?"Marked complete":"Unmarked"} (${r.length})`));let n=this.noteFolder;this.plugin.getUndoStack(n).push({label:`${s?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let o of i){let c=this.app.vault.getAbstractFileByPath(o.path);c&&(await this.app.fileManager.processFrontMatter(c,l=>{o.was?l.completed=!0:delete l.completed}),r.includes(o.id)&&a.push(o.id))}a.length>0&&await this.log.append({type:s?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(n),this.render()},redo:async()=>{for(let a of i){let o=this.app.vault.getAbstractFileByPath(a.path);o&&await this.app.fileManager.processFrontMatter(o,c=>{s?c.completed=!0:delete c.completed})}r.length>0&&await this.log.append({type:s?"complete":"uncomplete",id:r[0],payload:{ids:r,count:r.length,redo:!0}}),this.tree.rebuild(n),this.render()}})}isCompleted(t){return t.file?!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed:!1}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let s=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s)?s:null}attachRowDnD(t,e,s){t.addEventListener("dragstart",i=>{let r=this.selection.has(e.id)&&this.selection.size>1?[...this.selection]:[e.id];if(this.dragSourceIds=r,this.dragRowHeight=t.offsetHeight,t.addClass("is-dragging"),this.listEl&&(this.dragPlaceholder=this.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 a=this.dragSourceIds.slice();this.dragSourceIds=null;let o=this.dragPlaceholder.nextElementSibling,c=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let l,h="before";o&&o.classList.contains("stashpad-note")?(l=o.dataset.id,h="before"):c&&c.classList.contains("stashpad-note")&&(l=c.dataset.id,h="after"),l&&this.reorderToTarget(a,l,h)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",r.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(t,12,12)}catch{}}}),t.addEventListener("dragend",()=>{t.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),t.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let r=this.dropZone(i,t);this.clearDropIndicators(),r==="drop-into"?(this.removeDragPlaceholder(),t.addClass("drop-into")):(t.removeClass("drop-into"),this.placePlaceholder(t,r==="drop-above"?"before":"after"))}),t.addEventListener("dragleave",i=>{let r=t.getBoundingClientRect();(i.clientXr.right||i.clientYr.bottom)&&t.removeClass("drop-into")}),t.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let r=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,t);this.clearDropIndicators(),this.removeDragPlaceholder(),t.removeClass("is-dragging"),n==="drop-into"?this.reorderToTarget(r,e.id,"into"):this.reorderToTarget(r,e.id,n==="drop-above"?"before":"after")})}placePlaceholder(t,e){if(!this.dragPlaceholder||!this.listEl)return;let s=e==="before"?t:t.nextSibling;if(e==="before"&&this.dragPlaceholder.nextSibling===t||e==="after"&&this.dragPlaceholder.previousSibling===t)return;let i=!!this.dragPlaceholder.parentElement;this.listEl.insertBefore(this.dragPlaceholder,s),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 t=this.dragPlaceholder;t.style.height="0px",t.style.opacity="0",setTimeout(()=>{t.parentElement&&t.remove()},150)}dropZone(t,e){let s=e.getBoundingClientRect(),i=t.clientY-s.top;return is.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.listEl)for(let t of Array.from(this.listEl.querySelectorAll(".drop-into")))t.removeClass("drop-into")}isDescendant(t,e){let s=this.tree.get(t),i=new Set;for(;s&&s.parent&&!i.has(s.id);){if(s.parent===e)return!0;i.add(s.id),s=this.tree.get(s.parent)}return!1}async moveAcrossThenReorder(t,e,s,i){let r=[],n=new Set;for(let u of t){let y=this.tree.get(u);y?.file&&(r.push({id:u,path:y.file.path,oldParent:y.parent}),n.add(y.parent??V))}n.add(e);let a=this.noteFolder,o={};for(let u of n)o[u]=this.order.getOrder(a,u).slice();for(let u of r){let y=this.app.vault.getAbstractFileByPath(u.path);y&&(await this.app.fileManager.processFrontMatter(y,w=>{w.parent=e}),await this.log.append({type:"parent_change",id:u.id,payload:{from:u.oldParent,to:e,reason:"drag"}}),this.order.removeChild(a,u.id))}this.tree.rebuild(a);let c=this.tree.getChildren(e).map(u=>u.id),l=new Set(t),h=c.filter(u=>!l.has(u)),d=h.indexOf(s);d<0&&(d=h.length),i==="after"&&(d+=1);let v=[...h.slice(0,d),...t.filter(u=>!!this.tree.get(u)),...h.slice(d)];this.order.setOrder(a,e,v),await this.order.save(a),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}}),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(a),this.render(),new O.Notice(`Reparented ${t.length} note${t.length===1?"":"s"}`),this.plugin.getUndoStack(a).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let u of r){let y=this.app.vault.getAbstractFileByPath(u.path);y&&(await this.app.fileManager.processFrontMatter(y,w=>{u.oldParent===null||u.oldParent===void 0?w.parent=V:w.parent=u.oldParent}),await this.log.append({type:"parent_change",id:u.id,payload:{from:e,to:u.oldParent,reason:"drag-undo"}}))}for(let[u,y]of Object.entries(o))if(y.length===0){let w=this.order.cache.get(a)??{};delete w[u],this.order.cache.set(a,w)}else this.order.setOrder(a,u,y);await this.order.save(a),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(a),this.render()},redo:async()=>{for(let u of r){let y=this.app.vault.getAbstractFileByPath(u.path);y&&(await this.app.fileManager.processFrontMatter(y,w=>{w.parent=e}),this.order.removeChild(a,u.id))}this.order.setOrder(a,e,v),await this.order.save(a),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(a),this.render()}})}async reorderToTarget(t,e,s){let i=this.tree.get(e);if(!i)return;let r=t.map(b=>this.tree.get(b)).filter(b=>!!b&&!!b.file);if(r.length===0||r.some(b=>b.id===e))return;if(s==="into"){for(let b of r)if(this.isDescendant(e,b.id)){new O.Notice("Can't nest a note under one of its own descendants.");return}}let n=s==="into"?e:i.parent??V;if(r.some(b=>(b.parent??V)!==n)){let b=ft(),C=async()=>{s==="into"?await this.moveAcrossThenReorder(r.map(E=>E.id),n,"","after"):await this.moveAcrossThenReorder(r.map(E=>E.id),n,e,s)};if(b.confirmCrossParentDrag){let E=this.titleForNode(i),I=r.length,N=s==="into"?"Nest":"Move",D=s==="into"?"as children of":"under";new Lt(this.app,s==="into"?"Nest under target?":"Move under different parent?",`${N} ${I} note${I===1?"":"s"} ${D} "${E}"? Their parent will change.`,N,$=>{$&&C()}).open()}else await C();return}let o=n,c=r.map(b=>b.id),l=this.tree.getChildren(o).map(b=>b.id),h=new Set(c),d=l.filter(b=>!h.has(b)),v=d.indexOf(e);if(v<0)return;s==="after"&&(v+=1);let u=[...d.slice(0,v),...c,...d.slice(v)];if(Ve(u,l))return;let y=this.noteFolder,w=this.order.getOrder(y,o).slice();this.order.setOrder(y,o,u),await this.order.save(y),await this.forceManualMode(o),await this.log.append({type:"reorder",id:o,payload:{dir:"drag",parent:o,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(y),this.render(),new O.Notice(`Reordered ${c.length} note${c.length===1?"":"s"}`),this.plugin.getUndoStack(y).push({label:`Reorder (drag, ${c.length})`,undo:async()=>{if(w.length===0){let b=this.order.cache.get(y)??{};delete b[o],this.order.cache.set(y,b)}else this.order.setOrder(y,o,w);await this.order.save(y),await this.log.append({type:"reorder",id:o,payload:{dir:"undo",parent:o,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(y),this.render()},redo:async()=>{this.order.setOrder(y,o,u),await this.order.save(y),await this.log.append({type:"reorder",id:o,payload:{dir:"redo:drag",parent:o,ids:c,count:c.length}}),this.pendingFocusIds=c.slice(),this.tree.rebuild(y),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 l=[...this.selection].map(d=>this.tree.get(d)).filter(d=>!!d&&!!d.file);if(l.length===0)return;if(new Set(l.map(d=>d.parent)).size>1){new O.Notice("Reorder requires a single-parent selection.");return}e=l}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new O.Notice("Nothing to reorder.");return}let s=e[0].parent??V,i=this.tree.getChildren(s).map(l=>l.id);if(i.length===0)return;let r=new Set(e.map(l=>l.id)),n=i.filter(l=>r.has(l));if(n.length===0)return;let a=ys(i,n,t);if(Ve(a,i))return;let o=this.noteFolder,c=this.order.getOrder(o,s).slice();this.order.setOrder(o,s,a),await this.order.save(o),await this.forceManualMode(s),await this.log.append({type:"reorder",id:s,payload:{dir:t,parent:s,ids:n,count:n.length}}),this.pendingFocusIds=n.slice(),this.tree.rebuild(o),this.render(),new O.Notice(`Moved ${n.length} note${n.length===1?"":"s"} ${t}`),this.plugin.getUndoStack(o).push({label:`Reorder (${t})`,undo:async()=>{if(c.length===0){let l=this.order.cache.get(o)??{};delete l[s],this.order.cache.set(o,l)}else this.order.setOrder(o,s,c);await this.order.save(o),await this.log.append({type:"reorder",id:s,payload:{dir:"undo",parent:s,ids:n,count:n.length}}),this.pendingFocusIds=n.slice(),this.tree.rebuild(o),this.render()},redo:async()=>{this.order.setOrder(o,s,a),await this.order.save(o),await this.log.append({type:"reorder",id:s,payload:{dir:`redo:${t}`,parent:s,ids:n,count:n.length}}),this.pendingFocusIds=n.slice(),this.tree.rebuild(o),this.render()}})}async cmdDelete(){let t=this.getActionTargets();if(t.length===0){let d=this.tree.get(this.focusId);d?.file&&(t=[d])}if(t.length===0){new O.Notice("Nothing selected to delete.");return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],s=new Set,i=d=>{if(!s.has(d.id)){s.add(d.id);for(let v of this.tree.getChildren(d.id))i(v);e.push(d)}};for(let d of t)i(d);let r=[];for(let d of e){if(!d.file)continue;let v=await this.app.vault.read(d.file);r.push(...this.extractAttachments(this.stripFrontmatter(v)));let u=this.app.metadataCache.getFileCache(d.file)?.frontmatter;if(Array.isArray(u?.attachments))for(let y of u.attachments)typeof y=="string"&&y.trim()&&r.push(y)}let n=[...new Set(r)],a=e.length-t.length,o=async d=>{let v=await this.snapshotNotes(e,d),u=0;if(d)for(let C of n){let E=this.app.metadataCache.getFirstLinkpathDest(C,"");if(E)try{await this.app.fileManager.trashFile(E),await this.log.append({type:"attachment_remove",id:V,payload:{path:E.path}}),new O.Notice(`Deleted attachment "${E.name}"`),u+=1}catch{}}for(let C of e)if(C.file){try{await this.app.fileManager.trashFile(C.file)}catch{}await this.log.append({type:"delete",id:C.id,payload:{path:C.file.path,attachmentsRemoved:d?n:[]}})}this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(this.noteFolder),this.render();let y=u>0?` with ${u} attachment${u===1?"":"s"}`:"";new O.Notice(`Deleted ${t.length} note${t.length===1?"":"s"}${y}`);let w=this.noteFolder,b=t.map(C=>C.id);this.plugin.getUndoStack(w).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(v,b.slice())},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.trashNotesAndAttachments(v)}}),this.focusView()},c=ft(),l=c.confirmBulkDelete,h=n.length>0&&c.confirmAttachmentDelete;if(!l&&!h){await o(!1);return}new Mt(this.app,`${t.length} selected note${t.length===1?"":"s"}`,a,n.length,h,o).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new O.Notice("Pick a note to split.");return}let s=e.file,i=await this.app.vault.read(s),r=this.stripFrontmatter(i).replace(/\s+$/,""),n=r.split(/\r?\n/);if(r.trim().length<2){new O.Notice("Note is too short to split.");return}let a=i,o=s.path,c=async(l,h,d)=>{if(!l.trim()||!h.trim()){new O.Notice("Split would leave one part empty.");return}try{let v=i.startsWith("---")?i.slice(0,i.indexOf(` ----`,3)+4):"",u=v+(v?` -`:"")+l+` -`;await this.app.vault.modify(s,u);let y=e.parent??V,w=Date.parse(e.created||""),b=Number.isFinite(w)?new Date(w+1).toISOString():new Date().toISOString(),C=await this.createNoteUnder(h,y,{record:!1,createdOverride:b});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:C,...d}}),this.tree.rebuild(this.noteFolder),this.render(),new O.Notice("Note split.");let E=C?this.tree.get(C):void 0,I=E?.file?.path,N=I?await this.app.vault.read(E.file):null,D=this.noteFolder;this.plugin.getUndoStack(D).push({label:"Split note",undo:async()=>{if(I){let q=this.app.vault.getAbstractFileByPath(I);if(q)try{await this.app.fileManager.trashFile(q)}catch{}}let $=this.app.vault.getAbstractFileByPath(o);$&&await this.app.vault.modify($,a),this.tree.rebuild(D),this.render()},redo:async()=>{let $=this.app.vault.getAbstractFileByPath(o);$&&await this.app.vault.modify($,u),I&&N&&!await this.app.vault.adapter.exists(I)&&await this.app.vault.create(I,N),this.tree.rebuild(D),this.render()}})}catch(v){new O.Notice(`Stashpad: split failed (${v.message})`),console.error(v)}};new Xt(this.app,r,async l=>{let h=n.slice(0,l).join(` -`).replace(/\s+$/,""),d=n.slice(l).join(` -`).replace(/^\s+|\s+$/g,"");await c(h,d,{mode:"line",splitAtLine:l})},async l=>{let h=r.slice(0,l).replace(/\s+$/,""),d=r.slice(l).replace(/^\s+|\s+$/g,"");await c(h,d,{mode:"cursor",splitAtChar:l})}).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}async cmdExportStash(t){let e=this.collectExportRoots(t);if(e.length===0){new O.Notice("Nothing to export.");return}let s=this.collectExportSubtree(e);if(s.length===0){new O.Notice("No exportable notes (no files attached).");return}try{let i=await ze(this.app,{rootNotes:e.filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),allDescendants:s.filter(h=>!e.some(d=>d.id===h.id)).filter(h=>!!h.file).map(h=>({id:h.id,file:h.file})),sourceFolder:this.noteFolder}),r=(0,O.moment)().format("YYYYMMDD-HHmmss"),a=(e.length===1?this.titleForNode(e[0]):`stashpad-${e.length}notes`).replace(/[^\w.\-]+/g,"_").slice(0,60)||"stash-export",o=(this.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),c=`${this.noteFolder}/${o}`;await this.ensureFolder(c);let l=`${c}/${a}-${r}.${Nt}`;await this.app.vault.createBinary(l,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)),await this.log.append({type:"stash_export",id:e[0].id,payload:{path:l,noteCount:s.length,rootIds:e.map(h=>h.id)}}),new O.Notice(`Exported ${s.length} note${s.length===1?"":"s"} \u2192 ${l}`)}catch(i){new O.Notice(`Stashpad: export failed (${i.message})`),console.error(i)}}collectExportRoots(t){if(t?.file)return[t];if(this.selection.size>0)return[...this.selection].map(s=>this.tree.get(s)).filter(s=>!!s?.file);if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return[this.currentChildren[this.cursorIdx]];let e=this.tree.get(this.focusId);return e?.file?[e]:[]}collectExportSubtree(t){let e=new Set,s=[],i=r=>{if(!e.has(r.id)){e.add(r.id),r.file&&s.push(r);for(let n of this.tree.getChildren(r.id))i(n)}};for(let r of t)i(r);return s}async cmdImportStash(){let t=this.app.vault.getFiles().filter(i=>i.extension===Nt);if(t.length===0){new O.Notice("No .stash files found in this vault.");return}let e=this,s=new class extends O.FuzzySuggestModal{getItems(){return t}getItemText(i){return i.path}onChooseItem(i){e.processStashFile(i)}}(this.app);s.setPlaceholder("Pick a .stash file to import\u2026"),s.open()}async processStashFile(t){try{let e=await this.app.vault.readBinary(t),s=await re(this.app,new Uint8Array(e),this.noteFolder,this.collectExistingIds());this.tree.rebuild(this.noteFolder),this.render(),await this.log.append({type:"stash_import",id:V,payload:{from:t.path,into:this.noteFolder,noteCount:s.notesWritten,attachmentsWritten:s.attachmentsWritten,collisionsRenamed:s.collisionsRenamed}});try{await this.app.fileManager.trashFile(t)}catch{}let i=[`Imported ${s.notesWritten} note${s.notesWritten===1?"":"s"}`];s.attachmentsWritten&&i.push(`+ ${s.attachmentsWritten} attachment${s.attachmentsWritten===1?"":"s"}`),s.collisionsRenamed&&i.push(`(${s.collisionsRenamed} id collision${s.collisionsRenamed===1?"":"s"} renamed)`),new O.Notice(i.join(" "))}catch(e){new O.Notice(`Stashpad: import failed (${e.message})`),console.error(e)}}collectExistingIds(){let t=new Set,e=s=>{if(t.add(s),!!this.tree.get(s))for(let r of this.tree.getChildren(s))e(r.id)};return e(V),t}async createNoteUnder(t,e,s={record:!0}){await this.ensureFolder(this.noteFolder);let i=bt(),r=null;{let u=(this.plugin.settings.noteTemplates??{})[this.noteFolder.replace(/\/+$/,"")];if(u){let y=this.app.vault.getAbstractFileByPath(u);if(y&&y.extension==="md")try{let w=await this.app.vault.cachedRead(y),b=this.stripFrontmatter(w);r=this.app.metadataCache.getFileCache(y)?.frontmatter??{},b.includes("{{body}}")?t=b.replace(/\{\{body\}\}/g,t):t.trim()?b.trim()&&(t=`${t} +`)),new A.Notice(`Copied ${t.length} note(s).`)}async cmdCopyTree(){let t=this.getActionTargets();if(t.length===0){let r=this.tree.get(this.focusId);r?.file&&(t=[r])}if(t.length===0){new A.Notice("Nothing to copy.");return}let e=ft().prefixTimestampsOnCopy,s=[],i=async(r,n)=>{if(r.file){let a=await this.app.vault.cachedRead(r.file),o=this.stripFrontmatter(a).trim().split(/\r?\n/).join(" "),l=e?`${this.formatTimeInline(r.created)} `:"";s.push(`${" ".repeat(n)}- ${l}${o}`)}for(let a of this.tree.getChildren(r.id))await i(a,n+1)};for(let r of t)await i(r,0);await navigator.clipboard.writeText(s.join(` +`)),new A.Notice(`Copied tree (${s.length} entries).`)}async cmdCopyOutline(){let t=this.getActionTargets();if(t.length===0){let i=this.tree.get(this.focusId);i?.file&&(t=[i])}if(t.length===0){new A.Notice("Nothing to copy.");return}let e=[],s=(i,r)=>{if(!i.file)return;let n=" ".repeat(r);e.push(`${n}- ![[${i.file.basename}]]`);for(let a of this.tree.getChildren(i.id))s(a,r+1)};for(let i of t)s(i,0);await navigator.clipboard.writeText(e.join(` +`)),new A.Notice(`Copied outline (${e.length} entr${e.length===1?"y":"ies"}).`)}cmdToggleExpand(){let t=this.getActionTargets();if(!t.length)return;let e=t.some(s=>!this.expandedNotes.has(s.id));for(let s of t)e?this.expandedNotes.add(s.id):this.expandedNotes.delete(s.id);this.render()}async cloneSubtree(t,e,s){if(!t.file)return null;let i=t.file,r=await this.app.vault.read(i),n=this.stripFrontmatter(r),a=this.app.metadataCache.getFileCache(i)?.frontmatter??{},o=bt(),l=Kt(n,this.activeStopwords()),c=qt(l,o),d=`${this.noteFolder}/${c}`,h=new Date().toISOString(),g=this.extractAttachments(n),u=["---",`id: ${o}`,`parent: ${e}`,`created: ${h}`];if(g.length>0){u.push("attachments:");for(let w of g)u.push(` - "${w.replace(/"/g,'\\"')}"`)}else u.push("attachments: []");u.push("---",n),await this.ensureFolder(this.noteFolder),await this.app.vault.create(d,u.join(` +`)),s.push(d);let y=this.app.vault.getAbstractFileByPath(d);if(y){try{await this.app.fileManager.processFrontMatter(y,w=>{for(let[b,C]of Object.entries(a))b==="id"||b==="parent"||b==="created"||b==="attachments"||b==="position"||(w[b]=C)})}catch(w){console.warn("[Stashpad] cloneSubtree: processFrontMatter failed",w)}try{this.tree.insertSynthetic({id:o,parent:e,children:[],file:y,created:h})}catch{}}for(let w of this.tree.getChildren(t.id))await this.cloneSubtree(w,o,s);return o}async cmdClone(){let t=this.getActionTargets();if(!t.length){new A.Notice("Nothing to clone.");return}let e=this.noteFolder,s=[],i=[];for(let a of t){if(!a.file)continue;let o=a.parent??this.focusId,l=await this.cloneSubtree(a,o,s);l&&i.push(l)}if(!i.length)return;this.tree.rebuild(e),this.pendingFocusIds=i.slice(),this.render();let r=s.map(a=>this.app.vault.getAbstractFileByPath(a)).filter(a=>!!a&&a.extension==="md").map(a=>({id:Yt(a.basename)??a.basename,parent:null,children:[],file:a,created:new Date().toISOString()})),n=await this.snapshotNotes(r,!1);this.plugin.getUndoStack(e).push({label:`Clone ${i.length} note${i.length===1?"":"s"}`,undo:async()=>{for(let a of[...s].reverse()){let o=this.app.vault.getAbstractFileByPath(a);if(o)try{await this.app.fileManager.trashFile(o)}catch{}}this.tree.rebuild(e),this.render()},redo:async()=>{await this.restoreSnapshots(n,i)}}),new A.Notice(`Cloned ${i.length} note${i.length===1?"":"s"} (${s.length} file${s.length===1?"":"s"}).`)}cmdInsertTemplate(){new Ft(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 A.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 s=this.noteFolder,i=[],r=await this.cloneSubtree(e,this.focusId,i);if(!r)return;this.tree.rebuild(s),this.pendingFocusIds=[r],this.render();let n=i.map(o=>this.app.vault.getAbstractFileByPath(o)).filter(o=>!!o&&o.extension==="md").map(o=>({id:Yt(o.basename)??o.basename,parent:null,children:[],file:o,created:new Date().toISOString()})),a=await this.snapshotNotes(n,!1);this.plugin.getUndoStack(s).push({label:"Insert template",undo:async()=>{for(let o of[...i].reverse()){let l=this.app.vault.getAbstractFileByPath(o);if(l)try{await this.app.fileManager.trashFile(l)}catch{}}this.tree.rebuild(s),this.render()},redo:async()=>{await this.restoreSnapshots(a,[r])}}),new A.Notice(`Inserted template (${i.length} file${i.length===1?"":"s"}).`)}}).open()}navigateTo(t,e={}){if(this.listEl&&this.scrollByFocus.set(this.focusId,this.listEl.scrollTop),e.keepForwardStack||(this.navForwardStack=[]),this.focusId=t,this.persistFocus(),this.defaultCursorToLast(),this.syncComposerDraftForFocus(),this.pendingScrollRestore=this.scrollByFocus.get(t)??null,this.tagFilter){let s=this.tagFilter.toLowerCase();this.collectFolderTags().some(r=>r.raw.toLowerCase()===s)||(this.tagFilter=null)}if(this.colorFilter){let s=this.colorFilter.toLowerCase();this.collectFolderColors().some(r=>r.hex===s)||(this.colorFilter=null)}this.render(),this.refreshHeaderTitle(),this.viewRoot.focus({preventScroll:!0})}navigateBack(){this.navigateUp()}navigateForward(){let t=this.navForwardStack.pop();t&&this.tree.get(t)&&(this.tagFilter=null,this.colorFilter=null,this.navigateTo(t,{keepForwardStack:!0}))}navigateUp(){this.tagFilter=null,this.colorFilter=null;let t=this.tree.get(this.focusId);if(!t||t.parent==null)return this.navigateTo(j);let e=this.focusId;this.navForwardStack.push(e),this.listEl&&this.scrollByFocus.set(e,this.listEl.scrollTop),this.focusId=t.parent,this.persistFocus(),this.syncComposerDraftForFocus(),this.pendingScrollRestore=this.scrollByFocus.get(this.focusId)??null;let s=this.filterChildren(this.tree.getChildren(this.focusId)),i=s.findIndex(r=>r.id===e);this.selection.clear(),i>=0?(this.cursorIdx=i,this.selection.add(e),this.lastSelected=e):(this.cursorIdx=s.length-1,s.length>0&&(this.selection.add(s[s.length-1].id),this.lastSelected=s[s.length-1].id)),this.render(),this.refreshHeaderTitle(),this.revealCursorRow()}openBookmarks(){let t=this.app.internalPlugins?.plugins?.bookmarks?.instance?.items??[],e=this.allowedByBases(),s=new A.Menu,i=0;for(let r of t){if(r.type!=="file"||e&&!e.has(r.path))continue;let n=this.tree.idForPath(r.path);n&&(s.addItem(a=>a.setTitle(r.title||r.path).onClick(()=>this.navigateTo(n))),i++)}i||s.addItem(r=>r.setTitle("(no bookmarks in scope)").setDisabled(!0)),s.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)}async ensureHomeNote(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(n=>n.path.startsWith(t+"/"));for(let n of e)if(this.app.metadataCache.getFileCache(n)?.frontmatter?.id===j)return n;let s=`${t}/home-${j}.md`,i=new Date().toISOString(),r=["---",`id: ${j}`,"parent: null",`created: ${i}`,"attachments: []","---","","# Home","","This is your Stashpad home note. Edit me freely \u2014 everything else nests below.",""].join(` +`);return this.app.vault.create(s,r)}async migrateNullParents(){let t=this.noteFolder,e=this.app.vault.getMarkdownFiles().filter(s=>s.path.startsWith(t+"/"));for(let s of e){let i=this.app.metadataCache.getFileCache(s)?.frontmatter,r=i?.id;if(!r||r===j)continue;let n=i?.parent;(n==null||n===""||n==="null")&&(await this.app.fileManager.processFrontMatter(s,a=>{a.parent=j}),await this.log.append({type:"parent_change",id:r,payload:{from:null,to:j,reason:"migration"}}))}}async openInNewStashpadTab(t){let e=this.app.workspace.getLeaf("tab");await e.setViewState({type:kt,active:!0,state:{focusId:t,timeFilter:this.timeFilter,folderOverride:this.folderOverride}}),this.app.workspace.revealLeaf(e)}cmdOpenInEditor(t){if(t){this.openFileAtEnd(t.file);return}let e=this.getActionTargets();if(e.length)for(let s of e)s.file&&this.openFileAtEnd(s.file)}cmdOpenParentInEditor(){let t=this.tree.get(this.focusId);if(!t?.file){new A.Notice("No focused parent to open.");return}this.openFileAtEnd(t.file)}async openFileAtEnd(t){let e=this.app.workspace,s=this.leaf,i=e.getLeaf("tab");await i.openFile(t,{active:!0}),e.setActiveLeaf(i,{focus:!0}),e.revealLeaf(i);let r=e.on("active-leaf-change",()=>{if((()=>{let c=!1;return e.iterateAllLeaves(d=>{d===i&&(c=!0)}),c})())return;e.offref(r),(()=>{let c=!1;return e.iterateAllLeaves(d=>{d===s&&(c=!0)}),c})()&&(e.setActiveLeaf(s,{focus:!0}),e.revealLeaf(s))}),a=i.view?.editor;a&&requestAnimationFrame(()=>{try{let o=a.lastLine(),l=a.getLine(o)?.length??0;a.setCursor({line:o,ch:l}),a.scrollIntoView({from:{line:o,ch:l},to:{line:o,ch:l}},!0),a.focus()}catch{}})}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 A.Notice("Nothing to toggle.");return}let s=t.some(a=>!this.isCompleted(a)),i=[],r=[];for(let a of t){if(!a.file)continue;let o=this.isCompleted(a);i.push({id:a.id,path:a.file.path,was:o}),o!==s&&(await this.app.fileManager.processFrontMatter(a.file,l=>{s?l.completed=!0:delete l.completed}),r.push(a.id))}this.render(),r.length>0&&(await this.log.append({type:s?"complete":"uncomplete",id:r[0],payload:{ids:r,count:r.length}}),new A.Notice(`${s?"Marked complete":"Unmarked"} (${r.length})`));let n=this.noteFolder;this.plugin.getUndoStack(n).push({label:`${s?"Mark complete":"Unmark complete"} (${t.length})`,undo:async()=>{let a=[];for(let o of i){let l=this.app.vault.getAbstractFileByPath(o.path);l&&(await this.app.fileManager.processFrontMatter(l,c=>{o.was?c.completed=!0:delete c.completed}),r.includes(o.id)&&a.push(o.id))}a.length>0&&await this.log.append({type:s?"uncomplete":"complete",id:a[0],payload:{ids:a,count:a.length,undo:!0}}),this.tree.rebuild(n),this.render()},redo:async()=>{for(let a of i){let o=this.app.vault.getAbstractFileByPath(a.path);o&&await this.app.fileManager.processFrontMatter(o,l=>{s?l.completed=!0:delete l.completed})}r.length>0&&await this.log.append({type:s?"complete":"uncomplete",id:r[0],payload:{ids:r,count:r.length,redo:!0}}),this.tree.rebuild(n),this.render()}})}isCompleted(t){return t.file?!!this.app.metadataCache.getFileCache(t.file)?.frontmatter?.completed:!1}colorForNode(t){if(!t.file)return null;let e=this.app.metadataCache.getFileCache(t.file)?.frontmatter?.color;if(typeof e!="string")return null;let s=e.trim();return/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(s)?s:null}inheritedColorForNode(t){let e=t,s=0;for(;e&&e.id!==j;){let i=this.colorForNode(e);if(i)return{hex:i,depth:s};e=e.parent?this.tree.get(e.parent):void 0,s+=1}return null}attachRowDnD(t,e,s){t.addEventListener("dragstart",i=>{let r=this.selection.has(e.id)&&this.selection.size>1?[...this.selection]:[e.id];if(this.dragSourceIds=r,this.dragRowHeight=t.offsetHeight,t.addClass("is-dragging"),this.listEl&&(this.dragPlaceholder=this.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 a=this.dragSourceIds.slice();this.dragSourceIds=null;let o=this.dragPlaceholder.nextElementSibling,l=this.dragPlaceholder.previousElementSibling;this.removeDragPlaceholder();let c,d="before";o&&o.classList.contains("stashpad-note")?(c=o.dataset.id,d="before"):l&&l.classList.contains("stashpad-note")&&(c=l.dataset.id,d="after"),c&&this.reorderToTarget(a,c,d)}),this.dragPlaceholder.remove()),i.dataTransfer?.setData("text/plain",r.join(",")),i.dataTransfer){i.dataTransfer.effectAllowed="move";try{i.dataTransfer.setDragImage(t,12,12)}catch{}}}),t.addEventListener("dragend",()=>{t.removeClass("is-dragging"),this.clearDropIndicators(),this.removeDragPlaceholder(),this.dragSourceIds=null}),t.addEventListener("dragover",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.dataTransfer&&(i.dataTransfer.dropEffect="move");let r=this.dropZone(i,t);this.clearDropIndicators(),r==="drop-into"?(this.removeDragPlaceholder(),t.addClass("drop-into")):(t.removeClass("drop-into"),this.placePlaceholder(t,r==="drop-above"?"before":"after"))}),t.addEventListener("dragleave",i=>{let r=t.getBoundingClientRect();(i.clientXr.right||i.clientYr.bottom)&&t.removeClass("drop-into")}),t.addEventListener("drop",i=>{if(!this.dragSourceIds)return;i.preventDefault(),i.stopPropagation();let r=this.dragSourceIds.slice();this.dragSourceIds=null;let n=this.dropZone(i,t);this.clearDropIndicators(),this.removeDragPlaceholder(),t.removeClass("is-dragging"),n==="drop-into"?this.reorderToTarget(r,e.id,"into"):this.reorderToTarget(r,e.id,n==="drop-above"?"before":"after")})}placePlaceholder(t,e){if(!this.dragPlaceholder||!this.listEl)return;let s=e==="before"?t:t.nextSibling;if(e==="before"&&this.dragPlaceholder.nextSibling===t||e==="after"&&this.dragPlaceholder.previousSibling===t)return;let i=!!this.dragPlaceholder.parentElement;this.listEl.insertBefore(this.dragPlaceholder,s),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 t=this.dragPlaceholder;t.style.height="0px",t.style.opacity="0",setTimeout(()=>{t.parentElement&&t.remove()},150)}dropZone(t,e){let s=e.getBoundingClientRect(),i=t.clientY-s.top;return is.height*.7?"drop-below":"drop-into"}clearDropIndicators(){if(this.listEl)for(let t of Array.from(this.listEl.querySelectorAll(".drop-into")))t.removeClass("drop-into")}isDescendant(t,e){let s=this.tree.get(t),i=new Set;for(;s&&s.parent&&!i.has(s.id);){if(s.parent===e)return!0;i.add(s.id),s=this.tree.get(s.parent)}return!1}async moveAcrossThenReorder(t,e,s,i){let r=[],n=new Set;for(let u of t){let y=this.tree.get(u);y?.file&&(r.push({id:u,path:y.file.path,oldParent:y.parent}),n.add(y.parent??j))}n.add(e);let a=this.noteFolder,o={};for(let u of n)o[u]=this.order.getOrder(a,u).slice();for(let u of r){let y=this.app.vault.getAbstractFileByPath(u.path);y&&(await this.app.fileManager.processFrontMatter(y,w=>{w.parent=e}),await this.log.append({type:"parent_change",id:u.id,payload:{from:u.oldParent,to:e,reason:"drag"}}),this.order.removeChild(a,u.id))}this.tree.rebuild(a);let l=this.tree.getChildren(e).map(u=>u.id),c=new Set(t),d=l.filter(u=>!c.has(u)),h=d.indexOf(s);h<0&&(h=d.length),i==="after"&&(h+=1);let g=[...d.slice(0,h),...t.filter(u=>!!this.tree.get(u)),...d.slice(h)];this.order.setOrder(a,e,g),await this.order.save(a),await this.forceManualMode(e),await this.log.append({type:"reorder",id:e,payload:{dir:"drag-cross",parent:e,ids:t,count:t.length}}),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(a),this.render(),new A.Notice(`Reparented ${t.length} note${t.length===1?"":"s"}`),this.plugin.getUndoStack(a).push({label:`Move + reorder (${t.length})`,undo:async()=>{for(let u of r){let y=this.app.vault.getAbstractFileByPath(u.path);y&&(await this.app.fileManager.processFrontMatter(y,w=>{u.oldParent===null||u.oldParent===void 0?w.parent=j:w.parent=u.oldParent}),await this.log.append({type:"parent_change",id:u.id,payload:{from:e,to:u.oldParent,reason:"drag-undo"}}))}for(let[u,y]of Object.entries(o))if(y.length===0){let w=this.order.cache.get(a)??{};delete w[u],this.order.cache.set(a,w)}else this.order.setOrder(a,u,y);await this.order.save(a),this.pendingFocusIds=t.slice(),this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(a),this.render()},redo:async()=>{for(let u of r){let y=this.app.vault.getAbstractFileByPath(u.path);y&&(await this.app.fileManager.processFrontMatter(y,w=>{w.parent=e}),this.order.removeChild(a,u.id))}this.order.setOrder(a,e,g),await this.order.save(a),this.pendingFocusIds=t.slice(),this.focusId!==e&&(this.selection.clear(),this.cursorIdx=-1),this.tree.rebuild(a),this.render()}})}async reorderToTarget(t,e,s){let i=this.tree.get(e);if(!i)return;let r=t.map(b=>this.tree.get(b)).filter(b=>!!b&&!!b.file);if(r.length===0||r.some(b=>b.id===e))return;if(s==="into"){for(let b of r)if(this.isDescendant(e,b.id)){new A.Notice("Can't nest a note under one of its own descendants.");return}}let n=s==="into"?e:i.parent??j;if(r.some(b=>(b.parent??j)!==n)){let b=ft(),C=async()=>{s==="into"?await this.moveAcrossThenReorder(r.map(_=>_.id),n,"","after"):await this.moveAcrossThenReorder(r.map(_=>_.id),n,e,s)};if(b.confirmCrossParentDrag){let _=this.titleForNode(i),T=r.length,R=s==="into"?"Nest":"Move",P=s==="into"?"as children of":"under";new Rt(this.app,s==="into"?"Nest under target?":"Move under different parent?",`${R} ${T} note${T===1?"":"s"} ${P} "${_}"? Their parent will change.`,R,$=>{$&&C()}).open()}else await C();return}let o=n,l=r.map(b=>b.id),c=this.tree.getChildren(o).map(b=>b.id),d=new Set(l),h=c.filter(b=>!d.has(b)),g=h.indexOf(e);if(g<0)return;s==="after"&&(g+=1);let u=[...h.slice(0,g),...l,...h.slice(g)];if(qe(u,c))return;let y=this.noteFolder,w=this.order.getOrder(y,o).slice();this.order.setOrder(y,o,u),await this.order.save(y),await this.forceManualMode(o),await this.log.append({type:"reorder",id:o,payload:{dir:"drag",parent:o,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(y),this.render(),new A.Notice(`Reordered ${l.length} note${l.length===1?"":"s"}`),this.plugin.getUndoStack(y).push({label:`Reorder (drag, ${l.length})`,undo:async()=>{if(w.length===0){let b=this.order.cache.get(y)??{};delete b[o],this.order.cache.set(y,b)}else this.order.setOrder(y,o,w);await this.order.save(y),await this.log.append({type:"reorder",id:o,payload:{dir:"undo",parent:o,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(y),this.render()},redo:async()=>{this.order.setOrder(y,o,u),await this.order.save(y),await this.log.append({type:"reorder",id:o,payload:{dir:"redo:drag",parent:o,ids:l,count:l.length}}),this.pendingFocusIds=l.slice(),this.tree.rebuild(y),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 c=[...this.selection].map(h=>this.tree.get(h)).filter(h=>!!h&&!!h.file);if(c.length===0)return;if(new Set(c.map(h=>h.parent)).size>1){new A.Notice("Reorder requires a single-parent selection.");return}e=c}else this.cursorIdx>=0&&this.currentChildren[this.cursorIdx]&&(e=[this.currentChildren[this.cursorIdx]]);if(e.length===0){new A.Notice("Nothing to reorder.");return}let s=e[0].parent??j,i=this.tree.getChildren(s).map(c=>c.id);if(i.length===0)return;let r=new Set(e.map(c=>c.id)),n=i.filter(c=>r.has(c));if(n.length===0)return;let a=Ss(i,n,t);if(qe(a,i))return;let o=this.noteFolder,l=this.order.getOrder(o,s).slice();this.order.setOrder(o,s,a),await this.order.save(o),await this.forceManualMode(s),await this.log.append({type:"reorder",id:s,payload:{dir:t,parent:s,ids:n,count:n.length}}),this.pendingFocusIds=n.slice(),this.tree.rebuild(o),this.render(),new A.Notice(`Moved ${n.length} note${n.length===1?"":"s"} ${t}`),this.plugin.getUndoStack(o).push({label:`Reorder (${t})`,undo:async()=>{if(l.length===0){let c=this.order.cache.get(o)??{};delete c[s],this.order.cache.set(o,c)}else this.order.setOrder(o,s,l);await this.order.save(o),await this.log.append({type:"reorder",id:s,payload:{dir:"undo",parent:s,ids:n,count:n.length}}),this.pendingFocusIds=n.slice(),this.tree.rebuild(o),this.render()},redo:async()=>{this.order.setOrder(o,s,a),await this.order.save(o),await this.log.append({type:"reorder",id:s,payload:{dir:`redo:${t}`,parent:s,ids:n,count:n.length}}),this.pendingFocusIds=n.slice(),this.tree.rebuild(o),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 A.Notice("Nothing selected to delete.");return}if(t.length===1){await this.deleteNote(t[0]);return}let e=[],s=new Set,i=u=>{if(!s.has(u.id)){s.add(u.id);for(let y of this.tree.getChildren(u.id))i(y);e.push(u)}};for(let u of t)i(u);let r=e.filter(u=>!!u.file),n=await Promise.all(r.map(u=>this.app.vault.read(u.file))),a=[];for(let u=0;u{let y=await this.snapshotNotes(e,u),w=0;if(u)for(let T of o){let R=this.app.metadataCache.getFirstLinkpathDest(T,"");if(R)try{await this.app.fileManager.trashFile(R),await this.log.append({type:"attachment_remove",id:j,payload:{path:R.path}}),new A.Notice(`Deleted attachment "${R.name}"`),w+=1}catch{}}for(let T of e)if(T.file){try{await this.app.fileManager.trashFile(T.file)}catch{}await this.log.append({type:"delete",id:T.id,payload:{path:T.file.path,attachmentsRemoved:u?o:[]}})}this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(this.noteFolder),this.render();let b=w>0?` with ${w} attachment${w===1?"":"s"}`:"";new A.Notice(`Deleted ${t.length} note${t.length===1?"":"s"}${b}`);let C=this.noteFolder,_=t.map(T=>T.id);this.plugin.getUndoStack(C).push({label:`Delete ${t.length} note${t.length===1?"":"s"}`,undo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(y,_.slice())},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.trashNotesAndAttachments(y)}}),this.focusView()},d=ft(),h=d.confirmBulkDelete,g=o.length>0&&d.confirmAttachmentDelete;if(!h&&!g){await c(!1);return}new Ot(this.app,`${t.length} selected note${t.length===1?"":"s"}`,l,o.length,g,c).open()}async cmdSplit(t){let e=t??this.resolveActionTarget();if(!e?.file){new A.Notice("Pick a note to split.");return}let s=e.file,i=await this.app.vault.read(s),r=this.stripFrontmatter(i).replace(/\s+$/,""),n=r.split(/\r?\n/);if(r.trim().length<2){new A.Notice("Note is too short to split.");return}let a=i,o=s.path,l=async(c,d,h)=>{if(!c.trim()||!d.trim()){new A.Notice("Split would leave one part empty.");return}try{let g=i.startsWith("---")?i.slice(0,i.indexOf(` +---`,3)+4):"",u=g+(g?` +`:"")+c+` +`;await this.app.vault.modify(s,u);let y=e.parent??j,w=Date.parse(e.created||""),b=Number.isFinite(w)?new Date(w+1).toISOString():new Date().toISOString(),C=await this.createNoteUnder(d,y,{record:!1,createdOverride:b});await this.log.append({type:"rename",id:e.id,payload:{action:"split",into:C,...h}}),this.tree.rebuild(this.noteFolder),this.render(),new A.Notice("Note split.");let _=C?this.tree.get(C):void 0,T=_?.file?.path,R=T?await this.app.vault.read(_.file):null,P=this.noteFolder;this.plugin.getUndoStack(P).push({label:"Split note",undo:async()=>{if(T){let Y=this.app.vault.getAbstractFileByPath(T);if(Y)try{await this.app.fileManager.trashFile(Y)}catch{}}let $=this.app.vault.getAbstractFileByPath(o);$&&await this.app.vault.modify($,a),this.tree.rebuild(P),this.render()},redo:async()=>{let $=this.app.vault.getAbstractFileByPath(o);$&&await this.app.vault.modify($,u),T&&R&&!await this.app.vault.adapter.exists(T)&&await this.app.vault.create(T,R),this.tree.rebuild(P),this.render()}})}catch(g){new A.Notice(`Stashpad: split failed (${g.message})`),console.error(g)}};new Jt(this.app,r,async c=>{let d=n.slice(0,c).join(` +`).replace(/\s+$/,""),h=n.slice(c).join(` +`).replace(/^\s+|\s+$/g,"");await l(d,h,{mode:"line",splitAtLine:c})},async c=>{let d=r.slice(0,c).replace(/\s+$/,""),h=r.slice(c).replace(/^\s+|\s+$/g,"");await l(d,h,{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}async cmdExportStash(t){let e=this.collectExportRoots(t);if(e.length===0){new A.Notice("Nothing to export.");return}let s=this.collectExportSubtree(e);if(s.length===0){new A.Notice("No exportable notes (no files attached).");return}try{let i=await je(this.app,{rootNotes:e.filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),allDescendants:s.filter(d=>!e.some(h=>h.id===d.id)).filter(d=>!!d.file).map(d=>({id:d.id,file:d.file})),sourceFolder:this.noteFolder}),r=(0,A.moment)().format("YYYYMMDD-HHmmss"),a=(e.length===1?this.titleForNode(e[0]):`stashpad-${e.length}notes`).replace(/[^\w.\-]+/g,"_").slice(0,60)||"stash-export",o=(this.plugin.settings.exportFolder||"_exports").trim().replace(/^\/+|\/+$/g,""),l=`${this.noteFolder}/${o}`;await this.ensureFolder(l);let c=`${l}/${a}-${r}.${Bt}`;await this.app.vault.createBinary(c,i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength)),await this.log.append({type:"stash_export",id:e[0].id,payload:{path:c,noteCount:s.length,rootIds:e.map(d=>d.id)}}),new A.Notice(`Exported ${s.length} note${s.length===1?"":"s"} \u2192 ${c}`)}catch(i){new A.Notice(`Stashpad: export failed (${i.message})`),console.error(i)}}collectExportRoots(t){if(t?.file)return[t];if(this.selection.size>0)return[...this.selection].map(s=>this.tree.get(s)).filter(s=>!!s?.file);if(this.cursorIdx>=0&&this.currentChildren[this.cursorIdx])return[this.currentChildren[this.cursorIdx]];let e=this.tree.get(this.focusId);return e?.file?[e]:[]}collectExportSubtree(t){let e=new Set,s=[],i=r=>{if(!e.has(r.id)){e.add(r.id),r.file&&s.push(r);for(let n of this.tree.getChildren(r.id))i(n)}};for(let r of t)i(r);return s}async cmdImportStash(){let t=this.app.vault.getFiles().filter(i=>i.extension===Bt);if(t.length===0){new A.Notice("No .stash files found in this vault.");return}let e=this,s=new class extends A.FuzzySuggestModal{getItems(){return t}getItemText(i){return i.path}onChooseItem(i){e.processStashFile(i)}}(this.app);s.setPlaceholder("Pick a .stash file to import\u2026"),s.open()}async processStashFile(t){try{let e=await this.app.vault.readBinary(t),s=await ne(this.app,new Uint8Array(e),this.noteFolder,this.collectExistingIds());this.tree.rebuild(this.noteFolder),this.render(),await this.log.append({type:"stash_import",id:j,payload:{from:t.path,into:this.noteFolder,noteCount:s.notesWritten,attachmentsWritten:s.attachmentsWritten,collisionsRenamed:s.collisionsRenamed}});try{await this.app.fileManager.trashFile(t)}catch{}let i=[`Imported ${s.notesWritten} note${s.notesWritten===1?"":"s"}`];s.attachmentsWritten&&i.push(`+ ${s.attachmentsWritten} attachment${s.attachmentsWritten===1?"":"s"}`),s.collisionsRenamed&&i.push(`(${s.collisionsRenamed} id collision${s.collisionsRenamed===1?"":"s"} renamed)`),new A.Notice(i.join(" "))}catch(e){new A.Notice(`Stashpad: import failed (${e.message})`),console.error(e)}}collectExistingIds(){let t=new Set,e=s=>{if(t.add(s),!!this.tree.get(s))for(let r of this.tree.getChildren(s))e(r.id)};return e(j),t}async createNoteUnder(t,e,s={record:!0}){await this.ensureFolder(this.noteFolder);let i=bt(),r=null;{let u=(this.plugin.settings.noteTemplates??{})[this.noteFolder.replace(/\/+$/,"")];if(u){let y=this.app.vault.getAbstractFileByPath(u);if(y&&y.extension==="md")try{let w=await this.app.vault.cachedRead(y),b=this.stripFrontmatter(w);r=this.app.metadataCache.getFileCache(y)?.frontmatter??{},b.includes("{{body}}")?t=b.replace(/\{\{body\}\}/g,t):t.trim()?b.trim()&&(t=`${t} -${b}`):t=b}catch(w){console.warn("[Stashpad] template read failed",w)}}}let n=Vt(t,this.activeStopwords()),a=Kt(n,i),o=`${this.noteFolder}/${a}`,c=e??this.focusId,l=s.createdOverride??new Date().toISOString(),h=this.extractAttachments(t),d=this.currentAuthorLink();d&&this.ensureAuthorFile(d);let v=["---",`id: ${i}`,`parent: ${c}`,`created: ${l}`,`modified: ${l}`];if(d&&v.push(`author: "${d.link.replace(/"/g,'\\"')}"`),h.length>0){v.push("attachments:");for(let u of h)v.push(` - "${u.replace(/"/g,'\\"')}"`)}else v.push("attachments: []");v.push("---",t);try{let u=v.join(` -`);await this.app.vault.create(o,u);try{let y=this.app.vault.getAbstractFileByPath(o);if(y&&y.extension==="md"&&(this.tree.insertSynthetic({id:i,parent:c,children:[],file:y,created:l}),this.render(),r))try{await this.app.fileManager.processFrontMatter(y,w=>{for(let[b,C]of Object.entries(r))b==="id"||b==="parent"||b==="created"||b==="attachments"||b==="position"||w[b]===void 0&&(w[b]=C)})}catch(w){console.warn("[Stashpad] template fm overlay failed",w)}}catch{}if(await this.log.append({type:"create",id:i,payload:{path:o,parent:c}}),s.record!==!1){let y=this.noteFolder,w=t;this.plugin.getUndoStack(y).push({label:"Create note",undo:async()=>{let b=this.app.vault.getAbstractFileByPath(o);if(b)try{await this.app.fileManager.trashFile(b)}catch{}if(this.composerDraft=w,this.saveDraft(w),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=w;let C=w.length;this.composerInputEl.setSelectionRange(C,C),this.composerInputEl.focus()}this.tree.rebuild(y),this.render()},redo:async()=>{await this.app.vault.adapter.exists(o)||await this.app.vault.create(o,u),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(w),this.composerInputEl&&(this.composerInputEl.value=""),this.tree.rebuild(y),this.render()}})}return i}catch(u){return new O.Notice(`Stashpad: failed to create note (${u.message})`),null}}extractAttachments(t){let e=[],s=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,i;for(;(i=s.exec(t))!==null;)e.push(i[1]);return e}async ensureFolder(t){let e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof O.TFolder)){if(e)throw new Error(`${t} exists and is not a folder`);await this.app.vault.createFolder(t)}}async importAttachment(t){try{let e=await t.arrayBuffer(),s=`${this.noteFolder}/_attachments`;await this.ensureFolder(s);let i=t.name.replace(/[^\w.\-]+/g,"_"),r=Date.now().toString(36),n=`${s}/${r}-${i}`;return await this.app.vault.createBinary(n,e),await this.log.append({type:"attachment_add",id:V,payload:{path:n,name:t.name,size:t.size}}),new O.Notice(`Attached ${t.name}`),`![[${n}]]`}catch(e){return new O.Notice(`Stashpad: attachment failed (${e.message})`),null}}currentAuthorLink(){let t=(this.plugin.settings.authorName??"").trim(),e=(this.plugin.settings.authorId??"").trim();if(!t||!e)return null;let s=t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.noteFolder}/_authors/${s}-${e}.md`;return{link:`[[${i}|${t}]]`,path:i,name:t,id:e}}async ensureAuthorFile(t){try{let e=`${this.noteFolder}/_authors`;if(await this.ensureFolder(e),await this.app.vault.adapter.exists(t.path))return;let s=new Date().toISOString(),i=["---",`authorId: ${t.id}`,`name: "${t.name.replace(/"/g,'\\"')}"`,`created: ${s}`,"---",`# ${t.name}`].join(` -`);await this.app.vault.create(t.path,i)}catch(e){console.warn("[Stashpad] ensureAuthorFile failed",e)}}renderAuthorshipFooter(t,e){if(!e.file)return;let s=this.plugin.settings;if(!s.showAuthor&&!s.showContributors&&!s.showLastEdit)return;let i=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},r=typeof i.author=="string"?i.author:"",n=Array.isArray(i.contributors)?i.contributors.filter(u=>typeof u=="string"&&u.trim()!==""):[],a=typeof i.modified=="string"?i.modified:typeof i.created=="string"?i.created:"",o=s.showAuthor&&!!r,c=s.showContributors&&n.length>0,l=s.showLastEdit&&!!a;if(!o&&!c&&!l)return;let h=t.createDiv({cls:"stashpad-note-authorship"}),d=(u,y)=>{let w=y.replace(/^\[\[/,"").replace(/\]\]$/,""),b=w.indexOf("|"),C=b>=0?w.slice(0,b):w,E=b>=0?w.slice(b+1):w.split("/").pop()??w,I=u.createEl("a",{cls:"internal-link",text:E});I.setAttribute("data-href",C),I.setAttribute("href",C)},v=[];o&&v.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"by "}),d(u,r)}),c&&v.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"with "}),n.forEach((y,w)=>{w>0&&u.createSpan({text:", "}),d(u,y)})}),l&&v.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"edited "}),u.createSpan({text:this.formatTimeInline(a)})}),v.forEach((u,y)=>{y>0&&h.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let w=h.createSpan({cls:"stashpad-authorship-piece"});u(w)}),h.addEventListener("click",u=>this.handleRenderedClick(u,e))}scheduleContribution(t){let e=this.contribTimers.get(t.path);e&&clearTimeout(e);let s=setTimeout(()=>{this.contribTimers.delete(t.path),this.maybeRecordContribution(t)},1500);this.contribTimers.set(t.path,s)}async maybeRecordContribution(t){let e="";try{e=await this.app.vault.cachedRead(t)}catch{return}let s=this.stripFrontmatter(e),i=this.knownBodies.get(t.path);if(this.knownBodies.set(t.path,s),i===void 0||i===s)return;let r=this.currentAuthorLink();if(!r)return;this.ensureAuthorFile(r);let n=new Date().toISOString();try{await this.app.fileManager.processFrontMatter(t,a=>{a.modified=n;let o=typeof a.author=="string"?a.author:"",c=Array.isArray(a.contributors)?a.contributors.filter(v=>typeof v=="string"):[],l=`-${r.id}`,h=o.includes(l),d=c.some(v=>v.includes(l));!h&&!d&&c.push(r.link),a.contributors=c})}catch(a){console.warn("[Stashpad] maybeRecordContribution failed",a)}}activeStopwords(){return this.plugin.settings.slugStopWords??St}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,O.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=Yt(t.basename);if(!e||e===V)return;let s=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(s),r=Vt(i,this.activeStopwords()),n=Kt(r,e);if(t.name===n)return;let a=t.parent?`${t.parent.path}/${n}`:n;if(this.app.vault.getAbstractFileByPath(a))return;let o=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:o,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,O.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(e),i=this.extractAttachments(s),r=this.app.metadataCache.getFileCache(t)?.frontmatter,n=Array.isArray(r?.attachments)?r.attachments:[];n.length===i.length&&n.every((o,c)=>o===i[c])||await this.app.fileManager.processFrontMatter(t,o=>{o.attachments=i})}stripFrontmatter(t){let e=t.replace(/^/,""),s=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return s?e.slice(s[0].length):e}formatTime(t){if(!t)return"";let e=(0,O.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let i=ee(this.app);if(i)return`${e.format(i.dateFormat)} +${b}`):t=b}catch(w){console.warn("[Stashpad] template read failed",w)}}}let n=Kt(t,this.activeStopwords()),a=qt(n,i),o=`${this.noteFolder}/${a}`,l=e??this.focusId,c=s.createdOverride??new Date().toISOString(),d=this.extractAttachments(t),h=this.currentAuthorLink();h&&this.ensureAuthorFile(h);let g=["---",`id: ${i}`,`parent: ${l}`,`created: ${c}`,`modified: ${c}`];if(h&&g.push(`author: "${h.link.replace(/"/g,'\\"')}"`),d.length>0){g.push("attachments:");for(let u of d)g.push(` - "${u.replace(/"/g,'\\"')}"`)}else g.push("attachments: []");g.push("---",t);try{let u=g.join(` +`);await this.app.vault.create(o,u);try{let y=this.app.vault.getAbstractFileByPath(o);if(y&&y.extension==="md"&&(this.tree.insertSynthetic({id:i,parent:l,children:[],file:y,created:c}),this.render(),r))try{await this.app.fileManager.processFrontMatter(y,w=>{for(let[b,C]of Object.entries(r))b==="id"||b==="parent"||b==="created"||b==="attachments"||b==="position"||w[b]===void 0&&(w[b]=C)})}catch(w){console.warn("[Stashpad] template fm overlay failed",w)}}catch{}if(await this.log.append({type:"create",id:i,payload:{path:o,parent:l}}),s.record!==!1){let y=this.noteFolder,w=t;this.plugin.getUndoStack(y).push({label:"Create note",undo:async()=>{let b=this.app.vault.getAbstractFileByPath(o);if(b)try{await this.app.fileManager.trashFile(b)}catch{}if(this.composerDraft=w,this.saveDraft(w),this.recordLastSubmitted(""),this.composerInputEl){this.composerInputEl.value=w;let C=w.length;this.composerInputEl.setSelectionRange(C,C),this.composerInputEl.focus()}this.tree.rebuild(y),this.render()},redo:async()=>{await this.app.vault.adapter.exists(o)||await this.app.vault.create(o,u),this.composerDraft="",this.saveDraft(""),this.recordLastSubmitted(w),this.composerInputEl&&(this.composerInputEl.value=""),this.tree.rebuild(y),this.render()}})}return i}catch(u){return new A.Notice(`Stashpad: failed to create note (${u.message})`),null}}extractAttachments(t){let e=[],s=/!\[\[([^\]\|]+)(?:\|[^\]]+)?\]\]/g,i;for(;(i=s.exec(t))!==null;)e.push(i[1]);return e}async ensureFolder(t){let e=this.app.vault.getAbstractFileByPath(t);if(!(e instanceof A.TFolder)){if(e)throw new Error(`${t} exists and is not a folder`);await this.app.vault.createFolder(t)}}async importAttachment(t){try{let e=await t.arrayBuffer(),s=`${this.noteFolder}/_attachments`;await this.ensureFolder(s);let i=t.name.replace(/[^\w.\-]+/g,"_"),r=Date.now().toString(36),n=`${s}/${r}-${i}`;return await this.app.vault.createBinary(n,e),await this.log.append({type:"attachment_add",id:j,payload:{path:n,name:t.name,size:t.size}}),new A.Notice(`Attached ${t.name}`),`![[${n}]]`}catch(e){return new A.Notice(`Stashpad: attachment failed (${e.message})`),null}}currentAuthorLink(){let t=(this.plugin.settings.authorName??"").trim(),e=(this.plugin.settings.authorId??"").trim();if(!t||!e)return null;let s=t.replace(/[^\w\- ]+/g,"").trim().replace(/\s+/g,"-")||"author",i=`${this.noteFolder}/_authors/${s}-${e}.md`;return{link:`[[${i}|${t}]]`,path:i,name:t,id:e}}async ensureAuthorFile(t){try{let e=`${this.noteFolder}/_authors`;if(await this.ensureFolder(e),await this.app.vault.adapter.exists(t.path))return;let s=new Date().toISOString(),i=["---",`authorId: ${t.id}`,`name: "${t.name.replace(/"/g,'\\"')}"`,`created: ${s}`,"---",`# ${t.name}`].join(` +`);await this.app.vault.create(t.path,i)}catch(e){console.warn("[Stashpad] ensureAuthorFile failed",e)}}renderAuthorshipFooter(t,e){if(!e.file)return;let s=this.plugin.settings;if(!s.showAuthor&&!s.showContributors&&!s.showLastEdit)return;let i=this.app.metadataCache.getFileCache(e.file)?.frontmatter??{},r=typeof i.author=="string"?i.author:"",n=Array.isArray(i.contributors)?i.contributors.filter(u=>typeof u=="string"&&u.trim()!==""):[],a=typeof i.modified=="string"?i.modified:typeof i.created=="string"?i.created:"",o=s.showAuthor&&!!r,l=s.showContributors&&n.length>0,c=s.showLastEdit&&!!a;if(!o&&!l&&!c)return;let d=t.createDiv({cls:"stashpad-note-authorship"}),h=(u,y)=>{let w=y.replace(/^\[\[/,"").replace(/\]\]$/,""),b=w.indexOf("|"),C=b>=0?w.slice(0,b):w,_=b>=0?w.slice(b+1):w.split("/").pop()??w,T=u.createEl("a",{cls:"internal-link",text:_});T.setAttribute("data-href",C),T.setAttribute("href",C)},g=[];o&&g.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"by "}),h(u,r)}),l&&g.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"with "}),n.forEach((y,w)=>{w>0&&u.createSpan({text:", "}),h(u,y)})}),c&&g.push(u=>{u.createSpan({cls:"stashpad-authorship-label",text:"edited "}),u.createSpan({text:this.formatTimeInline(a)})}),g.forEach((u,y)=>{y>0&&d.createSpan({cls:"stashpad-authorship-sep",text:"\xB7"});let w=d.createSpan({cls:"stashpad-authorship-piece"});u(w)}),d.addEventListener("click",u=>this.handleRenderedClick(u,e))}scheduleContribution(t){let e=this.contribTimers.get(t.path);e&&clearTimeout(e);let s=setTimeout(()=>{this.contribTimers.delete(t.path),this.maybeRecordContribution(t)},1500);this.contribTimers.set(t.path,s)}async maybeRecordContribution(t){let e="";try{e=await this.app.vault.cachedRead(t)}catch{return}let s=this.stripFrontmatter(e),i=this.knownBodies.get(t.path);if(this.knownBodies.set(t.path,s),i===void 0||i===s)return;let r=this.currentAuthorLink();if(!r)return;this.ensureAuthorFile(r);let n=new Date().toISOString();try{await this.app.fileManager.processFrontMatter(t,a=>{a.modified=n;let o=typeof a.author=="string"?a.author:"",l=Array.isArray(a.contributors)?a.contributors.filter(g=>typeof g=="string"):[],c=`-${r.id}`,d=o.includes(c),h=l.some(g=>g.includes(c));!d&&!h&&l.push(r.link),a.contributors=l})}catch(a){console.warn("[Stashpad] maybeRecordContribution failed",a)}}activeStopwords(){return this.plugin.settings.slugStopWords??St}scheduleSlugRename(t){let e=this.slugDebouncers.get(t.path);e&&e.cancel(),e=(0,A.debounce)(()=>void this.maybeRenameForSlug(t),3e4),this.slugDebouncers.set(t.path,e),e()}async maybeRenameForSlug(t){let e=Yt(t.basename);if(!e||e===j)return;let s=await this.app.vault.cachedRead(t),i=this.stripFrontmatter(s),r=Kt(i,this.activeStopwords()),n=qt(r,e);if(t.name===n)return;let a=t.parent?`${t.parent.path}/${n}`:n;if(this.app.vault.getAbstractFileByPath(a))return;let o=t.path;try{await this.app.fileManager.renameFile(t,a),await this.log.append({type:"rename",id:e,payload:{from:o,to:a}})}catch{}}scheduleAttachmentSync(t){let e=this.attachmentDebouncers.get(t.path);e&&e.cancel(),e=(0,A.debounce)(()=>void this.syncAttachmentsFrontmatter(t),1500),this.attachmentDebouncers.set(t.path,e),e()}async syncAttachmentsFrontmatter(t){let e=await this.app.vault.cachedRead(t),s=this.stripFrontmatter(e),i=this.extractAttachments(s),r=this.app.metadataCache.getFileCache(t)?.frontmatter,n=Array.isArray(r?.attachments)?r.attachments:[];n.length===i.length&&n.every((o,l)=>o===i[l])||await this.app.fileManager.processFrontMatter(t,o=>{o.attachments=i})}stripFrontmatter(t){let e=t.replace(/^/,""),s=e.match(/^\s*---\s*\r?\n[\s\S]*?\r?\n---\s*(?:\r?\n|$)/);return s?e.slice(s[0].length):e}formatTime(t){if(!t)return"";let e=(0,A.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let i=se(this.app);if(i)return`${e.format(i.dateFormat)} ${e.format(i.timeFormat)}`}return`${e.format("YYYY.MM.DD")} -${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,O.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let i=ee(this.app);if(i){let r=/:ss/.test(i.timeFormat)?i.timeFormat:i.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(i.dateFormat)} ${e.format(r)}`}}return`${e.format("YYYY.MM.DD")} ${e.format("HH:mm:ss A")}`}scrollListToBottom(){let t=this.listEl;if(!t)return;this.stickToListBottom=!0;let e=()=>{t.scrollTop=t.scrollHeight};requestAnimationFrame(e),setTimeout(e,100),setTimeout(e,400),setTimeout(e,1e3)}openNoteMenu(t,e){if(!e.file)return;let s=e.file,i=new O.Menu;i.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),i.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(s)})),i.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),i.addSeparator(),i.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),i.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()})),i.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),i.addItem(r=>r.setTitle("Export to .stash").setIcon("package").onClick(()=>void this.cmdExportStash(e))),i.addSeparator(),i.addItem(r=>r.setTitle("Move to\u2026").onClick(()=>this.cmdMovePicker())),i.addItem(r=>r.setTitle("Move to Home").onClick(async()=>{await this.changeParent(e,V)})),i.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()})),i.addSeparator(),i.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{await this.deleteNote(e)})),i.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],s=h=>{for(let d of this.tree.getChildren(h.id))s(d),e.push(d)};s(t);let i=[...e,t],r=[];for(let h of i){if(!h.file)continue;let d=await this.app.vault.cachedRead(h.file);r.push(...this.extractAttachments(this.stripFrontmatter(d)));let v=this.app.metadataCache.getFileCache(h.file)?.frontmatter;if(Array.isArray(v?.attachments))for(let u of v.attachments)typeof u=="string"&&u.trim()&&r.push(u)}let n=[...new Set(r)],a=async h=>{let d=await this.snapshotNotes(i,h),v=0;if(h)for(let C of n){let E=this.app.metadataCache.getFirstLinkpathDest(C,"");if(E)try{await this.app.fileManager.trashFile(E),await this.log.append({type:"attachment_remove",id:V,payload:{path:E.path}}),new O.Notice(`Deleted attachment "${E.name}"`),v+=1}catch{}}for(let C of i)if(C.file){try{await this.app.fileManager.trashFile(C.file)}catch{}await this.log.append({type:"delete",id:C.id,payload:{path:C.file.path,attachmentsRemoved:h?n:[]}})}this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(this.noteFolder),this.render();let u=this.noteFolder,y=`Delete "${this.titleForNode(t)}"`,w=t.id,b=v>0?` with ${v} attachment${v===1?"":"s"}`:"";new O.Notice(`Deleted "${this.titleForNode(t)}"${b}`),this.plugin.getUndoStack(u).push({label:y,undo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(d,[w])},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.trashNotesAndAttachments(d)}})},o=ft(),c=e.length>0&&o.confirmBulkDelete,l=n.length>0&&o.confirmAttachmentDelete;if(!c&&!l){await a(!1),this.focusView();return}new Mt(this.app,this.titleForNode(t),e.length,n.length,l,async h=>{await a(h),this.focusView()}).open()}async changeParent(t,e,s={record:!0}){if(!t.file)return;let i=t.file,r=t.parent;if(r!==e&&e!==t.id&&(await this.app.fileManager.processFrontMatter(i,n=>{n.parent=e}),await this.log.append({type:"parent_change",id:t.id,payload:{from:r,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==r?(this.selection.clear(),this.cursorIdx=-1):this.focusId===r&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),s.quiet||new O.Notice("Reparented note"),s.record!==!1)){let n=this.noteFolder,a=i.path,o=t.id;this.plugin.getUndoStack(n).push({label:"Move note",undo:async()=>{let c=this.app.vault.getAbstractFileByPath(a);c&&(await this.app.fileManager.processFrontMatter(c,l=>{l.parent=r}),this.pendingFocusIds=[o],this.focusId!==r&&this.focusId!==e?(this.selection.clear(),this.cursorIdx=-1):this.focusId===e&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(n),this.render())},redo:async()=>{let c=this.app.vault.getAbstractFileByPath(a);c&&(await this.app.fileManager.processFrontMatter(c,l=>{l.parent=e}),this.pendingFocusIds=[o],this.focusId!==e&&this.focusId!==r?(this.selection.clear(),this.cursorIdx=-1):this.focusId===r&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(n),this.render())}})}}};function gs(g,m){return!m||g.metaKey||g.ctrlKey||g.altKey?!1:g.key.toLowerCase()===m.toLowerCase()}function ne(g,m){return m?m.includes("+")?vs(g,m):gs(g,m):!1}function rt(g,m){if(!m)return!1;let{primary:t,secondary:e,preferRight:s}=m;return t&&e?s?ne(g,e):ne(g,t):ne(g,t)||ne(g,e)}function Se(g){if(!g)return"";let m=O.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return g.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?m?"Cmd":"Ctrl":e.toLowerCase()==="alt"?m?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function vs(g,m){if(!m)return!1;let t=m.split("+").map(h=>h.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),s=new Set(t.slice(0,-1).map(h=>h.toLowerCase())),i=s.has("mod"),r=s.has("ctrl")||s.has("control"),n=s.has("cmd")||s.has("meta")||s.has("command"),a=s.has("alt")||s.has("option"),o=s.has("shift"),l=O.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?g.metaKey:g.ctrlKey;return i&&!l||r&&!g.ctrlKey||n&&!g.metaKey||a!==g.altKey||o!==g.shiftKey||!i&&(!r&&g.ctrlKey||!n&&g.metaKey)?!1:g.key.toLowerCase()===e}function Ze(g){return g.split("/").map(m=>m.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function ys(g,m,t){let e=new Set(m),s=g.filter(r=>!e.has(r)),i=g.findIndex(r=>e.has(r));if(i<0)return g.slice();switch(t){case"top":return[...m,...s];case"bottom":return[...s,...m];case"up":{let r=Math.max(0,i-1),n=s.slice();return n.splice(r,0,...m),n}case"down":{let r=(()=>{let c=-1;return g.forEach((l,h)=>{e.has(l)&&(c=h)}),c})(),n=0;for(let c=0;c"")}getLogPath(){return this.logPath}getDir(){return this.baseDir}async ensureDir(){if(this.dirOk)return;let m=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let s of t)e=e?`${e}/${s}`:s,await m.exists(e)||await m.mkdir(e);this.dirOk=!0}append(m){let t=m.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...m};t?e.author=t:delete e.author;let s=JSON.stringify(e)+` -`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let i=this.app.vault.adapter;if(typeof i.append=="function")await i.append(this.logPath,s);else{let r=await i.exists(this.logPath)?await i.read(this.logPath):"";await i.write(this.logPath,r+s)}}catch(i){console.warn("Stashpad: log append failed",i)}}),Promise.resolve()}async readState(){let m=this.app.vault.adapter;if(!await m.exists(this.statePath))return{};try{return JSON.parse(await m.read(this.statePath))}catch{return{}}}async writeState(m){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(m,null,2))}};var le=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(m){for(this.undoStack.push(m),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let m=this.undoStack.pop();if(!m)return null;try{await m.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(m),m}async redo(){let m=this.redoStack.pop();if(!m)return null;try{await m.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(m),m}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 ce=class extends ht.Plugin{constructor(){super(...arguments);this.settings={...Ct};this.undoStacks=new Map;this.sweptFolders=new Set;this.authorRenameInFlight=new Set;this.writeChain=Promise.resolve()}pluginPrivatePath(t=""){let s=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${s}/${t.replace(/^\/+/,"")}`:s}newLog(){return new oe(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),s=async()=>{let a=e.split("/").filter(Boolean),o="";for(let c of a)o=o?`${o}/${c}`:c,await t.exists(o)||await t.mkdir(o)},i=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,r=this.pluginPrivatePath("data.json");if(await t.exists(i)&&!await t.exists(r))try{await s();let a=await t.read(i);await t.write(r,a),console.debug("[Stashpad] migrated data.json \u2192",r)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let n=".stashpad";if(await t.exists(n))try{await s();let a=await t.list(n);for(let o of a.files){let c=o.replace(/^.*\//,""),l=this.pluginPrivatePath(c);if(!await t.exists(l))try{let h=await t.read(o);await t.write(l,h),console.debug("[Stashpad] migrated",o,"\u2192",l)}catch(h){console.warn(`Stashpad: failed to migrate ${o}`,h)}}}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(s){return console.warn("Stashpad: data.json parse failed",s),null}}async saveData(t){let e=this.app.vault.adapter,s=this.pluginPrivatePath();if(!await e.exists(s)){let i=s.split("/").filter(Boolean),r="";for(let n of i)r=r?`${r}/${n}`:n,await e.exists(r)||await e.mkdir(r)}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 s=this.app.vault.adapter,i=e.split("/").filter(Boolean),r="";for(let c of i)r=r?`${r}/${c}`:c,await s.exists(r)||await s.mkdir(r);let n=`${e}/Home.md`;if(await s.exists(n)){let c=this.app.vault.getAbstractFileByPath(n);c&&await this.app.fileManager.processFrontMatter(c,l=>{(typeof l.id!="string"||!l.id)&&(l.id=V),"parent"in l||(l.parent=null),(typeof l.created!="string"||!l.created)&&(l.created=new Date().toISOString())});return}let a=new Date().toISOString(),o=["---",`id: ${V}`,"parent: null",`created: ${a}`,"---","Home"].join(` -`);await this.app.vault.create(n,o)}collectColorsInFolder(t){let e=new Map,s=t.replace(/\/+$/,"");for(let r of this.app.vault.getMarkdownFiles()){let n=r.parent?.path?.replace(/\/+$/,"")??"";if(n!==s&&!n.startsWith(s+"/"))continue;let a=this.app.metadataCache.getFileCache(r)?.frontmatter,o=typeof a?.color=="string"?a.color.trim():"";if(!o||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(o))continue;let c=o.toLowerCase();e.set(c,(e.get(c)??0)+1)}let i=[...e.entries()].map(([r,n])=>({hex:r,count:n}));return i.sort((r,n)=>n.count-r.count||r.hex.localeCompare(n.hex)),i}async recolorAllInFolder(t,e,s){let i=t.replace(/\/+$/,""),r=e.toLowerCase(),n=0;for(let o of this.app.vault.getMarkdownFiles()){let c=o.parent?.path?.replace(/\/+$/,"")??"";if(c!==i&&!c.startsWith(i+"/"))continue;let l=this.app.metadataCache.getFileCache(o)?.frontmatter;if((typeof l?.color=="string"?l.color.trim().toLowerCase():"")===r)try{await this.app.fileManager.processFrontMatter(o,d=>{s?d.color=s:delete d.color}),n++}catch(d){console.warn(`Stashpad: recolor failed for ${o.path}`,d)}}let a=this.settings.colorAliases?.[i];if(a){let o=a[r];o&&(delete a[r],s&&(a[s.toLowerCase()]=o),Object.keys(a).length===0&&delete this.settings.colorAliases[i],await this.saveSettings())}return n}getColorAlias(t,e){let s=t.replace(/\/+$/,""),i=this.settings.colorAliases?.[s];if(!i)return;let r=i[e.toLowerCase()];return r&&r.trim()?r:void 0}async setColorAlias(t,e,s){let i=t.replace(/\/+$/,""),r=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[i]||(this.settings.colorAliases[i]={});let n=this.settings.colorAliases[i],a=s.trim();a?n[r]=a:delete n[r],Object.keys(n).length===0&&delete this.settings.colorAliases[i],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let s=t.trim().replace(/^\/+|\/+$/g,"");if(!s)return;let i=Date.now();for(;Date.now()-isetTimeout(r,80))}}discoverStashpadFolders(){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(e)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let i=e.parent?.path?.replace(/\/+$/,"")??"";i&&t.add(i)}return[...t].sort()}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),s=new Set(this.settings.searchExcludedFolders),r=this.discoverStashpadFolders().filter(o=>e.size>0?e.has(o):!s.has(o)),n=(t||"").trim().replace(/\/+$/,""),a=r.filter(o=>o!==n);return n&&a.unshift(n),a}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 s=this.newLog(),i={},r=this.app.vault.getMarkdownFiles().filter(c=>c.path===t||c.path.startsWith(t+"/"));for(let c of r){let l=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof l?.id=="string"?l.id.trim():"";if(!h)continue;let d=l&&"parent"in l?l.parent??null:null;i[h]={parent:d,path:c.path}}let n=await s.readState(),a=c=>c===t||c.startsWith(t+"/");if(!e.silent){for(let[c,l]of Object.entries(i)){let h=n[c];h?h.parent!==l.parent?await s.append({type:"parent_change",id:c,payload:{from:h.parent,to:l.parent}}):h.path!==l.path&&await s.append({type:"rename",id:c,payload:{from:h.path,to:l.path}}):await s.append({type:"create",id:c,payload:{path:l.path,parent:l.parent}})}for(let[c,l]of Object.entries(n))!i[c]&&a(l.path)&&await s.append({type:"missing",id:c,payload:{lastPath:l.path}})}let o={};for(let[c,l]of Object.entries(n))a(l.path)||(o[c]=l);for(let[c,l]of Object.entries(i))o[c]=l;await s.writeState(o)}catch(s){console.warn("Stashpad: integrity sweep failed",s)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new le,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),this.addSettingTab(new te(this.app,this)),this.registerView(kt,a=>new ae(a,this));let t=()=>{let a=Et(),o=!!a&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===a,c=!!o&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",c),document.body.classList.toggle("stashpad-active",!!o)};this.register(De(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t)),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let e=window.visualViewport,s=()=>{let a=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),o=a&&a.isConnected?a.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${o}px`);let c=0;e&&(c=Math.max(0,window.innerHeight-e.height-e.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${c}px`),document.body.classList.toggle("stashpad-keyboard-open",c>100)};s(),e&&(e.addEventListener("resize",s),e.addEventListener("scroll",s),this.register(()=>{e.removeEventListener("resize",s),e.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",()=>void this.activateView({reveal:!0})),this.addCommand({id:"stashpad-open",name:"Open Stashpad in new tab",callback:()=>void this.activateView({reveal:!1})}),this.addCommand({id:"stashpad-reveal",name:"Reveal or open Stashpad",callback:()=>void this.activateView({reveal:!0})});let i=a=>{let o=Et();o&&typeof o[a]=="function"&&o[a]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>i("toggleSplit")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>i("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>i("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>i("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>i("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>i("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>i("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>i("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>i("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>i("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>i("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>i("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>i("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>i("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>i("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>i("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>i("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>i("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>i("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>i("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>i("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>i("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>i("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>i("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>i("cmdToggleComplete")}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>i("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>i("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>i("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>i("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>i("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Switch this Stashpad tab to another folder\u2026",callback:()=>i("cmdOpenFolderPicker")}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:a=>{let o=Et(),c=o&&o.noteFolder;return c?(a||(new ht.Notice(`Running integrity check on "${c}"\u2026`),this.runIntegrityCheckOnFolder(c).then(()=>{new ht.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-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:a=>{let o=this.app.workspace.getActiveFile();return!o||o.extension!=="md"?!1:(a||this.adoptNote(o),!0)}}),this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let a=this.app.setting;!a?.open||!a?.openTabById||(a.open(),a.openTabById(this.manifest.id))}});let r=a=>{if(a.extension!==Nt)return;let o=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),c=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!o)return;let l=a.parent?.path||"";if((l.split("/").pop()??"")!==o||c&&l.endsWith(`/${c}`))return;let d=l.slice(0,l.length-o.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(a,d)};this.registerEvent(this.app.vault.on("create",a=>{a instanceof ht.TFile&&r(a)})),this.registerEvent(this.app.vault.on("rename",a=>{a instanceof ht.TFile&&r(a)}));let n=a=>{if(a.extension!=="md")return;let o=a.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(o)&&setTimeout(()=>{this.fixOrphanParentForFile(a)},800)};this.registerEvent(this.app.vault.on("create",a=>{a instanceof ht.TFile&&n(a)})),this.registerEvent(this.app.vault.on("rename",a=>{a instanceof ht.TFile&&n(a)})),this.registerEvent(this.app.vault.on("rename",(a,o)=>{a instanceof ht.TFile&&this.maybeAdoptAuthorRename(a,o)}))}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 s=this.authorNameToSafe(e);for(let i of this.discoverStashpadFolders()){let r=`${i}/_authors`;if(await this.app.vault.adapter.exists(r))for(let n of this.app.vault.getMarkdownFiles()){if(!n.path.startsWith(r+"/"))continue;let a=this.parseAuthorFilePath(n.path);if(!a||a.id!==t)continue;let o=`${r}/${s}-${t}.md`,c=n;if(n.path!==o)try{this.authorRenameInFlight.add(n.path),this.authorRenameInFlight.add(o),await this.app.fileManager.renameFile(n,o);let l=this.app.vault.getAbstractFileByPath(o);l&&(c=l)}catch(l){console.warn("[Stashpad] author file rename failed",l);continue}try{await this.refreshAuthorStub(c)}catch{}}}}async refreshAuthorStub(t){let e=(this.settings.authorName??"").trim(),s=(this.settings.authorRole??"").trim(),i=(this.settings.authorDepartment??"").trim();if(e)try{let r=await this.app.vault.read(t),n=r.replace(/^# .*$/m,`# ${e}`);n!==r&&await this.app.vault.modify(t,n),await this.app.fileManager.processFrontMatter(t,a=>{a.name=e,s?a.role=s:delete a.role,i?a.department=i:delete a.department})}catch(r){console.warn("[Stashpad] refreshAuthorStub failed",r)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let s=this.parseAuthorFilePath(t.path);if(!s)return;let i=(this.settings.authorId??"").trim();if(!i||s.id!==i)return;let r=s.name.trim();!r||r===(this.settings.authorName??"").trim()||(this.settings.authorName=r,await this.saveSettings(),await this.syncAuthorFilesToName())}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof e?.id=="string"?e.id.trim():"",i=e?.parent,r=typeof i=="string"?i.trim()!=="":i!=null,n=typeof e?.created=="string"&&e.created.trim()!=="",a=!s,o=!r,c=!n;if(!a&&!o&&!c)return;let{newId:l}=await Promise.resolve().then(()=>(Tt(),Zt)),h,d=!1,v=!1;if(await this.app.fileManager.processFrontMatter(t,w=>{if(a&&(typeof w.id=="string"&&w.id.trim()||(h=l(),w.id=h)),o){let b=w.parent;(typeof b=="string"?b.trim()!=="":b!=null)||(w.parent=V,d=!0)}c&&(typeof w.created=="string"&&w.created.trim()||(w.created=new Date(t.stat.ctime).toISOString(),v=!0))}),!h&&!d&&!v)return;let u=this.newLog(),y=h||s;y&&await u.append({type:"parent_change",id:y,payload:{from:null,to:V,reason:"orphan_auto_fix",path:t.path,addedId:!!h,addedParent:d,addedCreated:v}}),new ht.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}async autoImportStash(t,e){try{let s=new Uint8Array(await this.app.vault.readBinary(t)),i=Et(),r=new Set;if(i&&typeof i.collectExistingIds=="function"&&i.noteFolder===e)for(let o of i.collectExistingIds())r.add(o);else for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(e+"/"))continue;let c=this.app.metadataCache.getFileCache(o)?.frontmatter?.id;typeof c=="string"&&r.add(c)}let n=await re(this.app,s,e,r);try{await this.newLog().append({type:"stash_import",id:V,payload:{from:t.path,into:e,noteCount:n.notesWritten,attachmentsWritten:n.attachmentsWritten,collisionsRenamed:n.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let a=[`Auto-imported ${n.notesWritten} note${n.notesWritten===1?"":"s"} from ${t.name}`];n.attachmentsWritten&&a.push(`+ ${n.attachmentsWritten} attachment${n.attachmentsWritten===1?"":"s"}`),n.collisionsRenamed&&a.push(`(${n.collisionsRenamed} renamed)`),new ht.Notice(a.join(" ")),i&&typeof i.debouncedRender=="function"&&i.debouncedRender()}catch(s){new ht.Notice(`Stashpad: auto-import failed for ${t.name} \u2014 ${s.message}`),console.error(s)}}async rebootstrapAllFolders(){let t="__root__",e=new Set;for(let a of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==t)continue;let c=a.parent?.path;c&&e.add(c)}let s=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),i=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),r=[],n=async a=>{a&&(await this.app.vault.adapter.exists(a)||await this.app.vault.createFolder(a))};for(let a of e)try{s&&await n(`${a}/${s}`),i&&await n(`${a}/${i}`),r.push(a)}catch(o){console.warn(`Stashpad: rebootstrap skipped ${a}`,o)}return{touched:r}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let i=e.getLeavesOfType(kt);if(i.length>0){e.revealLeaf(i[0]);return}}let s=e.getLeaf("tab");await s.setViewState({type:kt,active:!0}),e.revealLeaf(s)}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let s=this.app.workspace.getLeaf("tab");await s.setViewState({type:kt,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(s)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,s=this.discoverStashpadFolders(),i=new Map;for(let r of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(r)?.frontmatter;if(!n)continue;let a=typeof n.author=="string"?n.author:"",o=Array.isArray(n.contributors)?n.contributors.filter(u=>typeof u=="string"):[],c=a.includes(e),l=o.some(u=>u.includes(e));if(!c&&!l)continue;let h=r.parent?.path??"",d=s.find(u=>h===u||h.startsWith(u+"/"));if(!d)continue;i.has(d)||i.set(d,{authored:0,contributed:0});let v=i.get(d);c&&v.authored++,l&&v.contributed++}return[...i.entries()].map(([r,n])=>({folder:r,...n})).sort((r,n)=>n.authored+n.contributed-(r.authored+r.contributed))}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),this.settings={...Ct,...t,shortcuts:{...Ct.shortcuts,...t?.shortcuts??{}},mod:{...Ct.mod,...t?.mod??{}},bindings:ws(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,drafts:bs(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...St]},ve(this.settings)}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),ve(this.settings),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 ht.Notice("No Stashpad folders found.");return}let e=new Set,s=this.app.vault.getMarkdownFiles();for(let h of s){let d=this.app.metadataCache.getFileCache(h)?.frontmatter,v=typeof d?.id=="string"?d.id.trim():"";v&&e.add(v)}let{newId:i}=await Promise.resolve().then(()=>(Tt(),Zt)),r=()=>{for(let h=0;h<100;h++){let d=i();if(!e.has(d))return e.add(d),d}for(let h=8;h<=16;h+=2){let d=i(h);if(!e.has(d))return e.add(d),d}throw new Error("Could not generate a unique id")},n=[];for(let h of s){let d=h.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(d))continue;let v=this.app.metadataCache.getFileCache(h)?.frontmatter,u=typeof v?.id=="string"?v.id.trim():"",y=v?.parent,w=typeof y=="string"?y.trim()!=="":y!=null,b=typeof v?.created=="string"&&v.created.trim()!=="",C=!u,E=!w,I=!b;!C&&!E&&!I||n.push({file:h,addId:C,addParent:E,addCreated:I})}if(n.length===0){new ht.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,o=0,c=this.newLog();for(let h of n)try{let d;await this.app.fileManager.processFrontMatter(h.file,y=>{if(h.addId&&(typeof y.id=="string"&&y.id.trim()||(d=r(),y.id=d)),h.addParent){let w=y.parent;(typeof w=="string"?w.trim()!=="":w!=null)||(y.parent=V)}h.addCreated&&(typeof y.created=="string"&&y.created.trim()||(y.created=new Date(h.file.stat.ctime).toISOString()))});let v=this.app.metadataCache.getFileCache(h.file)?.frontmatter,u=d??v?.id??"";u&&await c.append({type:"parent_change",id:u,payload:{from:null,to:V,reason:"orphan_fix",path:h.file.path,addedId:h.addId,addedParent:h.addParent,addedCreated:h.addCreated}}),a++}catch(d){console.warn("Stashpad: orphan fix failed for",h.file.path,d),o++}let l=o?` (${o} failed \u2014 see console)`:"";new ht.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${l}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Tt(),Zt)),s=new Set;for(let c of this.app.vault.getMarkdownFiles()){if(c.path===t.path)continue;let l=this.app.metadataCache.getFileCache(c)?.frontmatter,h=typeof l?.id=="string"?l.id.trim():"";h&&s.add(h)}let i=()=>{for(let c=0;c<50;c++){let l=e();if(!s.has(l))return l}for(let c=8;c<=16;c+=2){let l=e(c);if(!s.has(l))return l}throw new Error("Could not generate a unique id")},r=[],n=[];try{await this.app.fileManager.processFrontMatter(t,c=>{let l=typeof c.id=="string"?c.id.trim():"";!l||/\s/.test(l)||s.has(l)?(c.id=i(),r.push("id")):n.push("id"),c.parent!==void 0&&c.parent!==null&&String(c.parent).trim()!==""?n.push("parent"):(c.parent=V,r.push("parent")),typeof c.created=="string"&&c.created.trim()!==""?n.push("created"):(c.created=new Date(t.stat.ctime).toISOString(),r.push("created"))})}catch(c){new ht.Notice(`Adopt failed: ${c.message}`);return}let a=!1;try{let c=this.app.metadataCache.getFileCache(t)?.frontmatter,l=typeof c?.id=="string"?c.id.trim():"";if(l&&t.basename&&!t.basename.endsWith(`-${l}`)){let h=`${t.parent?t.parent.path+"/":""}${t.basename}-${l}.md`;await this.app.vault.adapter.exists(h)||(await this.app.fileManager.renameFile(t,h),a=!0)}}catch(c){console.warn("Stashpad: adopt rename failed",c)}if(r.length===0&&!a){new ht.Notice(`Already a Stashpad note (${n.join(", ")} present).`);return}let o=[];r.length&&o.push(`added: ${r.join(", ")}`),a&&o.push("renamed with id"),new ht.Notice(`Adopted into Stashpad \u2014 ${o.join("; ")}.`);try{let c=this.newLog(),l=this.app.metadataCache.getFileCache(t)?.frontmatter,h=l?.id??"";h&&await c.append({type:"create",id:h,payload:{path:t.path,parent:l?.parent??V,source:"adopt",added:r}})}catch{}}};function ws(g,m,t){let e=ge();for(let s of Rt){let i=m&&typeof m[s.id]=="string"?m[s.id]:t&&typeof t[s.id]=="string"?t[s.id]:null;i!=null&&i!==""&&(e[s.id].primary=i)}if(g&&typeof g=="object")for(let s of Rt){let i=g[s.id];!i||typeof i!="object"||(e[s.id]={primary:typeof i.primary=="string"?i.primary:e[s.id].primary,secondary:typeof i.secondary=="string"?i.secondary:"",preferRight:!!i.preferRight})}return e}function bs(g){let m={};if(!g||typeof g!="object")return m;for(let[t,e]of Object.entries(g))if(typeof e=="string")m[t]=e;else if(e&&typeof e=="object"){for(let s of Object.values(e))if(typeof s=="string"&&s.length>0){m[t]=s;break}}return m} +${e.format("HH:mm A")}`}formatTimeInline(t){if(!t)return"";let e=(0,A.moment)(t);if(!e.isValid())return"";if(ft().useTemplatesFormat){let i=se(this.app);if(i){let r=/:ss/.test(i.timeFormat)?i.timeFormat:i.timeFormat.replace(/(:mm)/,"$1:ss");return`${e.format(i.dateFormat)} ${e.format(r)}`}}return`${e.format("YYYY.MM.DD")} ${e.format("HH:mm:ss A")}`}scrollListToBottom(){let t=this.listEl;if(!t)return;this.stickToListBottom=!0,t.scrollTop=t.scrollHeight,this.stickyRowObserver?.disconnect();let e=()=>{if(!this.stickToListBottom){this.stickyRowObserver?.disconnect(),this.stickyRowObserver=null;return}t.scrollTop=t.scrollHeight},s=new ResizeObserver(e);for(let a of Array.from(t.children))a instanceof HTMLElement&&s.observe(a);this.stickyRowObserver=s;let i=performance.now(),r=t.scrollHeight,n=()=>{if(!this.stickToListBottom)return;let a=t.scrollHeight;a!==r&&(t.scrollTop=a,r=a),performance.now()-i<3e4&&requestAnimationFrame(n)};requestAnimationFrame(n)}openNoteMenu(t,e){if(!e.file)return;let s=e.file,i=new A.Menu;i.addItem(r=>r.setTitle("Open in new Stashpad tab").setIcon("layout-grid").onClick(()=>{this.openInNewStashpadTab(e.id)})),i.addItem(r=>r.setTitle("Open in editor").setIcon("file-text").onClick(()=>{this.openFileAtEnd(s)})),i.addItem(r=>r.setTitle("Focus in Stashpad").setIcon("arrow-right").onClick(()=>this.navigateTo(e.id))),i.addSeparator(),i.addItem(r=>r.setTitle("Split note\u2026").setIcon("split").onClick(()=>void this.cmdSplit(e))),i.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()})),i.addItem(r=>r.setTitle("Insert template\u2026").setIcon("file-plus-2").onClick(()=>this.cmdInsertTemplate())),i.addItem(r=>r.setTitle("Export to .stash").setIcon("package").onClick(()=>void this.cmdExportStash(e))),i.addSeparator(),i.addItem(r=>r.setTitle("Move to\u2026").onClick(()=>this.cmdMovePicker())),i.addItem(r=>r.setTitle("Move to Home").onClick(async()=>{await this.changeParent(e,j)})),i.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()})),i.addSeparator(),i.addItem(r=>r.setTitle("Delete").setIcon("trash").onClick(async()=>{await this.deleteNote(e)})),i.showAtMouseEvent(t)}async deleteNote(t){if(!t.file)return;let e=[],s=g=>{for(let u of this.tree.getChildren(g.id))s(u),e.push(u)};s(t);let i=[...e,t],r=i.filter(g=>!!g.file),n=await Promise.all(r.map(g=>this.app.vault.cachedRead(g.file))),a=[];for(let g=0;g{let u=await this.snapshotNotes(i,g),y=0;if(g)for(let T of o){let R=this.app.metadataCache.getFirstLinkpathDest(T,"");if(R)try{await this.app.fileManager.trashFile(R),await this.log.append({type:"attachment_remove",id:j,payload:{path:R.path}}),new A.Notice(`Deleted attachment "${R.name}"`),y+=1}catch{}}for(let T of i)if(T.file){try{await this.app.fileManager.trashFile(T.file)}catch{}await this.log.append({type:"delete",id:T.id,payload:{path:T.file.path,attachmentsRemoved:g?o:[]}})}this.selection.clear(),this.cursorIdx=-1,this.tree.rebuild(this.noteFolder),this.render();let w=this.noteFolder,b=`Delete "${this.titleForNode(t)}"`,C=t.id,_=y>0?` with ${y} attachment${y===1?"":"s"}`:"";new A.Notice(`Deleted "${this.titleForNode(t)}"${_}`),this.plugin.getUndoStack(w).push({label:b,undo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.restoreSnapshots(u,[C])},redo:async()=>{this.selection.clear(),this.cursorIdx=-1,await this.trashNotesAndAttachments(u)}})},c=ft(),d=e.length>0&&c.confirmBulkDelete,h=o.length>0&&c.confirmAttachmentDelete;if(!d&&!h){await l(!1),this.focusView();return}new Ot(this.app,this.titleForNode(t),e.length,o.length,h,async g=>{await l(g),this.focusView()}).open()}async changeParent(t,e,s={record:!0}){if(!t.file)return;let i=t.file,r=t.parent;if(r!==e&&e!==t.id&&(await this.app.fileManager.processFrontMatter(i,n=>{n.parent=e}),await this.log.append({type:"parent_change",id:t.id,payload:{from:r,to:e}}),this.pendingFocusIds=[t.id],this.focusId!==e&&this.focusId!==r?(this.selection.clear(),this.cursorIdx=-1):this.focusId===r&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),s.quiet||new A.Notice("Reparented note"),s.record!==!1)){let n=this.noteFolder,a=i.path,o=t.id;this.plugin.getUndoStack(n).push({label:"Move note",undo:async()=>{let l=this.app.vault.getAbstractFileByPath(a);l&&(await this.app.fileManager.processFrontMatter(l,c=>{c.parent=r}),this.pendingFocusIds=[o],this.focusId!==r&&this.focusId!==e?(this.selection.clear(),this.cursorIdx=-1):this.focusId===e&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(n),this.render())},redo:async()=>{let l=this.app.vault.getAbstractFileByPath(a);l&&(await this.app.fileManager.processFrontMatter(l,c=>{c.parent=e}),this.pendingFocusIds=[o],this.focusId!==e&&this.focusId!==r?(this.selection.clear(),this.cursorIdx=-1):this.focusId===r&&(this.selection.clear(),this.cursorIdx=-1,this.pendingFocusIds=null),this.tree.rebuild(n),this.render())}})}}};function ws(v,p){return!p||v.metaKey||v.ctrlKey||v.altKey?!1:v.key.toLowerCase()===p.toLowerCase()}function le(v,p){return p?p.includes("+")?bs(v,p):ws(v,p):!1}function rt(v,p){if(!p)return!1;let{primary:t,secondary:e,preferRight:s}=p;return t&&e?s?le(v,e):le(v,t):le(v,t)||le(v,e)}function xe(v){if(!v)return"";let p=A.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac");return v.split("+").map(t=>{let e=t.trim();return e?e.toLowerCase()==="mod"?p?"Cmd":"Ctrl":e.toLowerCase()==="alt"?p?"Opt":"Alt":e.length===1?e.toUpperCase():e:""}).filter(Boolean).join("+")}function bs(v,p){if(!p)return!1;let t=p.split("+").map(d=>d.trim()).filter(Boolean);if(t.length<2)return!1;let e=t[t.length-1].toLowerCase(),s=new Set(t.slice(0,-1).map(d=>d.toLowerCase())),i=s.has("mod"),r=s.has("ctrl")||s.has("control"),n=s.has("cmd")||s.has("meta")||s.has("command"),a=s.has("alt")||s.has("option"),o=s.has("shift"),c=A.Platform.isMacOS??navigator.platform.toLowerCase().includes("mac")?v.metaKey:v.ctrlKey;return i&&!c||r&&!v.ctrlKey||n&&!v.metaKey||a!==v.altKey||o!==v.shiftKey||!i&&(!r&&v.ctrlKey||!n&&v.metaKey)?!1:v.key.toLowerCase()===e}function Ke(v){return v.split("/").map(p=>p.split(" ").map(t=>t&&/^[a-z]/.test(t)?t[0].toUpperCase()+t.slice(1):t).join(" ")).join("/")}function Ss(v,p,t){let e=new Set(p),s=v.filter(r=>!e.has(r)),i=v.findIndex(r=>e.has(r));if(i<0)return v.slice();switch(t){case"top":return[...p,...s];case"bottom":return[...s,...p];case"up":{let r=Math.max(0,i-1),n=s.slice();return n.splice(r,0,...p),n}case"down":{let r=(()=>{let l=-1;return v.forEach((c,d)=>{e.has(c)&&(l=d)}),l})(),n=0;for(let l=0;l"")}getLogPath(){return this.logPath}getDir(){return this.baseDir}async ensureDir(){if(this.dirOk)return;let p=this.app.vault.adapter,t=this.baseDir.split("/").filter(Boolean),e="";for(let s of t)e=e?`${e}/${s}`:s,await p.exists(e)||await p.mkdir(e);this.dirOk=!0}append(p){let t=p.author??this.getAuthor()??"",e={ts:new Date().toISOString(),...p};t?e.author=t:delete e.author;let s=JSON.stringify(e)+` +`;return this.writeChain=this.writeChain.then(async()=>{try{await this.ensureDir();let i=this.app.vault.adapter;if(typeof i.append=="function")await i.append(this.logPath,s);else{let r=await i.exists(this.logPath)?await i.read(this.logPath):"";await i.write(this.logPath,r+s)}}catch(i){console.warn("Stashpad: log append failed",i)}}),Promise.resolve()}async readState(){let p=this.app.vault.adapter;if(!await p.exists(this.statePath))return{};try{return JSON.parse(await p.read(this.statePath))}catch{return{}}}async writeState(p){await this.ensureDir(),await this.app.vault.adapter.write(this.statePath,JSON.stringify(p,null,2))}};var he=class{constructor(){this.undoStack=[];this.redoStack=[];this.cap=30}push(p){for(this.undoStack.push(p),this.redoStack.length=0;this.undoStack.length>this.cap;)this.undoStack.shift()}async undo(){let p=this.undoStack.pop();if(!p)return null;try{await p.undo()}catch(t){throw console.error("Stashpad: undo failed",t),t}return this.redoStack.push(p),p}async redo(){let p=this.redoStack.pop();if(!p)return null;try{await p.redo()}catch(t){throw console.error("Stashpad: redo failed",t),t}return this.undoStack.push(p),p}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 pe=class extends ht.Plugin{constructor(){super(...arguments);this.settings={...xt};this.undoStacks=new Map;this.sweptFolders=new Set;this.authorRenameInFlight=new Set;this.writeChain=Promise.resolve()}pluginPrivatePath(t=""){let s=`${this.manifest.dir.replace(/\/+$/,"")}/.stashpad`;return t?`${s}/${t.replace(/^\/+/,"")}`:s}newLog(){return new de(this.app,this.pluginPrivatePath(),()=>(this.settings?.authorName??"").trim())}async migrateLegacyPaths(){let t=this.app.vault.adapter,e=this.pluginPrivatePath(),s=async()=>{let a=e.split("/").filter(Boolean),o="";for(let l of a)o=o?`${o}/${l}`:l,await t.exists(o)||await t.mkdir(o)},i=`${this.manifest.dir.replace(/\/+$/,"")}/data.json`,r=this.pluginPrivatePath("data.json");if(await t.exists(i)&&!await t.exists(r))try{await s();let a=await t.read(i);await t.write(r,a),console.debug("[Stashpad] migrated data.json \u2192",r)}catch(a){console.warn("Stashpad: data.json migration failed",a)}let n=".stashpad";if(await t.exists(n))try{await s();let a=await t.list(n);for(let o of a.files){let l=o.replace(/^.*\//,""),c=this.pluginPrivatePath(l);if(!await t.exists(c))try{let d=await t.read(o);await t.write(c,d),console.debug("[Stashpad] migrated",o,"\u2192",c)}catch(d){console.warn(`Stashpad: failed to migrate ${o}`,d)}}}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(s){return console.warn("Stashpad: data.json parse failed",s),null}}async saveData(t){let e=this.app.vault.adapter,s=this.pluginPrivatePath();if(!await e.exists(s)){let i=s.split("/").filter(Boolean),r="";for(let n of i)r=r?`${r}/${n}`:n,await e.exists(r)||await e.mkdir(r)}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 s=this.app.vault.adapter,i=e.split("/").filter(Boolean),r="";for(let l of i)r=r?`${r}/${l}`:l,await s.exists(r)||await s.mkdir(r);let n=`${e}/Home.md`;if(await s.exists(n)){let l=this.app.vault.getAbstractFileByPath(n);l&&await this.app.fileManager.processFrontMatter(l,c=>{(typeof c.id!="string"||!c.id)&&(c.id=j),"parent"in c||(c.parent=null),(typeof c.created!="string"||!c.created)&&(c.created=new Date().toISOString())});return}let a=new Date().toISOString(),o=["---",`id: ${j}`,"parent: null",`created: ${a}`,"---","Home"].join(` +`);await this.app.vault.create(n,o)}collectColorsInFolder(t){let e=new Map,s=t.replace(/\/+$/,"");for(let r of this.app.vault.getMarkdownFiles()){let n=r.parent?.path?.replace(/\/+$/,"")??"";if(n!==s&&!n.startsWith(s+"/"))continue;let a=this.app.metadataCache.getFileCache(r)?.frontmatter,o=typeof a?.color=="string"?a.color.trim():"";if(!o||!/^#([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$/i.test(o))continue;let l=o.toLowerCase();e.set(l,(e.get(l)??0)+1)}let i=[...e.entries()].map(([r,n])=>({hex:r,count:n}));return i.sort((r,n)=>n.count-r.count||r.hex.localeCompare(n.hex)),i}async recolorAllInFolder(t,e,s){let i=t.replace(/\/+$/,""),r=e.toLowerCase(),n=0;for(let o of this.app.vault.getMarkdownFiles()){let l=o.parent?.path?.replace(/\/+$/,"")??"";if(l!==i&&!l.startsWith(i+"/"))continue;let c=this.app.metadataCache.getFileCache(o)?.frontmatter;if((typeof c?.color=="string"?c.color.trim().toLowerCase():"")===r)try{await this.app.fileManager.processFrontMatter(o,h=>{s?h.color=s:delete h.color}),n++}catch(h){console.warn(`Stashpad: recolor failed for ${o.path}`,h)}}let a=this.settings.colorAliases?.[i];if(a){let o=a[r];o&&(delete a[r],s&&(a[s.toLowerCase()]=o),Object.keys(a).length===0&&delete this.settings.colorAliases[i],await this.saveSettings())}return n}getColorAlias(t,e){let s=t.replace(/\/+$/,""),i=this.settings.colorAliases?.[s];if(!i)return;let r=i[e.toLowerCase()];return r&&r.trim()?r:void 0}async setColorAlias(t,e,s){let i=t.replace(/\/+$/,""),r=e.toLowerCase();this.settings.colorAliases||(this.settings.colorAliases={}),this.settings.colorAliases[i]||(this.settings.colorAliases[i]={});let n=this.settings.colorAliases[i],a=s.trim();a?n[r]=a:delete n[r],Object.keys(n).length===0&&delete this.settings.colorAliases[i],await this.saveSettings()}async waitForStashpadFolder(t,e=2e3){let s=t.trim().replace(/^\/+|\/+$/g,"");if(!s)return;let i=Date.now();for(;Date.now()-isetTimeout(r,80))}}discoverStashpadFolders(){let t=new Set;for(let e of this.app.vault.getMarkdownFiles()){let s=this.app.metadataCache.getFileCache(e)?.frontmatter;if(typeof s?.id!="string"||!s.id.trim()||!s||!("parent"in s))continue;let i=e.parent?.path?.replace(/\/+$/,"")??"";i&&t.add(i)}return[...t].sort()}searchableFolders(t){let e=new Set(this.settings.searchIncludedFolders),s=new Set(this.settings.searchExcludedFolders),r=this.discoverStashpadFolders().filter(o=>e.size>0?e.has(o):!s.has(o)),n=(t||"").trim().replace(/\/+$/,""),a=r.filter(o=>o!==n);return n&&a.unshift(n),a}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 s=this.newLog(),i={},r=this.app.vault.getMarkdownFiles().filter(l=>l.path===t||l.path.startsWith(t+"/"));for(let l of r){let c=this.app.metadataCache.getFileCache(l)?.frontmatter,d=typeof c?.id=="string"?c.id.trim():"";if(!d)continue;let h=c&&"parent"in c?c.parent??null:null;i[d]={parent:h,path:l.path}}let n=await s.readState(),a=l=>l===t||l.startsWith(t+"/");if(!e.silent){for(let[l,c]of Object.entries(i)){let d=n[l];d?d.parent!==c.parent?await s.append({type:"parent_change",id:l,payload:{from:d.parent,to:c.parent}}):d.path!==c.path&&await s.append({type:"rename",id:l,payload:{from:d.path,to:c.path}}):await s.append({type:"create",id:l,payload:{path:c.path,parent:c.parent}})}for(let[l,c]of Object.entries(n))!i[l]&&a(c.path)&&await s.append({type:"missing",id:l,payload:{lastPath:c.path}})}let o={};for(let[l,c]of Object.entries(n))a(c.path)||(o[l]=c);for(let[l,c]of Object.entries(i))o[l]=c;await s.writeState(o)}catch(s){console.warn("Stashpad: integrity sweep failed",s)}}getUndoStack(t){let e=this.undoStacks.get(t);return e||(e=new he,this.undoStacks.set(t,e)),e}async onload(){await this.migrateLegacyPaths(),await this.loadSettings(),this.addSettingTab(new ee(this.app,this)),this.registerView(kt,a=>new ce(a,this));let t=()=>{let a=_t(),o=!!a&&this.app.workspace.activeLeaf&&this.app.workspace.activeLeaf.view===a,l=!!o&&this.settings.hideMobileToolbarInStashpad;document.body.classList.toggle("stashpad-hide-mobile-toolbar",l),document.body.classList.toggle("stashpad-active",!!o)};this.register(Le(t)),this.registerEvent(this.app.workspace.on("active-leaf-change",t)),t(),this.register(()=>document.body.classList.remove("stashpad-hide-mobile-toolbar","stashpad-active"));let e=window.visualViewport,s=()=>{let a=document.querySelector(".mobile-toolbar, .mobile-toolbar-container"),o=a&&a.isConnected?a.offsetHeight:0;document.body.style.setProperty("--stashpad-toolbar-h",`${o}px`);let l=0;e&&(l=Math.max(0,window.innerHeight-e.height-e.offsetTop)),document.body.style.setProperty("--stashpad-vv-bottom-gap",`${l}px`),document.body.classList.toggle("stashpad-keyboard-open",l>100)};s(),e&&(e.addEventListener("resize",s),e.addEventListener("scroll",s),this.register(()=>{e.removeEventListener("resize",s),e.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",()=>void this.activateView({reveal:!0})),this.addCommand({id:"stashpad-open",name:"Open Stashpad in new tab",callback:()=>void this.activateView({reveal:!1})}),this.addCommand({id:"stashpad-reveal",name:"Reveal or open Stashpad",callback:()=>void this.activateView({reveal:!0})});let i=a=>{let o=_t();o&&typeof o[a]=="function"&&o[a]()};this.addCommand({id:"stashpad-toggle-split",name:"Toggle split-on-newlines",callback:()=>i("toggleSplit")}),this.addCommand({id:"stashpad-pick-destination",name:"Pick destination for next note",callback:()=>i("openDestinationPicker")}),this.addCommand({id:"stashpad-search",name:"Search Stashpad notes",callback:()=>i("openSearchModal")}),this.addCommand({id:"stashpad-search-in-parent",name:"Search in current parent",callback:()=>i("openSearchInParentModal")}),this.addCommand({id:"stashpad-move-picker",name:"Move selection (picker)",callback:()=>i("cmdMovePicker")}),this.addCommand({id:"stashpad-merge",name:"Merge selection",callback:()=>i("cmdMerge")}),this.addCommand({id:"stashpad-copy",name:"Copy selection",callback:()=>i("cmdCopy")}),this.addCommand({id:"stashpad-copy-tree",name:"Copy focused subtree",callback:()=>i("cmdCopyTree")}),this.addCommand({id:"stashpad-copy-outline",name:"Copy as outline (nested embeds)",callback:()=>i("cmdCopyOutline")}),this.addCommand({id:"stashpad-split",name:"Split note\u2026",callback:()=>i("cmdSplit")}),this.addCommand({id:"stashpad-edit-note",name:"Edit note in new tab (selection)",callback:()=>i("cmdOpenInEditor")}),this.addCommand({id:"stashpad-edit-parent",name:"Edit parent note in new tab",callback:()=>i("cmdOpenParentInEditor")}),this.addCommand({id:"stashpad-delete",name:"Delete selection",callback:()=>i("cmdDelete")}),this.addCommand({id:"stashpad-move-up",name:"Move note up",callback:()=>i("cmdMoveUp")}),this.addCommand({id:"stashpad-move-down",name:"Move note down",callback:()=>i("cmdMoveDown")}),this.addCommand({id:"stashpad-move-to-top",name:"Move note to top",callback:()=>i("cmdMoveToTop")}),this.addCommand({id:"stashpad-move-to-bottom",name:"Move note to bottom",callback:()=>i("cmdMoveToBottom")}),this.addCommand({id:"stashpad-outdent",name:"Outdent (move to grandparent)",callback:()=>i("cmdOutdent")}),this.addCommand({id:"stashpad-set-color",name:"Set note color\u2026",callback:()=>i("cmdSetColor")}),this.addCommand({id:"stashpad-clone",name:"Clone selection (duplicate / copy notes)",callback:()=>i("cmdClone")}),this.addCommand({id:"stashpad-insert-template",name:"Insert template (clone an existing note)",callback:()=>i("cmdInsertTemplate")}),this.addCommand({id:"stashpad-toggle-expand",name:"Show more / show less (expand toggle)",callback:()=>i("cmdToggleExpand")}),this.addCommand({id:"stashpad-pick-move",name:"Move (in-list, arrow + Enter)",callback:()=>i("cmdInListPicker")}),this.addCommand({id:"stashpad-open-in-new-tab",name:"Open in new Stashpad tab",callback:()=>i("cmdOpenInNewStashpadTab")}),this.addCommand({id:"stashpad-toggle-complete",name:"Toggle complete (strikethrough)",callback:()=>i("cmdToggleComplete")}),this.addCommand({id:"stashpad-clone-tab",name:"Clone (duplicate / copy) this Stashpad tab",callback:()=>i("cmdCloneStashpadTab")}),this.addCommand({id:"stashpad-undo",name:"Undo last Stashpad action",callback:()=>i("cmdUndo")}),this.addCommand({id:"stashpad-redo",name:"Redo last undone Stashpad action",callback:()=>i("cmdRedo")}),this.addCommand({id:"stashpad-export-stash",name:"Export selection to .stash",callback:()=>i("cmdExportStash")}),this.addCommand({id:"stashpad-import-stash",name:"Import .stash file\u2026",callback:()=>i("cmdImportStash")}),this.addCommand({id:"stashpad-pick-folder",name:"Switch this Stashpad tab to another folder\u2026",callback:()=>i("cmdOpenFolderPicker")}),this.addCommand({id:"stashpad-run-integrity-check",name:"Run integrity check on active Stashpad folder",checkCallback:a=>{let o=_t(),l=o&&o.noteFolder;return l?(a||(new ht.Notice(`Running integrity check on "${l}"\u2026`),this.runIntegrityCheckOnFolder(l).then(()=>{new ht.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-adopt-note",name:"Adopt active note into Stashpad (fill missing frontmatter)",checkCallback:a=>{let o=this.app.workspace.getActiveFile();return!o||o.extension!=="md"?!1:(a||this.adoptNote(o),!0)}}),this.addCommand({id:"stashpad-open-settings",name:"Open Stashpad settings",callback:()=>{let a=this.app.setting;!a?.open||!a?.openTabById||(a.open(),a.openTabById(this.manifest.id))}});let r=a=>{if(a.extension!==Bt)return;let o=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),l=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,"");if(!o)return;let c=a.parent?.path||"";if((c.split("/").pop()??"")!==o||l&&c.endsWith(`/${l}`))return;let h=c.slice(0,c.length-o.length).replace(/\/+$/,"")||this.settings.folder;this.autoImportStash(a,h)};this.registerEvent(this.app.vault.on("create",a=>{a instanceof ht.TFile&&r(a)})),this.registerEvent(this.app.vault.on("rename",a=>{a instanceof ht.TFile&&r(a)}));let n=a=>{if(a.extension!=="md")return;let o=a.parent?.path?.replace(/\/+$/,"")??"";this.discoverStashpadFolders().includes(o)&&setTimeout(()=>{this.fixOrphanParentForFile(a)},800)};this.registerEvent(this.app.vault.on("create",a=>{a instanceof ht.TFile&&n(a)})),this.registerEvent(this.app.vault.on("rename",a=>{a instanceof ht.TFile&&n(a)})),this.registerEvent(this.app.vault.on("rename",(a,o)=>{a instanceof ht.TFile&&this.maybeAdoptAuthorRename(a,o)}))}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 s=this.authorNameToSafe(e);for(let i of this.discoverStashpadFolders()){let r=`${i}/_authors`;if(await this.app.vault.adapter.exists(r))for(let n of this.app.vault.getMarkdownFiles()){if(!n.path.startsWith(r+"/"))continue;let a=this.parseAuthorFilePath(n.path);if(!a||a.id!==t)continue;let o=`${r}/${s}-${t}.md`,l=n;if(n.path!==o)try{this.authorRenameInFlight.add(n.path),this.authorRenameInFlight.add(o),await this.app.fileManager.renameFile(n,o);let c=this.app.vault.getAbstractFileByPath(o);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(),s=(this.settings.authorRole??"").trim(),i=(this.settings.authorDepartment??"").trim();if(e)try{let r=await this.app.vault.read(t),n=r.replace(/^# .*$/m,`# ${e}`);n!==r&&await this.app.vault.modify(t,n),await this.app.fileManager.processFrontMatter(t,a=>{a.name=e,s?a.role=s:delete a.role,i?a.department=i:delete a.department})}catch(r){console.warn("[Stashpad] refreshAuthorStub failed",r)}}async maybeAdoptAuthorRename(t,e){if(this.authorRenameInFlight.delete(t.path)||this.authorRenameInFlight.delete(e))return;let s=this.parseAuthorFilePath(t.path);if(!s)return;let i=(this.settings.authorId??"").trim();if(!i||s.id!==i)return;let r=s.name.trim();!r||r===(this.settings.authorName??"").trim()||(this.settings.authorName=r,await this.saveSettings(),await this.syncAuthorFilesToName())}async fixOrphanParentForFile(t){try{let e=this.app.metadataCache.getFileCache(t)?.frontmatter,s=typeof e?.id=="string"?e.id.trim():"",i=e?.parent,r=typeof i=="string"?i.trim()!=="":i!=null,n=typeof e?.created=="string"&&e.created.trim()!=="",a=!s,o=!r,l=!n;if(!a&&!o&&!l)return;let{newId:c}=await Promise.resolve().then(()=>(Tt(),Zt)),d,h=!1,g=!1;if(await this.app.fileManager.processFrontMatter(t,w=>{if(a&&(typeof w.id=="string"&&w.id.trim()||(d=c(),w.id=d)),o){let b=w.parent;(typeof b=="string"?b.trim()!=="":b!=null)||(w.parent=j,h=!0)}l&&(typeof w.created=="string"&&w.created.trim()||(w.created=new Date(t.stat.ctime).toISOString(),g=!0))}),!d&&!h&&!g)return;let u=this.newLog(),y=d||s;y&&await u.append({type:"parent_change",id:y,payload:{from:null,to:j,reason:"orphan_auto_fix",path:t.path,addedId:!!d,addedParent:h,addedCreated:g}}),new ht.Notice(`Adopted ${t.basename} \u2192 Home`)}catch(e){console.warn("Stashpad: orphan auto-fix failed",e)}}async autoImportStash(t,e){try{let s=new Uint8Array(await this.app.vault.readBinary(t)),i=_t(),r=new Set;if(i&&typeof i.collectExistingIds=="function"&&i.noteFolder===e)for(let o of i.collectExistingIds())r.add(o);else for(let o of this.app.vault.getMarkdownFiles()){if(!o.path.startsWith(e+"/"))continue;let l=this.app.metadataCache.getFileCache(o)?.frontmatter?.id;typeof l=="string"&&r.add(l)}let n=await ne(this.app,s,e,r);try{await this.newLog().append({type:"stash_import",id:j,payload:{from:t.path,into:e,noteCount:n.notesWritten,attachmentsWritten:n.attachmentsWritten,collisionsRenamed:n.collisionsRenamed,auto:!0}})}catch{}try{await this.app.fileManager.trashFile(t)}catch{}let a=[`Auto-imported ${n.notesWritten} note${n.notesWritten===1?"":"s"} from ${t.name}`];n.attachmentsWritten&&a.push(`+ ${n.attachmentsWritten} attachment${n.attachmentsWritten===1?"":"s"}`),n.collisionsRenamed&&a.push(`(${n.collisionsRenamed} renamed)`),new ht.Notice(a.join(" ")),i&&typeof i.debouncedRender=="function"&&i.debouncedRender()}catch(s){new ht.Notice(`Stashpad: auto-import failed for ${t.name} \u2014 ${s.message}`),console.error(s)}}async rebootstrapAllFolders(){let t="__root__",e=new Set;for(let a of this.app.vault.getMarkdownFiles()){if(this.app.metadataCache.getFileCache(a)?.frontmatter?.id!==t)continue;let l=a.parent?.path;l&&e.add(l)}let s=(this.settings.importDropFolder||"").trim().replace(/^\/+|\/+$/g,""),i=(this.settings.exportFolder||"").trim().replace(/^\/+|\/+$/g,""),r=[],n=async a=>{a&&(await this.app.vault.adapter.exists(a)||await this.app.vault.createFolder(a))};for(let a of e)try{s&&await n(`${a}/${s}`),i&&await n(`${a}/${i}`),r.push(a)}catch(o){console.warn(`Stashpad: rebootstrap skipped ${a}`,o)}return{touched:r}}async activateView(t={reveal:!0}){let{workspace:e}=this.app;if(t.reveal){let i=e.getLeavesOfType(kt);if(i.length>0){e.revealLeaf(i[0]);return}}let s=e.getLeaf("tab");await s.setViewState({type:kt,active:!0}),e.revealLeaf(s)}async activateViewForFolder(t){let e=(t||"").replace(/^\/+|\/+$/g,"");if(!e)return;let s=this.app.workspace.getLeaf("tab");await s.setViewState({type:kt,active:!0,state:{folderOverride:e}}),this.app.workspace.revealLeaf(s)}collectAuthoredFolders(){let t=(this.settings.authorId??"").trim();if(!t)return[];let e=`-${t}`,s=this.discoverStashpadFolders(),i=new Map;for(let r of this.app.vault.getMarkdownFiles()){let n=this.app.metadataCache.getFileCache(r)?.frontmatter;if(!n)continue;let a=typeof n.author=="string"?n.author:"",o=Array.isArray(n.contributors)?n.contributors.filter(u=>typeof u=="string"):[],l=a.includes(e),c=o.some(u=>u.includes(e));if(!l&&!c)continue;let d=r.parent?.path??"",h=s.find(u=>d===u||d.startsWith(u+"/"));if(!h)continue;i.has(h)||i.set(h,{authored:0,contributed:0});let g=i.get(h);l&&g.authored++,c&&g.contributed++}return[...i.entries()].map(([r,n])=>({folder:r,...n})).sort((r,n)=>n.authored+n.contributed-(r.authored+r.contributed))}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),this.settings={...xt,...t,shortcuts:{...xt.shortcuts,...t?.shortcuts??{}},mod:{...xt.mod,...t?.mod??{}},bindings:ks(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:{},drafts:Cs(t?.drafts),lastSubmitted:t?.lastSubmitted&&typeof t.lastSubmitted=="object"?t.lastSubmitted:{},slugStopWords:Array.isArray(t?.slugStopWords)?t.slugStopWords:[...St]},be(this.settings)}queueWrite(){let t=this.writeChain.then(()=>this.saveData(this.settings));return this.writeChain=t.catch(()=>{}),t}async saveSettings(){await this.queueWrite(),be(this.settings),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 ht.Notice("No Stashpad folders found.");return}let e=new Set,s=this.app.vault.getMarkdownFiles();for(let d of s){let h=this.app.metadataCache.getFileCache(d)?.frontmatter,g=typeof h?.id=="string"?h.id.trim():"";g&&e.add(g)}let{newId:i}=await Promise.resolve().then(()=>(Tt(),Zt)),r=()=>{for(let d=0;d<100;d++){let h=i();if(!e.has(h))return e.add(h),h}for(let d=8;d<=16;d+=2){let h=i(d);if(!e.has(h))return e.add(h),h}throw new Error("Could not generate a unique id")},n=[];for(let d of s){let h=d.parent?.path?.replace(/\/+$/,"")??"";if(!t.has(h))continue;let g=this.app.metadataCache.getFileCache(d)?.frontmatter,u=typeof g?.id=="string"?g.id.trim():"",y=g?.parent,w=typeof y=="string"?y.trim()!=="":y!=null,b=typeof g?.created=="string"&&g.created.trim()!=="",C=!u,_=!w,T=!b;!C&&!_&&!T||n.push({file:d,addId:C,addParent:_,addCreated:T})}if(n.length===0){new ht.Notice("Nothing to fix \u2014 every note in a Stashpad folder already has id + parent + created.");return}let a=0,o=0,l=this.newLog();for(let d of n)try{let h;await this.app.fileManager.processFrontMatter(d.file,y=>{if(d.addId&&(typeof y.id=="string"&&y.id.trim()||(h=r(),y.id=h)),d.addParent){let w=y.parent;(typeof w=="string"?w.trim()!=="":w!=null)||(y.parent=j)}d.addCreated&&(typeof y.created=="string"&&y.created.trim()||(y.created=new Date(d.file.stat.ctime).toISOString()))});let g=this.app.metadataCache.getFileCache(d.file)?.frontmatter,u=h??g?.id??"";u&&await l.append({type:"parent_change",id:u,payload:{from:null,to:j,reason:"orphan_fix",path:d.file.path,addedId:d.addId,addedParent:d.addParent,addedCreated:d.addCreated}}),a++}catch(h){console.warn("Stashpad: orphan fix failed for",d.file.path,h),o++}let c=o?` (${o} failed \u2014 see console)`:"";new ht.Notice(`Fixed ${a} note${a===1?"":"s"} in Stashpad folders${c}.`)}async adoptNote(t){let{newId:e}=await Promise.resolve().then(()=>(Tt(),Zt)),s=new Set;for(let l of this.app.vault.getMarkdownFiles()){if(l.path===t.path)continue;let c=this.app.metadataCache.getFileCache(l)?.frontmatter,d=typeof c?.id=="string"?c.id.trim():"";d&&s.add(d)}let i=()=>{for(let l=0;l<50;l++){let c=e();if(!s.has(c))return c}for(let l=8;l<=16;l+=2){let c=e(l);if(!s.has(c))return c}throw new Error("Could not generate a unique id")},r=[],n=[];try{await this.app.fileManager.processFrontMatter(t,l=>{let c=typeof l.id=="string"?l.id.trim():"";!c||/\s/.test(c)||s.has(c)?(l.id=i(),r.push("id")):n.push("id"),l.parent!==void 0&&l.parent!==null&&String(l.parent).trim()!==""?n.push("parent"):(l.parent=j,r.push("parent")),typeof l.created=="string"&&l.created.trim()!==""?n.push("created"):(l.created=new Date(t.stat.ctime).toISOString(),r.push("created"))})}catch(l){new ht.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 d=`${t.parent?t.parent.path+"/":""}${t.basename}-${c}.md`;await this.app.vault.adapter.exists(d)||(await this.app.fileManager.renameFile(t,d),a=!0)}}catch(l){console.warn("Stashpad: adopt rename failed",l)}if(r.length===0&&!a){new ht.Notice(`Already a Stashpad note (${n.join(", ")} present).`);return}let o=[];r.length&&o.push(`added: ${r.join(", ")}`),a&&o.push("renamed with id"),new ht.Notice(`Adopted into Stashpad \u2014 ${o.join("; ")}.`);try{let l=this.newLog(),c=this.app.metadataCache.getFileCache(t)?.frontmatter,d=c?.id??"";d&&await l.append({type:"create",id:d,payload:{path:t.path,parent:c?.parent??j,source:"adopt",added:r}})}catch{}}};function ks(v,p,t){let e=we();for(let s of $t){let i=p&&typeof p[s.id]=="string"?p[s.id]:t&&typeof t[s.id]=="string"?t[s.id]:null;i!=null&&i!==""&&(e[s.id].primary=i)}if(v&&typeof v=="object")for(let s of $t){let i=v[s.id];!i||typeof i!="object"||(e[s.id]={primary:typeof i.primary=="string"?i.primary:e[s.id].primary,secondary:typeof i.secondary=="string"?i.secondary:"",preferRight:!!i.preferRight})}return e}function Cs(v){let p={};if(!v||typeof v!="object")return p;for(let[t,e]of Object.entries(v))if(typeof e=="string")p[t]=e;else if(e&&typeof e=="object"){for(let s of Object.values(e))if(typeof s=="string"&&s.length>0){p[t]=s;break}}return p} /*! Bundled license information: jszip/dist/jszip.min.js: diff --git a/manifest.json b/manifest.json index 9e73a6c..a5ce241 100644 --- a/manifest.json +++ b/manifest.json @@ -1,7 +1,7 @@ { "id": "stashpad", "name": "Stashpad", - "version": "0.52.0", + "version": "0.53.20", "minAppVersion": "1.7.0", "description": "Chat-style nested-notes view: rapid capture, outliner navigation, in-place editing.", "author": "Human", diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..51649e6 --- /dev/null +++ b/package-lock.json @@ -0,0 +1,686 @@ +{ + "name": "stashpad-obsidian", + "version": "0.4.1", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "stashpad-obsidian", + "version": "0.4.1", + "dependencies": { + "jszip": "^3.10.1" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "esbuild": "^0.21.0", + "obsidian": "latest", + "typescript": "^5.4.0" + } + }, + "node_modules/@codemirror/state": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/@codemirror/state/-/state-6.5.0.tgz", + "integrity": "sha512-MwBHVK60IiIHDcoMet78lxt6iw5gJOGSbNbOIVBHWVXIH4/Nq1+GQgLLGgI1KlnN86WDXsPudVaqYHKBIx7Eyw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@marijn/find-cluster-break": "^1.0.0" + } + }, + "node_modules/@codemirror/view": { + "version": "6.38.6", + "resolved": "https://registry.npmjs.org/@codemirror/view/-/view-6.38.6.tgz", + "integrity": "sha512-qiS0z1bKs5WOvHIAC0Cybmv4AJSkAXgX5aD6Mqd2epSLlVJsQl8NG23jCVouIgkh4All/mrbdsf2UOLFnJw0tw==", + "dev": true, + "license": "MIT", + "peer": true, + "dependencies": { + "@codemirror/state": "^6.5.0", + "crelt": "^1.0.6", + "style-mod": "^4.1.0", + "w3c-keyname": "^2.2.4" + } + }, + "node_modules/@esbuild/aix-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz", + "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "aix" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz", + "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz", + "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/android-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz", + "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz", + "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/darwin-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz", + "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz", + "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/freebsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz", + "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz", + "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz", + "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz", + "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-loong64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz", + "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==", + "cpu": [ + "loong64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-mips64el": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz", + "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==", + "cpu": [ + "mips64el" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-ppc64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz", + "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-riscv64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz", + "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-s390x": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz", + "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/linux-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz", + "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/netbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz", + "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "netbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/openbsd-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz", + "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openbsd" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/sunos-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz", + "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "sunos" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-arm64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz", + "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-ia32": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz", + "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@esbuild/win32-x64": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz", + "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">=12" + } + }, + "node_modules/@marijn/find-cluster-break": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@marijn/find-cluster-break/-/find-cluster-break-1.0.2.tgz", + "integrity": "sha512-l0h88YhZFyKdXIFNfSWpyjStDjGHwZ/U7iobcK1cQQD8sejsONdQtTVU+1wVN1PBw40PiiHB1vA5S7VTfQiP9g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/codemirror": { + "version": "5.60.8", + "resolved": "https://registry.npmjs.org/@types/codemirror/-/codemirror-5.60.8.tgz", + "integrity": "sha512-VjFgDF/eB+Aklcy15TtOTLQeMjTo07k7KAjql8OK5Dirr7a6sJY4T1uVBDuTVG9VEmn1uUsohOpYnVfgC6/jyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/tern": "*" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.19.39", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.39.tgz", + "integrity": "sha512-orrrD74MBUyK8jOAD/r0+lfa1I2MO6I+vAkmAWzMYbCcgrN4lCrmK52gRFQq/JRxfYPfonkr4b0jcY7Olqdqbw==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/tern": { + "version": "0.23.9", + "resolved": "https://registry.npmjs.org/@types/tern/-/tern-0.23.9.tgz", + "integrity": "sha512-ypzHFE/wBzh+BlH6rrBgS5I/Z7RD21pGhZ2rltb/+ZrVM1awdZwjx7hE5XfuYgHWk9uvV5HLZN3SloevCAp3Bw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/estree": "*" + } + }, + "node_modules/core-util-is": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/core-util-is/-/core-util-is-1.0.3.tgz", + "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", + "license": "MIT" + }, + "node_modules/crelt": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/crelt/-/crelt-1.0.6.tgz", + "integrity": "sha512-VQ2MBenTq1fWZUH9DJNGti7kKv6EeAuYr3cLwxUWhIu1baTaXh4Ib5W2CqHVqib4/MqbYGJqiL3Zb8GJZr3l4g==", + "dev": true, + "license": "MIT" + }, + "node_modules/esbuild": { + "version": "0.21.5", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", + "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "bin": { + "esbuild": "bin/esbuild" + }, + "engines": { + "node": ">=12" + }, + "optionalDependencies": { + "@esbuild/aix-ppc64": "0.21.5", + "@esbuild/android-arm": "0.21.5", + "@esbuild/android-arm64": "0.21.5", + "@esbuild/android-x64": "0.21.5", + "@esbuild/darwin-arm64": "0.21.5", + "@esbuild/darwin-x64": "0.21.5", + "@esbuild/freebsd-arm64": "0.21.5", + "@esbuild/freebsd-x64": "0.21.5", + "@esbuild/linux-arm": "0.21.5", + "@esbuild/linux-arm64": "0.21.5", + "@esbuild/linux-ia32": "0.21.5", + "@esbuild/linux-loong64": "0.21.5", + "@esbuild/linux-mips64el": "0.21.5", + "@esbuild/linux-ppc64": "0.21.5", + "@esbuild/linux-riscv64": "0.21.5", + "@esbuild/linux-s390x": "0.21.5", + "@esbuild/linux-x64": "0.21.5", + "@esbuild/netbsd-x64": "0.21.5", + "@esbuild/openbsd-x64": "0.21.5", + "@esbuild/sunos-x64": "0.21.5", + "@esbuild/win32-arm64": "0.21.5", + "@esbuild/win32-ia32": "0.21.5", + "@esbuild/win32-x64": "0.21.5" + } + }, + "node_modules/immediate": { + "version": "3.0.6", + "resolved": "https://registry.npmjs.org/immediate/-/immediate-3.0.6.tgz", + "integrity": "sha512-XXOFtyqDjNDAQxVfYxuF7g9Il/IbWmmlQg2MYKOH8ExIT1qg6xc4zyS3HaEEATgs1btfzxq15ciUiY7gjSXRGQ==", + "license": "MIT" + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", + "license": "ISC" + }, + "node_modules/isarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-1.0.0.tgz", + "integrity": "sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==", + "license": "MIT" + }, + "node_modules/jszip": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/jszip/-/jszip-3.10.1.tgz", + "integrity": "sha512-xXDvecyTpGLrqFrvkrUSoxxfJI5AH7U8zxxtVclpsUtMCq4JQ290LY8AW5c7Ggnr/Y/oK+bQMbqK2qmtk3pN4g==", + "license": "(MIT OR GPL-3.0-or-later)", + "dependencies": { + "lie": "~3.3.0", + "pako": "~1.0.2", + "readable-stream": "~2.3.6", + "setimmediate": "^1.0.5" + } + }, + "node_modules/lie": { + "version": "3.3.0", + "resolved": "https://registry.npmjs.org/lie/-/lie-3.3.0.tgz", + "integrity": "sha512-UaiMJzeWRlEujzAuw5LokY1L5ecNQYZKfmyZ9L7wDHb/p5etKaxXhohBcrw0EYby+G/NA52vRSN4N39dxHAIwQ==", + "license": "MIT", + "dependencies": { + "immediate": "~3.0.5" + } + }, + "node_modules/moment": { + "version": "2.29.4", + "resolved": "https://registry.npmjs.org/moment/-/moment-2.29.4.tgz", + "integrity": "sha512-5LC9SOxjSc2HF6vO2CyuTDNivEdoz2IvyJJGj6X8DJ0eFyfszE0QiEd+iXmBvUP3WHxSjFH/vIsA0EN00cgr8w==", + "dev": true, + "license": "MIT", + "engines": { + "node": "*" + } + }, + "node_modules/obsidian": { + "version": "1.12.3", + "resolved": "https://registry.npmjs.org/obsidian/-/obsidian-1.12.3.tgz", + "integrity": "sha512-HxWqe763dOqzXjnNiHmAJTRERN8KILBSqxDSEqbeSr7W8R8Jxezzbca+nz1LiiqXnMpM8lV2jzAezw3CZ4xNUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/codemirror": "5.60.8", + "moment": "2.29.4" + }, + "peerDependencies": { + "@codemirror/state": "6.5.0", + "@codemirror/view": "6.38.6" + } + }, + "node_modules/pako": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/pako/-/pako-1.0.11.tgz", + "integrity": "sha512-4hLB8Py4zZce5s4yd9XzopqwVv/yGNhV1Bl8NTmCq1763HeK2+EwVTv+leGeL13Dnh2wfbqowVPXCIO0z4taYw==", + "license": "(MIT AND Zlib)" + }, + "node_modules/process-nextick-args": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz", + "integrity": "sha512-3ouUOpQhtgrbOa17J7+uxOTpITYWaGP7/AhoR3+A+/1e9skrzelGi/dXzEYyvbxubEF6Wn2ypscTKiKJFFn1ag==", + "license": "MIT" + }, + "node_modules/readable-stream": { + "version": "2.3.8", + "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-2.3.8.tgz", + "integrity": "sha512-8p0AUk4XODgIewSi0l8Epjs+EVnWiK7NoDIEGU0HhE7+ZyY8D1IMY7odu5lRrFXGg71L15KG8QrPmum45RTtdA==", + "license": "MIT", + "dependencies": { + "core-util-is": "~1.0.0", + "inherits": "~2.0.3", + "isarray": "~1.0.0", + "process-nextick-args": "~2.0.0", + "safe-buffer": "~5.1.1", + "string_decoder": "~1.1.1", + "util-deprecate": "~1.0.1" + } + }, + "node_modules/safe-buffer": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.1.2.tgz", + "integrity": "sha512-Gd2UZBJDkXlY7GbJxfsE8/nvKkUEU1G38c1siN6QP6a9PT9MmHB8GnpscSmMJSoF8LOIrt8ud/wPtojys4G6+g==", + "license": "MIT" + }, + "node_modules/setimmediate": { + "version": "1.0.5", + "resolved": "https://registry.npmjs.org/setimmediate/-/setimmediate-1.0.5.tgz", + "integrity": "sha512-MATJdZp8sLqDl/68LfQmbP8zKPLQNV6BIZoIgrscFDQ+RsvK/BxeDQOgyxKKoh0y/8h3BqVFnCqQ/gd+reiIXA==", + "license": "MIT" + }, + "node_modules/string_decoder": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.1.1.tgz", + "integrity": "sha512-n/ShnvDi6FHbbVfviro+WojiFzv+s8MPMHBczVePfUpDJLwoLT0ht1l4YwBCbi8pJAveEEdnkHyPyTP/mzRfwg==", + "license": "MIT", + "dependencies": { + "safe-buffer": "~5.1.0" + } + }, + "node_modules/style-mod": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/style-mod/-/style-mod-4.1.3.tgz", + "integrity": "sha512-i/n8VsZydrugj3Iuzll8+x/00GH2vnYsk1eomD8QiRrSAeW6ItbCQDtfXCeJHd0iwiNagqjQkvpvREEPtW3IoQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/util-deprecate": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", + "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", + "license": "MIT" + }, + "node_modules/w3c-keyname": { + "version": "2.2.8", + "resolved": "https://registry.npmjs.org/w3c-keyname/-/w3c-keyname-2.2.8.tgz", + "integrity": "sha512-dpojBhNsCNN7T82Tm7k26A6G9ML3NkhDsnw9n/eoxSRlVBB4CEtIQ/KTCLI2Fwf3ataSXRhYFkQi3SlnFwPvPQ==", + "dev": true, + "license": "MIT" + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..e71ac04 --- /dev/null +++ b/package.json @@ -0,0 +1,20 @@ +{ + "name": "stashpad-obsidian", + "version": "0.53.20", + "private": true, + "scripts": { + "dev": "node esbuild.config.mjs", + "build": "node esbuild.config.mjs production", + "deploy:files": "node scripts/deploy.mjs", + "deploy": "npm run build && node scripts/deploy.mjs" + }, + "devDependencies": { + "@types/node": "^20.10.0", + "esbuild": "^0.21.0", + "obsidian": "latest", + "typescript": "^5.4.0" + }, + "dependencies": { + "jszip": "^3.10.1" + } +} diff --git a/scripts/deploy.mjs b/scripts/deploy.mjs new file mode 100644 index 0000000..358c0d4 --- /dev/null +++ b/scripts/deploy.mjs @@ -0,0 +1,79 @@ +#!/usr/bin/env node +// Copy the three plugin artifacts (main.js, manifest.json, styles.css) +// into the vault's plugin folder. Replaces a symlink-based setup that +// Obsidian Sync was indexing slowly. +// +// Configure the destination once: +// - Either set STASHPAD_DEPLOY in your environment. +// - Or create a `.deploy-target` file at the project root containing +// the absolute path of the vault plugin folder, e.g.: +// /Users/you/Vault/.obsidian/plugins/stashpad +// The file is gitignored. +// +// Usage: +// npm run deploy — build + copy +// npm run deploy:files — copy only (no build) + +import { existsSync, readFileSync, copyFileSync, mkdirSync, statSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +// Use fileURLToPath so spaces (and other URL-encoded chars) in the +// project path don't break the resolved filesystem path. +const ROOT = resolve(fileURLToPath(new URL("..", import.meta.url))); +const ARTIFACTS = ["main.js", "manifest.json", "styles.css"]; + +function resolveTarget() { + const envTarget = process.env.STASHPAD_DEPLOY?.trim(); + if (envTarget) return resolve(envTarget); + const cfgPath = join(ROOT, ".deploy-target"); + if (existsSync(cfgPath)) { + const raw = readFileSync(cfgPath, "utf8").trim(); + if (raw) return resolve(raw); + } + return null; +} + +function fail(msg) { + console.error(`\n[deploy] ${msg}\n`); + process.exit(1); +} + +const target = resolveTarget(); +if (!target) { + 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" + + "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}`); + } +} +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++; +} +if (missing.length) { + console.warn(`[deploy] WARNING: missing artifacts: ${missing.join(", ")} — did you build?`); +} +console.log(`[deploy] copied ${copied}/${ARTIFACTS.length} → ${target}`); diff --git a/src/active-view.ts b/src/active-view.ts new file mode 100644 index 0000000..31a5867 --- /dev/null +++ b/src/active-view.ts @@ -0,0 +1,19 @@ +let active: any = null; +const listeners = new Set<() => void>(); + +export function setActiveView(v: any): void { + if (active === v) return; + active = v; + for (const fn of listeners) fn(); +} +export function getActiveView(): any { return active; } +export function clearActiveView(v: any): void { + if (active === v) { + active = null; + for (const fn of listeners) fn(); + } +} +export function onActiveViewChange(fn: () => void): () => void { + listeners.add(fn); + return () => listeners.delete(fn); +} diff --git a/src/composer-autocomplete.ts b/src/composer-autocomplete.ts new file mode 100644 index 0000000..cdb09de --- /dev/null +++ b/src/composer-autocomplete.ts @@ -0,0 +1,359 @@ +import { App, Scope, TFile } from "obsidian"; + +/** + * Composer autocomplete: a lightweight popup attached to a plain + *